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.geowebcache.service.wmts.WMTSGetCapabilities.java

protected WMTSGetCapabilities(TileLayerDispatcher tld, GridSetBroker gsb, HttpServletRequest servReq,
        String baseUrl, String contextPath, URLMangler urlMangler) {
    this.tld = tld;
    this.gsb = gsb;

    String forcedBaseUrl = ServletUtils.stringFromMap(servReq.getParameterMap(), servReq.getCharacterEncoding(),
            "base_url");

    if (forcedBaseUrl != null) {
        this.baseUrl = forcedBaseUrl;
    } else {/*from   w w w.ja  v  a2 s. c  om*/
        this.baseUrl = urlMangler.buildURL(baseUrl, contextPath, WMTSService.SERVICE_PATH);
    }

}

From source file:org.apache.shindig.social.opensocial.service.JsonRpcServlet.java

@Override
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    SecurityToken token = getSecurityToken(servletRequest);
    if (token == null) {
        sendSecurityError(servletResponse);
        return;/*from w w  w. j ava  2 s.  c  o m*/
    }

    setCharacterEncodings(servletRequest, servletResponse);
    servletResponse.setContentType("application/json");

    try {
        String content = IOUtils.toString(servletRequest.getInputStream(),
                servletRequest.getCharacterEncoding());
        if ((content.indexOf('[') != -1) && content.indexOf('[') < content.indexOf('{')) {
            // Is a batch
            JSONArray batch = new JSONArray(content);
            dispatchBatch(batch, servletRequest, servletResponse, token);
        } else {
            JSONObject request = new JSONObject(content);
            dispatch(request, servletRequest, servletResponse, token);
        }
    } catch (JSONException je) {
        sendBadRequest(je, servletResponse);
    }
}

From source file:edu.unc.lib.dl.admin.controller.AbstractSwordController.java

public String updateDatastream(String pid, String datastream, HttpServletRequest request,
        HttpServletResponse response) {// w  w w .j a v a 2 s .  co m
    String responseString = null;
    String dataUrl = swordUrl + "object/" + pid;
    if (datastream != null)
        dataUrl += "/" + datastream;

    Abdera abdera = new Abdera();
    Entry entry = abdera.newEntry();
    Parser parser = abdera.getParser();
    Document<FOMExtensibleElement> doc;
    HttpClient client;
    PutMethod method;

    ParserOptions parserOptions = parser.getDefaultParserOptions();
    parserOptions.setCharset(request.getCharacterEncoding());

    try {

        doc = parser.parse(request.getInputStream(), parserOptions);
        entry.addExtension(doc.getRoot());

        client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
        client.getParams().setAuthenticationPreemptive(true);
        method = new PutMethod(dataUrl);
        // Pass the users groups along with the request
        method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

        Header header = new Header("Content-Type", "application/atom+xml");
        method.setRequestHeader(header);
        StringWriter stringWriter = new StringWriter(2048);
        StringRequestEntity requestEntity;
        entry.writeTo(stringWriter);
        requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8");
        method.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding not supported", e);
        return null;
    } catch (IOException e) {
        log.error("IOException while writing entry", e);
        return null;
    }

    try {
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());
        if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // success
            return "";
        } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) {
            if (method.getStatusCode() == 500)
                log.warn("Failed to upload " + datastream + " " + method.getURI().getURI());
            // probably a validation problem
            responseString = method.getResponseBodyAsString();
            return responseString;
        } else {
            response.setStatus(500);
            throw new Exception("Failure to update fedora content due to response of: "
                    + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return responseString;
}

From source file:org.chiba.adapter.web.HttpRequestHandler.java

/**
 * @param request Servlet request/*w  w  w .  jav a  2s.  c  om*/
 * @param trigger Trigger control
 * @return the calculated trigger
 * @throws XFormsException If an error occurs
 */
protected String processMultiPartRequest(HttpServletRequest request, String trigger) throws XFormsException {
    DiskFileUpload upload = new DiskFileUpload();

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = "ISO-8859-1";
    }

    upload.setRepositoryPath(this.uploadRoot);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("root dir for uploads: " + this.uploadRoot);
    }

    List items;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException fue) {
        throw new XFormsException(fue);
    }

    Map formFields = new HashMap();
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        String itemName = item.getName();
        String fieldName = item.getFieldName();
        String id = fieldName.substring(Config.getInstance().getProperty("chiba.web.dataPrefix").length());

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Multipart item name is: " + itemName + " and fieldname is: " + fieldName
                    + " and id is: " + id);
            LOGGER.debug("Is formfield: " + item.isFormField());
            LOGGER.debug("Content: " + item.getString());
        }

        if (item.isFormField()) {

            // check for upload-remove action
            if (fieldName.startsWith(getRemoveUploadPrefix())) {
                id = fieldName.substring(getRemoveUploadPrefix().length());
                // if data is null, file will be removed ...
                // TODO: remove the file from the disk as well
                chibaBean.updateControlValue(id, "", "", null);
                continue;
            }

            // It's a field name, it means that we got a non-file
            // form field. Upload is not required. We must treat it as we
            // do in processUrlencodedRequest()
            processMultipartParam(formFields, fieldName, item, encoding);
        } else {

            String uniqueFilename = new File(getUniqueParameterName("file"), new File(itemName).getName())
                    .getPath();

            File savedFile = new File(this.uploadRoot, uniqueFilename);

            byte[] data = null;

            data = processMultiPartFile(item, id, savedFile, encoding, data);

            // if data is null, file will be removed ...
            // TODO: remove the file from the disk as well
            chibaBean.updateControlValue(id, item.getContentType(), itemName, data);
        }

        // handle regular fields
        if (formFields.size() > 0) {

            Iterator it = formFields.keySet().iterator();
            while (it.hasNext()) {

                fieldName = (String) it.next();
                String[] values = (String[]) formFields.get(fieldName);

                // [1] handle data
                handleData(fieldName, values);

                // [2] handle selector
                handleSelector(fieldName, values[0]);

                // [3] handle trigger
                trigger = handleTrigger(trigger, fieldName);
            }
        }
    }

    return trigger;
}

