Example usage for javax.servlet.http HttpServletRequest getCharacterEncoding

List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCharacterEncoding.

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:com.adaptris.core.http.jetty.MessageConsumer.java

@Override
public AdaptrisMessage createMessage(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    AdaptrisMessage msg = null;/*from w  ww .j  a v a 2 s . c  o m*/
    OutputStream out = null;
    try {
        logHeaders(request);
        if (getEncoder() != null) {
            msg = getEncoder().readMessage(request);
        } else {
            msg = defaultIfNull(getMessageFactory()).newMessage();
            out = msg.getOutputStream();
            if (request.getContentLength() == -1) {
                IOUtils.copy(request.getInputStream(), out);
            } else {
                StreamUtil.copyStream(request.getInputStream(), out, request.getContentLength());
            }
            out.flush();
        }
        msg.setContentEncoding(request.getCharacterEncoding());
        addParamMetadata(msg, request);
        addHeaderMetadata(msg, request);
    } catch (CoreException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        IOUtils.closeQuietly(out);
    }
    return msg;
}

From source file:org.getobjects.servlets.WOServletAdaptor.java

protected void woService(final HttpServletRequest _rq, final HttpServletResponse _r) {
    log.debug("woService ...");

    if (this.WOApp == null) {
        log.error("Cannot run service, missing application object!");
        return;/*from w  w  w . ja  va2 s.c o m*/
    }

    try {
        /* Changed in Jetty 6.1.12/6.1.14 (JETTY-633). Default encoding is now
         * Latin-1, which breaks Safari/Firefox, which submit forms in UTF-8.
         * (I think if the page was delivered in UTF-8)
         * (w/o tagging the charset in the content-type?!) 
         */
        if (_rq.getCharacterEncoding() == null)
            _rq.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 is unsupported encoding?!", e);
        e.printStackTrace();
    }

    final WORequest rq = new WOServletRequest(_rq, _r);
    final WOResponse r;

    try {
        log.debug("  dispatch ...");
        r = this.WOApp.dispatchRequest(rq);

        if (r != null) {
            log.debug("  flush ...");
            r.flush();

            if (!r.isStreaming())
                this.sendWOResponseToServletResponse(r, _r);
        } else
            log.debug("  got no response.");
    } catch (Exception e) {
        log.debug("dispatch exception", e);
        e.printStackTrace();
    }

    if (rq != null)
        rq.dispose(); /* this will delete temporary files, eg of file uploads */

    log.debug("done woService.");
}

From source file:org.apache.struts2.dispatcher.Dispatcher.java

private void applyEncoding(HttpServletRequest request, String encoding) {
    try {//ww  w  . j  a v a  2  s.  c o  m
        if (!encoding.equals(request.getCharacterEncoding())) {
            // if the encoding is already correctly set and the parameters have been already read
            // do not try to set encoding because it is useless and will cause an error
            request.setCharacterEncoding(encoding);
        }
    } catch (Exception e) {
        LOG.error("Error setting character encoding to '{}' - ignoring.", encoding, e);
    }
}

From source file:nl.strohalm.cyclos.http.RequestProcessingFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    // For performance reasons, these settings which will be used on every request are stored in the request context, not relying to the proxy
    // stored on the application context. See SettingsHelper.initialize()
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final AccessSettings accessSettings = settingsService.getAccessSettings();
    request.setAttribute(SettingsHelper.LOCAL_KEY, localSettings);
    request.setAttribute(SettingsHelper.ACCESS_KEY, accessSettings);
    request.setAttribute("datePattern",
            messageHelper.getDatePatternDescription(localSettings.getDatePattern()));
    request.setAttribute("timePattern",
            messageHelper.getTimePatternDescription(localSettings.getTimePattern()));

    final String requestEncoding = request.getCharacterEncoding();
    if (StringUtils.isEmpty(requestEncoding)) {
        request.setCharacterEncoding(localSettings.getCharset());
    }//from  w w  w  . ja  va  2  s  . co  m
    response.setCharacterEncoding(localSettings.getCharset());

    chain.doFilter(request, response);
}

From source file:org.jahia.params.ParamBean.java

/**
 * parse the PathInfo elements and convert them to emultated request parameters. the parameters are stored in a HashMap
 * (customParameters) where they can be looked up by a customized version of this.getParameter().
 * <p/>//from   w ww. java  2 s.c  o  m
 * todo we might want to extend this in order to store parameter info either in the session or in the URL. Session for shorter URLs and
 * URL for bookmarking. This should be configurable in the properties, or maybe even for the page.
 *
 * @param request the HttpRequest object
 */
