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:net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files//from  ww  w  .  j av a2 s.  c om
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        List<FileItem> items = upload.parseRequest(request);
        Map<String, List<String>> params = new HashMap<String, List<String>>();

        for (FileItem item : items) {
            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? item.getString() : item.getString(charset));
            }
            // Else store the file param
            else {
                files.put(item.getFieldName(), item);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*from  w  w w. java  2s. c om*/

    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())).append("\n");
    log.append("---- Body END\n");

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

From source file:fr.cph.stock.web.servlet.portfolio.ModifyEquityServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    try {/*ww w .jav  a2  s  . c om*/
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String lang = CookieManagement.getCookieLanguage(Arrays.asList(request.getCookies()));
        LanguageFactory language = LanguageFactory.getInstance();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Double quantity = null, unitCostPrice = null, stopLoss = null, objective = null, yieldPersonal = null,
                parityPersonal = null;
        String namePersonal = null, sectorPersonal = null, industryPersonal = null, marketCapPersonal = null;
        try {
            if (request.getParameter("delete") != null) {
                if (request.getParameter("manual") != null) {
                    String id = request.getParameter("id");
                    String companyId = request.getParameter("companyId");
                    Equity e = new Equity();
                    e.setid(Integer.parseInt(id));
                    business.deleteEquity(e);
                    Company company = new Company();
                    company.setId(Integer.parseInt(companyId));
                    business.deleteCompany(company);
                    request.setAttribute("modified", language.getLanguage(lang).get("CONSTANT_DELETED") + " !");
                } else {
                    String id = request.getParameter("id");
                    Equity e = new Equity();
                    e.setid(Integer.parseInt(id));
                    business.deleteEquity(e);
                    request.setAttribute("modified", language.getLanguage(lang).get("CONSTANT_DELETED") + " !");
                }
            } else {
                String ticker = request.getParameter("ticker");
                String namePerso = request.getParameter("namePersonal");
                if (!namePerso.equals("")) {
                    namePersonal = namePerso;
                }
                String sectorPerso = request.getParameter("sectorPersonal");
                if (!sectorPerso.equals("")) {
                    sectorPersonal = sectorPerso;
                }
                String industryPerso = request.getParameter("industryPersonal");
                if (!industryPerso.equals("")) {
                    industryPersonal = industryPerso;
                }
                String marketCapPerso = request.getParameter("marketCapPersonal");
                if (!marketCapPerso.equals("")) {
                    marketCapPersonal = marketCapPerso;
                }
                String quant = request.getParameter("quantity");
                if (!quant.equals("")) {
                    quantity = NumberUtils.createDouble(quant);
                } else {
                    quantity = 0.0;
                }
                String unitCostP = request.getParameter("unitCostPrice");
                if (!unitCostP.equals("")) {
                    unitCostPrice = NumberUtils.createDouble(unitCostP);
                } else {
                    unitCostPrice = 0.0;
                }
                String stopLo = request.getParameter("stopLoss");
                if (!stopLo.equals("")) {
                    stopLoss = NumberUtils.createDouble(stopLo);
                }
                String objc = request.getParameter("objective");
                if (!objc.equals("")) {
                    objective = NumberUtils.createDouble(objc);
                }
                String yieldPerso = request.getParameter("yieldPersonal");
                if (!yieldPerso.equals("")) {
                    yieldPersonal = NumberUtils.createDouble(yieldPerso);
                }
                String parityPerso = request.getParameter("modifyParityPersonal");
                if (!parityPerso.equals("")) {
                    parityPersonal = NumberUtils.createDouble(parityPerso);
                }
                if (quantity == 0) {
                    request.setAttribute("modifyError", "Error: quantity can not be 0");
                } else {
                    Equity equity = new Equity();
                    equity.setNamePersonal(namePersonal);
                    equity.setSectorPersonal(sectorPersonal);
                    equity.setIndustryPersonal(industryPersonal);
                    equity.setMarketCapPersonal(marketCapPersonal);
                    equity.setQuantity(quantity);
                    equity.setUnitCostPrice(unitCostPrice);
                    equity.setStopLossLocal(stopLoss);
                    equity.setObjectivLocal(objective);
                    equity.setYieldPersonal(yieldPersonal);
                    equity.setParityPersonal(parityPersonal);
                    business.updateEquity(user.getId(), ticker, equity);
                    request.setAttribute("modified",
                            language.getLanguage(lang).get("CONSTANT_MODIFIED") + " !");
                }
                if (request.getParameter("manual") != null) {
                    String companyId = request.getParameter("companyId");
                    String quote = request.getParameter("quote");
                    Double quoteRes = null;
                    Integer companyIdRes = null;
                    if (quote != null && !quote.equals("") && companyId != null && !companyId.equals("")) {
                        quoteRes = Double.parseDouble(quote);
                        companyIdRes = Integer.parseInt(companyId);
                        business.updateCompanyManual(companyIdRes, quoteRes);
                    }
                }
            }
        } catch (YahooException e) {
            LOG.warn(e.getMessage(), e);
            request.setAttribute("modifyError", "Error: " + e.getMessage());
        } catch (NumberFormatException e) {
            LOG.warn(e.getMessage(), e);
            request.setAttribute("modifyError", "Error: " + e.getMessage());
        }
        request.getRequestDispatcher("home").forward(request, response);
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new ServletException("Error: " + t.getMessage(), t);
    }
}

