001    /*
002     * Copyright © 2008, 2012 Pedro Agulló Soliveres.
003     * 
004     * This file is part of DirectJNgine.
005     *
006     * DirectJNgine is free software: you can redistribute it and/or modify
007     * it under the terms of the GNU Lesser General Public License as published by
008     * the Free Software Foundation, either version 3 of the License.
009     *
010     * Commercial use is permitted to the extent that the code/component(s)
011     * do NOT become part of another Open Source or Commercially developed
012     * licensed development library or toolkit without explicit permission.
013     *
014     * DirectJNgine is distributed in the hope that it will be useful,
015     * but WITHOUT ANY WARRANTY; without even the implied warranty of
016     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
017     * GNU Lesser General Public License for more details.
018     *
019     * You should have received a copy of the GNU Lesser General Public License
020     * along with DirectJNgine.  If not, see <http://www.gnu.org/licenses/>.
021     * 
022     * This software uses the ExtJs library (http://extjs.com), which is 
023     * distributed under the GPL v3 license (see http://extjs.com/license).
024     */
025    
026    package com.softwarementors.extjs.djn.servlet;
027    
028    import java.util.ArrayList;
029    import java.util.Enumeration;
030    import java.util.List;
031    
032    import javax.servlet.ServletConfig;
033    import javax.servlet.http.HttpServletRequest;
034    
035    import org.apache.log4j.Logger;
036    
037    import com.softwarementors.extjs.djn.StringBuilderUtils;
038    import com.softwarementors.extjs.djn.StringUtils;
039    
040    import edu.umd.cs.findbugs.annotations.CheckForNull;
041    import edu.umd.cs.findbugs.annotations.NonNull;
042    
043    public final class ServletUtils {
044      @NonNull
045      private static final Logger logger = Logger.getLogger( ServletUtils.class);
046      
047      public ServletUtils() {
048        // Avoid instantiation
049      }
050    
051      public static String getRequiredParameter( ServletConfig conf, String parameterName ) {
052        assert conf != null;
053        assert !StringUtils.isEmpty(parameterName);
054        
055        String result = conf.getInitParameter( parameterName );
056        assert !StringUtils.isEmpty(result);
057        return result;
058      }
059      
060      @CheckForNull public static String getParameter( ServletConfig conf, String parameterName, String valueIfNotSpecified ) {
061        assert conf != null;
062        assert !StringUtils.isEmpty(parameterName);
063        
064        String result = conf.getInitParameter( parameterName );
065        if( result != null ) {
066          result = result.trim();
067        }
068        if( StringUtils.isEmpty(result) ) {
069          return valueIfNotSpecified;
070        }
071        return result;
072      }
073    
074      public static boolean getBooleanParameter( ServletConfig conf, String parameterName, boolean valueIfNotSpecified ) {
075        assert conf != null;
076        assert !StringUtils.isEmpty(parameterName);
077        
078        String valueIfNotSpecifiedString = "false";
079        if( valueIfNotSpecified) {
080          valueIfNotSpecifiedString = "true";
081        }
082        String valueString = getParameter( conf, parameterName, valueIfNotSpecifiedString);
083        assert valueString != null;
084        boolean result = valueString.equalsIgnoreCase("true") || valueString.equals("1");
085        return result;
086      }
087      
088      public static int getIntParameterGreaterOrEqualToValue( ServletConfig conf, String parameterName, int minValue, int valueIfNotSpecified ) {
089        assert conf != null;
090        assert !StringUtils.isEmpty(parameterName);
091        
092        assert valueIfNotSpecified >= minValue;
093        
094        String resultString = getParameter( conf, parameterName, Integer.toString(valueIfNotSpecified));
095        if( StringUtils.isEmpty(resultString) ) {
096          return valueIfNotSpecified;
097        }
098        
099        try {
100          int result = Integer.parseInt(resultString);
101          if( result < minValue ) {
102            ServletConfigurationException ex = ServletConfigurationException.forParameterMustBeAnIntegerGreaterOrEqualToValue( parameterName, result, minValue );
103            logger.fatal( ex.getMessage(), ex );
104            throw ex;
105          }
106          return result;
107        }
108        catch( NumberFormatException e) {
109          ServletConfigurationException ex = ServletConfigurationException.forParameterMustBeAValidInteger( parameterName, resultString );
110          logger.fatal( ex.getMessage(), ex );
111          throw ex;
112        }
113        
114      }
115      
116      public static void checkRequiredParameters( ServletConfig conf, String... parameterNames ) {
117        assert conf != null;
118        assert parameterNames != null;
119        assert parameterNames.length > 0;
120        
121        List<String> missingParameters = new ArrayList<String>();
122        for( String parameterName : parameterNames ) {
123          String result = conf.getInitParameter( parameterName );
124          if( StringUtils.isEmpty(result) ) {
125            missingParameters.add( "'" + parameterName + "'" );
126          }
127        }
128        if( !missingParameters.isEmpty() ) {
129          ServletConfigurationException ex = ServletConfigurationException.forMissingRequiredConfigurationParameter( missingParameters );
130          logger.fatal(ex);
131          throw ex;
132        }
133      }
134      
135      public static String getDetailedRequestInformation(HttpServletRequest request) {
136        assert request != null;
137        
138        String contentType = request.getContentType();
139        if( contentType == null ) {
140          contentType = "";
141        }
142        String method = request.getMethod();    
143        StringBuilder result = new StringBuilder(); 
144        StringBuilderUtils.appendAll( result, "RequestType=", contentType, ", Method=", method,
145            ", ContextPath=", request.getContextPath(),
146            ", ServletPath=", request.getServletPath(), 
147            ", PathInfo=", request.getPathInfo(),
148            ", QueryString=", request.getQueryString(),
149            ", CharacterEncoding=", request.getCharacterEncoding(),
150            ", AuthType=", request.getAuthType(),
151            ", ContentType=", request.getContentType(),
152            ", Scheme=", request.getScheme(),
153            ", Locale=", request.getLocale().toString(),
154            ". " );
155        
156            
157        result.append( "Headers: " ); 
158        Enumeration<?> headers = request.getHeaderNames();
159        while( headers.hasMoreElements() ) {
160          String headerName = (String)headers.nextElement();
161          StringBuilderUtils.appendAll( result, "'", headerName, "'=" );
162          Enumeration<?> headerContent = request.getHeaders(headerName);
163          while( headerContent.hasMoreElements() ) {
164            String headerValue = (String)headerContent.nextElement();
165            result.append( headerValue );
166            result.append( ", " );
167          }
168        }
169        return result.toString();
170      }
171    }