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.tern.web.MultiPartEnabledRequest.java

private void readHttpParams(HttpServletRequest req) throws FileUploadException {
    List all = uploadFiles(req);/*from w w w  .  j  av a 2 s . c o  m*/

    // read form fields
    for (Iterator it = all.iterator(); it.hasNext();) {
        FileItem item = (FileItem) it.next();

        if (item.isFormField()) {
            List valList = valueList(httpParams, item.getFieldName());
            if (req.getCharacterEncoding() != null) {
                try {
                    valList.add(item.getString(req.getCharacterEncoding()));
                } catch (UnsupportedEncodingException e) {
                    Trace.write(Trace.Error, e, "");
                    valList.add(item.getString(/*encoding?*/));
                }
            } else
                valList.add(item.getString(/*encoding?*/));
        } else {
            List valList = valueList(fileItems, item.getFieldName());
            valList.add(item);
        }
    }

    // convert lists of values to arrays
    for (Iterator it = httpParams.keySet().iterator(); it.hasNext();) {
        String name = (String) it.next();
        List valList = (List) httpParams.get(name);
        httpParams.put(name, toStringArray(valList));
    }

    for (Iterator it = fileItems.keySet().iterator(); it.hasNext();) {
        String name = (String) it.next();
        List valList = (List) fileItems.get(name);
        fileItems.put(name, toFileItemArray(valList));
    }
}

From source file:org.apache.tapestry.multipart.DefaultMultipartDecoder.java

/**
 * Decodes the request, storing the part map (keyed on query parameter name, 
 * value is {@link IPart} into the request as an attribute.
 * //from ww w .  j a  v  a 2 s  .  c  o  m
 * @throws ApplicationRuntimeException if decode fails, for instance the
 * request exceeds getMaxSize()
 * 
 **/

public void decode(HttpServletRequest request) {
    Map partMap = new HashMap();

    request.setAttribute(PART_MAP_ATTRIBUTE_NAME, partMap);

    // The encoding that will be used to decode the string parameters
    // It should NOT be null at this point, but it may be 
    // if the older Servlet API 2.2 is used
    String encoding = request.getCharacterEncoding();

    // DiskFileUpload is not quite threadsafe, so we create a new instance
    // for each request.

    DiskFileUpload upload = new DiskFileUpload();

    List parts = null;

    try {
        if (encoding != null)
            upload.setHeaderEncoding(encoding);
        parts = upload.parseRequest(request, _thresholdSize, _maxSize, _repositoryPath);
    } catch (FileUploadException ex) {
        throw new ApplicationRuntimeException(
                Tapestry.format("DefaultMultipartDecoder.unable-to-decode", ex.getMessage()), ex);
    }

    int count = Tapestry.size(parts);

    for (int i = 0; i < count; i++) {
        FileItem uploadItem = (FileItem) parts.get(i);

        if (uploadItem.isFormField()) {
            try {
                String name = uploadItem.getFieldName();
                String value;
                if (encoding == null)
                    value = uploadItem.getString();
                else
                    value = uploadItem.getString(encoding);

                ValuePart valuePart = (ValuePart) partMap.get(name);
                if (valuePart != null) {
                    valuePart.add(value);
                } else {
                    valuePart = new ValuePart(value);
                    partMap.put(name, valuePart);
                }
            } catch (UnsupportedEncodingException ex) {
                throw new ApplicationRuntimeException(Tapestry.format("illegal-encoding", encoding), ex);
            }
        } else {
            UploadPart uploadPart = new UploadPart(uploadItem);

            partMap.put(uploadItem.getFieldName(), uploadPart);
        }
    }

}

From source file:de.bermuda.arquillian.example.ContentTypeProxyServlet.java