From source file:com.aplos.core.listeners.MultipartRequest.java

public MultipartRequest(HttpServletRequest request, ServletFileUpload servletFileUpload) throws IOException {
    super(request);
    formParams = new LinkedHashMap<String, List<String>>();
    fileParams = new LinkedHashMap<String, List<FileItem>>();

    encoding = request.getCharacterEncoding();

    parseRequest(request, servletFileUpload);
}

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

/**
 * @param request/*from w w  w .j a  v  a  2 s.  c  om*/
 * @return
 */
private String getEncoding(HttpServletRequest request) {
    String charsetEncoding = request.getCharacterEncoding();
    if (charsetEncoding == null) {
        charsetEncoding = Constants.DEFAULT_ENCODING;
    }
    return charsetEncoding;
}

From source file:org.alfresco.repo.web.scripts.TenantWebScriptServlet.java

protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled())
        logger.debug("Processing tenant request (" + req.getMethod() + ") " + req.getRequestURL()
                + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));

    if (req.getCharacterEncoding() == null) {
        req.setCharacterEncoding("UTF-8");
    }// w  ww  .ja v a  2s.  c  o  m

    setLanguageFromRequestHeader(req);

    try {
        WebScriptServletRuntime runtime = getRuntime(req, res);
        runtime.executeScript();
    } catch (IllegalStateException e) {
        if (e.getMessage().contains("getOutputStream() has already been called for this response")) {
            if (logger.isDebugEnabled()) {
                logger.warn("Client has cut off communication", e);
            } else {
                logger.warn("Client has cut off communication");
            }
        } else {
            throw e;
        }
    } finally {
        // clear threadlocal
        I18NUtil.setLocale(null);
        // clear authentication and tenant context
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*w w  w  . j  a va 2s  . c o  m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files/*w w  w .  ja  va2 s.  c  om*/
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }/*from  w  w w  .  j a v  a  2 s  .  c  o m*/

        public String getContentType() {
            return req.getContentType();
        }

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:org.opencms.util.CmsRequestUtil.java

/**
 * Parses a request of the form <code>multipart/form-data</code>.
 * //  ww  w  .  j  a va  2 s . com
 * The result list will contain items of type <code>{@link FileItem}</code>.
 * If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
 * 
 * @param request the HTTP servlet request to parse
 * 
 * @return the list of <code>{@link FileItem}</code> extracted from the multipart request,
 *      or <code>null</code> if the request was not of type <code>multipart/form-data</code>
 */
public static List<FileItem> readMultipartFileItems(HttpServletRequest request) {

    if (!ServletFileUpload.isMultipartContent(request)) {
        return null;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File(OpenCms.getSystemInfo().getPackagesRfsPath()));
    ServletFileUpload fu = new ServletFileUpload(factory);
    // set encoding to correctly handle special chars (e.g. in filenames)
    fu.setHeaderEncoding(request.getCharacterEncoding());
    List<FileItem> result = new ArrayList<FileItem>();
    try {
        List<FileItem> items = CmsCollectionsGenericWrapper.list(fu.parseRequest(request));
        if (items != null) {
            result = items;
        }
    } catch (FileUploadException e) {
        LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_MULIPART_REQ_FAILED_0), e);
    }
    return result;
}