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.googlesource.gerrit.plugins.github.notification.WebhookServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (Strings.emptyToNull(config.webhookUser) == null) {
        logger.error("No webhookUser defined: cannot process GitHub events");
        resp.sendError(SC_INTERNAL_SERVER_ERROR);
        return;/*www  .jav  a 2 s.  c o  m*/
    }

    WebhookEventHandler<?> handler = getWebhookHandler(req.getHeader("X-Github-Event"));
    if (handler == null) {
        resp.sendError(SC_NOT_FOUND);
        return;
    }

    try (BufferedReader reader = req.getReader()) {
        String body = Joiner.on("\n").join(CharStreams.readLines(reader));
        if (!validateSignature(req.getHeader("X-Hub-Signature"), body, req.getCharacterEncoding())) {
            logger.error("Signature mismatch to the payload");
            resp.sendError(SC_FORBIDDEN);
            return;
        }

        session.get().setUserAccountId(Account.Id.fromRef(config.webhookUser));
        GitHubLogin login = loginProvider.get(config.webhookUser);
        if (login == null || !login.isLoggedIn()) {
            logger.error("Cannot login to github as {}. {}.webhookUser is not correctly configured?",
                    config.webhookUser, GitHubConfig.CONF_SECTION);
            resp.setStatus(SC_INTERNAL_SERVER_ERROR);
            return;
        }
        requestScopedLoginProvider.get(req).login(login.getToken());

        if (callHander(handler, body)) {
            resp.setStatus(SC_NO_CONTENT);
        } else {
            resp.sendError(SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.liferay.util.servlet.UploadServletRequest.java

public UploadServletRequest(HttpServletRequest req) throws IOException {

    super(req);//from w  w w.j a  v a2 s. c o  m

    _params = new LinkedHashMap();

    try {
        //DiskFileUpload diskFileUpload = new DiskFileUpload(
        //   new LiferayFileItemFactory(DEFAULT_TEMP_DIR));

        ServletFileUpload diskFileUpload = new LiferayDiskFileUpload(
                new LiferayFileItemFactory(DEFAULT_TEMP_DIR), req);

        diskFileUpload.setSizeMax(DEFAULT_SIZE_MAX);

        List list = diskFileUpload.parseRequest(req);

        for (int i = 0; i < list.size(); i++) {
            LiferayFileItem fileItem = (LiferayFileItem) list.get(i);

            if (fileItem.isFormField()) {
                fileItem.setString(req.getCharacterEncoding());
            }

            LiferayFileItem[] fileItems = (LiferayFileItem[]) _params.get(fileItem.getFieldName());

            if (fileItems == null) {
                fileItems = new LiferayFileItem[] { fileItem };
            } else {
                LiferayFileItem[] newFileItems = new LiferayFileItem[fileItems.length + 1];

                System.arraycopy(fileItems, 0, newFileItems, 0, fileItems.length);

                newFileItems[newFileItems.length - 1] = fileItem;

                fileItems = newFileItems;
            }

            _params.put(fileItem.getFieldName(), fileItems);
            if (fileItem.getFileName() != null)
                _params.put(fileItem.getFileName(), new LiferayFileItem[] { fileItem });

        }
    } catch (FileUploadException fue) {
        Logger.error(this, fue.getMessage(), fue);
    }
}

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

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

From source file:com.keithhutton.ws.proxy.ProxyServlet.java

protected XmlRpcHttpRequestConfigImpl getConfig(HttpServletRequest pRequest) {
    XmlRpcHttpRequestConfigImpl result = newConfig(pRequest);
    XmlRpcHttpServerConfig serverConfig = (XmlRpcHttpServerConfig) getConfig();
    result.setBasicEncoding(serverConfig.getBasicEncoding());
    result.setContentLengthOptional(/* www  .  java2 s . c  o  m*/
            serverConfig.isContentLengthOptional() && (pRequest.getHeader("Content-Length") == null));
    result.setEnabledForExtensions(serverConfig.isEnabledForExtensions());
    result.setGzipCompressing(HttpUtil.isUsingGzipEncoding(pRequest.getHeader("Content-Encoding")));
    result.setGzipRequesting(HttpUtil.isUsingGzipEncoding(pRequest.getHeaders("Accept-Encoding")));
    result.setEncoding(pRequest.getCharacterEncoding());
    result.setEnabledForExceptions(serverConfig.isEnabledForExceptions());
    HttpUtil.parseAuthorization(result, pRequest.getHeader("Authorization"));
    return result;
}

From source file:org.eclipse.rdf4j.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  ww . j  a va2 s .  com*/
private ModelAndView processQuery(Transaction txn, 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);
    }

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

    try {
        Query query = getQuery(txn, queryStr, request, response);

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

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

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

            queryResult = txn.evaluate(bQuery);
            registry = BooleanQueryResultWriterRegistry.getInstance();
            view = BooleanQueryResultView.getInstance();
        } else {
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "Unsupported query type: " + query.getClass().getName());
        }
    } catch (QueryInterruptedException | InterruptedException | ExecutionException e) {
        logger.info("Query interrupted", e);
        throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query execution interrupted");
    } catch (QueryEvaluationException e) {
        logger.info("Query evaluation error", e);
        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.
    return new ModelAndView(view, model);
}

