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.seasar.struts.upload.S2MultipartRequestHandler.java

@SuppressWarnings("unchecked")
@Override//from   w  w w.jav  a  2s .c  om
protected void addTextParameter(HttpServletRequest request, FileItem item) {
    String name = item.getFieldName();
    String value = null;
    boolean haveValue = false;
    String encoding = request.getCharacterEncoding();
    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (Exception e) {
        }
    }
    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }
        haveValue = true;
    }
    if (request instanceof MultipartRequestWrapper) {
        MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
        wrapper.setParameter(name, value);
    }
    String[] oldArray = (String[]) elementsText.get(name);
    String[] newArray;
    if (oldArray != null) {
        newArray = new String[oldArray.length + 1];
        System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        newArray[oldArray.length] = value;
    } else {
        newArray = new String[] { value };
    }
    elementsText.put(name, newArray);
    elementsAll.put(name, newArray);
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private void add(HttpServletRequest request, String pathInfo, HttpServletResponse response) throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {// w w  w  .j av a  2 s .c o  m
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    Map<String, Object> values = mapper.readValue(reader, TYPE_FLATMAP);

    if (validator != null) {
        ValidationResult result = validator.validate(values, eventType);
        if (result == null || result.isSuccess()) {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(validateReusltWriter.writeValueAsString(result));
        }
    } else {
        JetstreamEvent event = createEvent(values, eventType);
        inboundChannel.onMessage(event);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:org.roosster.mappers.ApiServletMapper.java

/**
 *///from  w  w w  . j a va2s . co m
protected Map parseRequestArguments(HttpServletRequest req) throws Exception {
    Map args = super.parseRequestArguments(req);

    if ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod())) {
        InputStream stream = req.getInputStream();

        if (stream != null) {

            String bodyEnc = req.getCharacterEncoding();
            if (bodyEnc == null)
                bodyEnc = inputEncoding;

            String body = IOUtils.toString(stream, bodyEnc);

            if (body != null && !"".equals(body)) {

                // parse request body through entry parser
                EntryList entryList = new EntryParser().parse(body, bodyEnc);
                args.put(Constants.PARAM_ENTRIES, entryList);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("**************************************************");
                    LOG.debug("RequestBody: encoding " + bodyEnc + "\n");
                    LOG.debug(body);
                    LOG.debug("**************************************************");
                }
            }
        }
    }

    return args;
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * /* www.  jav a2s .  c om*/
 * @param req
 *            the request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

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

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

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

From source file:org.bonitasoft.console.common.server.login.filter.RestAPIAuthorizationFilter.java

protected String getRequestBody(final HttpServletRequest request) throws ServletException {
    try {/*from   w  w  w.ja  va2  s  . c  o  m*/
        final ServletInputStream inputStream = request.getInputStream();
        return IOUtils.toString(inputStream, request.getCharacterEncoding());
    } catch (final IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private void batchAdd(HttpServletRequest request, String pathInfo, HttpServletResponse response)
        throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {/*from w w  w .j  av  a 2s  .  c o m*/
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    List<Map<String, Object>> eventList = mapper.readValue(reader, TYPE_LIST_OF_MAP);
    List<ValidationResult> failedEvents = null;
    for (Map<String, Object> values : eventList) {
        if (validator != null) {
            ValidationResult result = validator.validate(values, eventType);
            if (result == null || result.isSuccess()) {
                JetstreamEvent event = createEvent(values, eventType);
                inboundChannel.onMessage(event);
            } else {
                if (failedEvents == null) {
                    failedEvents = new ArrayList<ValidationResult>();
                }
                failedEvents.add(result);
            }
        } else {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
        }
    }
    if (failedEvents == null) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter printWriter = response.getWriter();
        printWriter.write("[");
        for (int i = 0, t = failedEvents.size() - 1; i < t; i++) {
            printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(i)));
            printWriter.write(",");
        }
        printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(failedEvents.size() - 1)));
        printWriter.write("]");
    }

}

From source file:org.deegree.services.wpvs.controller.WPVSController.java

/**
 * @param normalizedKVPParams/*from w w  w.j ava2 s. c o  m*/
 * @param request
 * @param response
 * @throws ServletException
 */
