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:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Add the <code>FileItem</code> as a paramter into the <code>MultipartForm</code>.
 *///from  www .j  ava2s  .  c  o  m
private void addField(HttpServletRequest request, FileItem item, MultipartForm form) {
    String name = item.getFieldName();

    String value;
    try {
        String encoding = StringUtils.defaultString(request.getCharacterEncoding(), "UTF-8");
        value = item.getString(encoding);
    } catch (UnsupportedEncodingException ex) {
        value = item.getString();
    }
    form.addParameter(name, value);

    String[] values = request.getParameterValues(name);
    if (values != null) {
        form.addparameterValues(name, values);
    }
}

From source file:jetbrick.web.mvc.multipart.CommonsFileUpload.java

@Override
public MultipartRequest transform(HttpServletRequest request) throws IOException {
    String contextType = request.getHeader("Content-Type");
    if (contextType == null || !contextType.startsWith("multipart/form-data")) {
        return null;
    }//ww w. ja va  2s. c om

    String encoding = request.getCharacterEncoding();

    MultipartRequest req = new MultipartRequest(request);
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(encoding);

    try {
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String fieldName = item.getFieldName();
            InputStream stream = item.openStream();
            try {
                if (item.isFormField()) {
                    req.setParameter(fieldName, Streams.asString(stream, encoding));
                } else {
                    String originalFilename = item.getName();
                    if (originalFilename == null || originalFilename.length() == 0) {
                        continue;
                    }
                    File diskFile = UploadUtils.getUniqueTemporaryFile(originalFilename);
                    OutputStream fos = new FileOutputStream(diskFile);

                    try {
                        IoUtils.copy(stream, fos);
                    } finally {
                        IoUtils.closeQuietly(fos);
                    }

                    FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
                    req.addFile(filePart);
                }
            } finally {
                IoUtils.closeQuietly(stream);
            }
        }
    } catch (FileUploadException e) {
        throw new IllegalStateException(e);
    }

    return req;
}

From source file:de.jaxenter.eesummit.caroline.gui.filter.LogFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String remoteAddress = null;/*from w  w  w  .  j  a v  a  2s.  co  m*/
    String sessionId = null;
    String uid = "0";

    long start = 0;
    String url = "";
    String method = "";
    Throwable throwable = null;
    boolean dropped = false;
    String agent = null;
    try {
        Validate.isTrue(request instanceof HttpServletRequest, "filter oops?");
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getCharacterEncoding() == null || forceRequestEncoding) {
            req.setCharacterEncoding(requestEncoding);
        }

        url = req.getRequestURI();
        method = req.getMethod();
        String qs = req.getQueryString();
        agent = req.getHeader("User-Agent");
        if (qs != null) {
            url += "?" + qs;
        }

        for (String stopUrl : dropUrls) { // does any stopUrl match url
            if (url.indexOf(stopUrl) != -1) {
                dropped = true;
                break; // stop searching
            }
        }

        if (!dropped) {
            if (ndcEnabled) {
                if (ndcAddress) {
                    String forwarded = req.getHeader("X-Forwarded-For");
                    if (forwarded != null) {
                        remoteAddress = forwarded;
                    } else {
                        remoteAddress = request.getRemoteAddr();
                    }
                }
                if (ndcSession) {
                    HttpSession session = req.getSession(false); // do not create
                    if (session != null) {
                        sessionId = session.getId();
                        String sessOID = (String) session.getAttribute("USER_ID_LOG");
                        uid = sessOID == null ? "0" : sessOID;
                    }
                }
            }
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request start ").append(method).append(" ").append(url).append(" UA=").append(agent);
            logger.info(msg.toString());
            start = System.currentTimeMillis();
        }

        filterChain.doFilter(request, response);
    } catch (IOException e) {
        throwable = e;
        throw e;
    } catch (ServletException e) {
        if (e.getRootCause() != null) {
            throwable = e.getRootCause();
        } else {
            throwable = e;
        }
        throw e;
    } catch (Throwable e) { // be sure to get all errors
        throwable = e;
        throw new ServletException(e);
    } finally {
        if (!dropped) {
            long time = System.currentTimeMillis() - start;
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request done ").append(method).append(" ");
            msg.append(url).append(" time=").append(time).append("ms");

            if (throwable == null) {
                logger.info(msg.toString());
            } else {
                String name = throwable.getClass().getSimpleName();
                msg.append(" ex=").append(name);
                msg.append(" msg=").append(throwable.getMessage());
                if (name.equals("ViewExpiredException") || name.equals("ClientAbortException")) {
                    logger.warn(msg.toString());
                } else {
                    msg.append(" UA=").append(agent); // also log agent in error case
                    logger.error(msg.toString());
                }
            }
        }
    }
}

