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.jessma.util.http.FileUploader.java

/** 
 * //  ww  w . ja va 2s .  com
 * @param request   : {@link HttpServletRequest} 
 * @param response   : {@link HttpServletResponse} 
 * 
 * @return         : ? {@link Result#SUCCESS} 
 *                      {@link FileUploader#getCause()} ?
 * 
 */
public Result upload(HttpServletRequest request, HttpServletResponse response) {
    reset();

    String absolutePath = getAbsoluteSavePath(request);
    if (absolutePath == null) {
        cause = new FileNotFoundException(String.format("path '%s' not found or is not directory", savePath));
        return Result.INVALID_SAVE_PATH;
    }

    ServletFileUpload sfu = getFileUploadComponent();
    List<FileItemInfo> fiis = new ArrayList<FileItemInfo>();

    List<FileItem> items = null;
    Result result = Result.SUCCESS;

    String encoding = servletHeaderencoding != null ? servletHeaderencoding : request.getCharacterEncoding();
    FileNameGenerator fnGenerator = fileNameGenerator != null ? fileNameGenerator : DEFAULT_FILE_NAME_GENERATOR;

    try {
        items = (List<FileItem>) sfu.parseRequest(request);
    } catch (FileUploadException e) {
        cause = e;

        if (e instanceof FileSizeLimitExceededException)
            result = Result.FILE_SIZE_EXCEEDED;
        else if (e instanceof SizeLimitExceededException)
            result = Result.SIZE_EXCEEDED;
        else if (e instanceof InvalidContentTypeException)
            result = Result.INVALID_CONTENT_TYPE;
        else if (e instanceof IOFileUploadException)
            result = Result.FILE_UPLOAD_IO_EXCEPTION;
        else
            result = Result.OTHER_PARSE_REQUEST_EXCEPTION;
    }

    if (result == Result.SUCCESS) {
        result = parseFileItems(items, fnGenerator, absolutePath, encoding, fiis);
        if (result == Result.SUCCESS)
            result = writeFiles(fiis);
    }

    return result;
}

From source file:org.ow2.petals.binding.restproxy.in.AbstractRESTService.java

/**
 * @param path/*from   w  w  w  .j  av a2  s  .  c om*/
 * @param request
 * @return
 */
private Map<String, Object> createProperties(final String path, final HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();

    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_URL, path);

    Enumeration<?> headers = request.getHeaderNames();
    if (headers != null) {
        while (headers.hasMoreElements()) {
            Object object = headers.nextElement();
            String key = object.toString();
            result.put(org.ow2.petals.messaging.framework.message.Constants.HEADER + "." + key,
                    request.getHeader(key));
        }
    }

    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_LENGTH, request.getContentLength());
    String contentType = HTTPUtils.getContentType(request.getContentType());
    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_TYPE, contentType);
    final String charsetEncoding = request.getCharacterEncoding();
    result.put(org.ow2.petals.messaging.framework.message.Constants.CHARSET_ENCODING, charsetEncoding);
    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_METHOD, request.getMethod());

    // get form data which is not XML!
    Enumeration<?> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String paramName = (String) e.nextElement();
        String[] values = request.getParameterValues(paramName.toString());
        int i = 0;
        for (String string : values) {
            result.put(org.ow2.petals.messaging.framework.message.Constants.PARAMETERS + "." + (i++) + "."
                    + paramName, string);
        }
    }

    for (String key : result.keySet()) {
        this.logger.debug("From HTTPRequest : Property '" + key + "' = '" + result.get(key) + "'");
    }
    return result;
}

From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    assert request != null;
    assert response != null;

    NDC.push("rid=" + Long.toString(getUniqueRequestId()));
    try {//from  w w  w .j ava  2 s  . com
        Timer timer = new Timer();
        try {
            attachThreadLocalData(request, response);
            try {
                if (logger.isTraceEnabled()) {
                    String requestInfo = ServletUtils.getDetailedRequestInformation(request);
                    logger.trace("Request info: " + requestInfo);
                }

                String requestEncoding = request.getCharacterEncoding();
                // If we don't know what the request encoding is, assume it to be UTF-8
                if (StringUtils.isEmpty(requestEncoding)) {
                    request.setCharacterEncoding(EncodingUtils.UTF8);
                }
                response.setCharacterEncoding(EncodingUtils.UTF8);

                RequestType type = getFromRequestContentType(request);
                processRequest(request, response, type);
            } finally {
                detachThreadLocalData();
            }
        } finally {
            timer.stop();
            timer.logDebugTimeInMilliseconds("Total servlet processing time");
        }

    } finally {
        NDC.pop();
    }
}

From source file:temporal.web.DemoServlet.java

