KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > www > WebUtils


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: WebUtils.java,v 1.18 2007/02/20 04:12:33 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.www;
23
24 import java.io.BufferedInputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.UnsupportedEncodingException JavaDoc;
29 import java.net.MalformedURLException JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.net.URLEncoder JavaDoc;
32 import java.util.Enumeration JavaDoc;
33 import java.util.Properties JavaDoc;
34 import java.util.logging.Logger JavaDoc;
35
36 import javax.servlet.ServletConfig JavaDoc;
37 import javax.servlet.ServletContext JavaDoc;
38 import javax.servlet.ServletException JavaDoc;
39 import javax.servlet.ServletOutputStream JavaDoc;
40 import javax.servlet.http.HttpServletRequest JavaDoc;
41 import javax.servlet.http.HttpServletResponse JavaDoc;
42
43 import org.opensubsystems.core.util.Config;
44 import org.opensubsystems.core.util.Log;
45 import org.opensubsystems.core.util.MimeTypeConstants;
46
47 /**
48  * Collection of useful methods for Web environment.
49  *
50  * @version $Id: WebUtils.java,v 1.18 2007/02/20 04:12:33 bastafidli Exp $
51  * @author Miro Halas
52  * @code.reviewer Miro Halas
53  * @code.reviewed 1.13 2006/05/01 23:41:09 jlegeny
54  */