From source file:org.opencms.ade.sitemap.CmsAliasBulkEditHelper.java

/**
 * Imports uploaded aliases from a request.<p>
 *
 * @param request the request containing the uploaded aliases
 * @param response the response/*from  w ww. j  a v  a  2s  .c  o  m*/
 * @throws Exception if something goes wrong
 */
public void importAliases(HttpServletRequest request, HttpServletResponse response) throws Exception {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    @SuppressWarnings("unchecked")
    List<FileItem> items = upload.parseRequest(request);
    byte[] data = null;
    String siteRoot = null;
    String separator = ",";
    for (FileItem fileItem : items) {
        String name = fileItem.getFieldName();
        if (PARAM_IMPORTFILE.equals(name)) {
            data = fileItem.get();
        } else if (PARAM_SITEROOT.equals(name)) {
            siteRoot = new String(fileItem.get(), request.getCharacterEncoding());
        } else if (PARAM_SEPARATOR.equals(name)) {
            separator = new String(fileItem.get(), request.getCharacterEncoding());
        }
    }
    List<CmsAliasImportResult> result = new ArrayList<CmsAliasImportResult>();
    if ((siteRoot != null) && (data != null)) {
        result = OpenCms.getAliasManager().importAliases(m_cms, data, siteRoot, separator);
    }
    String key = CmsVfsSitemapService.addAliasImportResult(result);
    // only respond with a key, then the client can get the data for the key via GWT-RPC
    response.getWriter().print(key);
}

From source file:net.sf.ginp.GinpServlet.java

/**
 *  Central Processor of HTTP Methods. This method gets the model for the
 *  users session, extracts the Command Parameters and preforms the command
 *  specified in the request. It then redirects or if cookies are used
 *  forwards the response to the JSP govened by the new state. If a
 *  significant error occurs it should be throwned up to here so that a
 *  debug page can be displayed. If a user sees a debug page then that is
 *  bad so lets try to find out about it and so we can fix it.
 *
 *@param  req                   HTTP Request
 *@param  res                   HTTP Response
 *@exception  IOException       Description of the Exception
 *//*from w  w  w . ja  v a 2 s. c  o m*/
public final void doHttpMethod(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    // Set the Character Encoding. Do this first before access ing the req
    // and res objects, otherwise they take the system default.
    try {
        req.setCharacterEncoding(Configuration.getCharacterEncoding());

        //res.setCharacterEncoding(Configuration.getCharacterEncoding());
        res.setContentType("text/html; charset=\"" + Configuration.getCharacterEncoding() + "\"");
        setNoCache(res);

        // Debug
        log.debug("req.getContentType(): " + req.getContentType());
        log.debug("Request Charactor Encoding:" + req.getCharacterEncoding());
    } catch (java.io.UnsupportedEncodingException e) {
        log.error("Error setting Character Encoding. Check Configuration", e);
    }

    try {
        //Retrieve the model for this web app
        GinpModel model = ModelUtil.getModel(req);

        //This controller modifies the model via commands
        executeCommand(req, model);

        // The updated model is now available in the request,
        // go to the view page
        String url = model.getCurrentPage();

        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("doHttpMethod url=" + url + " " + model.getDebugInfo());
        }

        // Forward to New URL
        forwardToPage(req, res, url);

        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("DONE");
        }
    } catch (Exception ex) {
        log.error("doHttpMethod", ex);
        handleError(req, res, ex);
    }
}