void generateOutput(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    InputStream in = null;/*from www .  j av  a2s. c o  m*/
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {
            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {
            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            FileItemIterator it = uploader.getItemIterator(request);
            /*  @SuppressWarnings("unchecked") // bad commons API
            /*  List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
              Iterator<FileItem> it = items.iterator();*/
            while (it.hasNext()) {
                log("found item");
                FileItemStream item = it.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    //   String val = item.getString();
                    String val = org.apache.commons.fileupload.util.Streams.asString(stream);
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = org.apache.commons.fileupload.util.Streams.asString(stream).getBytes();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/*w ww  .j a  va 2 s  .c  o m*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:com.aliasi.demo.framework.DemoServlet.java

void generateOutput(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    InputStream in = null;//  ww w. jav  a 2s. com
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {

            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {

            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked") // bad commons API
            List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                log("found item");
                FileItem item = it.next();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    String val = item.getString();
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = item.get();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:org.compiere.mobile.WWindow.java

/**
 *    Update Field Values from Parameter
 *   @param request request//from  ww w  .j  a v  a2s. c o  m
 *   @param wsc session context
 *   @param ws window status
 *   @return true if error
 */
private boolean updateFields(HttpServletRequest request, MobileSessionCtx wsc, WWindowStatus ws) {
    boolean error = false;
    try {
        String enc = request.getCharacterEncoding();
        if (enc == null)
            request.setCharacterEncoding(MobileEnv.ENCODING);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Set CharacterEncoding=" + MobileEnv.ENCODING, e);
    }
    //  loop through parameters
    Enumeration en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        //  ignore hidden commands
        if (key.equals(P_Command) || key.equals(P_ChangedColumn) || key.equals(P_MR_RowNo) || key.equals(P_Tab))
            continue;
        GridField mField = ws.curTab.getField(key);
        //   log.fine("executeSave - Key=" + key + " - " + mField);
        //  we found a writable field
        if (mField != null && mField.isEditable(true)) {
            String oldValue = MobileUtil.getParameter(request, key);
            String newValue = MobileUtil.getParameter(request, key + "F");
            String value = null;
            if (newValue != null) {
                Object val = lookupValue(newValue, mField.getLookup());
                if (val != null)
                    value = val.toString();
            }
            if (value == null)
                value = oldValue;

            Object dbValue = mField.getValue();
            boolean fieldError = false;
            String columnName = mField.getColumnName();
            log.finest(columnName + ": " + (dbValue == null ? "null" : dbValue.toString()) + " -> "
                    + (value == null ? "null" : value.toString()));
            //  same = both null
            if (dbValue == null && value == null)
                continue;
            //   new value null
            else if (dbValue != null && value == null)
                ws.curTab.setValue(mField, null);
            //  from null to new value
            else if (dbValue == null && value != null)
                fieldError = !setFieldValue(wsc, ws, mField, value);
            //  same
            else if (dbValue.equals(value))
                continue;
            else
                fieldError = !setFieldValue(wsc, ws, mField, value);
            //
            if (!error && fieldError) {
                log.info("Error: " + mField.getColumnName());
                error = true;
            }
        }
    } //  for all parameters

    //   Re-Do Changed Column to overwrite
    /*String columnName = WebUtil.getParameter (request, P_ChangedColumn);
    if (columnName != null && columnName.length() > 0)
    {
       GridField mField = ws.curTab.getField(columnName);
       if (mField != null)
       {
    String value = WebUtil.getParameter(request, columnName);
    Object newValue = getFieldValue (wsc, mField, value);
    if (!ERROR.equals(newValue))
    {
       //   De-Selected Check Boxes are null 
       if (newValue == null && mField.getDisplayType() == DisplayType.YesNo)
          newValue = "N";
       log.fine("ChangedColumn: " + columnName + "=" + newValue);
       ws.curTab.setValue(mField, newValue);
    }
       }
    }*/
    return error;
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    assert request != null;
    assert response != null;

    NDC.push("rid=" + Long.toString(getUniqueRequestId()));
    try {/* w ww.j av  a2 s  . c  o m*/
        Timer timer = new Timer();
        try {
            attachThreadLocalData(request, response);
            try {
                if (logger.isTraceEnabled()) {
                    String requestInfo = ServletUtils.getDetailedRequestInformation(request);
                    logger.trace("Request info: " + requestInfo);
                }

                response.setContentType("text/html"); // MUST be "text/html" for uploads to work!
                String requestEncoding = request.getCharacterEncoding();
                // If we don't know what the request encoding is, assume it to be UTF-8
                if (StringUtils.isEmpty(requestEncoding)) {
                    request.setCharacterEncoding(EncodingUtils.UTF8);
                }
                response.setCharacterEncoding(EncodingUtils.UTF8);

                RequestType type = getFromRequestContentType(request);
                switch (type) {
                case FORM_SIMPLE_POST:
                    this.processor.processSimpleFormPostRequest(request.getReader(), response.getWriter());
                    break;
                case FORM_UPLOAD_POST:
                    processUploadFormPost(request, response);
                    break;
                case JSON:
                    this.processor.processJsonRequest(request.getReader(), response.getWriter());
                    break;
                case POLL:
                    this.processor.processPollRequest(request.getReader(), response.getWriter(),
                            request.getPathInfo());
                    break;
                }
            } finally {
                detachThreadLocalData();
            }
        } finally {
            timer.stop();
            timer.logDebugTimeInMilliseconds("Total servlet processing time");
        }

    } finally {
        NDC.pop();
    }
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

private void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*w  w w  .  ja v  a2  s .  c  o  m*/

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:org.apereo.portal.url.UrlSyntaxProviderImpl.java

/**
 * Tries to determine the encoded from the request, if not available falls back to configured default.
 * //from w ww  .  java  2s  .  co  m
 * @param request The current request.
 * @return The encoding to use.
 */
protected String getEncoding(HttpServletRequest request) {
    final String encoding = request.getCharacterEncoding();
    if (encoding != null) {
        return encoding;
    }

    return this.defaultEncoding;
}