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:es.logongas.encuestas.presentacion.controller.EncuestaController.java

@RequestMapping(value = { "/finalizar.html" })
public ModelAndView finalizar(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    String viewName;//from  ww  w .  j a  v a  2 s  . c  om

    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(EncuestaController.class.getName()).log(Level.WARNING,
                    "no existe el juego de caracteres utf-8", ex);
        }
    }

    RespuestaEncuesta respuestaEncuesta = getEncuestaState(request).getRespuestaEncuesta();

    List<BusinessMessage> businessMessages = respuestaEncuesta.validate();
    if ((businessMessages != null) && (businessMessages.size() > 0)) {
        Encuesta encuesta = respuestaEncuesta.getEncuesta();
        model.put("encuesta", encuesta);
        model.put("businessMessages", businessMessages);
        viewName = "encuestas/error_encuesta";
    } else {
        Date fechaRespuesta = new Date();
        respuestaEncuesta.setFechaRespuesta(fechaRespuesta);
        respuestaEncuesta.setCurso(getCursoFromDate(fechaRespuesta));

        daoFactory.getDAO(RespuestaEncuesta.class).insert(respuestaEncuesta);
        CodigoVerificacionSeguro codigoVerificacionSeguro = CodigoVerificacionSeguro
                .getInstance(respuestaEncuesta.getIdRespuestaEncuesta());
        respuestaEncuesta.setCodigoVerificacionSeguro(codigoVerificacionSeguro);
        daoFactory.getDAO(RespuestaEncuesta.class).update(respuestaEncuesta);

        URI backURI = getEncuestaState(request).getBackURI();

        clearEncuestaState(request);

        model.put("codigoVerificacionSeguro", codigoVerificacionSeguro);
        model.put("backURI", backURI);
        viewName = "encuestas/finalizar";
    }

    return new ModelAndView(viewName, model);
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:es.logongas.encuestas.presentacion.controller.EncuestaController.java

@RequestMapping(value = { "/anterior.html" })
public ModelAndView anterior(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    String viewName;// w w w.  j a v  a 2  s . com

    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(EncuestaController.class.getName()).log(Level.WARNING,
                    "no existe el juego de caracteres utf-8", ex);
        }
    }

    int idPregunta;
    try {
        idPregunta = Integer.parseInt(request.getParameter("idPregunta"));
    } catch (NumberFormatException ex) {
        throw new BusinessException(new BusinessMessage(null, "El N de pregunta no es vlido"));
    }

    Pregunta pregunta = (Pregunta) daoFactory.getDAO(Pregunta.class).read(idPregunta);
    if (pregunta == null) {
        throw new BusinessException(new BusinessMessage(null, "La pregunta solicitada no existe"));
    }

    RespuestaEncuesta respuestaEncuesta = getEncuestaState(request).getRespuestaEncuesta();
    if (respuestaEncuesta.isPreguntaValida(pregunta) == false) {
        throw new BusinessException(
                new BusinessMessage(null, "La pregunta solicitada no es vlida en esta encuesta"));
    }

    RespuestaPregunta respuestaPregunta = respuestaEncuesta.getRespuestaPregunta(pregunta);
    populateRespuestaFromRequest(request, respuestaPregunta);

    Pregunta anteriorPregunta = respuestaEncuesta.getRespuestaPregunta(pregunta).anterior();

    if (anteriorPregunta != null) {
        viewName = "redirect:/pregunta.html?idPregunta=" + anteriorPregunta.getIdPregunta();
    } else {
        //Era la primera pregunta
        //As que vamos al BackURL
        viewName = "redirect:" + getEncuestaState(request).getBackURI().toASCIIString();
    }

    return new ModelAndView(viewName, model);
}

From source file:org.geowebcache.service.wms.WMSService.java