private void sendGetViewResponse(Map<String, String> normalizedKVPParams, HttpServletRequest request,
        HttpResponseBuffer response) throws ServletException {
    try {
        String encoding = (request.getCharacterEncoding() == null) ? "UTF-8" : request.getCharacterEncoding();
        GetView gvReq = GetViewKVPAdapter.create(normalizedKVPParams, encoding, service.getTranslationVector(),
                service.getNearClippingPlane(), service.getFarClippingPlane());

        // first see if the requested image typ is supported
        GetViewResponseParameters responseParameters = gvReq.getResponseParameters();
        String format = responseParameters.getFormat();
        testResultMimeType(format);

        // render the image
        BufferedImage gvResponseImage = service.getImage(gvReq);
        String ioFormat = mimeToFormat(format);
        LOG.debug("Requested format: " + format + " was mapped to response ioformat: " + ioFormat);
        if (gvResponseImage != null) {
            try {
                ImageIO.write(gvResponseImage, ioFormat, response.getOutputStream());
            } catch (IOException e) {
                throw new OWSException(
                        "An error occurred while writing the result image to the stream because: "
                                + e.getLocalizedMessage(),
                        NO_APPLICABLE_CODE);
            }
            response.setContentLength(response.getBufferSize());
            response.setContentType(format);

        }
    } catch (OWSException e) {
        sendServiceException(e, response);
    }

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload")
@POST/*from   w  ww . j  ava 2 s  .c o m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(FormDataMultiPart form, @Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    Map<String, List<FormDataBodyPart>> map = form.getFields();
    for (String key : map.keySet()) {
        FormDataBodyPart filePart = form.getField(key);
        //?
        InputStream inputStream = filePart.getValueAs(InputStream.class);
        FormDataContentDisposition disposition = filePart.getFormDataContentDisposition();
        System.out.println(filePart.getMediaType());
        if (disposition.getFileName() == null) {//
            System.out.println(key + "!" + filePart.getValue());
        } else {
            String fileName = new String(disposition.getFileName().getBytes("ISO8859-1"), CHARSET);
            if (fileName != null && !fileName.trim().equals("")) {
                String name = Calendar.getInstance().getTimeInMillis() + fileName;
                String path = request.getServletContext().getRealPath("/");
                path += File.separator + "data" + File.separator + name;
                File file = new File(path);
                try {
                    FileUtils.copyInputStreamToFile(inputStream, file);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return "{\"success\": false}";
                }
            }
        }
    }
    return "{\"success\": true}";
}

From source file:org.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();/*from w w  w  . j ava2  s  .  c  o m*/
    host = req.getServerName();
    port = req.getServerPort();
    contextPath = req.getContextPath();
    servletPath = req.getServletPath();
    pathInfo = req.getPathInfo();
    characterEncoding = req.getCharacterEncoding();
    method = req.getMethod();
    final Cookie[] cookies = req.getCookies();

    // cookies
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            this.cookies.add(new CapturedCookie(cookie));
        }
    }
    // headers
    for (@SuppressWarnings("unchecked")
    final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) {
        final String name = names.nextElement();
        @SuppressWarnings("unchecked")
        final Enumeration<String> values = req.getHeaders(name);
        if (values != null) {
            for (; values.hasMoreElements();) {
                this.addHeader(new CapturedHeader(name, values.nextElement()));
            }
        }
    }
    // if we use the normal 'toString' on maps, and arrays, we get pretty
    // poor results
    // Use ArrayLists instead to get a nice output
    @SuppressWarnings("unchecked")
    final Map<String, String[]> paramMap = req.getParameterMap();
    if (paramMap != null) {
        for (final String key : paramMap.keySet()) {
            final String[] vals = paramMap.get(key);
            this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals)));
        }
    }
    // handle multipart posts
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        final FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            @SuppressWarnings("unchecked")
            final List<FileItem> items = upload.parseRequest(req);
            for (final FileItem item : items) {
                fileItems.add(new CapturedFileItem(item));
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException("Error handling multipart content", e);
        }
    }

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST//from  w  ww  .j  av a 2  s.c o m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}