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:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req) throws IOException {
    String contentType = StringUtils.substringBefore(req.getContentType(), ";");
    if ("application/json".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        LwM2mNode node;/*from w  ww . j  a v  a  2  s.  c  o  m*/
        try {
            node = gson.fromJson(content, LwM2mNode.class);
        } catch (JsonSyntaxException e) {
            throw new InvalidRequestException("unable to parse json to tlv:" + e.getMessage(), e);
        }
        return node;
    } else if ("text/plain".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1));
        return LwM2mSingleResource.newStringResource(rscId, content);
    }
    throw new InvalidRequestException("content type " + req.getContentType() + " not supported");
}

From source file:org.araneaframework.servlet.filter.StandardServletFileUploadFilterService.java

protected void action(Path path, InputData input, OutputData output) throws Exception {
    HttpServletRequest request = ((ServletInputData) input).getRequest();

    if (FileUpload.isMultipartContent(request)) {
        Map fileItems = new HashMap();
        Map parameterLists = new HashMap();

        // Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();

        if (useRequestEncoding)
            upload.setHeaderEncoding(request.getCharacterEncoding());
        else if (multipartEncoding != null)
            upload.setHeaderEncoding(multipartEncoding);

        // Set upload parameters
        if (maximumCachedSize != null)
            upload.setSizeThreshold(maximumCachedSize.intValue());
        if (maximumSize != null)
            upload.setSizeMax(maximumSize.longValue());
        if (tempDirectory != null)
            upload.setRepositoryPath(tempDirectory);

        // Parse the request
        List items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileItems.put(item.getFieldName(), item);
            } else {
                List parameterValues = (List) parameterLists.get(item.getFieldName());

                if (parameterValues == null) {
                    parameterValues = new ArrayList();
                    parameterLists.put(item.getFieldName(), parameterValues);
                }//from  w  w w . ja v a2  s. co m

                parameterValues.add(item.getString());
            }
        }

        log.debug("Parsed multipart request, found '" + fileItems.size() + "' file items and '"
                + parameterLists.size() + "' request parameters");

        output.extend(ServletFileUploadInputExtension.class,
                new StandardServletFileUploadInputExtension(fileItems));

        request = new MultipartWrapper(request, parameterLists);
        ((ServletOverridableInputData) input).setRequest(request);
    }

    super.action(path, input, output);
}

From source file:com.google.nigori.server.NigoriServlet.java

private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException {

    if (maxLength != 0 && req.getContentLength() > maxLength) {
        return null;
    }/*from   w  w  w . j  ava  2  s  .  c om*/

    String charsetName = req.getCharacterEncoding();
    if (charsetName == null) {
        charsetName = MessageLibrary.CHARSET;
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName));
        StringBuilder json = new StringBuilder();
        char[] buffer = new char[64 * 1024];
        int charsRemaining = maxJsonQueryLength;
        int charsRead;
        while ((charsRead = in.read(buffer)) != -1) {
            charsRemaining -= charsRead;
            if (charsRemaining < 0) {
                throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Json request exceeds server maximum length of " + maxLength);
            }
            json.append(buffer, 0, charsRead);
        }
        return json.toString();
    } catch (IOException ioe) {
        throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal error receiving data from client.");
    }
}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }// w  ww .  java 2s .c om

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String usernamePassword = new String(decoded,
            Objects.firstNonNull(request.getCharacterEncoding(), "UTF-8"));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}

From source file:yoyo.framework.screen.iface.jsf.UploadRenderer.java

/**
 * ???/*from ww  w. j av a 2  s.  c  o  m*/
 * @param request HTTP?
 * @param item FILE
 * @param valueType 
 * @return ?
 * @throws FacesException ?
 */
@SuppressWarnings("static-method")
private Object findSubmittedValue(final HttpServletRequest request, final FileItem item,
        final Class<?> valueType) throws FacesException {
    Object newValue;
    if (valueType == byte[].class) {
        newValue = item.get();
    } else if (valueType == InputStream.class) {
        try {
            newValue = item.getInputStream();
        } catch (final IOException ex) {
            throw new FacesException(ex);
        }
    } else {
        final String encoding = request.getCharacterEncoding();
        if (encoding != null) {
            try {
                newValue = item.getString(encoding);
            } catch (final UnsupportedEncodingException ex) {
                newValue = item.getString();
            }
        } else {
            newValue = item.getString();
        }
    }
    return newValue;
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//  w  w w  . ja v  a2s.  co  m
}

From source file:org.seasar.struts.upload.S2MultipartRequestHandler.java

@SuppressWarnings("unchecked")
@Override/*from   www . j  a  v a2 s  .  c  om*/
public void handleRequest(HttpServletRequest request) throws ServletException {
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
    ServletFileUpload upload = new ServletFileUpload(
            new DiskFileItemFactory((int) getSizeThreshold(ac), new File(getRepositoryPath(ac))));
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax(ac));
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (SizeLimitExceededException e) {
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        request.setAttribute(SIZE_EXCEPTION_KEY, e);
        try {
            InputStream is = request.getInputStream();
            try {
                byte[] buf = new byte[1024];
                @SuppressWarnings("unused")
                int len = 0;
                while ((len = is.read(buf)) != -1) {
                }
            } catch (Exception ignore) {
            } finally {
                try {
                    is.close();
                } catch (Exception ignore) {
                }
            }
        } catch (Exception ignore) {
        }
        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);
        }
    }
}

