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.gbif.portal.web.filter.CriteriaUtil.java

/**
 * Fix the criteria values to can be understood by the database. Usually when one of them contain
 * characters with accents./*  w w w  . j  av a 2  s  .  c o  m*/
 * 
 * @param request
 * @param criteria
 * @throws UnsupportedEncodingException
 */
public static void fixEncoding(HttpServletRequest request, CriteriaDTO criteria)
        throws UnsupportedEncodingException {
    if (request.getCharacterEncoding() != "UTF-8") {
        for (int c = 0; c < criteria.size(); c++) {
            criteria.get(c).setValue(URLEncoder.encode(criteria.get(c).getValue(), "UTF-8"));
            criteria.get(c).setValue(URLDecoder.decode(criteria.get(c).getValue(), "UTF-8"));
            if (criteria.get(c).getDisplayValue() != null) {
                criteria.get(c).setDisplayValue(URLEncoder.encode(criteria.get(c).getDisplayValue(), "UTF-8"));
                criteria.get(c).setDisplayValue(URLDecoder.decode(criteria.get(c).getDisplayValue(), "UTF-8"));
            }
            request.setCharacterEncoding("UTF-8");
        }
    }
}

From source file:net.jadler.stubbing.server.jetty.RequestUtils.java

public static Request convert(HttpServletRequest source) throws IOException {
    String method = source.getMethod();
    URI requestUri = URI.create(source.getRequestURL() + getQueryString(source));
    InputStream body = source.getInputStream();
    InetSocketAddress localAddress = new InetSocketAddress(source.getLocalAddr(), source.getLocalPort());
    InetSocketAddress remoteAddress = new InetSocketAddress(source.getRemoteAddr(), source.getRemotePort());
    String encoding = source.getCharacterEncoding();
    Map<String, List<String>> headers = converHeaders(source);
    return new Request(method, requestUri, headers, body, localAddress, remoteAddress, encoding);
}

From source file:org.jsecurity.web.WebUtils.java

/**
 * Determine the encoding for the given request.
 * Can be overridden in subclasses./* ww  w  . j av a2s. c o  m*/
 * <p>The default implementation checks the request's
 * {@link ServletRequest#getCharacterEncoding() character encoding}, and if that
 * <code>null</code>, falls back to the {@link #DEFAULT_CHARACTER_ENCODING}.
 *
 * @param request current HTTP request
 * @return the encoding for the request (never <code>null</code>)
 * @see javax.servlet.ServletRequest#getCharacterEncoding()
 */
protected static String determineEncoding(HttpServletRequest request) {
    String enc = request.getCharacterEncoding();
    if (enc == null) {
        enc = DEFAULT_CHARACTER_ENCODING;
    }
    return enc;
}

From source file:org.apache.hadoop.yarn.webapp.util.WebAppUtils.java

private static String getURLEncodedQueryString(HttpServletRequest request) {
    String queryString = request.getQueryString();
    if (queryString != null && !queryString.isEmpty()) {
        String reqEncoding = request.getCharacterEncoding();
        if (reqEncoding == null || reqEncoding.isEmpty()) {
            reqEncoding = "ISO-8859-1";
        }/*from w w  w.j  a v  a  2s .c  om*/
        Charset encoding = Charset.forName(reqEncoding);
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding);
        return URLEncodedUtils.format(params, encoding);
    }
    return null;
}

From source file:org.wso2.carbon.bpmn.rest.common.utils.Utils.java

public static byte[] processMultiPartFile(HttpServletRequest httpServletRequest, String contentMessage)
        throws IOException {
    //Content-Type: multipart/form-data; boundary="----=_Part_2_1843361794.1448198281814"

    String encoding = httpServletRequest.getCharacterEncoding();

    if (encoding == null) {
        encoding = DEFAULT_ENCODING;/*from   w  w w. j  a v  a  2  s .c  om*/
        httpServletRequest.setCharacterEncoding(encoding);
    }

    byte[] requestBodyArray = IOUtils.toByteArray(httpServletRequest.getInputStream());
    if (requestBodyArray == null || requestBodyArray.length == 0) {
        throw new ActivitiIllegalArgumentException("No :" + contentMessage + "was found in request body.");
    }

    String requestContentType = httpServletRequest.getContentType();

    StringBuilder contentTypeString = new StringBuilder();
    contentTypeString.append("Content-Type: " + requestContentType);
    contentTypeString.append("\r");
    contentTypeString.append(System.getProperty("line.separator"));

    byte[] contentTypeArray = contentTypeString.toString().getBytes(encoding);

    byte[] aggregatedRequestBodyByteArray = new byte[contentTypeArray.length + requestBodyArray.length];

    System.arraycopy(contentTypeArray, 0, aggregatedRequestBodyByteArray, 0, contentTypeArray.length);
    System.arraycopy(requestBodyArray, 0, aggregatedRequestBodyByteArray, contentTypeArray.length,
            requestBodyArray.length);

    boolean debugEnabled = log.isDebugEnabled();

    int index = requestContentType.indexOf("boundary");

    if (index <= 0) {
        throw new ActivitiIllegalArgumentException("boundary tag not found in the request header.");
    }
    String boundaryString = requestContentType.substring(index + "boundary=".length());
    boundaryString = boundaryString.replaceAll("\"", "").trim();

    if (debugEnabled) {
        log.debug("----------Content-Type:-----------\n" + httpServletRequest.getContentType());
        log.debug("\n\n\n\n");
        log.debug("\n\n\n\n----------Aggregated Request Body:-----------\n"
                + new String(aggregatedRequestBodyByteArray));
        log.debug("boundaryString:" + boundaryString);
    }

    byte[] boundary = boundaryString.getBytes(encoding);
    ByteArrayInputStream content = new ByteArrayInputStream(aggregatedRequestBodyByteArray);
    MultipartStream multipartStream = new MultipartStream(content, boundary,
            aggregatedRequestBodyByteArray.length, null);

    boolean nextPart = multipartStream.skipPreamble();
    if (debugEnabled) {
        log.debug(nextPart);
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] byteArray = null;
    // Get first file in the map, ignore possible other files
    while (nextPart) {
        //
        if (debugEnabled) {

            String header = multipartStream.readHeaders();
            printHeaders(header);
        }

        multipartStream.readBodyData(byteArrayOutputStream);
        byteArray = byteArrayOutputStream.toByteArray();

        nextPart = multipartStream.readBoundary();
    }

    return byteArray;
}

From source file:org.opendatakit.odktables.util.ServiceUtils.java

@SuppressWarnings("unused")
public static void examineRequest(ServletContext sc, HttpServletRequest req, HttpHeaders httpHeaders) {
    MultivaluedMap<String, String> headers = httpHeaders.getRequestHeaders();
    StringBuilder b = new StringBuilder();
    for (String headerName : headers.keySet()) {
        List<String> fieldValues = headers.get(headerName);
        for (String fieldValue : fieldValues) {
            b.append(headerName).append(": ").append(fieldValue).append("\n");
        }// www  .  ja v  a2s  .  c om
    }
    String contentType = req.getContentType();
    String charEncoding = req.getCharacterEncoding();
    String headerSet = b.toString();
    Cookie[] cookies = req.getCookies();
    String method = req.getMethod();
    String ctxtPath = req.getContextPath();
    String pathInfo = req.getPathInfo();
    String query = req.getQueryString();
    boolean sessionId = req.isRequestedSessionIdValid();
}

From source file:grails.converters.XML.java

/**
 * Parses the give XML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest/*  w  w w  . j  av  a 2  s .c o m*/
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing XML", e);
    }
}