private void buildCustomParameterMapFromPathInfo(final HttpServletRequest request, final String extraParams) {

    if (logger.isDebugEnabled()) {
        logger.debug("buildCustomParameters: " + extraParams);
    }

    // Parse the PathInfo and build a custom parameter map
    String pathInfo = null;
    try {
        String characterEncoding = request.getCharacterEncoding();
        if (characterEncoding == null)
            characterEncoding = "UTF-8";
        pathInfo = URLDecoder.decode(request.getRequestURI(), characterEncoding);
        String str = request.getContextPath() + request.getServletPath();
        pathInfo = pathInfo.substring(str.length());
    } catch (Exception e) {
        pathInfo = request.getPathInfo();
    }

    buildCustomParameterMapFromPathInfo(pathInfo, extraParams, request.getServletPath());

    // Hollis : In case we have Multipart request
    // Append other parameters parsed from query string
    if (isMultipartRequest(request)) {

        final Map<String, String> queryStringParams = new HashMap<String, String>();

        ServletIncludeRequestWrapper.parseStringParameters(queryStringParams, request.getQueryString(),
                request.getCharacterEncoding(), true);
        for (Entry<String, String> entry : queryStringParams.entrySet()) {
            getCustomParameters().put(entry.getKey(), new String[] { entry.getValue() });
        }
    }
}

From source file:org.jabsorb.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in.
 * Looks in the session for a JSONRPCBridge and if not found there,
 * uses the global bridge; then passes off the
 * JSON-PRC call to be handled by the JSONRPCBridge found.
 *
 * @param request servlet request from browser.
 * @param response servlet response to browser.
 *
 * @throws IOException if an IOException occurs during processing.
 *///  w w  w  .j a va  2s . co m
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();
        int begin = receiveString.indexOf("{");
        int end = receiveString.lastIndexOf("}") + 1;
        receiveString = receiveString.substring(begin, end);

        // save the json-rpc data in a special request attribute, in case a jetty 
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown and this 
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("receive: " + receiveString);
        log.debug("receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("send: " + sendString);
        log.debug("send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug(
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warn("gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("not gzipping because size is " + bout.length + " (less than the GZIP_THRESHOLD of "
                        + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

From source file:org.openrdf.http.server.repository.transaction.TransactionController.java

/**
 * Evaluates a query on the given connection and returns the resulting
 * {@link QueryResultView}. The {@link QueryResultView} will take care of
 * correctly releasing the connection back to the
 * {@link ActiveTransactionRegistry}, after fully rendering the query result
 * for sending over the wire.//from  w  w  w  .j a  va2  s. co  m
 */
private ModelAndView processQuery(RepositoryConnection conn, UUID txnId, HttpServletRequest request,
        HttpServletResponse response) throws IOException, HTTPException {
    String queryStr = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_QUERY_MIME_TYPE)) {
        final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                : "UTF-8";
        queryStr = IOUtils.toString(request.getInputStream(), encoding);
    } else {
        queryStr = request.getParameter(QUERY_PARAM_NAME);
    }

    Query query = getQuery(conn, queryStr, request, response);

    View view;
    Object queryResult;
    FileFormatServiceRegistry<? extends FileFormat, ?> registry;

    try {
        if (query instanceof TupleQuery) {
            TupleQuery tQuery = (TupleQuery) query;

            queryResult = tQuery.evaluate();
            registry = TupleQueryResultWriterRegistry.getInstance();
            view = TupleQueryResultView.getInstance();
        } else if (query instanceof GraphQuery) {
            GraphQuery gQuery = (GraphQuery) query;

            queryResult = gQuery.evaluate();
            registry = RDFWriterRegistry.getInstance();
            view = GraphQueryResultView.getInstance();
        } else if (query instanceof BooleanQuery) {
            BooleanQuery bQuery = (BooleanQuery) query;

            queryResult = bQuery.evaluate();
            registry = BooleanQueryResultWriterRegistry.getInstance();
            view = BooleanQueryResultView.getInstance();
        } else {
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "Unsupported query type: " + query.getClass().getName());
        }
    } catch (QueryInterruptedException e) {
        logger.info("Query interrupted", e);
        ActiveTransactionRegistry.INSTANCE.returnTransactionConnection(txnId);
        throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query evaluation took too long");
    } catch (QueryEvaluationException e) {
        logger.info("Query evaluation error", e);
        ActiveTransactionRegistry.INSTANCE.returnTransactionConnection(txnId);
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Query evaluation error: " + e.getMessage());
        }
    }
    Object factory = ProtocolUtil.getAcceptableService(request, response, registry);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(QueryResultView.FILENAME_HINT_KEY, "query-result");
    model.put(QueryResultView.QUERY_RESULT_KEY, queryResult);
    model.put(QueryResultView.FACTORY_KEY, factory);
    model.put(QueryResultView.HEADERS_ONLY, false); // TODO needed for HEAD
                                                    // requests.
    model.put(QueryResultView.TRANSACTION_ID_KEY, txnId);
    return new ModelAndView(view, model);
}