From source file:org.mule.transport.servlet.MockHttpServletRequestBuilder.java

public HttpServletRequest buildRequest() throws Exception {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getMethod()).thenReturn(method);

    Enumeration<String> emptyEnumeration = new Hashtable<String, String>().elements();
    when(mockRequest.getParameterNames()).thenReturn(emptyEnumeration);

    when(mockRequest.getRequestURI()).thenReturn(requestUri);
    when(mockRequest.getQueryString()).thenReturn(queryString);
    when(mockRequest.getInputStream()).thenReturn(inputStream);
    when(mockRequest.getSession(anyBoolean())).thenReturn(session);
    when(mockRequest.getCharacterEncoding()).thenReturn(characterEncoding);
    when(mockRequest.getLocalPort()).thenReturn(localPort);
    when(mockRequest.getContentType()).thenReturn(contentType);
    when(mockRequest.getRemoteAddr()).thenReturn(host);
    when(mockRequest.getHeader(eq(HttpConstants.HEADER_HOST))).thenReturn(host);
    when(mockRequest.getPathInfo()).thenReturn(pathInfo);

    addParameterExpectations(mockRequest);
    addAttributeExpectations(mockRequest);
    addHeaderExpectations(mockRequest);//from ww w  . j av a  2s .  c o  m

    return mockRequest;
}

From source file:com.easarrive.image.thumbor.executer.controller.ThumborConfigureController.java

/**
 * ??//from w  w w.jav a 2s. c o  m
 *
 * @param request  
 * @param response ?
 * @return ??
 */
@RequestMapping(value = "/reload", method = { RequestMethod.POST })
@ResponseBody
public DataDeliveryWrapper<Boolean> reloadConfig(HttpServletRequest request, HttpServletResponse response) {
    //??
    String acceptEncoding = this.getAcceptEncoding(request);
    try {
        String version = request.getHeader("VERSION");
        String sign = request.getHeader("DATA_SIGN");
        String charset = request.getHeader("CHARSET");

        //??
        String dataJson = this.getRequestBody(request);

        //?
        if (StringUtil.isEmpty(charset)) {
            charset = request.getCharacterEncoding();
        }
        if (StringUtil.isEmpty(charset)) {
            charset = Constant.Charset.UTF8;
        }

        //
        if (StringUtil.isEmpty(version)) {
            return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_NOT_FOUND,
                    this.encode("", acceptEncoding), false);
        } else if (!"1.0.0.0.1".equals(version)) {
            return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_NOT_FOUND,
                    this.encode("??", acceptEncoding), false);
        } else if (StringUtil.isEmpty(sign)) {
            return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_NOT_FOUND,
                    this.encode("??", acceptEncoding), false);
        } else if (StringUtil.isEmpty(dataJson)) {
            return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_NOT_FOUND,
                    this.encode("?", acceptEncoding), false);
        }

        String signTemp = DigestUtils.md5Hex(dataJson);
        if (!sign.equals(signTemp)) {
            return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_FORBIDDEN,
                    this.encode("??", acceptEncoding), false);
        }

        ConfigureFactory.clear();
        //            ThumborConfigure configure = ConfigureFactory.getConfigure();
        //            if (logger.isInfoEnabled()) {
        //                logger.info("??  {}", configure);
        //            }
        ThumborConfigureMap configureMap = ConfigureFactory.getConfigureMap();
        if (logger.isInfoEnabled()) {
            logger.info("??  {}", configureMap);
        }
        return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_OK,
                this.encode("Thumbor ???", acceptEncoding), true);
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error("Thumbor ?", e);
        }
        return new DataDeliveryWrapper<Boolean>(HttpStatus.SC_INTERNAL_SERVER_ERROR,
                this.encode("Thumbor ??", acceptEncoding), false);
    }
}