From source file:com.eternity.common.communication.servlet.SyncDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;/* w ww .  j  av a2 s .c  o  m*/

    if (charset == null) {
        charset = "UTF-8";
    }

    contentType += ";" + charset;

    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        log.warn("Received request with invalid content type of: {} (derived: {})", req.getContentType(),
                contentType);
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim() + ";" + charset);
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.println("{\"status\": 400, \"errors\": [\"Unacceptable or missing ACCEPT header!\"]}");
        log.warn(
                "Cannot return data in formats: {}  - if you think this is wrong please check character encodings.",
                acceptsHeader);
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    if (message.subsystemName == null) {
        message.subsystemName = req.getRequestURL().toString().replaceFirst(".*/([^/?]+).*", "$1");
    }
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    Response result = MessageConsumer.dispatchMessage(message, null, hostName);
    resp.setStatus(result.getStatus());
    resp.getOutputStream().write(result.data.array());
}

From source file:de.ifgi.mosia.wpswfs.BaseServlet.java

@Override
protected void doPost(final HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    RequestHandler handler;//  w ww  . j a v a 2 s  .  c  om
    String payload;
    String enc;
    try {
        enc = req.getCharacterEncoding();

        if (enc == null || enc.isEmpty()) {
            enc = CharEncoding.ISO_8859_1;
        }

        payload = Util.readContent(req.getInputStream(), enc);
        handler = resolveHandlerFromPost(payload);
    } catch (ServiceException e) {
        throw new RuntimeException(e);
    }

    if (handler == null) {
        handler = genericHandler;
    }

    try {
        handler.handlePostRequest(req, resp, payload, enc);
    } catch (ServiceException e) {
        throw new IOException(e);
    }
}

From source file:com.mawujun.util.web.UrlPathHelper.java

/**
 * Determine the encoding for the given request.
 * Can be overridden in subclasses./*from   w  w w.  ja  va2s.  co  m*/
 * <p>The default implementation checks the request encoding,
 * falling back to the default encoding specified for this resolver.
 * @param request current HTTP request
 * @return the encoding for the request (never <code>null</code>)
 * @see javax.servlet.ServletRequest#getCharacterEncoding()
 * @see #setDefaultEncoding
 */
protected String determineEncoding(HttpServletRequest request) {
    String enc = request.getCharacterEncoding();
    if (enc == null) {
        enc = getDefaultEncoding();
    }
    return enc;
}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

private Object createPayloadFromTextContent(HttpServletRequest request) throws IOException {
    String charset = request.getCharacterEncoding() != null ? request.getCharacterEncoding() : "utf-8";
    return new String(FileCopyUtils.copyToByteArray(request.getInputStream()), charset);
}

From source file:com.bluexml.side.Framework.alfresco.shareLanguagePicker.CustomWebScriptServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Processing request (" + req.getMethod() + ") " + req.getRequestURL()
                + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
    }/*from   w ww .j  a va  2  s  . c  o  m*/

    if (req.getCharacterEncoding() == null) {
        req.setCharacterEncoding("UTF-8");
    }
    // initialize the request context
    RequestContext context = null;
    try {
        context = FrameworkHelper.initRequestContext(req);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    LanguageSetter.setLanguageFromLayoutParam(req, context);

    WebScriptServletRuntime runtime = new WebScriptServletRuntime(container, authenticatorFactory, req, res,
            serverProperties);
    runtime.executeScript();
}

From source file:com.jd.survey.web.security.AccountController.java

/**
 * helper function for encoding paths //ww w  . j a  va  2s .  co  m
 * @param pathSegment
 * @param httpServletRequest
 * @return
 */
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
    log.info("encodeUrlPathSegment()");
    try {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
            log.error(uee);
        }
        return pathSegment;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.apache.shindig.gadgets.servlet.MakeRequestHandler.java

/**
 * Set http request post data according to servlet request.
 * It uses header encoding if available, and defaulted to utf8
 * Override the function if different behavior is needed.
 *//*from   w  ww  . j  av a 2s.  c  o  m*/
protected void setPostData(HttpServletRequest request, HttpRequest req) throws GadgetException {
    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }
    try {
        req.setPostBody(getParameter(request, POST_DATA_PARAM, "").getBytes(encoding.toUpperCase()));
    } catch (UnsupportedEncodingException e) {
        // We might consider enumerating at least a small list of encodings
        // that we must always honor. For now, we return SC_BAD_REQUEST since
        // the encoding parameter could theoretically be anything.
        throw new GadgetException(Code.HTML_PARSE_ERROR, e, HttpResponse.SC_BAD_REQUEST);
    }
}