private void copyRequestBody(HttpServletRequest req, PostMethod post) throws IOException {
    BufferedReader contentReader = req.getReader();
    StringBuilder content = new StringBuilder();
    String contentLine = "";
    while (contentLine != null) {
        content.append(contentLine);//  w  ww .ja  va  2s .co m
        contentLine = contentReader.readLine();
    }
    StringRequestEntity requestEntity = new StringRequestEntity(content.toString(), req.getContentType(),
            req.getCharacterEncoding());
    post.setRequestEntity(requestEntity);
    requestLogger.info("RequestBody: " + content);
}

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected ServletFileUpload createServletFileUpload(HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());/*from ww  w .j  a  va 2  s. c o m*/
    return upload;
}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    int length = req.getContentLength();
    String ctype = req.getContentType();
    String cenc = req.getCharacterEncoding();
    //    this.log("CLEN: " + length);
    this.log("CTYPE: " + ctype);
    this.log("CENC : " + cenc);
    String body = MiscUtil.readBody(req);
    this.log("BODY:\n" + body);
    long tsmillis = getServerTimestamp(req);

    String rspMsg = null;/*from  w ww.  j a  va 2  s. c  o  m*/
    try {
        JSONObject retval = new JSONObject();
        double serverTimestamp = MiscUtil.toWeaveTimestampDouble(tsmillis);
        retval.put("modified", serverTimestamp);
        JSONArray successArray = new JSONArray();
        JSONArray failedArray = new JSONArray();
        JSONArray clientsArray = new JSONArray(body);
        for (int ii = 0; ii < clientsArray.length(); ii++) {
            // todo catch exceptions in loop
            JSONObject clientObj = clientsArray.getJSONObject(ii);
            String nodeId = clientObj.getString("id");
            updateClient(req, tsmillis, clientObj);
            successArray.put(nodeId);
        }
        //      failedArray.put(nodeId);
        retval.put("success", successArray);
        retval.put("failed", failedArray);
        rspMsg = retval.toString();
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } catch (JSONException e) {
        log(e.getMessage(), e);
    }

    log("RESPONSE: " + rspMsg);
    if (rspMsg != null) {
        resp.setContentType("application/json");
        PrintWriter writer2 = resp.getWriter();
        writer2.append(rspMsg);
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = StringUtils.trimToNull(request.getContentType());
    String encoding = StringUtils.trimToNull(request.getCharacterEncoding());
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    Curator curator = loadCurator(request);

    if (mediaType != null && mediaType.indexOf(';') > 0) {
        mediaType = mediaType.substring(0, mediaType.indexOf(';'));
    }//from   w w w  .  j a  v  a 2 s.  c  om

    if (!StringUtils.equalsIgnoreCase(mediaType, MEDIA_TYPE_OBO)
            || !StringUtils.equalsIgnoreCase(encoding, "utf-8")) {
        log("Failed to import ontology: invalid media type or encoding " + mediaType + ";charset=" + encoding);
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    } else if (pathInfo == null || pathInfo.length() <= 1) {
        log("Failed to import ontology: ontology name not include in path");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else if (curator == null) {
        log("Failed to import ontology: curator not found in request");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } else {
        try {
            String ontologyName = pathInfo.substring(1);
            importService.importOntology(ontologyName, request.getInputStream(), curator);
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "public, max-age=0");
        } catch (DuplicateEntityException e) {
            log("Failed to import ontology: duplicate term", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidEntityException e) {
            log("Failed to import ontology: invalid entity", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidFormatException e) {
            log("Failed to import ontology: invalid format", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            log("Failed to import ontology: system error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setContentLength(0);
}

From source file:org.codelibs.fess.mylasta.direction.sponsor.FessMultipartRequestHandler.java

protected ServletFileUpload createServletFileUpload(final HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());//from  ww  w  .  j ava 2s . c o  m
    return upload;
}

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

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
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());//from   ww  w .j  av  a  2s.  co  m
}

From source file:org.jolokia.http.AgentServlet.java

private ServletRequestHandler newPostHttpRequestHandler() {
    return new ServletRequestHandler() {
        /** {@inheritDoc} */
        public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
            String encoding = pReq.getCharacterEncoding();
            InputStream is = pReq.getInputStream();
            return requestHandler.handlePostRequest(pReq.getRequestURI(), is, encoding, getParameterMap(pReq));
        }/* w w w  .j  ava 2  s. co m*/
    };
}

From source file:org.cerberus.servlet.crud.usermanagement.UpdateMyUserReporting1.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject jsonResponse = new JSONObject();

    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);

    String login = request.getUserPrincipal().getName();
    String charset = request.getCharacterEncoding();
    /**// w  w w  . j  a v a  2  s . c  om
     * Parse parameters - list of values
     */
    List<String> tcstatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcstatus"), null, charset);
    List<String> groupList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("group"),
            null, charset);
    List<String> tcactiveList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcactive"), null, charset);
    List<String> priorityList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("priority"), null, charset);

    List<String> countryList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("country"), null, charset);
    List<String> browserList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("browser"), null, charset);
    List<String> tcestatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcestatus"), null, charset);

    //environment
    List<String> environmentList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("environment"), null, charset);
    List<String> projectList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("project"), null, charset);
    /**
     * Parse parameters - free text
     */
    String ip = StringEscapeUtils.escapeHtml4(request.getParameter("ip"));
    String port = StringEscapeUtils.escapeHtml4(request.getParameter("port"));
    String tag = StringEscapeUtils.escapeHtml4(request.getParameter("tag"));
    String browserversion = StringEscapeUtils.escapeHtml4(request.getParameter("browserversion"));
    String comment = StringEscapeUtils.escapeHtml4(request.getParameter("comment"));

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);

    try {
        User user = userService.findUserByKey(login);
        if (user != null) {
            JSONObject preferences = new JSONObject();

            if (tcstatusList != null) {
                preferences.put("s", tcstatusList);
            }
            if (groupList != null) {
                preferences.put("g", groupList);
            }
            if (tcactiveList != null) {
                preferences.put("a", tcactiveList);
            }
            if (priorityList != null) {
                preferences.put("pr", priorityList);
            }
            if (countryList != null) {
                preferences.put("co", countryList);
            }
            if (browserList != null) {
                preferences.put("b", browserList);
            }
            if (tcestatusList != null) {
                preferences.put("es", tcestatusList);
            }
            if (environmentList != null) {
                preferences.put("e", environmentList);
            }
            if (projectList != null) {
                preferences.put("prj", projectList);
            }

            if (!StringUtil.isNullOrEmpty(ip)) {
                preferences.put("ip", ip);
            }
            if (!StringUtil.isNullOrEmpty(port)) {
                preferences.put("p", port);
            }
            if (!StringUtil.isNullOrEmpty(tag)) {
                preferences.put("t", tag);
            }
            if (!StringUtil.isNullOrEmpty(browserversion)) {
                preferences.put("br", browserversion);
            }
            if (!StringUtil.isNullOrEmpty(comment)) {
                preferences.put("cm", comment);
            }

            user.setReportingFavorite(preferences.toString());
            userService.updateUser(user); //TODO: when converting to the new standard this should return an answer
            //re-send the updated preferences 

            jsonResponse.put("preferences", preferences);

            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution reporting filters ")
                    .replace("%OPERATION%", "Update"));

            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createPrivateCalls("/UpdateMyUserReporting1", "UPDATE",
                    "Update user reporting preference for user: " + login, request);
        } else {
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to update User was not found!"));
        }

        jsonResponse.put("messageType", msg.getMessage().getCodeString());
        jsonResponse.put("message", msg.getDescription());
    } catch (JSONException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    } catch (CerberusException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}