From source file:jeeves.server.sources.ServiceRequestFactory.java

/** Builds the request with data supplied by tomcat.
  * A request is in the form: srv/<language>/<service>[!]<parameters>
  *///w  w w .ja  va 2s. c om

public static ServiceRequest create(HttpServletRequest req, HttpServletResponse res, String uploadDir,
        int maxUploadSize) throws Exception {
    String url = req.getPathInfo();

    // FIXME: if request character encoding is undefined set it to UTF-8

    String encoding = req.getCharacterEncoding();
    try {
        // verify that encoding is valid
        Charset.forName(encoding);
    } catch (Exception e) {
        encoding = null;
    }

    if (encoding == null) {
        try {
            req.setCharacterEncoding(Jeeves.ENCODING);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }

    //--- extract basic info

    HttpServiceRequest srvReq = new HttpServiceRequest(res);

    srvReq.setDebug(extractDebug(url));
    srvReq.setLanguage(extractLanguage(url));
    srvReq.setService(extractService(url));
    srvReq.setJSONOutput(extractJSONFlag(url));
    String ip = req.getRemoteAddr();
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;
    srvReq.setAddress(ip);
    srvReq.setOutputStream(res.getOutputStream());

    //--- discover the input/output methods

    String accept = req.getHeader("Accept");

    if (accept != null) {
        int soapNDX = accept.indexOf("application/soap+xml");
        int xmlNDX = accept.indexOf("application/xml");
        int htmlNDX = accept.indexOf("html");

        if (soapNDX != -1)
            srvReq.setOutputMethod(OutputMethod.SOAP);

        else if (xmlNDX != -1 && htmlNDX == -1)
            srvReq.setOutputMethod(OutputMethod.XML);
    }

    if ("POST".equals(req.getMethod())) {
        srvReq.setInputMethod(InputMethod.POST);

        String contType = req.getContentType();

        if (contType != null) {
            if (contType.indexOf("application/soap+xml") != -1) {
                srvReq.setInputMethod(InputMethod.SOAP);
                srvReq.setOutputMethod(OutputMethod.SOAP);
            }

            else if (contType.indexOf("application/xml") != -1 || contType.indexOf("text/xml") != -1)
                srvReq.setInputMethod(InputMethod.XML);
        }
    }

    //--- retrieve input parameters

    InputMethod input = srvReq.getInputMethod();

    if ((input == InputMethod.XML) || (input == InputMethod.SOAP)) {
        if (req.getMethod().equals("GET"))
            srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize));
        else
            srvReq.setParams(extractXmlParameters(req));
    } else {
        //--- GET or POST
        srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize));
    }

    srvReq.setHeaders(extractHeaders(req));

    return srvReq;
}

From source file:org.ejbca.ui.web.RequestHelper.java

/** Sets the default character encoding for decoding post and get parameters. 
 * First tries to get the character encoding from the request, if the browser is so kind to tell us which it is using, which it never does...
 * Otherwise, when the browser is silent, it sets the character encoding to the same encoding that we use to display the pages.
 * /*from  w  ww . ja  v  a  2 s . c om*/
 * @param request HttpServletRequest   
 * @throws UnsupportedEncodingException 
 * 
 */
public static void setDefaultCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException {
    String encoding = request.getCharacterEncoding();
    if (StringUtils.isEmpty(encoding)) {
        encoding = org.ejbca.config.WebConfiguration.getWebContentEncoding();
        if (log.isDebugEnabled()) {
            log.debug("Setting encoding to default value: " + encoding);
        }
        request.setCharacterEncoding(encoding);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Setting encoding to value from request: " + encoding);
        }
        request.setCharacterEncoding(encoding);
    }
}

From source file:gov.va.vinci.chartreview.util.CRSchemaXML.java

/**
 * Parses the give CRSchemaXML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest//from   w  w w  . j a va 2s  .  co m
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing CRSchemaXML", e);
    }
}