KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > taglib > common > URLTag


1 /* ===============================================================================
2 *
3 * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4 *
5 * ===============================================================================
6 *
7 * Copyright (C)
8 *
9 * This program is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU General Public License version 2, as published by the
11 * Free Software Foundation. See the file LICENSE.html for more information.
12 *
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19 * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20 *
21 * ===============================================================================
22 */

23 package org.infoglue.deliver.taglib.common;
24
25 import java.util.ArrayList JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.jsp.JspException JavaDoc;
34 import javax.servlet.jsp.JspTagException JavaDoc;
35
36 import org.apache.log4j.Logger;
37 import org.infoglue.deliver.taglib.TemplateControllerTag;
38
39 /**
40  * This class implements the <common:urlBuilder> tag, which creates an url
41  * from a base url (user supplied or taken from the request),
42  * a query string (user supplied ot taken from the reuest) and
43  * any number of parameters specified using nested <common:parameter> tags.
44  */

45 public class URLTag extends TemplateControllerTag
46 {
47
48     private final static Logger logger = Logger.getLogger(URLTag.class.getName());
49
50     /**
51      *
52      */

53     private static final long serialVersionUID = 4433903132736259601L;
54
55     /**
56      * The universal version identifier.
57      */

58
59     /**
60      * The base url to use when constructing the url.
61      */

62     private String JavaDoc baseURL;
63     
64     /**
65      * The query to use when constructing the url.
66      */

67     private String JavaDoc query;
68     
69     /**
70      * The parameter names to exclude from the quertyString. Commasseperated string.
71      */

72     private String JavaDoc excludedQueryStringParameters;
73     
74     /**
75      * The parameter that controls if the full servername etc should be included in the base url.
76      */

77     private boolean fullBaseUrl = false;
78     
79     /**
80      * The parameters to use when constructing the url.
81      */

82     private List JavaDoc parameters; // type: <String>, format: <name>=<value>
83

84     /**
85      * The names of all parameters added.
86      */

87     private Map JavaDoc parameterNames; // <type>: <String>-><String>
88

89     /**
90      * Tells the tag if the nice uri option should be disabled if enabled.
91      */

92     
93     private boolean disableNiceURI = false;
94     
95     /**
96      * Tells if parameter should be allowed even though there are parameters with that name
97      */

98     private boolean allowMultipleArguments = false;
99     
100     /**
101      * Default constructor.
102      */

103     public URLTag()
104     {
105         super();
106     }
107
108     /**
109      * Initializes the parameters to make it accessible for the children tags (if any).
110      *
111      * @return indication of whether to evaluate the body or not.
112      * @throws JspException if an error occurred while processing this tag.
113      */

114     public int doStartTag() throws JspException JavaDoc
115     {
116         return EVAL_BODY_INCLUDE;
117     }
118     
119     /**
120      * Generates the url and either sets the result attribute or writes the url
121      * to the output stream.
122      *
123      * @return indication of whether to continue evaluating the JSP page.
124      * @throws JspException if an error occurred while processing this tag.
125      */

126     public int doEndTag() throws JspException JavaDoc
127     {
128         addQueryParameters();
129         produceResult(generateURL());
130         parameters = null;
131         parameterNames = null;
132         return EVAL_PAGE;
133     }
134
135     /**
136      * Returns the parameters to use when constructing the url.
137      *
138      * @return the parameters to use when constructing the url.
139      */

140     private List JavaDoc getParameters()
141     {
142         if(parameters == null)
143         {
144             parameters = new ArrayList JavaDoc();
145         }
146         return parameters;
147     }
148     
149     /**
150      * Returns the name of all parameters that has been added.
151      *
152      * @return the name of all parameters that has been added.
153      */

154     private Map JavaDoc getParameterNames()
155     {
156         if(parameterNames == null)
157         {
158             parameterNames = new HashMap JavaDoc();
159         }
160         return parameterNames;
161     }
162     
163     /**
164      *
165      */

166     protected final void addParameter(final String JavaDoc name, final String JavaDoc value)
167     {
168         getParameters().add(name + "=" + value);
169         getParameterNames().put(name, name);
170     }
171     
172     /**
173      * Returns the url attribute if present; otherwise the url is taken from the request.
174      *
175      * @return the url attribute if present; otherwise the url is taken from the request.
176      */

177     private String JavaDoc getBaseURL()
178     {
179         String JavaDoc newBaseUrl = "";
180         try
181         {
182             logger.info("fullBaseUrl:" + fullBaseUrl);
183             if(this.fullBaseUrl)
184             {
185                 int indexOfProtocol = getRequest().getRequestURL().indexOf("://");
186                 int indexFirstSlash = getRequest().getRequestURL().indexOf("/", indexOfProtocol + 3);
187                 String JavaDoc base = null;
188                 if(indexFirstSlash > -1)
189                     base = getRequest().getRequestURL().substring(0, indexFirstSlash);
190                 else
191                     base = getRequest().getRequestURL().substring(0);
192                 
193                 String JavaDoc currentPageUrl = this.getController().getCurrentPageUrl().toString();
194                 currentPageUrl = currentPageUrl.split("\\?")[0];
195                 newBaseUrl = (baseURL == null) ? base + currentPageUrl : baseURL;
196             }
197             else
198             {
199                 String JavaDoc currentPageUrl = this.getController().getCurrentPageUrl().toString();
200                 currentPageUrl = currentPageUrl.split("\\?")[0];
201                 newBaseUrl = (baseURL == null) ? currentPageUrl : baseURL;
202             }
203         }
204         catch(Exception JavaDoc e)
205         {
206             logger.warn("Error:", e);
207             newBaseUrl = (baseURL == null) ? getRequest().getRequestURL().toString() : baseURL;
208         }
209         logger.info("newBaseUrl:" + newBaseUrl);
210         return newBaseUrl;
211     }
212     
213     /**
214      * Returns the query attribute if present; otherwise the query is taken from the request.
215      *
216      * @return the query attribute if present; otherwise the query is taken from the request.
217      */

218     private String JavaDoc getQuery()
219     {
220         String JavaDoc q = (query == null) ? getRequest().getQueryString() : query;
221         if(q != null && (q.startsWith("?") || q.startsWith("&")))
222         {
223             return q.substring(1);
224         }
225         return q;
226     }
227     
228     /**
229      * Returns the (http) request object.
230      *
231      * @return the (http) request object.
232      */

233     private final HttpServletRequest JavaDoc getRequest()
234     {
235         return (HttpServletRequest JavaDoc) pageContext.getRequest();
236     }
237     
238     /**
239      * Adds the parameter from the query string to the parameters to use
240      * when constructing the url. If a parameter present in the query already
241      * exists in the parameters, the query parameter will be skipped.
242      *
243      * @throws JspException if the format of the query string is illegal.
244      */

245     private void addQueryParameters() throws JspException JavaDoc
246     {
247         if(getQuery() != null)
248         {
249             for(final StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(getQuery(), "&"); st.hasMoreTokens(); )
250             {
251                 final String JavaDoc token = st.nextToken();
252                 final StringTokenizer JavaDoc parameter = new StringTokenizer JavaDoc(token, "=");
253                 if(parameter.countTokens() == 0 || parameter.countTokens() > 2)
254                 {
255                     throw new JspTagException JavaDoc("Illegal query parameter [" + token + "].");
256                 }
257                 final String JavaDoc name = parameter.nextToken();
258                 final String JavaDoc value = parameter.hasMoreTokens() ? parameter.nextToken() : "";
259                 if(allowMultipleArguments || !getParameterNames().containsKey(name))
260                 {
261                     if(excludedQueryStringParameters == null || excludedQueryStringParameters.indexOf(name) == -1)
262                         addParameter(name, value);
263                 }
264             }
265         }
266     }
267     
268     /**
269      * Generates the url string.
270      *
271      * @return the url.
272      */

273     public String JavaDoc generateURL()
274     {
275         if(!getParameters().isEmpty())
276         {
277             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
278             for(Iterator JavaDoc i = getParameters().iterator(); i.hasNext(); )
279             {
280                 String JavaDoc parameter = i.next().toString();
281                 sb.append(parameter + (i.hasNext() ? "&" : ""));
282             }
283             if(getBaseURL().indexOf("?") > -1)
284                 return getBaseURL() + (sb.toString().length() > 0 ? "&" + sb.toString() : "");
285             else
286                 return getBaseURL() + (sb.toString().length() > 0 ? "?" + sb.toString() : "");
287         }
288         return getBaseURL();
289     }
290
291     /**
292      * Sets the base url attribute.
293      *
294      * @param baseURL the base url to use.
295      * @throws JspException if an error occurs while evaluating base url parameter.
296      */

297     public void setBaseURL(final String JavaDoc baseURL) throws JspException JavaDoc
298     {
299         this.baseURL = evaluateString("url", "baseURL", baseURL);
300     }
301
302     /**
303      * Sets the query attribute.
304      *
305      * @param query the query to use.
306      * @throws JspException if an error occurs while evaluating query parameter.
307      */

308     public void setQuery(final String JavaDoc query) throws JspException JavaDoc
309     {
310         this.query = evaluateString("url", "query", query);
311     }
312     
313     public void setExcludedQueryStringParameters(String JavaDoc excludedQueryStringParameters) throws JspException JavaDoc
314     {
315         this.excludedQueryStringParameters = evaluateString("url", "excludedQueryStringParameters", excludedQueryStringParameters);
316     }
317
318     public void setFullBaseUrl(boolean fullBaseUrl)
319     {
320         this.fullBaseUrl = fullBaseUrl;
321     }
322     
323     public void setDisableNiceURI(boolean disableNiceURI)
324     {
325         this.disableNiceURI = disableNiceURI;
326     }
327
328     public void setAllowMultipleArguments(boolean allowMultipleArguments)
329     {
330         this.allowMultipleArguments = allowMultipleArguments;
331     }
332 }
333
Popular Tags