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:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

private void handleFormField(HttpServletRequest servletRequest, FileItem item)
        throws UnsupportedEncodingException {
    LOG.debug("Item is a normal form field");
    List<String> values = params.get(item.getFieldName());
    if (values == null) {
        values = new ArrayList<String>();
        params.put(item.getFieldName(), values);
    }// w  w w.  j av  a  2s . c o  m
    String charset = servletRequest.getCharacterEncoding();
    values.add(charset != null ? item.getString(charset) : item.getString());
}

From source file:net.triptech.metahive.web.DefinitionController.java

/**
 * List the definitions.//w  ww .  j  a  v  a 2s . com
 *
 * @param name the name
 * @param category the category
 * @param page the page
 * @param size the size
 * @param uiModel the ui model
 * @param request the http servlet request
 * @return the string
 */
@RequestMapping(method = RequestMethod.GET)
public String list(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "category", required = false) String category,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size, Model uiModel,
        HttpServletRequest request) {

    int sizeNo = size == null ? DEFAULT_PAGE_SIZE : size.intValue();
    int pageNo = page == null ? 0 : page.intValue() - 1;

    DefinitionFilter filter = new DefinitionFilter();
    filter.setEncoding(request.getCharacterEncoding());

    String defaultNameFilter = getMessage("metahive_datadictionary_filter_name");

    if (StringUtils.isNotBlank(name) && !StringUtils.equalsIgnoreCase(name, defaultNameFilter)) {
        filter.setName(name);
    }
    if (StringUtils.isNotBlank(category) && !StringUtils.equalsIgnoreCase(category, "-")) {
        filter.setCategory(category);
    }

    uiModel.addAttribute("definitions", Definition.findDefinitionEntries(filter, pageNo * sizeNo, sizeNo));

    float nrOfPages = (float) Definition.countDefinitions(filter) / sizeNo;

    uiModel.addAttribute("resultCounts", resultCounts());
    uiModel.addAttribute("page", pageNo + 1);
    uiModel.addAttribute("size", sizeNo);
    uiModel.addAttribute("filter", filter);
    uiModel.addAttribute("maxPages",
            (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));

    return "definitions/list";
}

From source file:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java

/**
 * Execute a SPARQL 1.1 Update request using update via POST directly; 
 * see details at http://www.w3.org/TR/sparql11-protocol/\#update-operation
 * //from   w w w  .  ja v a 2 s.c  o m
 * @param request the servlet request (to retrieve the SPARQL 1.1 Update query passed in the
 *            body of the POST request)
 * @HTTP 200 in case the update was carried out successfully
 * @HTTP 400 in case the update query is missing or invalid
 * @HTTP 500 in case the update was not successful
 * @return empty content in case the update was successful, the error message in case an error
 *         occurred
 */
@POST
@Path(UPDATE)
@Consumes("application/sparql-update")
public Response updatePostDirectly(@Context HttpServletRequest request,
        @QueryParam("output") String resultType) {
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("utf-8");
        }
        String q = CharStreams.toString(request.getReader());
        return update(q, resultType, request);
    } catch (IOException e) {
        return Response.serverError().entity(WebServiceUtil.jsonErrorResponse(e)).build();
    }
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }//  w  w w  .jav  a2 s  .  c o m
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:uk.ac.lancs.e_science.fileUpload.UploadRenderer.java

public void decode(FacesContext context, UIComponent component) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId);

    Object newValue;/*ww w.ja  v a  2s. c  o m*/
    ValueBinding binding = component.getValueBinding("value");
    if (binding != null) {
        if (binding.getType(context) == byte[].class) {
            newValue = item.get();
        }
        if (binding.getType(context) == FileItem.class) {
            newValue = item;
        } else {
            String encoding = request.getCharacterEncoding();
            if (encoding != null)
                try {
                    newValue = item.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    newValue = item.getString();
                }
            else
                newValue = item.getString();
        }
        ((EditableValueHolder) component).setSubmittedValue(newValue);
    }

    Object target;
    binding = component.getValueBinding("target");
    if (binding != null)
        target = binding.getValue(context);
    else
        target = component.getAttributes().get("target");

}

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

@RequestMapping(value = { "/ultima.html" })
public ModelAndView ultima(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    String viewName;/*from ww w  .j  a v  a 2s  .co  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);
        }
    }

    Pregunta ultimaPregunta;
    ultimaPregunta = getEncuestaState(request).getRespuestaEncuesta().getUltimaPregunta();
    if (ultimaPregunta == null) {
        throw new BusinessException(new BusinessMessage(null, "La encuesta no tiene preguntas"));
    }

    viewName = "redirect:/pregunta.html?idPregunta=" + ultimaPregunta.getIdPregunta();

    return new ModelAndView(viewName, model);
}

From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getCharacterEncoding() == null)
        req.setCharacterEncoding("UTF-8");
    resp.setContentType("application/json; charset=utf-8");
    resp.setCharacterEncoding("UTF-8");

    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.setHeader("Access-Control-Allow-Methods", "GET, POST");
    resp.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Requested-With, Accept");

    if (null == req.getPathInfo() || "/".equalsIgnoreCase(req.getPathInfo())) {
        handleSenseiRequest(req, resp, _senseiBroker);
    } else if ("/get".equalsIgnoreCase(req.getPathInfo())) {
        handleStoreGetRequest(req, resp);
    } else if ("/sysinfo".equalsIgnoreCase(req.getPathInfo())) {
        handleSystemInfoRequest(req, resp);
    } else if (req.getPathInfo().startsWith("/admin/jmx/")) {
        handleJMXRequest(req, resp);/*ww  w .  ja  va2s. co m*/
    } else if (req.getPathInfo().startsWith("/federatedBroker/")) {
        if (federatedBroker == null) {
            try {
                writeEmptyResponse(req, resp, new SenseiError("The federated broker wasn't initialized",
                        ErrorType.FederatedBrokerUnavailable));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        handleSenseiRequest(req, resp, federatedBroker);
    } else {
        handleSenseiRequest(req, resp, _senseiBroker);
    }
}

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

@Test
public void containerDrainedBody() throws IOException, ServletException {
    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(new byte[0]));
    expect(request.getContentLength()).andReturn(0);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/*from ww  w .  j  a v  a 2  s .c o m*/

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

    // This is the assert since the request would be unwrapped if the body contained parameters
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(request);
    workflow.perform(chain);

    verify(request, chain);
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private void processUpload(HttpServletRequest request, String saveDir)
        throws FileUploadException, UnsupportedEncodingException {
    for (FileItem item : parseRequest(request, saveDir)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found item " + item.getFieldName());
        }/*from w  ww. j  av a2s .c  om*/
        if (item.isFormField()) {
            processNormalFormField(item, request.getCharacterEncoding());
        } else {
            processFileField(item);
        }
    }
}

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

@RequestMapping(value = { "/pregunta.html" })
public ModelAndView pregunta(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    String viewName;//from   ww w .java 2s . co  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 idPregunta;
    try {
        idPregunta = Integer.parseInt(request.getParameter("idPregunta"));
    } catch (NumberFormatException ex) {
        throw new BusinessException(
                new BusinessMessage(null, "El N de pregunta no es vlido.No es un nmero"));
    }

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

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

    RespuestaPregunta respuestaPregunta = getEncuestaState(request).getRespuestaEncuesta()
            .getRespuestaPregunta(pregunta);
    model.put("respuestaPregunta", respuestaPregunta);
    viewName = "encuestas/pregunta";

    return new ModelAndView(viewName, model);
}