KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > URLUtilities


1 /*
2 Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4 This library is free software; you can redistribute it and/or modify it under the terms
5 of the GNU Lesser General Public License as published by the Free Software Foundation;
6 either version 2.1 of the License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU Lesser General Public License for more details.
11 */

12
13 /*--
14
15  Copyright (C) 2001-2002 Anthony Eden.
16  All rights reserved.
17
18  Redistribution and use in source and binary forms, with or without
19  modification, are permitted provided that the following conditions
20  are met:
21
22  1. Redistributions of source code must retain the above copyright
23     notice, this list of conditions, and the following disclaimer.
24
25  2. Redistributions in binary form must reproduce the above copyright
26     notice, this list of conditions, and the disclaimer that follows
27     these conditions in the documentation and/or other materials
28     provided with the distribution.
29
30  3. The name "JPublish" must not be used to endorse or promote products
31     derived from this software without prior written permission. For
32     written permission, please contact me@anthonyeden.com.
33
34  4. Products derived from this software may not be called "JPublish", nor
35     may "JPublish" appear in their name, without prior written permission
36     from Anthony Eden (me@anthonyeden.com).
37
38  In addition, I request (but do not require) that you include in the
39  end-user documentation provided with the redistribution and/or in the
40  software itself an acknowledgement equivalent to the following:
41      "This product includes software developed by
42       Anthony Eden (http://www.anthonyeden.com/)."
43
44  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
45  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
46  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
48  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
53  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
54  POSSIBILITY OF SUCH DAMAGE.
55
56  For more information on JPublish, please see <http://www.jpublish.org/>.
57
58  */

59 package com.openedit.util;
60
61 import java.io.UnsupportedEncodingException JavaDoc;
62 import java.net.URLDecoder JavaDoc;
63 import java.net.URLEncoder JavaDoc;
64
65 import javax.servlet.http.HttpServletRequest JavaDoc;
66 import javax.servlet.http.HttpServletResponse JavaDoc;
67
68 import org.apache.commons.logging.Log;
69 import org.apache.commons.logging.LogFactory;
70
71
72 /**
73  * Utility class for building URLs.
74  *
75  * @author Anthony Eden
76  */

