Class HttpSupport

java.lang.Object
org.javalite.activeweb.HttpSupport
All Implemented Interfaces:
RequestAccess
Direct Known Subclasses:
AppController, HttpSupportFilter

public class HttpSupport extends Object implements RequestAccess
Author:
Igor Polevoy
  • Constructor Details

    • HttpSupport

      public HttpSupport()
  • Method Details

    • logInfo

      protected void logInfo(String info)
    • logDebug

      protected void logDebug(String info)
    • logWarning

      protected void logWarning(String info)
    • logWarning

      protected void logWarning(String info, Throwable e)
    • logError

      protected void logError(String info)
    • logError

      protected void logError(Throwable e)
    • logError

      protected void logError(String info, Throwable e)
    • assign

      protected void assign(String name, Object value)
      Assigns a value for a view.
      Parameters:
      name - name of value
      value - value.
    • view

      protected void view(String name, Object value)
      Parameters:
      name - name of object to be passed to view
      value - object to be passed to view
    • status

      protected int status()
      Returns status code from current response.
      Returns:
      status code or -1 if controller response was not generated (error)
    • view

      protected void view(Map values)
      Convenience method, calls assign(String, Object) internally. The keys in teh map are converted to String values.
      Parameters:
      values - map with values to pass to view.
    • view

      protected void view(Object... values)
      Convenience method to pass multiple names and corresponding values to a view.
      Parameters:
      values - - pairs of names and values. such as: name1, value1, name2, value2, etc. Number of arguments must be even.
    • flash

      protected void flash(Map values)
      Flash method to display multiple flash messages. Takes in a map of names and values for a flash. Keys act like names, and values act like... ehr.. values.
      Parameters:
      values - values to flash.
      See Also:
      flash(String, Object)
    • flash

      protected void flash(Object... values)
      Flash method to display multiple flash messages. Takes in a vararg of values for flash. Number of arguments must be even. Format: name, value, name, value, etc.
      Parameters:
      values - values to flash.
      See Also:
      flash(String, Object)
    • flash

      protected void flash(String name)
      Sets a flash name for a flash with a body. Here is a how to use a tag with a body:
       <@flash name="warning">
               <div class="warning">${message}</div>
             </@flash>
       
      If body refers to variables (as in this example), then such variables need to be passed in to the template as usual using the view(String, Object) method.
      Parameters:
      name - name of a flash
    • flash

      protected void flash(String name, Object value)
      Sends value to flash. Flash survives one more request. Using flash is typical for POST/GET pattern,
      Parameters:
      name - name of value to flash
      value - value to live for one more request in current session.
    • render

      protected HttpSupport.RenderBuilder render(String template, Map values)
      Renders results with a template. This call must be the last call in the action.
      Parameters:
      template - - template name, must be "absolute", starting with slash, such as: "/controller_dir/action_template".
      values - map with values to pass to view.
      Returns:
      instance of HttpSupport.RenderBuilder, which is used to provide additional parameters.
    • redirect

      protected HttpSupport.HttpBuilder redirect(String path)
      Redirects to a an action of this controller, or an action of a different controller. This method does not expect a full URL.
      Parameters:
      path - - expected to be a path within the application.
      Returns:
      instance of HttpSupport.HttpBuilder to accept additional information.
    • redirect

      protected HttpSupport.HttpBuilder redirect(URL url)
      Redirects to another URL (usually another site).
      Parameters:
      url - absolute URL: http://domain/path....
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirectToReferrer

      protected HttpSupport.HttpBuilder redirectToReferrer(String defaultReference)
      Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to the defaultReference.
      Parameters:
      defaultReference - where to redirect - can be absolute or relative; this will be used in case the request does not provide a "Referrer" header.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirectToReferrer

      protected HttpSupport.HttpBuilder redirectToReferrer()
      Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to the root of the application.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, String action, Object id)
      Convenience method for redirect(Class, java.util.Map).
      Parameters:
      controllerClass - controller class where to send redirect.
      action - action to redirect to.
      id - id to redirect to.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, Object id)
      Convenience method for redirect(Class, java.util.Map).
      Parameters:
      controllerClass - controller class where to send redirect.
      id - id to redirect to.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, String action)
      Convenience method for redirect(Class, java.util.Map).
      Parameters:
      controllerClass - controller class where to send redirect.
      action - action to redirect to.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected HttpSupport.HttpBuilder redirect()
      Redirects to the same controller, and action "index". This is equivalent to
           redirect(BooksController.class);
       
      given that the current controller is BooksController.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass)
      Redirects to given controller, action "index" without any parameters.
      Parameters:
      controllerClass - controller class where to send redirect.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • redirect

      protected <T extends AppController> HttpSupport.HttpBuilder redirect(Class<T> controllerClass, Map params)
      Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as:
       
       /controller/action/id
       
       
      for regular controllers, and:
       
       /controller/id/action
       
       
      for RESTful controllers. For RESTful controllers, the action names are limited to those described in RESTful and allowed on a GET URLs, which are: "edit_form" and "new_form".

      The map may contain any number of other key/value pairs, which will be converted to a query string for the redirect URI. Example:

      Method:

       
       redirect(app.controllers.PersonController.class,  org.javalite.common.Collections.map("action", "show", "id", 123, "format", "json", "restrict", "true"));
       
       
      will generate the following URI:
       
       /person/show/123?format=json&restrict=true
       
       
      This method will also perform URL - encoding of special characters if necessary.
      Parameters:
      controllerClass - controller class
      params - map with request parameters.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • respond

      protected HttpSupport.HttpBuilder respond(String text)
      This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services and to support AJAX.
      Parameters:
      text - text of response.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • sendFile

      protected HttpSupport.HttpBuilder sendFile(File file, boolean delete)
      Convenience method for downloading files. This method will force the browser to find a handler(external program) for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header "Content-Disposition" based on a file name.
      Parameters:
      file - file to download.
      delete - true to delete the file after processing
      Returns:
      builder instance.
    • sendFile

      protected HttpSupport.HttpBuilder sendFile(File file)
      Convenience method for downloading files. This method will force the browser to find a handler(external program) for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header "Content-Disposition" based on a file name.
      Parameters:
      file - file to download.
      Returns:
      builder instance.
    • getFile

      protected FileItem getFile(String fieldName, List<FormItem> formItems)
      Convenience method to get file content from multipart/form-data request. If more than one files with the same name are submitted, only one is returned.
      Parameters:
      fieldName - name of form field from the multipart/form-data request corresponding to the uploaded file.
      formItems - form items retrieved from multipart/form-data request.
      Returns:
      InputStream from which to read content of uploaded file or null if FileItem with this name is not found.
    • getHttpServletRequest

      protected javax.servlet.http.HttpServletRequest getHttpServletRequest()
      Direct access to current HttpServletRequest for low level operations.
      Returns:
      instance of current HttpServletRequest.
    • getHttpServletResponse

      protected javax.servlet.http.HttpServletResponse getHttpServletResponse()
      Direct access to current HttpServletResponse for low level operations.
      Returns:
      instance of current HttpServletResponse.
    • uploadedFiles

      protected Iterator<FormItem> uploadedFiles()
      Returns a collection of uploaded files from a multi-part port request. Uses request encoding if one provided, and sets no limit on the size of upload.
      Returns:
      a collection of uploaded files from a multi-part port request.
    • uploadedFiles

      protected Iterator<FormItem> uploadedFiles(String encoding)
      Returns a collection of uploaded files from a multi-part port request. Sets no limit on the size of upload.
      Parameters:
      encoding - specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.
      Returns:
      a collection of uploaded files from a multi-part port request.
    • uploadedFiles

      protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize)
      Returns a collection of uploaded files from a multi-part port request.
      Parameters:
      encoding - specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.
      maxFileSize - maximum file size in the upload in bytes. -1 indicates no limit.
      Returns:
      a collection of uploaded files from a multi-part port request.
    • multipartFormItems

      protected List<FormItem> multipartFormItems()
      Convenience method, calls multipartFormItems(String). Does not set encoding before reading request.
      Returns:
      a collection of uploaded files/fields from a multi-part request.
      See Also:
      multipartFormItems(String)
    • multipartFormItems

      protected List<FormItem> multipartFormItems(String encoding)
      Returns a collection of uploaded files and form fields from a multi-part request. This method uses DiskFileItemFactory. As a result, it is recommended to add the following to your web.xml file:
         <listener>
            <listener-class>
               org.apache.commons.fileupload.servlet.FileCleanerCleanup
            </listener-class>
         </listener>
      
      For more information, see: Using FileUpload The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept larger files, create a file called activeweb.properties, add it to your classpath and place this property to the file:
       #max upload size
       maxUploadSize = 20000000
       
      Alternatively, just call this method and pass a per-request parameter for the size: multipartFormItems(String, long).
      Parameters:
      encoding - specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.
      Returns:
      a collection of uploaded files from a multi-part request.
    • multipartForm

      protected MultipartForm multipartForm()
      Returns:
      MultipartForm object for convenience.
    • multipartForm

      protected MultipartForm multipartForm(String encoding, long maxUploadSize)
      Parameters:
      encoding - encoding to use to read values from request
      maxUploadSize - set max upload size
      Returns:
      MultipartForm object for convenience.
    • multipartFormItems

      protected List<FormItem> multipartFormItems(String encoding, long maxUploadSize)
      Returns a collection of uploaded files and form fields from a multi-part request. This method uses DiskFileItemFactory. As a result, it is recommended to add the following to your web.xml file:
         <listener>
            <listener-class>
               org.apache.commons.fileupload.servlet.FileCleanerCleanup
            </listener-class>
         </listener>
      
      For more information, see: Using FileUpload
      Parameters:
      encoding - specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.
      maxUploadSize - maximum size of the upload in bytes. A value of -1 indicates no maximum.
      Returns:
      a collection of uploaded files from a multi-part request.
    • getMap

      protected Map<String,​String> getMap(String hashName)
      Returns a map parsed from a request if parameter names have a "hash" syntax:
        <input type="text" name="account[name]" />
              <input type="text" name="account[number]" />
       
      will result in a map where keys are names of hash elements, and values are values of these elements from request. For the example above, the map will have these values:
           { "name":"John", "number": "123" }
       
      Parameters:
      hashName - - name of a hash. In the example above, it will be "account".
      Returns:
      map with name/value pairs parsed from request.
    • getMap

      protected Map<String,​String> getMap(String hashName, List<FormItem> formItems)
      Convenience method to get parameter map in case multipart/form-data request was used. This method will skip files, and will only return form fields that are not files. Returns a map parsed from a request if parameter names have a "hash" syntax:
        <input type="text" name="account[name]" />
        <input type="text" name="account[number]" />
       
      will result in a map where keys are names of hash elements, and values are values of these elements from request. For the example above, the map will have these values:
           { "name":"John", "number": "123" }
       
      Parameters:
      hashName - - name of a hash. In the example above, it will be "account".
      formItems - form items retrieved from multipart/form-data request.
      Returns:
      map with name/value pairs parsed from request.
    • setRequestEncoding

      protected void setRequestEncoding(String encoding)
      Sets character encoding for request. Has to be called before reading any parameters of getting input stream.
      Parameters:
      encoding - encoding to be set.
    • setResponseEncoding

      protected void setResponseEncoding(String encoding)
      Sets character encoding for response.
      Parameters:
      encoding - encoding to be set.
    • setEncoding

      protected void setEncoding(String encoding)
      Sets character encoding on the response.
      Parameters:
      encoding - character encoding for response.
    • encoding

      protected void encoding(String encoding)
      Parameters:
      encoding - encoding of response to client
    • getEncoding

      protected String getEncoding()
      Controllers can override this method to return encoding they require. Encoding set in method setEncoding(String) trumps this setting.
      Returns:
      null. If this method is not overridden and encoding is not set from an action or filter, encoding will be set according to container implementation.
    • setContentLength

      protected void setContentLength(int length)
      Sets content length of response.
      Parameters:
      length - content length of response.
    • setLocale

      protected void setLocale(Locale locale)
      Sets locale on response.
      Parameters:
      locale - locale for response.
    • locale

      protected void locale(Locale locale)
      Parameters:
      locale - locale for response
    • session

      protected SessionFacade session()
      Returns reference to a current session. Creates a new session of one does not exist.
      Returns:
      reference to a current session.
    • session

      protected void session(String name, Serializable value)
      Convenience method, sets an object on a session. Equivalent of:
       
           session().put(name, value)
       
       
      Parameters:
      name - name of object
      value - object itself.
    • sessionObject

      protected Object sessionObject(String name)
      Convenience method, returns object from session, equivalent of:
       
           session().get(name)
       
       
      Parameters:
      name - name of object,
      Returns:
      session object.
    • sessionString

      protected String sessionString(String name)
      Convenience method, returns object from session, equivalent of:
       
           String val = (String)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionInteger

      protected Integer sessionInteger(String name)
      Convenience method, returns object from session, equivalent of:
       
           Integer val = (Integer)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionBoolean

      protected Boolean sessionBoolean(String name)
      Convenience method, returns object from session, equivalent of:
       
           Boolean val = (Boolean)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionDouble

      protected Double sessionDouble(String name)
      Convenience method, returns object from session, equivalent of:
       
           Double val = (Double)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionFloat

      protected Float sessionFloat(String name)
      Convenience method, returns object from session, equivalent of:
       
           Float val = (Float)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionLong

      protected Long sessionLong(String name)
      Convenience method, returns object from session, equivalent of:
       
           Long val = (Long)session().get(name)
       
       
      Parameters:
      name - name of object
      Returns:
      value
    • sessionHas

      protected boolean sessionHas(String name)
      Returns true if session has named object, false if not.
      Parameters:
      name - name of object.
      Returns:
      true if session has named object, false if not.
    • sendCookie

      protected void sendCookie(Cookie cookie)
      Sends cookie to browse with response.
      Parameters:
      cookie - cookie to send.
    • sendCookie

      protected void sendCookie(String name, String value)
      Sends cookie to browse with response.
      Parameters:
      name - name of cookie
      value - value of cookie.
    • sendPermanentCookie

      protected void sendPermanentCookie(String name, String value)
      Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years.
      Parameters:
      name - name of cookie
      value - value of cookie.
    • header

      protected void header(String name, String value)
      Adds a header to response.
      Parameters:
      name - name of header.
      value - value of header.
    • applicationJSON

      protected void applicationJSON()
      A convenience method. Sets the "Content-Type" header on the response to "application/json".
    • header

      protected void header(String name, Object value)
      Adds a header to response.
      Parameters:
      name - name of header.
      value - value of header.
    • streamOut

      protected HttpSupport.HttpBuilder streamOut(InputStream in)
      Streams content of the reader to the HTTP client.
      Parameters:
      in - input stream to read bytes from.
      Returns:
      HttpSupport.HttpBuilder, to accept additional information.
    • getRealPath

      protected String getRealPath(String path)
      Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..

      The real path returned will be in a form appropriate to the computer and operating system on which the servlet

      container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

      JavaDoc copied from: http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29

      Parameters:
      path - a String specifying a virtual path
      Returns:
      a String specifying the real path, or null if the translation cannot be performed
    • outputStream

      protected OutputStream outputStream()
      Use to send raw data to HTTP client. Content type and headers will not be set. Response code will be set to 200.
      Returns:
      instance of output stream to send raw data directly to HTTP client.
    • outputStream

      protected OutputStream outputStream(String contentType)
      Use to send raw data to HTTP client. Status will be set to 200.
      Parameters:
      contentType - content type
      Returns:
      instance of output stream to send raw data directly to HTTP client.
    • outputStream

      protected OutputStream outputStream(String contentType, Map headers, int status)
      Use to send raw data to HTTP client.
      Parameters:
      contentType - content type
      headers - set of headers.
      status - status.
      Returns:
      instance of output stream to send raw data directly to HTTP client.
    • writer

      protected PrintWriter writer()
      Produces a writer for sending raw data to HTTP clients. Content type content type not be set on the response. Headers will not be send to client. Status will be set to 200.
      Returns:
      instance of a writer for writing content to HTTP client.
    • writer

      protected PrintWriter writer(String contentType, Map headers, int status)
      Produces a writer for sending raw data to HTTP clients.
      Parameters:
      contentType - content type. If null - will not be set on the response
      headers - headers. If null - will not be set on the response
      status - will be sent to browser.
      Returns:
      instance of a writer for writing content to HTTP client.
    • blank

      protected boolean blank(String... names)
      Returns true if any named request parameter is blank.
      Parameters:
      names - names of request parameters.
      Returns:
      true if any request parameter is blank.
    • merge

      protected String merge(String template, Map values)
      Will merge a template and return resulting string. This method is used for just merging some text with dynamic values. Once you have the result, you can send it by email, external web service, save it to a database, etc.
      Parameters:
      template - name of template - same as in regular templates. Example: "/email-templates/welcome".
      values - values to be merged into template.
      Returns:
      merged string
    • getResponseHeaders

      protected Map<String,​String> getResponseHeaders()
      Returns response headers
      Returns:
      map with response headers.
    • sanitize

      protected String sanitize(String unsafeContent)
      Cleans HTML from harmful tags, making XSS impossible.

      For example, input like this:

            <html><script> alert('hello');</script><div>this is a clean part</div></html>
       
      Will produce output like this:
           this is a clean part
       
      Parameters:
      unsafeContent - unsafe content. Something that an end user typed into a text area, or input that may include a script tag or other garbage.
      Returns:
      sanitized version of input
    • getRequestInputStream

      protected InputStream getRequestInputStream()
      Returns InputStream of the request.
      Returns:
      InputStream of the request
    • getRequestStream

      protected InputStream getRequestStream()
      Returns:
      input stream to read data sent by client.
    • getRequestString

      protected String getRequestString()
      Reads entire request data as String. Do not use for large data sets to avoid memory issues, instead use getRequestInputStream().
      Returns:
      data sent by client as string.
    • getRequestBytes

      protected byte[] getRequestBytes()
      Reads entire request data as byte array. Do not use for large data sets to avoid memory issues.
      Returns:
      data sent by client as string.
    • jsonList

      protected List jsonList()
      Converts posted JSON array to a Java List. Example of a JSON array: [1, 2, 3].
      Returns:
      Java List converted from posted JSON string.
    • jsonMap

      protected Map jsonMap()
      Converts posted JSON map to a Java Map. Example JSON map: {"name":"John", "age":21}.
      Returns:
      Java Map converted from posted JSON string map.
    • jsonMaps

      protected Map[] jsonMaps()
      Converts posted JSON maps to a Java Maps array. Example JSON map: [{"name":"John", "age":21}, {"name":"Jane", "age":20}].
      Returns:
      Java Maps converted from posted JSON string maps.
    • values

      protected Map values()
      Returns a mutable Map with all the values from the current request context. Use this to get/put/modify values from current place on the stack down stream (from filters to controllers, to views).
      Returns:
      a mutable Map with all values from/for current request context.