From source file:eionet.gdem.utils.MultipartFileUpload.java

/**
 * @param request//from  w  ww .j av a 2s  .c om
 *            Servlet request
 * @throws GDEMException
 *             If an error occurs
 */
public void processMultiPartRequest(HttpServletRequest request) throws GDEMException {

    List items = null;
    setEncoding(request.getCharacterEncoding());
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException fue) {
        throw new GDEMException(fue.toString());
    }

    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        // String itemName = item.getName();
        String fieldName = item.getFieldName();
        // String id = (String) this.parameterNames.get(fieldName);

        /*
         * System.out.println("Multipart item name is: " + itemName + " and fieldname is: " + fieldName); // + " and id is: " +
         * id); System.out.println("Is formfield: " + item.isFormField()); System.out.println("Content: " + item.getString());
         */
        if (item.isFormField()) {
            // It's a field name, it means that we got a non-file
            // form field. Upload is not required.
            String itemValue = null;
            try {
                // use encoding from request
                itemValue = item.getString(getEncoding());
            } catch (UnsupportedEncodingException e) {
                // use default encoding
                itemValue = item.getString();
            }

            if (_params.containsKey(fieldName)) {
                Object curObj = _params.get(fieldName);
                List valueList = null;

                if (curObj instanceof String) {
                    valueList = new ArrayList();
                    valueList.add((String) curObj);
                } else if (curObj instanceof List) {
                    valueList = (List) curObj;
                }
                valueList.add(itemValue);
                _params.put(fieldName, valueList);
            } else {
                _params.put(fieldName, itemValue);
            }
        } else {
            _fileItem = item;
            addFileItem(_fileItem);
            String fileName = getFileItemName(_fileItem.getName());
            setFileName(fileName);
            if (_uploadAtOnce)
                saveFile();
        }
    }
}

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

@RequestMapping(value = "/advanced", method = RequestMethod.POST)
public String advancedSearchProcess(@RequestParam(value = "id", required = false) String id,
        @RequestParam(value = "action", required = false) FilterAction action, Model uiModel,
        HttpServletRequest request) {

    RecordFilter filter = new RecordFilter();
    filter.setEncoding(request.getCharacterEncoding());
    filter.processSearchForm(request);/*  w ww  . j a v  a 2 s . c o  m*/

    Map<String, RecordFilter> searches = getSearches(request);

    if (StringUtils.isNotBlank(id) && searches.containsKey(id)) {
        // This is a modify search operation - get the processed filter vector
        FilterVector vector = null;

        if (filter.getFilterVectors() != null && filter.getFilterVectors().size() > 0) {
            vector = filter.getFilterVectors().get(0);

            if (action != null) {
                vector.setAction(action);
            }
        }
        // Add the vector to the existing search if it is not null
        filter = searches.get(id);
        if (vector != null) {
            filter.getFilterVectors().add(vector);
        }
    }

    // Add the filter to the search array
    searches.put(filter.getId(), filter);

    request.getSession().setAttribute("searches", searches);

    return "redirect:/records?id=" + filter.getId();
}

From source file:easyJ.http.upload.CommonsMultipartRequestHandler.java

/**
 * Adds a regular text parameter to the set of text parameters for this
 * request and also to the list of all parameters. Handles the case of
 * multiple values for the same parameter by using an array for the
 * parameter value.//from  w ww . j  av  a 2s. c  o  m
 * 
 * @param request
 *                The request in which the parameter was specified.
 * @param item
 *                The file item for the parameter to add.
 */
protected void addTextParameter(HttpServletRequest request, FileItem item) {
    String name = item.getFieldName();
    String value = null;

    try {
        value = item.getString(request.getCharacterEncoding());
    } catch (Exception e) {
        value = item.getString();
    }

    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:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java

/**
 * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed in the body of the
 * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
 * <p/>/*from w  ww .  j a va 2  s  .  c om*/
 * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/
 *
 * @param request     the servlet request (to retrieve the SPARQL 1.1 Query passed in the body of the POST request)
 * @param resultType  the format for serializing the query results ("html", "json", or "xml")
 * @HTTP 200 in case the query was executed successfully
 * @HTTP 500 in case there was an error during the query evaluation
 * @return the query result in the format passed as argument
 */
@POST
@Path(SELECT)
public Response selectPost(@QueryParam("output") String resultType, @Context HttpServletRequest request) {
    try {
        if (resultType != null && outputMapper.containsKey(resultType))
            resultType = outputMapper.get(resultType);
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("utf-8");
        }
        String query = CharStreams.toString(request.getReader());
        //String query = IOUtils.toString(request.getInputStream(),"utf-8");
        log.debug("Query: {}", query);
        return select(query, resultType, request);
    } catch (IOException e) {
        log.error("body not found", e);
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    }
}