@Override
public ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response)
        throws GeoWebCacheException {
    final String encoding = request.getCharacterEncoding();
    final Map requestParameterMap = request.getParameterMap();

    String[] keys = { "layers", "request", "tiled", "cached", "metatiled", "width", "height" };
    Map<String, String> values = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding, keys);

    // Look for layer
    String layers = values.get("layers");

    // Get the TileLayer
    TileLayer tileLayer = null;//from w  w w  . java 2s  . co  m
    if (layers != null) {
        tileLayer = tld.getTileLayer(layers);
    }
    // Look for requests that are not getmap
    String req = values.get("request");
    if (req != null && !req.equalsIgnoreCase("getmap")) {
        // One more chance
        if (layers == null || layers.length() == 0) {
            layers = ServletUtils.stringFromMap(requestParameterMap, encoding, "layer");
            values.put("LAYERS", layers);

            if (layers != null) {
                tileLayer = tld.getTileLayer(layers);
            }
        }

        Map<String, String> filteringParameters = null;
        // If tileLayer is not null, then request parameters are extracted from it-
        if (tileLayer != null) {
            filteringParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding);
        }

        // Creation of a Conveyor Tile with a fake Image/png format and the associated parameters.
        ConveyorTile tile = new ConveyorTile(sb, layers, null, null, ImageMime.png, filteringParameters,
                request, response);
        tile.setHint(req.toLowerCase());
        tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE);
        return tile;
    }
    if (layers == null) {
        throw new ServiceException("Unable to parse layers parameter from request.");
    }

    // Check whether this request is missing tiled=true
    final boolean tiled = Boolean.valueOf(values.get("tiled"));
    if (proxyNonTiledRequests && tiled) {
        ConveyorTile tile = new ConveyorTile(sb, layers, request, response);
        tile.setHint(req);
        tile.setRequestHandler(Conveyor.RequestHandler.SERVICE);
        return tile;
    }

    String[] paramKeys = { "format", "srs", "bbox" };
    final Map<String, String> paramValues = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding,
            paramKeys);

    final Map<String, String> fullParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding);

    final MimeType mimeType;
    String format = paramValues.get("format");
    try {
        mimeType = MimeType.createFromFormat(format);
    } catch (MimeException me) {
        throw new ServiceException("Unable to determine requested format, " + format);
    }

    final SRS srs;
    {
        String requestSrs = paramValues.get("srs");
        if (requestSrs == null) {
            throw new ServiceException("No SRS specified");
        }
        srs = SRS.getSRS(requestSrs);
    }

    final BoundingBox bbox;
    {
        String requestBbox = paramValues.get("bbox");
        try {
            bbox = new BoundingBox(requestBbox);
            if (bbox == null || !bbox.isSane()) {
                throw new ServiceException(
                        "The bounding box parameter (" + requestBbox + ") is missing or not sane");
            }
        } catch (NumberFormatException nfe) {
            throw new ServiceException("The bounding box parameter (" + requestBbox + ") is invalid");
        }
    }

    final int tileWidth = Integer.parseInt(values.get("width"));
    final int tileHeight = Integer.parseInt(values.get("height"));

    final List<GridSubset> crsMatchingSubsets = tileLayer.getGridSubsetsForSRS(srs);
    if (crsMatchingSubsets.isEmpty()) {
        throw new ServiceException("Unable to match requested SRS " + srs + " to those supported by layer");
    }

    long[] tileIndexTarget = new long[3];
    GridSubset gridSubset;
    {
        GridSubset bestMatch = findBestMatchingGrid(bbox, crsMatchingSubsets, tileWidth, tileHeight,
                tileIndexTarget);
        if (bestMatch == null) {
            // proceed as it used to be
            gridSubset = crsMatchingSubsets.get(0);
            tileIndexTarget = null;
        } else {
            gridSubset = bestMatch;
        }
    }

    if (fullWMS) {
        // If we support full WMS we need to do a few tests to determine whether
        // this is a request that requires us to recombine tiles to respond.
        long[] tileIndex = null;
        if (tileIndexTarget == null) {
            try {
                tileIndex = gridSubset.closestIndex(bbox);
            } catch (GridMismatchException gme) {
                // Do nothing, the null is info enough
            }
        } else {
            tileIndex = tileIndexTarget;
        }

        if (tileIndex == null || gridSubset.getTileWidth() != tileWidth
                || gridSubset.getTileHeight() != tileHeight
                || !bbox.equals(gridSubset.boundsFromIndex(tileIndex), 0.02)) {
            log.debug("Recombinining tiles to respond to WMS request");
            ConveyorTile tile = new ConveyorTile(sb, layers, request, response);
            tile.setHint("getmap");
            tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE);
            return tile;
        }
    }

    long[] tileIndex = tileIndexTarget == null ? gridSubset.closestIndex(bbox) : tileIndexTarget;

    gridSubset.checkTileDimensions(tileWidth, tileHeight);

    return new ConveyorTile(sb, layers, gridSubset.getName(), tileIndex, mimeType, fullParameters, request,
            response);
}

