View Javadoc

1   package org.apache.turbine.util.uri;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import javax.servlet.http.HttpServletResponse;
23  
24  import org.apache.commons.lang.StringUtils;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  import org.apache.turbine.Turbine;
30  import org.apache.turbine.TurbineConstants;
31  
32  import org.apache.turbine.util.RunData;
33  import org.apache.turbine.util.ServerData;
34  
35  /***
36   * This is the base class for all dynamic URIs in the Turbine System.
37   *
38   * All of the classes used for generating URIs are derived from this.
39   *
40   * @author <a href="mailto:jon@clearink.com">Jon S. Stevens</a>
41   * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
42   * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
43   * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a>
44   * @version $Id: BaseURI.java 534527 2007-05-02 16:10:59Z tv $
45   */
46  
47  public abstract class BaseURI
48          implements URI,
49                     URIConstants
50  {
51      /*** Logging */
52      private static Log log = LogFactory.getLog(BaseURI.class);
53  
54      /*** ServerData Object for scheme, name, port etc. */
55      private ServerData serverData =
56              new ServerData(null, HTTP_PORT, HTTP, null, null);
57  
58      /*** Whether we want to redirect or not. */
59      private boolean redirect = false;
60  
61      /*** Servlet response interface. */
62      private HttpServletResponse response = null;
63  
64      /*** Reference Anchor (#ref) */
65      private String reference = null;
66  
67      /*
68       * ========================================================================
69       *
70       * Constructors
71       *
72       * ========================================================================
73       *
74       */
75  
76      /***
77       * Empty C'tor. Uses Turbine.getDefaultServerData().
78       *
79       */
80      public BaseURI()
81      {
82          init(Turbine.getDefaultServerData());
83          setResponse(null);
84      }
85  
86      /***
87       * Constructor with a RunData object
88       *
89       * @param runData A RunData object
90       */
91      public BaseURI(RunData runData)
92      {
93          init(runData.getServerData());
94          setResponse(runData.getResponse());
95      }
96  
97      /***
98       * Constructor, set explicit redirection
99       *
100      * @param runData A RunData object
101      * @param redirect True if redirection allowed.
102      */
103     public BaseURI(RunData runData, boolean redirect)
104     {
105         init(runData.getServerData());
106         setResponse(runData.getResponse());
107         setRedirect(redirect);
108     }
109 
110     /***
111      * Constructor with a ServerData object
112      *
113      * @param serverData A ServerData object
114      */
115     public BaseURI(ServerData serverData)
116     {
117         init(serverData);
118         setResponse(null);
119     }
120 
121     /***
122      * Constructor, set explicit redirection
123      *
124      * @param serverData A ServerData object
125      * @param redirect True if redirection allowed.
126      */
127     public BaseURI(ServerData serverData, boolean redirect)
128     {
129         init(serverData);
130         setResponse(null);
131         setRedirect(redirect);
132     }
133 
134     /*
135      * ========================================================================
136      *
137      * Init
138      *
139      * ========================================================================
140      *
141      */
142 
143     /***
144      * Init with a ServerData object
145      *
146      * @param serverData A ServerData object
147      *
148      */
149     private void init(ServerData serverData)
150     {
151         log.debug("init(" + serverData + ")");
152 
153         if(serverData != null)
154         {
155             // We must clone this, because if BaseURI is used in a pull tool,
156             // then the fields might be changed. If we don't clone, this might pull
157             // through to the ServerData object saved at firstRequest() in the
158             // Turbine object.
159             this.serverData = (ServerData) serverData.clone();
160         }
161         else
162         {
163             log.error("Passed null ServerData object!");
164         }
165         reference = null;
166     }
167 
168     /*
169      * ========================================================================
170      *
171      * Getter / Setter
172      *
173      * ========================================================================
174      *
175      */
176 
177     /***
178      * Set the redirect Flag
179      *
180      * @param redirect The new value of the redirect flag.
181      */
182     public void setRedirect(boolean redirect)
183     {
184         this.redirect = redirect;
185     }
186 
187     /***
188      * Returns the current value of the Redirect flag
189      *
190      * @return True if Redirect is allowed
191      *
192      */
193     public boolean isRedirect()
194     {
195         return redirect;
196     }
197 
198     /***
199      * Gets the script name (/servlets/Turbine).
200      *
201      * @return A String with the script name.
202      */
203     public String getScriptName()
204     {
205         return serverData.getScriptName();
206     }
207 
208     /***
209      * Sets the script name (/servlets/Turbine).
210      *
211      * @param scriptName A String with the script name.
212      */
213     public void setScriptName(String scriptName)
214     {
215         serverData.setScriptName(scriptName);
216     }
217 
218     /***
219      * Gets the context path.
220      *
221      * @return A String with the context path.
222      */
223     public String getContextPath()
224     {
225         return serverData.getContextPath();
226     }
227 
228     /***
229      * Sets the context path.
230      *
231      * @param contextPath A String with the context path
232      */
233     public void setContextPath(String contextPath)
234     {
235         serverData.setContextPath(contextPath);
236     }
237 
238     /***
239      * Gets the server name.
240      *
241      * @return A String with the server name.
242      */
243     public String getServerName()
244     {
245         return serverData.getServerName();
246     }
247 
248     /***
249      * Sets the server name.
250      *
251      * @param serverName A String with the server name.
252      */
253     public void setServerName(String serverName)
254     {
255         serverData.setServerName(serverName);
256     }
257 
258     /***
259      * Gets the server port.
260      *
261      * @return A String with the server port.
262      */
263     public int getServerPort()
264     {
265         int serverPort = serverData.getServerPort();
266 
267         if (serverPort == 0)
268         {
269             if(getServerScheme().equals(HTTPS))
270             {
271                 serverPort = HTTPS_PORT;
272             }
273             else
274             {
275                 serverPort = HTTP_PORT;
276             }
277         }
278         return serverPort;
279     }
280 
281     /***
282      * Sets the server port.
283      *
284      * @param serverPort An int with the port.
285      */
286     public void setServerPort(int serverPort)
287     {
288         serverData.setServerPort(serverPort);
289     }
290 
291     /***
292      * Method to specify that a URI should use SSL. The default port
293      * is used.
294      */
295     public void setSecure()
296     {
297         setSecure(HTTPS_PORT);
298     }
299 
300     /***
301      * Method to specify that a URI should use SSL.
302      * Whether or not it does is determined from Turbine.properties.
303      * If use.ssl in the Turbine.properties is set to false, then
304      * http is used in any case. (Default of use.ssl is true).
305      *
306      * @param port An int with the port number.
307      */
308     public void setSecure(int port)
309     {
310         boolean useSSL =
311                 Turbine.getConfiguration()
312                 .getBoolean(TurbineConstants.USE_SSL_KEY,
313                         TurbineConstants.USE_SSL_DEFAULT);
314 
315         setServerScheme(useSSL ? HTTPS : HTTP);
316         setServerPort(port);
317     }
318 
319     /***
320      * Sets the scheme (HTTP or HTTPS).
321      *
322      * @param serverScheme A String with the scheme.
323      */
324     public void setServerScheme(String serverScheme)
325     {
326         serverData.setServerScheme(StringUtils.isNotEmpty(serverScheme)
327                 ? serverScheme : "");
328     }
329 
330     /***
331      * Returns the current Server Scheme
332      *
333      * @return The current Server scheme
334      *
335      */
336     public String getServerScheme()
337     {
338         String serverScheme = serverData.getServerScheme();
339 
340         return StringUtils.isNotEmpty(serverScheme) ? serverScheme : HTTP;
341     }
342 
343     /***
344      * Sets a reference anchor (#ref).
345      *
346      * @param reference A String containing the reference.
347      */
348     public void setReference(String reference)
349     {
350         this.reference = reference;
351     }
352 
353     /***
354      * Returns the current reference anchor.
355      *
356      * @return A String containing the reference.
357      */
358     public String getReference()
359     {
360         return hasReference() ? reference : "";
361     }
362 
363     /***
364      * Does this URI contain an anchor? (#ref)
365      *
366      * @return True if this URI contains an anchor.
367      */
368     public boolean hasReference()
369     {
370         return StringUtils.isNotEmpty(reference);
371     }
372 
373     /*
374      * ========================================================================
375      *
376      * Protected / Private Methods
377      *
378      * ========================================================================
379      *
380      */
381 
382     /***
383      * Set a Response Object to use when creating the
384      * response string.
385      *
386      */
387     protected void setResponse(HttpServletResponse response)
388     {
389         this.response = response;
390     }
391 
392     /***
393      * Returns the Response Object from the Servlet Container.
394      *
395      * @return The Servlet Response object or null
396      *
397      */
398     protected HttpServletResponse getResponse()
399     {
400         return response;
401     }
402 
403     /***
404      * Append the Context Path and Script Name to the passed
405      * String Buffer.
406      *
407      * <p>
408      * This is a convenience method to be
409      * used in the Link output routines of derived classes to
410      * easily append the correct path.
411      *
412      * @param sb The StringBuffer to store context path and script name.
413      */
414     protected void getContextAndScript(StringBuffer sb)
415     {
416         String context = getContextPath();
417 
418         if(StringUtils.isNotEmpty(context))
419         {
420             if(context.charAt(0) != '/')
421             {
422                 sb.append('/');
423             }
424             sb.append (context);
425         }
426 
427         // /servlet/turbine
428         String script = getScriptName();
429 
430         if(StringUtils.isNotEmpty(script))
431         {
432             if(script.charAt(0) != '/')
433             {
434                 sb.append('/');
435             }
436             sb.append (script);
437         }
438     }
439 
440     /***
441      * Appends Scheme, Server and optionally the port to the
442      * supplied String Buffer.
443      *
444      * <p>
445      * This is a convenience method to be
446      * used in the Link output routines of derived classes to
447      * easily append the correct server scheme.
448      *
449      * @param sb The StringBuffer to store the scheme and port information.
450      */
451     protected void getSchemeAndPort(StringBuffer sb)
452     {
453         // http(s)://<servername>
454         sb.append(getServerScheme());
455         sb.append(URIConstants.URI_SCHEME_SEPARATOR);
456         sb.append(getServerName());
457 
458         // (:<port>)
459         if ((getServerScheme().equals(HTTP)
460                     && getServerPort() != HTTP_PORT)
461                 || (getServerScheme().equals(HTTPS)
462                         && getServerPort() != HTTPS_PORT))
463         {
464             sb.append(':');
465             sb.append(getServerPort());
466         }
467     }
468 
469     /***
470      * Encodes a Response Uri according to the Servlet Container.
471      * This might add a Java session identifier or do redirection.
472      * The resulting String can be used in a page or template.
473      *
474      * @param uri The Uri to encode
475      *
476      * @return An Uri encoded by the container.
477      */
478     protected String encodeResponse(String uri)
479     {
480         String res = uri;
481 
482         HttpServletResponse response = getResponse();
483 
484         if(response == null)
485         {
486             log.debug("No Response Object!");
487         }
488         else
489         {
490             try
491             {
492                 if(isRedirect())
493                 {
494                     log.debug("Should Redirect");
495                     res = response.encodeRedirectURL(uri);
496                 }
497                 else
498                 {
499                     res = response.encodeURL(uri);
500                 }
501             }
502             catch(Exception e)
503             {
504                 log.error("response" + response + ", uri: " + uri);
505                 log.error("While trying to encode the URI: ", e);
506             }
507         }
508 
509         log.debug("encodeResponse():  " + res);
510         return res;
511     }
512 }