From source file:org.geoserver.filters.LoggingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    String message = "";
    String body = null;/*from w  w  w  .java 2 s .c o  m*/
    String path = "";

    if (enabled) {
        if (req instanceof HttpServletRequest) {
            HttpServletRequest hreq = (HttpServletRequest) req;

            path = hreq.getRemoteHost() + " \"" + hreq.getMethod() + " " + hreq.getRequestURI();
            if (hreq.getQueryString() != null) {
                path += "?" + hreq.getQueryString();
            }
            path += "\"";

            message = "" + path;
            message += " \"" + noNull(hreq.getHeader("User-Agent"));
            message += "\" \"" + noNull(hreq.getHeader("Referer")) + "\" ";
            message += "\" \"" + noNull(hreq.getHeader("Content-type")) + "\" ";

            if (logBodies && (hreq.getMethod().equals("PUT") || hreq.getMethod().equals("POST"))) {
                message += " request-size: " + hreq.getContentLength();
                message += " body: ";

                String encoding = hreq.getCharacterEncoding();
                if (encoding == null) {
                    // the default encoding for HTTP 1.1
                    encoding = "ISO-8859-1";
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes;
                try (InputStream is = hreq.getInputStream()) {
                    IOUtils.copy(is, bos);
                    bytes = bos.toByteArray();

                    body = new String(bytes, encoding);
                }

                req = new BufferedRequestWrapper(hreq, encoding, bytes);
            }
        } else {
            message = "" + req.getRemoteHost() + " made a non-HTTP request";
        }

        logger.info(message + (body == null ? "" : "\n" + body + "\n"));
        long startTime = System.currentTimeMillis();
        chain.doFilter(req, res);
        long requestTime = System.currentTimeMillis() - startTime;
        logger.info(path + " took " + requestTime + "ms");
    } else {
        chain.doFilter(req, res);
    }

}

From source file:org.geowebcache.proxy.ProxyDispatcher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String methStr = request.getMethod();
    if (!methStr.equalsIgnoreCase("POST")) {
        throw new ServletException("Illegal method " + methStr + " for this proxy.");
    }/* w  w w . j a  v  a 2  s  . c o  m*/

    String urlStr = request.getParameter("url");
    if (urlStr == null || urlStr.length() == 0 || !urlStr.startsWith("http://")) {
        throw new ServletException("Expected url parameter.");
    }

    synchronized (this) {
        long time = System.currentTimeMillis();
        if (time - lastRequest < 1000) {
            throw new ServletException("Only one request per second please.");
        } else {
            lastRequest = time;
        }
    }

    log.info("Proxying request for " + request.getRemoteAddr() + " to " + " " + urlStr);

    String charEnc = request.getCharacterEncoding();
    if (charEnc == null) {
        charEnc = "UTF-8";
    }
    String decodedUrl = URLDecoder.decode(urlStr, charEnc);

    URL url = new URL(decodedUrl);
    HttpURLConnection wmsBackendCon = (HttpURLConnection) url.openConnection();

    if (wmsBackendCon.getContentEncoding() != null) {
        response.setCharacterEncoding(wmsBackendCon.getContentEncoding());
    }

    response.setContentType(wmsBackendCon.getContentType());

    int read = 0;
    byte[] data = new byte[1024];
    while (read > -1) {
        read = wmsBackendCon.getInputStream().read(data);
        if (read > -1) {
            response.getOutputStream().write(data, 0, read);
        }
    }

    return null;
}

From source file:org.geowebcache.service.wms.WMSTileFuser.java

protected WMSTileFuser(TileLayerDispatcher tld, StorageBroker sb, HttpServletRequest servReq)
        throws GeoWebCacheException {
    this.sb = sb;

    String[] keys = { "layers", "format", "srs", "bbox", "width", "height", "transparent", "bgcolor", "hints" };

    Map<String, String> values = ServletUtils.selectedStringsFromMap(servReq.getParameterMap(),
            servReq.getCharacterEncoding(), keys);

    // TODO Parameter filters?

    String layerName = values.get("layers");
    layer = tld.getTileLayer(layerName);

    gridSubset = layer.getGridSubsetForSRS(SRS.getSRS(values.get("srs")));

    outputFormat = (ImageMime) ImageMime.createFromFormat(values.get("format"));

    List<MimeType> ml = layer.getMimeTypes();
    Iterator<MimeType> iter = ml.iterator();

    ImageMime firstMt = null;//from  ww w .  j  a v a2s .  c o m

    if (iter.hasNext()) {
        firstMt = (ImageMime) iter.next();
    }
    boolean outputGif = outputFormat.getInternalName().equalsIgnoreCase("gif");
    while (iter.hasNext()) {
        MimeType mt = iter.next();
        if (outputGif) {
            if (mt.getInternalName().equalsIgnoreCase("gif")) {
                this.srcFormat = (ImageMime) mt;
                break;
            }
        }
        if (mt.getInternalName().equalsIgnoreCase("png")) {
            this.srcFormat = (ImageMime) mt;
        }
    }

    if (srcFormat == null) {
        srcFormat = firstMt;
    }

    reqBounds = new BoundingBox(values.get("bbox"));

    reqWidth = Integer.valueOf(values.get("width"));

    reqHeight = Integer.valueOf(values.get("height"));

    fullParameters = layer.getModifiableParameters(servReq.getParameterMap(), servReq.getCharacterEncoding());
    if (values.get("hints") != null) {
        hints = HintsLevel.getHintsForMode(values.get("hints")).getRenderingHints();
    }
}