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.deegree.enterprise.servlet.ProxyServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String url = req.getParameter("URL");
    try {/*from  w  ww . j a  v  a2 s  .c o m*/
        HttpMethod result = HttpUtils.performHttpPost(url, req.getInputStream(), 0, null, null,
                req.getContentType(), req.getCharacterEncoding(), null);
        InputStream in = result.getResponseBodyAsStream();
        IOUtils.getInstance().copyStreams(in, resp.getOutputStream());
        in.close();
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:upload.UploadAction.java

private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {

        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }/*  w w  w  . ja va2  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.mule.transport.servlet.ServletMuleMessageFactory.java

protected void setupCharacterEncoding(HttpServletRequest request, DefaultMuleMessage message) {
    String characterEncoding = request.getCharacterEncoding();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(ServletConnector.CHARACTER_ENCODING_PROPERTY_KEY, characterEncoding);

    message.addInboundProperties(properties);
}

From source file:org.nuxeo.ecm.webengine.app.WebEngineFilter.java

public void preRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // need to set the encoding of characters manually
    if (null == request.getCharacterEncoding()) {
        request.setCharacterEncoding("UTF-8");
    }//  ww  w  .j  ava  2 s .com
    // response.setCharacterEncoding("UTF-8");
}

From source file:com.eternity.common.communication.servlet.SyncJSONDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;//  w w  w  .  ja  va2  s  .c o  m
    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (charset == null) {
        charset = "UTF-8";
    }

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim());
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable or missing ACCEPT header!");
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    Object result = MessageConsumer.dispatchMessage(message, null, hostName);
    resp.getOutputStream().write(encoder.encode(result).array());
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Sets the character encoding for reading parameters and content from a request in a JSP page.
 *
 * @param request The servlet request object
 *///from  w  w w . jav a 2 s  . c o  m
public static void setUTF8(HttpServletRequest request) {
    ArgumentNotValid.checkNotNull(request, "request");
    // Why is this in an if block? Suppose we forward from a page where
    // we read file input from the request. Trying to set the character
    // encoding again here will throw an exception!
    // This is a bit of a hack - we know that _if_ we have set it,
    // we have set it to UTF-8, so this way we won't set it twice...
    if (request.getCharacterEncoding() == null || !request.getCharacterEncoding().equals("UTF-8")) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ArgumentNotValid("Should never happen! UTF-8 not supported", e);
        }
    }
}

From source file:com.jd.survey.web.security.AuthorityController.java

String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
    log.info("encodeUrlPathSegment()");
    try {/*from   ww  w  . ja  v a  2 s .  c om*/
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
            log.error(uee);
        }
        return pathSegment;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.eternity.common.communication.servlet.AsyncDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;//w w w .j av a2  s .  com
    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (charset == null) {
        charset = "UTF-8";
    }

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim());
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable or missing ACCEPT header!");
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    MessageConsumer.dispatchAsyncMessage(message, null, hostName);
    Response result = new Response();
    result.setStatus(200);
    resp.getOutputStream().write(encoder.encode(result).array());
}

From source file:org.cerberus.servlet.crud.countryenvironment.ReadApplicationObjectImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w  . j a  v a2 s . c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException {
    String charset = request.getCharacterEncoding();

    String application = ParameterParserUtil
            .parseStringParamAndDecodeAndSanitize(request.getParameter("application"), "", charset);
    String object = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("object"), "",
            charset);

    int width = (!StringUtils.isEmpty(request.getParameter("w"))) ? Integer.valueOf(request.getParameter("w"))
            : -1;
    int height = (!StringUtils.isEmpty(request.getParameter("h"))) ? Integer.valueOf(request.getParameter("h"))
            : -1;

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IApplicationObjectService applicationObjectService = appContext.getBean(IApplicationObjectService.class);

    BufferedImage image = applicationObjectService.readImageByKey(application, object);
    BufferedImage b;
    if (image != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        /**
         * If width and height not defined, get image in real size
         */
        if (width == -1 && height == -1) {
            b = image;
        } else {
            ResampleOp rop = new ResampleOp(DimensionConstrain.createMaxDimension(width, height, true));
            rop.setNumberOfThreads(4);
            b = rop.filter(image, null);
        }
        ImageIO.write(b, "png", baos);
        //        byte[] bytesOut = baos.toByteArray();
    } else {
        // create a buffered image
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        b = ImageIO.read(bis);
        bis.close();
    }

    response.setHeader("Last-Modified",
            DateUtils.addDays(Calendar.getInstance().getTime(), 2 * 360).toGMTString());
    response.setHeader("Expires", DateUtils.addDays(Calendar.getInstance().getTime(), 2 * 360).toGMTString());

    ImageIO.write(b, "png", response.getOutputStream());
}

From source file:com.kirayim.homesec.service.impl.ImageManagerImpl.java

@Override
public Image handleFileUpload(long cameraId, HttpServletRequest request) {
    String extension = null;//from   ww  w .  j  av a 2 s  . co m
    Date uploadTime = new Date();

    String encoding = request.getCharacterEncoding();

    if (encoding == null) {
        try {
            request.setCharacterEncoding(encoding = "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            logger.warn("Bad encoding", ex);
        }
    }

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    Camera camera = cameraManager.get(cameraId);

    if (camera == null) {
        throw new NotAllowedException("Imvalid camera ID");
    }

    if (!camera.getOwner().equals(user)) {
        throw new NotAllowedException("Camera doesn't belong to current user");
    }

    /* -------------------------------------------------
     * Calculate output file name
     * ------------------------------------------------- */

    String name = String.format("homesec_image_%1$08d_%2$TY%2$Tm%2$Td_%2$TH%2$TM%2$TS%2$TL",
            camera.getCameraId(), uploadTime);

    /* -------------------------------------------------
     * Get uploaded file and write to destination
     * ------------------------------------------------- */

    try {
        if (request.getParts().size() > 1) {
            throw new NotAllowedException("Only one image upload per transaction");
        }

        for (Part part : request.getParts()) {
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            String contentType = part.getContentType();

            if (contentType != null) {
                try {
                    MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
                    MimeType mimeType = allTypes.forName(contentType);

                    extension = mimeType.getExtension();

                    name += extension;

                } catch (MimeTypeException mimeTypeException) {
                    logger.warn("Mime? ", mimeTypeException);
                }
            }

            File outputFile = new File(uploadDir, name);

            OutputStream out = new FileOutputStream(outputFile);

            InputStream in = part.getInputStream();

            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } catch (IOException | ServletException e) {
        throw new BadRequestException(e);
    }

    /* -------------------------------------------------
     * If extension is unknown, re-read file to try
     * and get extension
     * ------------------------------------------------- */

    if (extension == null) {
        // TODO:
    }

    /* -------------------------------------------------
     * Save image record in DB
     * ------------------------------------------------- */

    Image image = new Image(camera, name, uploadTime);

    dao.save(image);

    return image;
}