Class ServletUtils

java.lang.Object
com.groiss.servlet.ServletUtils

public class ServletUtils extends Object
Utility methods to use in servlets.
  • Field Details

    • ADMIN_SESSION

      public static final String ADMIN_SESSION
      Name of the Session attribute to determine if it is an admin session.
      See Also:
    • ADMIN_URL

      public static final String ADMIN_URL
      Fully qualified name of the main entry method to the administration.
      See Also:
  • Method Details

    • init

      public static void init()
      Initialize the ServletUtils. Automatically called by startup and at configuration change.
    • getContextPath

      public static String getContextPath()
      Returns the context path of the web application.
    • getServerAddress

      public static String getServerAddress(HttpServletRequest req)
      Returns the a string of the follwing form: <protocol>://<hostname>:<port>/<contextpath>
      Parameters:
      req - the current request
    • isAdminSession

      public static boolean isAdminSession(HttpServletRequest req)
      check if the session is an admin session
    • isAdminConnector

      public static Boolean isAdminConnector(HttpServletRequest req)
      This method return TRUE if admin port or address is specified and the request uses this connector. It returns FALSE if the connector is not used and null if no extra connector is defined.
    • checkAdminSession

      public static void checkAdminSession(HttpServletRequest req)
      check if the session is an admin session and throw exception if it is not.
    • logRequest

      public static HttpServletRequest logRequest(HttpServletRequest req, HttpServletResponse res, org.slf4j.Logger effectiveLogger)
      Log the parameters of an HttpRequest. Will also wrap the request within a MultiPartRequest if it was "POST"ed and the content type was "multipart/form-data". Wrapping is avoided when the query string contains "preserveRequest". Will also add "Cache-Control: private" header to the response.
      Parameters:
      req - the request
      res - the response
      effectiveLogger - the loger to use. If it is null the logger of ServletUtils will be used.
      Returns:
      the request.
    • logParameters

      public static void logParameters(HttpServletRequest req, org.slf4j.Logger effectiveLogger)
      Logs the parameters of an HttpRequest at log level INFO. Single parameters longer than 128 characters are truncated in the output. Parameters named "password" or "avw_password" are masked as sequence of asterisks.
      Parameters:
      req - the request
      effectiveLogger - the logger to use.
    • logRequestProcessed

      public static void logRequestProcessed(long startTime, HttpServletRequest req, HttpServletResponse resp)
      Logs the duration of an HttpRequest. If the duration of the request was longer than the configuration parameter "httpd.response.timeout.threshold", then it is logged at loglevel WARN. If the state of the response is HttpServletResponse.SC_INTERNAL_SERVER_ERROR, is logged at level WARN, else loglevel DEBUG is being used.
      Parameters:
      startTime - the start time of the request.
      req - the request
      resp - the response
    • isAllowed

      public static boolean isAllowed(HttpServletRequest req, HttpServletResponse res, List<String> allowedMethods, String allowedMethodsString, org.slf4j.Logger effectiveLogger) throws IOException
      Determines if the method of an HttpRequest is allowed. If the used method is not contained in the allowedMethods, then an error is send back with HttpServletResponse.SC_METHOD_NOT_ALLOWED.
      Parameters:
      req - the request to check
      res - the response to send the error back
      allowedMethods - a list of Strings containing the permissible methods.
      allowedMethodsString - the string of methods to be used foe the "allow" response header.
      effectiveLogger - the logger to use. Requests with non permissible methods are logger at level WARN.
      Returns:
      true if the methos is permissible, false else.
      Throws:
      IOException
    • checkURL

      public static void checkURL(HttpServletRequest req, String url)
      Check the permissibility of the request with the URLChecker. ThreadPrincipal must be set before calling this method.
      Parameters:
      req - the request as context for the check
      url - the url to check
    • checkSessionIP

      public static void checkSessionIP(HttpServletRequest req, HttpServletResponse res, HttpSession s)
      Checks if the remote address of the request matches the address in session attribute "ip". Throws ApplicationException 466 if it does not match. Check is only carried out if configuration parameter "ep.check.ip" is set. Also calls IpChangeListener.
      Parameters:
      req -
      s -
    • addModificationInfo

      public static void addModificationInfo(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale)
      Adds some header fields to the response so we can determine modification on the next request. adds an ETag and a Last-Modified-Header
      Parameters:
      req - request
      resp - response
      lastModified - last modification timestamp
      locale - the current locale
    • addModificationInfo

      public static void addModificationInfo(HttpServletRequest req, HttpServletResponse resp, long lastModified, Locale locale, String ctx)
      Adds some header fields to the response so we can determine modification on the next request
      adds an ETag and a Last-Modified-Header
      Parameters:
      req - request
      resp - response
      lastModified - last modification timestamp
      locale - the current locale
    • isModifiedSince

      public static boolean isModifiedSince(HttpServletRequest req, long lastModified, Locale l)
      returns true if the requested resource has been modified since the last request. the following methods are used:
      1. check the ETag-header
      2. check the if-modified-since - header
      Parameters:
      req - request
      lastModified - last modification timestamp
      l - the current locale
      Returns:
      true if the resource has been modified since the last request, false otherwise
    • isModifiedSince

      public static boolean isModifiedSince(HttpServletRequest req, long lastModified, Locale l, String ctx)
      Returns true if the requested resource has been modified since the last request.
      the following methods are used:
      1. check the ETag-header
      2. check the if-modified-since - header
      Parameters:
      req - request
      lastModified - last modification timestamp
      l - the current locale
      ctx - an optional context-string to be appended to the etag
      Returns:
      true if the resource has been modified since the last request, false otherwise
    • setExpiresImmediatelyForGuest

      public static void setExpiresImmediatelyForGuest(HttpServletRequest req, HttpServletResponse res)
      If no user is currently logged in, it's required, that some resources are not cached, so the user gets the new files as soon he loggs in.
      Parameters:
      req -
      res -
    • writeToResp

      public static void writeToResp(HttpServletResponse res, Page page)
      Write a page to the response. First the headers are written, then the content is written.
      Parameters:
      res - the response to write to
      page - the page to write.
    • writeToResp

      public static void writeToResp(HttpServletResponse res, String pageStr)
      Write a string to the response. First tries to use the writer of the response. If the writer is not available, the output stream of the response is being used.
      Parameters:
      res - the response to write to
      pageStr - the string to write
    • writeHeaders

      public static void writeHeaders(HttpServletResponse res, Page page)
      Write the headers of a page to the response.
      Parameters:
      res - the response to write to
      page - the page which headers are to be written
    • writeToResp

      public static void writeToResp(HttpServletRequest req, HttpServletResponse res, Page page, String pageStr, Throwable t)
      Write a page to the response. If the Throwable is not null, an error response will be generated. Else, First, the headers are written, then the content is dealt with. If pageStr is not null, it will be used, the page content is ignored. Else, the page Content will be written.
      Parameters:
      req - the request
      res - the reponse to write to
      page - the page to write (if pageStr is null)
      pageStr - the string to write
      t - the throwable
    • setLocale

      @Deprecated public static Locale setLocale(HttpServletRequest req)
      Sets the threadcontext locale and return it.
    • setLocale

      public static Locale setLocale(HttpServletRequest req, Principal u)
      Set the threadcontext Locale and return it. Also sets the HttpSession "locale" attribute. The locale is retrieved from the following locations, in the given order:
      1. from the HttpSession "locale" attribute
      2. the browser locale (if "locale.from.browser" is configured)
      3. the locale of the user associated with the passed Principal (if not null)
      4. locale from the guest user
      5. locale from the "{serverid}_locale" cookie
      6. default locale
      Parameters:
      req - the request to use
      u - the user to use (may be nul)
      Returns:
      the locale
    • getBrowserLocale

      public static Locale getBrowserLocale(HttpServletRequest req)
      Read the locale from the browser. The "Accept-Language" header of the request is used in combination with the available locales on the Server (see Settings.getAvailableLocales()). If no match with the available locales could be made or in case of a missing request header, Locale.getDefault() is returned.
      Parameters:
      req - the request to read the initial locale value from
      Returns:
      the locale
    • setThreadTimeZone

      public static void setThreadTimeZone(HttpServletRequest req, HttpSession s, TimeZone tz, org.slf4j.Logger l) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
      Sets the time zone in the threadcontext from a number of sources.
      Parameters:
      req - the HttpServletRequest
      s - the HttpSession
      tz - an initial time zone
      l - the logger to use
      Throws:
      IllegalAccessException
      InvocationTargetException
      NoSuchMethodException
    • setNoCache

      public static void setNoCache(HttpServletResponse res)
      Sets appropriate headers on the response to avoid caching. This must be called before the response is committed.
      Parameters:
      res - the HttpServletResponse
    • setNoTransform

      public static void setNoTransform(HttpServletResponse res)
      Sets appropriate headers on the response to avoid caching and to avoid intermediate transformations (e.g. compression). This must be called before the response is committed.
      Parameters:
      res - the HttpServletResponse
    • setPrivateCache

      public static void setPrivateCache(HttpServletResponse res)
      Sets appropriate headers on the response to enable private caching This must be called before the response is committed.
      Parameters:
      res - the HttpServletResponse
    • getParameterFromURL

      public static String getParameterFromURL(String urlString, String paramName)
      Parse a String in the same manner as an URL of an HttpServletRequest would be parsed and extract one parameter from it (all elements up to and including the first question mark are removed first).
      Parameters:
      urlString - the string the parameter is to be extracted from
      paramName - the name of the parameter to extract from urlString
      Returns:
      the extracted parameter value, or null
    • getParameterFromQuery

      public static String getParameterFromQuery(String queryString, String paramName)
      Parse a String in the same manner as a querystring of an HttpServletRequest would be parsed and extract one parameter from it. The query string is the part of the URL that starts after the first question mark.
      Parameters:
      queryString - the string the parameter is to be extracted from
      paramName - the name of the parameter to extract from queryString
      Returns:
      the extracted parameter value, or null