77 public class URLUtilities
78 {
79     /** The URL path separator. */
80     public static final String JavaDoc URL_PATH_SEPARATOR = "/";
81     private static Log log = LogFactory.getLog(URLUtilities.class);
82
83     /**
84      * Construct a new URLUtilities class which can use the given request and response objects to
85      * build URLs.
86      */

87     private HttpServletRequest JavaDoc fieldRequest;
88     private HttpServletResponse JavaDoc fieldResponse;
89
90     public URLUtilities(
91         HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
92     {
93         this.fieldRequest = request;
94         this.fieldResponse = response;
95     }
96     
97     /**
98      * The only non-buggy way to get a file name is to look at the full URL then chop off the
99      * context to make it a relative URL
100      *
101      * @return /index.html
102      */

103     public static String JavaDoc getPathWithoutContext(String JavaDoc inContext, String JavaDoc fullpath, String JavaDoc inDefault)
104     {
105         String JavaDoc nameOnly = fullpath;
106         if (fullpath.startsWith(inContext)){
107             nameOnly = fullpath.substring(inContext.length());
108         }
109
110         if (nameOnly.equals("/") || (nameOnly.length() == 0))
111         {
112             nameOnly += inDefault;
113         }
114         else if (nameOnly.indexOf('.') == -1)
115         {
116             if ( !nameOnly.endsWith("/"))
117             {
118                 nameOnly += '/';
119             }
120             nameOnly += inDefault;
121         }
122
123         return nameOnly;
124     }
125
126     /**
127      * This includes the webapp name but not the page name
128      *
129      * @return http://www.acme.com/webapp/
130      */

131     public String JavaDoc buildBasePath(String JavaDoc path)
132     {
133         StringBuffer JavaDoc ctx = fieldRequest.getRequestURL();
134         String JavaDoc servername = ctx.substring(0, ctx.indexOf("/", 7)); //just the server name
135

136         if (path.lastIndexOf('/') > -1)
137         {
138             path = path.substring(0, path.lastIndexOf('/'));
139
140             return servername + path + "/";
141         }
142         else
143         {
144             return servername + "/";
145         }
146     }
147
148     /**
149      * This is the server name only
150      *
151      * returns http://www.acme.com/
152      */

153     public String JavaDoc buildRoot()
154     {
155         StringBuffer JavaDoc ctx = fieldRequest.getRequestURL();
156         String JavaDoc servername = ctx.substring(0, ctx.indexOf("/", 7));
157
158         return servername + "/";
159     }
160
161     /**
162      * Build an HTTPS (Secure Socket Layer) method relative to the application context using the
163      * given path.
164      *
165      */

166     public String JavaDoc buildSecure(String JavaDoc path)
167     {
168         return buildSecure(path, 0);
169     }
170
171     /**
172      * Build an HTTPS (Secure Socket Layer) method relative to the application context using the
173      * given path. This version of the <code>buildSecure</code> method allows you to specify the
174      * port number. A port number of 0 will cause the port argument to be ignored.
175      *
176      * @param path The path
177      * @param port The port
178      *
179      * @return DOCME
180      */

181     public String JavaDoc buildSecure(String JavaDoc path, int port)
182     {
183         return build(path, "https", port);
184     }
185
186     /**
187      * Build an HTTP URL relative to the application context using the given path.
188      *
189      * @param path The path
190      *
191      * @return DOCME
192      */

193     public String JavaDoc buildStandard(String JavaDoc path)
194     {
195         return buildStandard(path, 0);
196     }
197
198     /**
199      * Build an HTTP URL relative to the application context using the given path. This version
200      * of the <code>buildStandard</code> method allows you to specify the port number. A port
201      * number of 0 will cause the port argument to be ignored.
202      *
203      * @param path The path
204      * @param port The port
205      *
206      * @return DOCME
207      */

208     public String JavaDoc buildStandard(String JavaDoc path, int port)
209     {
210         return build(path, "http", port);
211     }
212
213     /**
214      * Percent-encode the given String. This method delegates to the URLEncoder.encode() method.
215      *
216      * @param s The String to encode
217      *
218      * @return The encoded String
219      *
220      * @see java.net.URLEncoder
221      */

222     public String JavaDoc encode(String JavaDoc s)
223     {
224         if (s == null)
225         {
226             return null;
227         }
228
229         return URLEncoder.encode(s);
230     }
231
232     /**
233      * Build an HTTP URL relative to the application context using the given path. This is a path
234      * such as /path/myfile.html but is encoded
235      * If you want to unencoded path use $content.path or getOriginalPath()
236      *
237      * @return /webapp/path/myfile.html
238      */

239     public String JavaDoc getOriginalUrl()
240     {
241         String JavaDoc path = fieldRequest.getRequestURI();
242         String JavaDoc home = relativeHomePrefix();
243         path = path.substring(home.length());
244         return encode( path );
245     }
246     /**
247      * This is the path that the browser is on.
248      * /sub/index page.html
249      * @return
250      */

251     public String JavaDoc getOriginalPath()
252     {
253         String JavaDoc requestedPath = getRequest().getRequestURI();
254         try
255         {
256             requestedPath = URLDecoder.decode(requestedPath, "UTF-8");
257         }
258         catch (UnsupportedEncodingException JavaDoc ex)
259         {
260             log.error( ex );
261         }
262     
263         String JavaDoc contextPath = getRequest().getContextPath();
264         if ( requestedPath.startsWith( contextPath ) )
265         {
266             requestedPath = requestedPath.substring(contextPath.length());
267         }
268         return requestedPath;
269     }
270
271
272     /**
273      * Build an HTTP URL relative to the application context using the given path. This is a path
274      * such as http://servername/webapp/path/myfile.html
275      *
276      * @return /webapp/path/myfile.html
277      */

278     public String JavaDoc requestPath()
279     {
280         StringBuffer JavaDoc ctx = fieldRequest.getRequestURL();
281         String JavaDoc requestPath = ctx.substring(ctx.indexOf("/", 7)); //just the path
282

283         return requestPath;
284     }
285     /**
286      * Is the full path with arguments included
287      * /webappname/sub/index.html?test=1234
288      */

289     
290     public String JavaDoc requestPathWithArguments()
291     {
292         String JavaDoc path = fieldRequest.getRequestURI();
293         if ( fieldRequest.getQueryString() != null && fieldRequest.getQueryString().length() > 0)
294         {
295             path = path + "?" + fieldRequest.getQueryString();
296         }
297         return path;
298     }
299     /**
300      * Is the full path with arguments included
301      * /sub/index.html?test=1234
302      */

303     
304     public String JavaDoc requestPathWithArgumentsNoContext()
305     {
306         String JavaDoc path = fieldRequest.getRequestURI();
307         if ( fieldRequest.getQueryString() != null && fieldRequest.getQueryString().length() > 0)
308         {
309             path = path + "?" + fieldRequest.getQueryString();
310         }
311         String JavaDoc home = relativeHomePrefix();
312         path = path.substring(home.length());
313         return path;
314     }
315     /**
316      * Report the site name, e.g. http://www.openeditpro.com
317      *
318      * @return The site's root URL
319      */

320     public String JavaDoc siteRoot()
321     {
322         StringBuffer JavaDoc ctx = fieldRequest.getRequestURL();
323         String JavaDoc siteRoot = ctx.substring( 0, ctx.indexOf("/", 8) ); //8 comes from https://
324
return siteRoot;
325     }
326
327     /**
328      * A simple hack to escape XML, stolen from Jakarta commons XmlUtils
329      *
330      * @param inStr
331      *
332      * @return String
333      */

334     public static String JavaDoc xmlEscape(String JavaDoc inStr)
335     {
336         if ( inStr == null )
337         {
338             return null;
339         }
340         //can you just blindly replace any & since it might be part of &apos;?
341
inStr = inStr.replaceAll("&", "&amp;");
342
343         inStr = inStr.replaceAll("<", "&lt;");
344         inStr = inStr.replaceAll(">", "&gt;");
345         inStr = inStr.replaceAll("\"", "&quot;");
346
347         //IE seems to espace the & for some reason inStr = inStr.replaceAll("'", "&apos;");
348
return inStr;
349     }
350     
351     public static String JavaDoc xmlUnescape(String JavaDoc inStr)
352     {
353         if ( inStr == null )
354         {
355             return null;
356         }
357         //can you just blindly replace any & since it might be part of &apos;?
358
inStr = inStr.replaceAll("&amp;","&");
359
360         inStr = inStr.replaceAll("&lt;", "<");
361         inStr = inStr.replaceAll("&gt;", ">");
362         inStr = inStr.replaceAll("&quot;", "\"");
363
364         //IE seems to espace the & for some reason inStr = inStr.replaceAll("'", "&apos;");
365
return inStr;
366     }
367
368     /**
369      * If I am located in /webapp/demo/test.html my prefix would be /demo/ to get back to the base
370      * /webapp level
371      *
372      * The rule is you can tack on $home + "/somepage.html" without getting //somepage.html
373      *
374      *
375      * @return Object
376      */

377     public String JavaDoc relativeHomePrefix()
378     {
379         String JavaDoc rootdir = fieldRequest.getContextPath();
380
381         if ((rootdir != null) && (rootdir.length() > 0))
382         {
383             if ( rootdir.endsWith("/"))
384             {
385                 rootdir = rootdir.substring(0,rootdir.length() - 1);
386             }
387             return rootdir;
388         }
389         else
390         {
391             return "";
392         }
393
394     }
395
396     /**
397      * Build a URL using the given path, protocol and port. The path will be relative to the
398      * current context.
399      *
400      * @param path The path
401      * @param protocol (i.e. http or https)
402      * @param port The port (0 to ignore the port argument)
403      *
404      * @return The URL as a String
405      */

406     protected String JavaDoc build(String JavaDoc path, String JavaDoc protocol, int port)
407     {
408         String JavaDoc serverName = fieldRequest.getServerName();
409         String JavaDoc contextPath = fieldRequest.getContextPath();
410
411         log.debug("Server name: " + serverName);
412         log.debug("Context path: " + contextPath);
413
414         if (!contextPath.endsWith(URL_PATH_SEPARATOR))
415         {
416             contextPath = contextPath + URL_PATH_SEPARATOR;
417         }
418
419         if (path.startsWith(URL_PATH_SEPARATOR))
420         {
421             path = path.substring(1);
422         }
423
424         String JavaDoc requestPath = contextPath + path;
425         log.debug("Request path: " + requestPath);
426
427         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
428         buffer.append(protocol);
429         buffer.append("://");
430         buffer.append(serverName);
431
432         int realPort = fieldRequest.getServerPort();
433
434         if (port > 0)
435         {
436             realPort = port;
437         }
438
439         if (
440             (realPort > 0) &&
441                 !((protocol.equals("http") && (realPort == 80)) ||
442                 (protocol.equals("https") && (realPort == 443))))
443         {
444             buffer.append(":");
445             buffer.append(realPort);
446         }
447
448         if (!requestPath.startsWith(URL_PATH_SEPARATOR))
449         {
450             buffer.append(URL_PATH_SEPARATOR);
451         }
452
453         buffer.append(requestPath);
454
455         log.debug("URL: '" + buffer + "'");
456
457         return buffer.toString();
458     }
459     public PathUtilities getPathUtilities()
460     {
461         return new PathUtilities();
462     }
463
464     public HttpServletResponse JavaDoc getResponse()
465     {
466         return fieldResponse;
467     }
468
469     public void setResponse(HttpServletResponse JavaDoc inResponse)
470     {
471         fieldResponse = inResponse;
472     }
473
474     public HttpServletRequest JavaDoc getRequest()
475     {
476         return fieldRequest;
477     }
478
479     public void setRequest(HttpServletRequest JavaDoc inRequest)
480     {
481         fieldRequest = inRequest;
482     }
483 }
484
Popular Tags