From source file:org.ejbca.ui.web.HttpUpload.java

/**
 * Creates a new upload state and receives all file and parameter data.
 * This constructor can only be called once per request.
 * /*ww w . j  a v  a 2 s  . com*/
 * Use getParameterMap() and getFileMap() on the new object to access the data.
 * 
 * @param request The servlet request object. 
 * @param fileFields The names of the file fields to receive uploaded data from.
 * @param maxbytes Maximum file size.
 * @throws IOException if there are network problems, etc.
 * @throws FileUploadException if the request is invalid.
 */
@SuppressWarnings("unchecked") // Needed in some environments, and detected as unnecessary in others. Do not remove!
public HttpUpload(HttpServletRequest request, String[] fileFields, int maxbytes)
        throws IOException, FileUploadException {
    if (ServletFileUpload.isMultipartContent(request)) {
        final Map<String, ArrayList<String>> paramTemp = new HashMap<String, ArrayList<String>>();
        fileMap = new HashMap<String, byte[]>();

        final ServletFileUpload upload = new ServletFileUpload();
        final FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            final String name = item.getFieldName();
            if (item.isFormField()) {
                ArrayList<String> values = paramTemp.get(name);
                if (values == null) {
                    values = new ArrayList<String>();
                    paramTemp.put(name, values);
                }
                values.add(Streams.asString(item.openStream(), request.getCharacterEncoding()));
            } else if (ArrayUtils.contains(fileFields, name)) {
                byte[] data = getFileBytes(item, maxbytes);
                if (data != null && data.length > 0) {
                    fileMap.put(name, data);
                }
            }
        }

        // Convert to String,String[] map
        parameterMap = new ParameterMap();
        for (Entry<String, ArrayList<String>> entry : paramTemp.entrySet()) {
            final ArrayList<String> values = entry.getValue();
            final String[] valuesArray = new String[values.size()];
            parameterMap.put(entry.getKey(), values.toArray(valuesArray));
        }
    } else {
        parameterMap = new ParameterMap(request.getParameterMap());
        fileMap = new HashMap<String, byte[]>();
    }
}

From source file:org.jabsorb.ng.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in. Looks in the session for a
 * JSONRPCBridge and if not found there, uses the global bridge; then passes
 * off the JSON-PRC call to be handled by the JSONRPCBridge found.
 * //  w w  w  . j  a  va 2  s  .  c o m
 * @param request
 *            servlet request from browser.
 * @param response
 *            servlet response to browser.
 * 
 * @throws IOException
 *             if an IOException occurs during processing.
 */
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();

        // save the json-rpc data in a special request attribute, in case a
        // jetty
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown
        // and this
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("service", "jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("service", "receive: " + receiveString);
        log.debug("service", "receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("service", "can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("service", "send: " + sendString);
        log.debug("service", "send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip
        // compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug("service",
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warning("service", "gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("service", "not gzipping because size is " + bout.length
                        + " (less than the GZIP_THRESHOLD of " + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("service", "not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

From source file:org.apache.struts.upload.CommonsMultipartRequestHandler.java

/**
 * <p> Parses the input stream and partitions the parsed items into a set
 * of form fields and a set of file items. In the process, the parsed
 * items are translated from Commons FileUpload <code>FileItem</code>
 * instances to Struts <code>FormFile</code> instances. </p>
 *
 * @param request The multipart request to be processed.
 * @throws ServletException if an unrecoverable error occurs.
 *//*from w ww.  j a v  a  2  s .  co m*/
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // Create and configure a DIskFileUpload instance.
    DiskFileUpload upload = new DiskFileUpload();

    // The following line is to support an "EncodingFilter"
    // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());

    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));

    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold(ac));

    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(ac));

    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;

    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);

        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();

    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}