55 public final class WebUtils
56 {
57    // Configuration settings ///////////////////////////////////////////////////
58

59    /**
60     * Name of the property specifying what port the embedded web server should
61     * start on.
62     * @see #s_iConfiguredWebPort
63     */

64    public static final String JavaDoc WEBSERVER_PORT = "oss.webserver.port";
65
66    /**
67     * Name of the property specifying what port sthe embedded web server should
68     * accepts SSL requests.
69     * @see #s_iConfiguredWebPortSecure
70     */

71    public static final String JavaDoc WEBSERVER_PORT_SECURE = "oss.webserver.port.secure";
72
73    /**
74     * Name of the property for size of the buffer used to serve files.
75     * @see #s_iWebFileBufferSize
76     * @see #WEBFILE_BUFFER_DEFAULT_SIZE
77     */

78    public static final String JavaDoc WEBUTILS_WEBFILE_BUFFER_SIZE = "oss.webserver.servebuffer.size";
79
80    // Constants ////////////////////////////////////////////////////////////////
81

82    /**
83     * Default value for the WEBUTILS_WEBFILE_BUFFER_SIZE.
84     * @see #s_iWebFileBufferSize
85     * @see #WEBUTILS_WEBFILE_BUFFER_SIZE
86     */

87    public static final int WEBFILE_BUFFER_DEFAULT_SIZE = 40960;
88
89    // Cached values ////////////////////////////////////////////////////////////
90

91    /**
92     * Logger for this class
93     */

94    private static Logger JavaDoc s_logger = Log.getInstance(WebUtils.class);
95
96    /**
97     * Size of the buffer used to send files.
98     * @see #WEBUTILS_WEBFILE_BUFFER_SIZE
99     * @see #WEBFILE_BUFFER_DEFAULT_SIZE
100     */

101    protected static int s_iWebFileBufferSize;
102
103    /**
104     * HTTP server port the web application was originally configred to run on.
105     * This port may differ from the actual port in case the server was not
106     * able to start on the configured port and it started on a different one
107     * and it adjusted the configured port.
108     */

109    protected static int s_iConfiguredWebPort;
110
111    /**
112     * HTTP server port the web application is running on.
113     */

114    protected static int s_iWebPort;
115
116    /**
117     * HTTP server port the web application was originally configred to accept
118     * SSL requests. This port may differ from the actual port in case the server
119     * was not able to start on the configured port and it started on a different
120     * 1one and it adjusted the configured port.
121     */

122    protected static int s_iConfiguredWebPortSecure;
123
124    /**
125     * HTTPS server port the web application is running on (SSL port).
126     */

127    protected static int s_iWebPortSecure;
128
129    // Constructors /////////////////////////////////////////////////////////////
130

131    /**
132     * Static initializer
133     */

134    static
135    {
136       Properties JavaDoc prpSettings;
137       
138       prpSettings = Config.getInstance().getPropertiesSafely();
139
140       // Load default size of buffer to serve files
141
s_iWebFileBufferSize = Config.getIntPropertyInRange(
142                                        prpSettings,
143                                        WEBUTILS_WEBFILE_BUFFER_SIZE,
144                                        WEBFILE_BUFFER_DEFAULT_SIZE,
145                                        "Size of a buffer to serve files ",
146                                        // Use some reasonable lower limit
147
4096,
148                                        // This should be really limited
149
// by size of available memory
150
100000000);
151       
152       // Load the port where the webserver should be accepting requests in non
153
// SSL mode
154
s_iConfiguredWebPortSecure = Config.getIntPropertyInRange(
155                                              prpSettings,
156                                              WEBSERVER_PORT_SECURE,
157                                              WebCommonConstants.HTTP_SECURE_PORT_DEFAULT,
158                                              "Web server port",
159                                              WebCommonConstants.HTTP_PORT_MIN,
160                                              WebCommonConstants.HTTP_PORT_MAX);
161       s_iWebPortSecure = s_iConfiguredWebPortSecure;
162       
163       
164       // Load the port where the webserver should be accepting requests in non
165
// SSL mode
166
s_iConfiguredWebPort = Config.getIntPropertyInRange(
167                                        prpSettings,
168                                        WEBSERVER_PORT,
169                                        WebCommonConstants.HTTP_PORT_DEFAULT,
170                                        "Web server port",
171                                        WebCommonConstants.HTTP_PORT_MIN,
172                                       WebCommonConstants.HTTP_PORT_MAX);
173       s_iWebPort = s_iConfiguredWebPort;
174    }
175    
176    /**
177     * Private constructor since this class cannot be instantiated
178     */

179    private WebUtils(
180    )
181    {
182       // Do nothing
183
}
184    
185    // Public methods ///////////////////////////////////////////////////////////
186

187    /**
188     * Get value of port, which was configured to accepts non SSL requests on.
189     *
190     * @return int - port configured to accepts non SSL requests
191     */

192    public static int getConfiguredPort(
193    )
194    {
195       return s_iConfiguredWebPort;
196    }
197    
198    /**
199     * Get value of port, which actually accepts non SSL requests on.
200     *
201     * @return int - port to accepts non SSL requests
202     */

203    public static int getActualPort(
204    )
205    {
206       return s_iWebPort;
207    }
208    
209    /**
210     * Get value of port, which was configured to accepts SSL requests on.
211     *
212     * @return int - port to accepts SSL requests
213     */

214    public static int getConfiguredSSLPort(
215    )
216    {
217       return s_iConfiguredWebPortSecure;
218    }
219    
220    /**
221     * Get value of port, which was configured to accepts SSL requests on.
222     *
223     * @return int - port to accepts SSL requests
224     */

225    public static int getActualSSLPort(
226    )
227    {
228       return s_iWebPortSecure;
229    }
230    
231    /**
232     * Serve files to the Internet.
233     *
234     * @param hsrpResponse - the servlet response.
235     * @param strRealPath - real path to the file to server
236     * @throws IOException - an error has occured while accessing the file or writing response
237     */

238    public static void serveFile(
239       HttpServletResponse JavaDoc hsrpResponse,
240       String JavaDoc strRealPath
241    ) throws IOException JavaDoc
242    {
243       // TODO: Improve: Figure out, how we don't have to serve the file,
244
// but the webserver will!!! (cos.jar has a method for it, but the license
245
// is to prohibitive to use it. Maybe Jetty has one too)
246

247       ServletOutputStream JavaDoc sosOut = hsrpResponse.getOutputStream();
248       byte[] arBuffer = new byte[s_iWebFileBufferSize];
249       File JavaDoc flImage = new File JavaDoc(strRealPath);
250       FileInputStream JavaDoc fisReader = new FileInputStream JavaDoc(flImage);
251
252       // get extension of the file
253
String JavaDoc strExt = strRealPath.substring(strRealPath.lastIndexOf(".") + 1,
254                                             strRealPath.length());
255       // set content type for particular extension
256
hsrpResponse.setContentType(MimeTypeConstants.getMimeType(strExt));
257       hsrpResponse.setBufferSize(WEBFILE_BUFFER_DEFAULT_SIZE);
258       hsrpResponse.setContentLength((int)flImage.length());
259
260       // TODO: Performance: BufferedInputStream allocate additional internal
261
// buffer so we have two buffers for each file of given size, evaluate
262
// if this is faster than non buffered read and if it is not, then get
263
// rid of it. But the preference is to get rif of this method all together,
264
BufferedInputStream JavaDoc bisReader = new BufferedInputStream JavaDoc(fisReader,
265                                                               s_iWebFileBufferSize);
266       int iRead;
267
268       try
269       {
270          while (true)
271          {
272             iRead = bisReader.read(arBuffer);
273             if (iRead != -1)
274             {
275                sosOut.write(arBuffer, 0, iRead);
276             }
277             else
278             {
279                break;
280             }
281          }
282       }
283       finally
284       {
285          try
286          {
287             fisReader.close();
288          }
289          finally
290          {
291             sosOut.close();
292          }
293       }
294    }
295    
296    /**
297     * Reconstruct full URL from HTTP request with protocol, full path and query
298     * strings.
299     *
300     * @param hsrqRequest - the servlet request.
301     * @return String - full URL
302     */

303    public static String JavaDoc getFullRequestURL(
304       HttpServletRequest JavaDoc hsrqRequest
305    )
306    {
307       String JavaDoc strQueryString;
308       StringBuffer JavaDoc sbURL;
309
310       strQueryString = hsrqRequest.getQueryString();
311       if (strQueryString == null)
312       {
313          sbURL = new StringBuffer JavaDoc();
314       }
315       else
316       {
317          sbURL = new StringBuffer JavaDoc("?");
318          sbURL.append(strQueryString);
319       }
320
321       return hsrqRequest.getRequestURL().append(sbURL).toString();
322    }
323
324    /**
325     * Reconstruct full URL from HTTP request with protocol, full path but
326     * without query strings.
327     *
328     * @param hsrqRequest - the servlet request.
329     * @return String - full URL
330     */

331    public static String JavaDoc getRequestURLWithoutQuery(
332       HttpServletRequest JavaDoc hsrqRequest
333    )
334    {
335       return hsrqRequest.getRequestURL().toString();
336    }
337
338    /**
339     * Get full path from HTTP request consisting of the servlet path and the
340     * path info
341     *
342     * @param hsrqRequest - the servlet request
343     * @return - full URL
344     */

345    public static String JavaDoc getFullRequestPath(
346       HttpServletRequest JavaDoc hsrqRequest
347    )
348    {
349       StringBuffer JavaDoc sbPath;
350       String JavaDoc strPath;
351       String JavaDoc strExtraPath;
352
353       strPath = hsrqRequest.getServletPath();
354       if (strPath == null)
355       {
356          strPath = "";
357       }
358       strExtraPath = hsrqRequest.getPathInfo();
359       if (strExtraPath != null)
360       {
361          sbPath = new StringBuffer JavaDoc(strPath);
362          sbPath.append(strExtraPath);
363          strPath = sbPath.toString();
364       }
365       
366       return strPath;
367    }
368    
369    /**
370     * Adjust non secure server port number the web application is currently running on.
371     *
372     * @param hsrqRequest - the servlet request.
373     */

374    public static void adjust(
375       HttpServletRequest JavaDoc hsrqRequest
376    )
377    {
378       if (hsrqRequest.isSecure())
379       {
380          s_iWebPortSecure = hsrqRequest.getServerPort();
381       }
382       else
383       {
384          s_iWebPort = hsrqRequest.getServerPort();
385       }
386    }
387    
388    /**
389     * Switch URL to HTTP or HTTPS and also particular ports.
390     *
391     * @param hsrqRequest - the servlet request
392     * @param strURL - relative URL
393     * @param bIsSecure - flag signaling if url should be switched to secure
394     * - true = switch to secure (use HTTPS)
395     * - false = switch to unsecure (use HTTP)
396     * @return String - absolute URL
397     */

398    public static String JavaDoc toggleSecure(
399       HttpServletRequest JavaDoc hsrqRequest,
400       String JavaDoc strURL,
401       boolean bIsSecure
402    )
403    {
404       URL JavaDoc uURL = null;
405       URL JavaDoc uSwitchedURL = null;
406       
407       String JavaDoc strUrlReturn = strURL;
408       
409       // find out if strURL sent as parameter is absolute or relative
410
try
411       {
412          // try to construct URL from source parameter
413
uURL = new URL JavaDoc(strURL);
414          // at this point we should have switched URL object so retrieve
415
// and return string of absolute URL
416
strUrlReturn = uURL.toExternalForm();
417
418          // if there is used currently secure mode (used HTTPS) and application secure
419
// is TRUE, don't make changes
420
// if there is used currently secure mode (used HTTPS) and application secure
421
// is FALSE, change url to not secure (HTTP)
422
if (bIsSecure)
423          {
424             // -------------------------------------------------------
425
// change http -> https and not secure port -> secure port
426
// -------------------------------------------------------
427
if (uURL.getProtocol().equals(WebCommonConstants.PROTOCOL_HTTP))
428             {
429                // change protocol and port number to secure one
430
uSwitchedURL = new URL JavaDoc(WebCommonConstants.PROTOCOL_HTTPS,
431                                       uURL.getHost(),
432                                       s_iWebPortSecure,
433                                       uURL.getFile());
434                // at this point we should have switched URL object so retrieve
435
// and return string of absolute URL
436
strUrlReturn = uSwitchedURL.toExternalForm();
437             }
438          }
439          else
440          {
441             // -------------------------------------------------------
442
// change https -> http and secure port -> not secure port
443
// -------------------------------------------------------
444
if (uURL.getProtocol().equals(WebCommonConstants.PROTOCOL_HTTPS))
445             {
446                // change secure protocol and port number to not secure one
447
uSwitchedURL = new URL JavaDoc(WebCommonConstants.PROTOCOL_HTTP,
448                                       uURL.getHost(),
449                                       s_iWebPort,
450                                       uURL.getFile());
451                // at this point we should have switched URL object so retrieve
452
// and return string of absolute URL
453
strUrlReturn = uSwitchedURL.toExternalForm();
454             }
455          }
456       }
457       catch (MalformedURLException JavaDoc excMURLE)
458       {
459          // there was problem with constructing URL so log this and do nothing
460
s_logger.warning("Error occured while constructing URL.");
461       }
462       
463       return strUrlReturn;
464    }
465
466    /**
467     * Create debug string containing all parameter names and their values from
468     * the request.
469     *
470     * @param hsrqRequest - the servlet request.
471     * @return String - debug string containing all parameter names and their
472     * values from the request
473     */

474    public static String JavaDoc debug(
475       HttpServletRequest JavaDoc hsrqRequest
476    )
477    {
478       Enumeration JavaDoc enumNames;
479       String JavaDoc strParam;
480       String JavaDoc[] arParams;
481       int iIndex;
482       StringBuffer JavaDoc sbfReturn = new StringBuffer JavaDoc();
483
484       sbfReturn.append("HttpServletRequest=[");
485       sbfReturn.append("FullURL=");
486       sbfReturn.append(getFullRequestURL(hsrqRequest));
487       sbfReturn.append(";");
488       for (enumNames = hsrqRequest.getParameterNames();
489            enumNames.hasMoreElements();)
490       {
491          strParam = (String JavaDoc)enumNames.nextElement();
492          arParams = hsrqRequest.getParameterValues(strParam);
493          sbfReturn.append("Param=");
494          sbfReturn.append(strParam);
495          sbfReturn.append(" values=");
496          for (iIndex = 0; iIndex < arParams.length; iIndex++)
497          {
498             sbfReturn.append(arParams[iIndex]);
499             if (iIndex < (arParams.length - 1))
500             {
501                sbfReturn.append(";");
502             }
503          }
504          if (enumNames.hasMoreElements())
505          {
506             sbfReturn.append(";");
507          }
508       }
509       sbfReturn.append("]");
510
511       return sbfReturn.toString();
512    }
513    
514    /**
515     * Create debug string containing all parameter names and their values from
516     * the config.
517     *
518     * @param scConfig - config to print out
519     * @return String - debug string containing all parameter names and their
520     * values from the config
521     */

522    public static String JavaDoc debug(
523       ServletConfig JavaDoc scConfig
524    )
525    {
526       Enumeration JavaDoc enumNames;
527       String JavaDoc strParam;
528       StringBuffer JavaDoc sbfReturn = new StringBuffer JavaDoc();
529
530       sbfReturn.append("ServletConfig=[ServletName=");
531       sbfReturn.append(scConfig.getServletName());
532       sbfReturn.append(";");
533       for (enumNames = scConfig.getInitParameterNames();
534            enumNames.hasMoreElements();)
535       {
536          strParam = (String JavaDoc)enumNames.nextElement();
537          sbfReturn.append("Param=");
538          sbfReturn.append(strParam);
539          sbfReturn.append(" value=");
540          sbfReturn.append(scConfig.getInitParameter(strParam));
541          if (enumNames.hasMoreElements())
542          {
543             sbfReturn.append(";");
544          }
545       }
546       sbfReturn.append("]");
547
548       return sbfReturn.toString();
549    }
550
551    /**
552     * Create debug string containing all parameter names and their values from
553     * the context.
554     *
555     * @param scContext - context to print out
556     * @return String - debug string containing all parameter names and their
557     * values from the context
558     */

559    public static String JavaDoc debug(
560       ServletContext JavaDoc scContext
561    )
562    {
563       Enumeration JavaDoc enumNames;
564       String JavaDoc strParam;
565       StringBuffer JavaDoc sbfReturn = new StringBuffer JavaDoc();
566
567       sbfReturn.append("ServletContext=[ServletContextName=");
568       sbfReturn.append(scContext.getServletContextName());
569       sbfReturn.append(";");
570       for (enumNames = scContext.getInitParameterNames();
571            enumNames.hasMoreElements();)
572       {
573          strParam = (String JavaDoc)enumNames.nextElement();
574          sbfReturn.append("Param=");
575          sbfReturn.append(strParam);
576          sbfReturn.append(" value=");
577          sbfReturn.append(scContext.getInitParameter(strParam));
578          if (enumNames.hasMoreElements())
579          {
580             sbfReturn.append(";");
581          }
582       }
583       sbfReturn.append("]");
584
585       return sbfReturn.toString();
586    }
587
588    /**
589     * Forward request back to the same page where it came from.
590     *
591     * @param hsrqRequest - the servlet request.
592     * @param hsrpResponse - the servlet response.
593     * @throws IOException - an error while writing response
594     * @throws ServletException - an error while serving the request
595     */

596    public static void forwardToOrigin(
597       HttpServletRequest JavaDoc hsrqRequest,
598       HttpServletResponse JavaDoc hsrpResponse
599    ) throws IOException JavaDoc,
600             ServletException JavaDoc
601    {
602       hsrpResponse.sendRedirect(getFullRequestURL(hsrqRequest));
603    }
604
605    /**
606     * Test if the real path is path for the main index page. It either doesn't
607     * contain any path e.g. http://www.bastafidli.com or just a root directory
608     * http://www.bastafidli.com/.
609     *
610     * @param hsrqRequest - the servlet request.
611     * @return boolean - true if the page is main index page
612     */

613    public static boolean isMainIndexPage(
614       HttpServletRequest JavaDoc hsrqRequest
615    )
616    {
617       String JavaDoc strPath;
618       int iFirstIndex = -1;
619       int iLastIndex = -1;
620
621       strPath = getFullRequestPath(hsrqRequest);
622
623       // If there are two folder separators, the request is for the subindex
624
// page, otherwise it is for the main index page
625
iFirstIndex = strPath.indexOf(WebCommonConstants.URL_SEPARATOR_CHAR);
626       if (iFirstIndex == 0)
627       {
628          iLastIndex = strPath.lastIndexOf(WebCommonConstants.URL_SEPARATOR_CHAR);
629       }
630
631       // If there is no / both values will be -1
632
// there is only one or none /
633
return (iFirstIndex == iLastIndex)
634                 // there is no /
635
&& ((iFirstIndex == -1)
636                 // there is one / and it is the last
637
|| (strPath.endsWith(WebCommonConstants.URL_SEPARATOR)
638                 // or it ends with index.html
639
|| strPath.endsWith(WebCommonConstants.DEFAULT_DIRECTORY_WEB_PAGE)));
640    }
641
642    /**
643     * Test if the requested path is path for the index page. It either points
644     * just to a directory http://www.bastafidli.com/directory/ or it ends with
645     * index.html e.g. http://www.bastafidli.com/directory.html.
646     *
647     * @param hsrqRequest - the servlet request.
648     * @return boolean - true if the page is index page for the folder false otherwise
649     */

650    public static boolean isIndexPage(
651       HttpServletRequest JavaDoc hsrqRequest
652    )
653    {
654       String JavaDoc strPath;
655
656       strPath = getFullRequestPath(hsrqRequest);
657
658       return strPath.endsWith(WebCommonConstants.URL_SEPARATOR)
659              || strPath.endsWith(WebCommonConstants.DEFAULT_DIRECTORY_WEB_PAGE)
660              // Or it doesnt' end with '/' but there is no extension
661
|| (!strPath.endsWith(WebCommonConstants.URL_SEPARATOR)
662                 && (strPath.indexOf(WebCommonConstants.EXTENSION_SEPARATOR) == -1));
663    }
664
665    /**
666     * Test if the requested path is path for the regular (.html) page.
667     *
668     * @param hsrqRequest - the servlet request.
669     * @return boolean - true if the page is regular web page (ends with .html)
670     */

671    public static boolean isStaticWebPage(
672       HttpServletRequest JavaDoc hsrqRequest
673    )
674    {
675       String JavaDoc strPath;
676
677       strPath = getFullRequestPath(hsrqRequest);
678
679       return strPath.endsWith(WebCommonConstants.WEB_PAGE_EXTENSION);
680    }
681    
682    /**
683     * Read property from from different configuration locations.
684     * 1st try read from external configuration file
685     * 2nd try to read from servlet config (init-param within web.xml)
686     * 3rd try to read from servlet context (context-param within web.xml)
687     *
688     * @param scConfig - servlet config to search (application configuration file
689     * is known by other mean)
690     * @param strPropertyName - name of the property to read
691     * @param strDefaultValue - default value of the property returned in case
692     * the value is not found, null is allows
693     * @param bEmptyAllowed - is empty string valid value of the property
694     * @return String - value of the property
695     */

696    public static String JavaDoc readProperty(
697       ServletConfig JavaDoc scConfig,
698       String JavaDoc strPropertyName,
699       String JavaDoc strDefaultValue,
700       boolean bEmptyAllowed
701    )
702    {
703       String JavaDoc strPropertyValue;
704       Properties JavaDoc prpSettings;
705
706       // try to read property from external configuration file
707
prpSettings = Config.getInstance().getPropertiesSafely();
708       strPropertyValue = prpSettings.getProperty(strPropertyName, null);
709       
710       if ((strPropertyValue == null)
711          || ((strPropertyValue.length() == 0) && (!bEmptyAllowed)))
712       {
713          // didn't found, try to read property from init-param within web.xml
714
strPropertyValue = scConfig.getInitParameter(strPropertyName);
715
716          if ((strPropertyValue == null)
717              || ((strPropertyValue.length() == 0) && (!bEmptyAllowed)))
718          {
719             // didn't found, try to read property from context-param within web.xml
720
strPropertyValue = scConfig.getServletContext().getInitParameter(
721                                                                strPropertyName);
722             if ((strPropertyValue == null)
723                || ((strPropertyValue.length() == 0) && (!bEmptyAllowed)))
724             {
725                // still didn't found, set up default value
726
strPropertyValue = strDefaultValue;
727             }
728          }
729       }
730
731       return strPropertyValue;
732    }
733
734    /**
735     * Read property from from different configuration locations.
736     * 1st try read from external configuration file
737     * 2nd try to read from servlet context (context-param within web.xml)
738     *
739     * @param scContext - servlet context to search (application configuration file
740     * is known by other mean)
741     * @param strPropertyName - name of the property to read
742     * @param strDefaultValue - default value of the property returned in case
743     * the value is not found, null is allows
744     * @param bEmptyAllowed - is empty string valid value of the property
745     * @return String - value of the property
746     */

747    public static String JavaDoc readProperty(
748       ServletContext JavaDoc scContext,
749       String JavaDoc strPropertyName,
750       String JavaDoc strDefaultValue,
751       boolean bEmptyAllowed
752    )
753    {
754       String JavaDoc strPropertyValue;
755       Properties JavaDoc prpSettings;
756       
757       // try to read property from external configuration file
758
prpSettings = Config.getInstance().getPropertiesSafely();
759       strPropertyValue = prpSettings.getProperty(strPropertyName, null);
760
761       if ((strPropertyValue == null)
762          || ((strPropertyValue.length() == 0) && (!bEmptyAllowed)))
763       {
764          // didn't found, try to read property from context-param within web.xml
765
strPropertyValue = scContext.getInitParameter(strPropertyName);
766          if ((strPropertyValue == null)
767             || ((strPropertyValue.length() == 0) && (!bEmptyAllowed)))
768          {
769             // still didn't found, set up default value
770
strPropertyValue = strDefaultValue;
771          }
772       }
773
774       return strPropertyValue;
775    }
776    
777    /**
778     * Encode URL string by method URLEncoder.encode() - after this encoding
779     * all spaces will be encoded as + character. But there is also problem
780     * with decoding this + character - it is decoded again as character + .
781     * It means after 1st encode process we will replace all occurences of + by
782     * code for space.
783     * E.g. input string = "abc def"
784     * after encoded = "abc+def"
785     * after replace = "abc%20def"
786     * @param strInput - input string that has to be encoded
787     * @return - encoded string
788     * @throws UnsupportedEncodingException - error while encode process
789     */

790    public static String JavaDoc encode(
791       String JavaDoc strInput
792    ) throws UnsupportedEncodingException JavaDoc
793    {
794       String JavaDoc strEncoded = URLEncoder.encode(strInput, "UTF-8");
795       return strEncoded.replaceAll("\\+", "%20");
796    }
797 }
798
Popular Tags