From source file:org.brutusin.rpc.http.RpcServlet.java

/**
 *
 * @param req//from   w w w .  java2 s  .  co m
 * @return
 * @throws IOException
 */
private static Map<String, String[]> parseMultipartParameters(HttpServletRequest req) throws IOException {
    if (isMultipartContent(req)) {
        Map<String, String[]> multipartParameters = new HashMap();
        Map<String, List<String>> map = new HashMap();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            req.setAttribute(REQ_ATT_MULTIPART_ITERATOR, iter);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
                    break;
                }
                List<String> list = map.get(item.getFieldName());
                if (list == null) {
                    list = new ArrayList();
                    map.put(item.getFieldName(), list);
                }
                String encoding = req.getCharacterEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                list.add(Miscellaneous.toString(item.openStream(), encoding));
            }
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        }
        for (Map.Entry<String, List<String>> entrySet : map.entrySet()) {
            String key = entrySet.getKey();
            List<String> value = entrySet.getValue();
            multipartParameters.put(key, value.toArray(new String[value.size()]));
        }
        return multipartParameters;
    }
    return null;
}

From source file:org.brekka.paveway.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    UploadingFilesContext filesContext = getFilesContext(req);

    String fileName = null;//  w  ww .j av  a2 s.com
    String contentDispositionStr = req.getHeader(ContentDisposition.HEADER);
    if (contentDispositionStr != null) {
        String encoding = req.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        ContentDisposition contentDisposition = ContentDisposition.valueOf(contentDispositionStr, encoding);
        fileName = contentDisposition.getFilename();
    }
    String accept = req.getHeader("Accept");
    String contentType = req.getHeader("Content-Type");
    String contentLengthStr = req.getHeader("Content-Length");
    String contentRangeStr = req.getHeader(ContentRange.HEADER);

    FileItemFactory factory;
    try {
        if (contentType.equals("multipart/form-data")) {
            if (fileName == null) {
                // Handles a standard file upload
                factory = new EncryptedFileItemFactory(0, null, getPavewayService(), filesContext.getPolicy());
                handle(factory, filesContext, req, resp);
            } else {
                throw new UnsupportedOperationException("This mode is no longer supported");
            }
        } else {
            ContentRange contentRange;
            if (contentRangeStr == null && contentLengthStr == null) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content-Range or Content-Length must be specified");
                return;
            } else if (contentRangeStr != null) {
                contentRange = ContentRange.valueOf(contentRangeStr);
            } else if (contentLengthStr != null) {
                Long contentLength = Long.valueOf(contentLengthStr);
                contentRange = new ContentRange(0, contentLength.longValue() - 1, contentLength.longValue());
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Only one of Content-Range or Content-Length must be specified");
                return;
            }
            UUID id = processUpload(fileName, contentRange, contentType, req);
            if (accept != null && accept.contains("application/json")) {
                resp.setContentType("application/json");
                resp.getWriter().printf("{\"id\": \"%s\"}", id);
            }
        }
    } catch (PavewayException e) {
        switch ((PavewayErrorCode) e.getErrorCode()) {
        case PW700:
            resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
            return;
        case PW701:
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        default:
            throw e;
        }
    } catch (FileUploadException e) {
        throw new PavewayException(PavewayErrorCode.PW800, e, "");
    }

    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.atricore.idbus.kernel.main.mediation.camel.component.logging.HttpLogMessageBuilder.java

public String buildLogMessage(Message message) {

    HttpExchange httpEx = (HttpExchange) message.getExchange();

    if (message instanceof HttpMessage) {

        HttpServletRequest hreq = httpEx.getRequest();

        StringBuffer logMsg = new StringBuffer(1024);

        logMsg.append("<http-request method=\"").append(hreq.getMethod()).append("\"").append("\n\t url=\"")
                .append(hreq.getRequestURL()).append("\"").append("\n\t content-type=\"")
                .append(hreq.getContentType()).append("\"").append("\n\t content-length=\"")
                .append(hreq.getContentLength()).append("\"").append("\n\t content-encoding=\"")
                .append(hreq.getCharacterEncoding()).append("\"").append(">");

        Enumeration headerNames = hreq.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration headers = hreq.getHeaders(headerName);

            logMsg.append("\n\t<header name=\"").append(headerName).append("\">");

            while (headers.hasMoreElements()) {
                String headerValue = (String) headers.nextElement();
                logMsg.append("\n\t\t<header-value>").append(headerValue).append("</header-value>");
            }// w  w w.j  a  v  a2  s  .c o m

            logMsg.append("\n\t</header>");

        }

        Enumeration params = hreq.getParameterNames();
        while (params.hasMoreElements()) {
            String param = (String) params.nextElement();
            logMsg.append("\n\t<parameter name=\"").append(param).append("\">");
            logMsg.append("\n\t\t\t<value>").append(hreq.getParameter(param)).append("</value>");
            logMsg.append("\n\t</parameter>");
        }

        logMsg.append("\n</http-request>");

        return logMsg.toString();
    } else {
        StringBuffer logMsg = new StringBuffer(1024);
        logMsg.append("\t<http-response />");
        return logMsg.toString();
    }
}