From source file:es.logongas.encuestas.presentacion.controller.EncuestaController.java

@RequestMapping(value = { "/encuesta.html" })
public ModelAndView encuesta(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    String viewName;//w  ww  . jav a2  s  .c  o  m

    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(EncuestaController.class.getName()).log(Level.WARNING,
                    "no existe el juego de caracteres utf-8", ex);
        }
    }

    int idEncuesta;
    URI backURI;
    try {
        idEncuesta = Integer.parseInt(request.getParameter("idEncuesta"));
    } catch (NumberFormatException ex) {
        throw new BusinessException(new BusinessMessage(null, "El N de encuesta no es vlido"));
    }

    try {
        if ((request.getParameter("backURI") == null) || (request.getParameter("backURI").trim().equals(""))) {
            backURI = new URI(request.getContextPath() + "/");
        } else {
            backURI = new URI(request.getParameter("backURI"));
        }
    } catch (Exception ex) {
        throw new BusinessException(new BusinessMessage(null, "El backURI no es vlido"));
    }

    Encuesta encuesta = (Encuesta) daoFactory.getDAO(Encuesta.class).read(idEncuesta);
    if (encuesta == null) {
        throw new BusinessException(new BusinessMessage(null, "La encuesta solicitada no existe"));
    }

    if (encuesta.isEncuestaHabilitada() == false) {
        throw new BusinessException(
                new BusinessMessage(null, "La encuesta solicitada no es posible realizarla actualmente"));
    }

    RespuestaEncuesta respuestaEncuesta = new RespuestaEncuesta(encuesta);
    EncuestaState encuestaState = new EncuestaState(respuestaEncuesta, backURI);
    setEncuestaState(request, encuestaState);

    Pregunta pregunta = respuestaEncuesta.getPrimeraPregunta();
    if (pregunta == null) {
        throw new BusinessException(new BusinessMessage(null, "La encuesta no tiene preguntas"));
    }
    viewName = "redirect:/pregunta.html?idPregunta=" + pregunta.getIdPregunta();

    return new ModelAndView(viewName, model);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void singleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-single-file.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);//from  w w w  .j a  va2 s  .  c  o  m

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfile").get(0).file), "test");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void multipleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-multiple-files.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);//www.  java  2 s  .  c  o  m

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(0).file), "test");
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(1).file), "test2");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:uk.ac.ed.epcc.webapp.servlet.MultiPartServletService.java

@SuppressWarnings("deprecation")
@Override/*from   w  w w .  ja v a 2 s .  c  o m*/
public Map<String, Object> makeParams(HttpServletRequest req) {

    Map<String, Object> h = super.makeParams(req);
    if (FileUploadBase.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        Logger log = conn.getService(LoggerService.class).getLogger(getClass());
        log.debug("Processing multipart form");
        //       Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        try {
            items = upload.parseRequest(req);
            String characterEncoding = req.getCharacterEncoding();
            for (Iterator it = items.iterator(); it.hasNext();) {
                FileItem i = (FileItem) it.next();
                String name = i.getFieldName();

                if (i.isFormField()) {
                    log.debug("add parameter <" + name + ":" + i.getString() + ">");
                    try {
                        if (characterEncoding == null) {
                            h.put(name, i.getString());
                        } else {
                            h.put(name, i.getString(characterEncoding));
                        }
                    } catch (UnsupportedEncodingException e) {
                        h.put(name, i.getString());
                    }
                } else {
                    if (i.getSize() > 0) {
                        log.debug("add file " + name + ":" + i.getName() + " length:" + i.getSize() + " type:"
                                + i.getContentType());
                        h.put(name, new FileItemStreamData(conn, i));
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new ConsistencyError("Error parsing multipart form", e);
        }
    }
    return h;
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseCombine() throws IOException, ServletException {
    Map<String, String[]> oldParams = new HashMap<>();
    oldParams.put("param1", new String[] { "oldvalue1", "oldvalue2" });
    oldParams.put("param2", new String[] { "oldvalue3" });

    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(oldParams);
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/*  w  ww . j a  v a 2s  .  c o m*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "oldvalue1", "oldvalue2", "value1", "value2" })
            .put("param2", new String[] { "oldvalue3", "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseMultiple() throws IOException, ServletException {
    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//  w  w  w .j  av  a2 s .c  o  m

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "value1", "value2" }).put("param2", new String[] { "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}