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.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Gets a named parameter from the http request. The given parameter name
 * must be in UTF-8./*from w  w w  .  j av  a2 s  .  co  m*/
 * 
 * @param request
 *            incoming http request
 * @param parameterName
 *            parameter name
 * @return
 */

public static String getParameter(HttpServletRequest request, String parameterName) {

    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding(UTF_8_ENCODE);
        } catch (UnsupportedEncodingException e) {
        }
    }
    return request.getParameter(parameterName);
}

From source file:com.doitnext.http.router.DefaultInvoker.java

void mapParametersToArguments(Annotation[][] parameterAnnotations, Class<?>[] parameterTypes,
        Map<String, PathElement> variableMatches, HttpServletRequest req, HttpServletResponse resp,
        String terminus, PathMatch pm, Object[] arguments) throws Exception {
    Map<String, String[]> queryArgs = parseQueryArgs(req);
    for (int x = 0; x < parameterTypes.length; x++) {
        if (parameterTypes[x].equals(HttpServletRequest.class)) {
            arguments[x] = req;/*w  w  w.ja  v  a 2  s  .  com*/
            continue;
        }
        if (parameterTypes[x].equals(HttpServletResponse.class)) {
            arguments[x] = resp;
            continue;
        }
        if (parameterAnnotations[x].length > 0) {
            for (int y = 0; y < parameterAnnotations[x].length; y++) {
                Annotation annotation = parameterAnnotations[x][y];
                if (annotation instanceof PathParameter) {
                    mapPathParameter((PathParameter) annotation, arguments, parameterTypes[x], variableMatches,
                            x);
                    break;
                } else if (annotation instanceof QueryParameter) {
                    mapQueryParameter((QueryParameter) annotation, arguments, parameterTypes[x], queryArgs, x);
                    break;
                } else if (annotation instanceof Terminus) {
                    if (parameterTypes[x].isAssignableFrom(String.class)) {
                        arguments[x] = terminus;
                        break;
                    } else {
                        throw new UnsupportedConversionException(String.class, parameterTypes[x]);
                    }
                } else if (annotation instanceof RequestBody) {
                    RequestDeserializer deserializer = selectDeserializer(pm);
                    Object argument = deserializer.deserialize(req.getInputStream(), parameterTypes[x],
                            pm.getRoute().getRequestType(), req.getCharacterEncoding());
                    arguments[x] = argument;
                    break;
                }
            }
        }
    }
}

From source file:wicket.protocol.http.WicketFilter.java

/**
 * Handles servlet page requests.//from  www.  j  a v a 2  s. co m
 * 
 * @param servletRequest
 *            Servlet request object
 * @param servletResponse
 *            Servlet response object
 * @throws ServletException
 *             Thrown if something goes wrong during request handling
 * @throws IOException
 */
public final void doGet(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // First, set the webapplication for this thread
    Application.set(webApplication);

    // Create a new webrequest
    final WebRequest request = webApplication.newWebRequest(servletRequest);

    if (webApplication.getRequestCycleSettings().getRenderStrategy() == RenderStrategy.REDIRECT_TO_BUFFER) {
        String queryString = servletRequest.getQueryString();
        if (!Strings.isEmpty(queryString)) {
            // Try to see if there is a redirect stored
            ISessionStore sessionStore = webApplication.getSessionStore();
            String sessionId = sessionStore.getSessionId(request, false);
            if (sessionId != null) {
                BufferedHttpServletResponse bufferedResponse = webApplication.popBufferedResponse(sessionId,
                        queryString);

                if (bufferedResponse != null) {
                    bufferedResponse.writeTo(servletResponse);
                    // redirect responses are ignored for the request
                    // logger...
                    return;
                }
            }
        }
    }

    // If the request does not provide information about the encoding of its
    // body (which includes POST parameters), than assume the default
    // encoding as defined by the wicket application. Bear in mind that the
    // encoding of the request usually is equal to the previous response.
    // However it is a known bug of IE that it does not provide this
    // information. Please see the wiki for more details and why all other
    // browser deliberately copied that bug.
    if (servletRequest.getCharacterEncoding() == null) {
        try {
            // The encoding defined by the wicket settings is used to encode
            // the responses. Thus, it is reasonable to assume the request
            // has the same encoding. This is especially important for
            // forms and form parameters.
            servletRequest.setCharacterEncoding(
                    webApplication.getRequestCycleSettings().getResponseRequestEncoding());
        } catch (UnsupportedEncodingException ex) {
            throw new WicketRuntimeException(ex.getMessage());
        }
    }

    // Get session for request
    final WebSession session = webApplication.getSession(request);

    // Create a response object and set the output encoding according to
    // wicket's application setttings.
    final WebResponse response = webApplication.newWebResponse(servletResponse);
    response.setAjax(request.isAjax());
    response.setCharacterEncoding(webApplication.getRequestCycleSettings().getResponseRequestEncoding());

    try {
        RequestCycle cycle = session.newRequestCycle(request, response);
        try {
            // Process request
            cycle.request();
        } catch (AbortException e) {
            // noop
        }
    } finally {
        // Close response
        response.close();

        // Clean up thread local session
        Session.unset();

        // Clean up thread local application
        Application.unset();
    }
}

From source file:it.classhidra.core.controller.bean.java

public void initNormal(HttpServletRequest request) throws bsControllerException {
    xmloutput = false;//  ww  w. j  a  v a2  s  .  c o  m
    jsonoutput = false;
    boolean inputBase64 = (request.getParameter(bsController.CONST_ID_INPUTBASE64) != null
            && (request.getParameter(bsController.CONST_ID_INPUTBASE64).equalsIgnoreCase("true")
                    || request.getParameter(bsController.CONST_ID_INPUTBASE64)
                            .equalsIgnoreCase(Base64.encodeBase64String("true".getBytes()))));

    Enumeration en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        String value = request.getParameter(key);
        String format = request.getParameter("$format_" + key);
        String replaceOnBlank = request.getParameter("$replaceOnBlank_" + key);
        String replaceOnErrorFormat = request.getParameter("$replaceOnErrorFormat_" + key);

        if (inputBase64) {
            String charset = (request.getCharacterEncoding() == null
                    || request.getCharacterEncoding().equals("")) ? "UTF-8" : request.getCharacterEncoding();
            try {
                if (value != null)
                    value = new String(Base64.decodeBase64(value), charset);
            } catch (Exception e) {
            }
            try {
                if (format != null)
                    format = new String(Base64.decodeBase64(format), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnBlank != null)
                    replaceOnBlank = new String(Base64.decodeBase64(replaceOnBlank), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnErrorFormat != null)
                    replaceOnErrorFormat = new String(Base64.decodeBase64(replaceOnErrorFormat), charset);
            } catch (Exception e) {
            }
        }

        if (key.indexOf(".") == -1) {
            try {
                Object makedValue = null;
                if (format != null) {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeFormatedValue1(delegated, format, value, key,
                                replaceOnBlank, replaceOnErrorFormat);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeFormatedValue1(this, format, value, key,
                                    replaceOnBlank, replaceOnErrorFormat);
                    } else {
                        makedValue = util_makeValue.makeFormatedValue1(this, format, value, key, replaceOnBlank,
                                replaceOnErrorFormat);
                    }
                } else {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeValue1(delegated, value, key);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeValue1(this, value, key);
                    } else {
                        makedValue = util_makeValue.makeValue1(this, value, key);
                    }
                }
                setCampoValueWithPoint(key, makedValue);
            } catch (Exception e) {
                try {
                    Object makedValue = null;
                    if (format != null) {
                        if (delegated != null) {
                            makedValue = util_makeValue.makeFormatedValue(delegated, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                            if (makedValue == null)
                                makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                        getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        } else {
                            makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        }
                    } else
                        makedValue = util_makeValue.makeValue(value, getCampoValue(key));
                    setCampoValueWithPoint(key, makedValue);
                } catch (Exception ex) {
                    if (parametersFly == null)
                        parametersFly = new HashMap();
                    if (key != null && key.length() > 0 && key.indexOf(0) != '$')
                        parametersFly.put(key, value);
                }
            }
        } else {

            Object writeValue = null;
            Object current_requested = (delegated == null) ? this : delegated;

            String last_field_name = null;
            StringTokenizer st = new StringTokenizer(key, ".");
            while (st.hasMoreTokens()) {
                if (st.countTokens() > 1) {
                    String current_field_name = st.nextToken();
                    try {
                        if (writeValue == null && current_requested instanceof HashMap)
                            writeValue = ((HashMap) current_requested).get(current_field_name);
                        if (writeValue == null)
                            writeValue = util_reflect.getValue(current_requested,
                                    "get" + util_reflect.adaptMethodName(current_field_name), null);
                        if (writeValue == null)
                            writeValue = util_reflect.getValue(current_requested, current_field_name, null);
                        if (writeValue == null && current_requested instanceof i_bean)
                            writeValue = ((i_bean) current_requested).get(current_field_name);
                    } catch (Exception e) {
                    }
                    current_requested = writeValue;
                } else {
                    last_field_name = st.nextToken();
                }
                writeValue = null;
            }

            if (current_requested != null) {
                try {
                    if (format != null)
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeFormatedValue1(current_requested, format, value,
                                        last_field_name, replaceOnBlank, replaceOnErrorFormat));
                    else
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeValue1(current_requested, value, last_field_name));
                } catch (Exception e) {
                    try {
                        if (format != null)
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeFormatedValue((delegated == null) ? this : delegated,
                                            format, value, getCampoValue(key), replaceOnBlank,
                                            replaceOnErrorFormat));
                        else
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeValue(value, getCampoValue(key)));
                    } catch (Exception ex) {
                    }
                }
            }

        }
    }
}

From source file:org.ofbiz.webapp.event.RestEventHandler.java

private Map getServiceContext(HttpServletRequest request, DispatchContext dctx, ModelService model,
        Locale locale) throws EventHandlerException {

    // get the http upload configuration
    String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size",
            "-1", dctx.getDelegator());
    long maxUploadSize = -1;
    try {/*from w  w w . j  av a2 s  .  com*/
        maxUploadSize = Long.parseLong(maxSizeStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                module);
        maxUploadSize = -1;
    }
    // get the http size threshold configuration - files bigger than this will be
    // temporarly stored on disk during upload
    String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties",
            "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
    int sizeThreshold = 10240; // 10K
    try {
        sizeThreshold = Integer.parseInt(sizeThresholdStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                module);
        sizeThreshold = -1;
    }
    // directory used to temporarily store files that are larger than the configured size threshold
    String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties",
            "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
    String encoding = request.getCharacterEncoding();
    // check for multipart content types which may have uploaded items
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = FastMap.newInstance();
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        //session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                       item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = FastList.newInstance();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    //request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = FastMap.newInstance();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getAttribute(name);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                //ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            //                   if (UtilValidate.isEmpty(value)) {
            //                       Object tempVal = request.getSession().getAttribute(name);
            //                       if (tempVal != null) {
            //                           value = tempVal;
            //                       }
            //                   }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    return serviceContext;

}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as was sent in the
 * given {@link HttpServletRequest}.//from ww  w . j  ava2  s .  co  m
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest        The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 */
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

        // Replace more completely if destination server is https :
        if (targetSsl) {
            clientUrl = "http://" + clientUrl;
            serverUrl = "https://" + serverUrl;
        }
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace("POST Content Type: {} Encoding: {} Content: {}",
            new Object[] { contentType, encoding, postContent });
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:org.apache.hadoop.test.mock.MockRequestMatcher.java

public void match(HttpServletRequest request) throws IOException {
    if (methods != null) {
        assertThat(//  w  w  w .ja va2 s  .c om
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " is not using one of the expected HTTP methods",
                methods, hasItem(request.getMethod()));
    }
    if (pathInfo != null) {
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected pathInfo", request.getPathInfo(), is(pathInfo));
    }
    if (requestURL != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected requestURL",
                request.getRequestURL().toString(), is(requestURL));
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " does not have the expected value for header " + name,
                    request.getHeader(name), is(headers.get(name)));
        }
    }
    if (cookies != null) {
        List<Cookie> requestCookies = Arrays.asList(request.getCookies());
        for (Cookie cookie : cookies) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " does not have the expected cookie " + cookie, requestCookies, hasItem(cookie));
        }
    }
    if (contentType != null) {
        String[] requestContentType = request.getContentType().split(";", 2);
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected content type", requestContentType[0], is(contentType));
    }
    if (characterEncoding != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected character encoding",
                request.getCharacterEncoding(), equalToIgnoringCase(characterEncoding));
    }
    if (contentLength != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected content length",
                request.getContentLength(), is(contentLength));
    }
    if (attributes != null) {
        for (String name : attributes.keySet()) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " is missing attribute '" + name + "'", request.getAttribute(name), notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " has wrong value for attribute '" + name + "'",
                    request.getAttribute(name), is(request.getAttribute(name)));
        }
    }
    // Note: Cannot use any of the expect.getParameter*() methods because they will read the
    // body and we don't want that to happen.
    if (queryParams != null) {
        String queryString = request.getQueryString();
        Map<String, String[]> requestParams = parseQueryString(queryString == null ? "" : queryString);
        for (String name : queryParams.keySet()) {
            String[] values = requestParams.get(name);
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                    + queryString + " is missing parameter '" + name + "'", values, notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                            + queryString + " is missing a value for parameter '" + name + "'",
                    Arrays.asList(values), hasItem(queryParams.get(name)));
        }
    }
    if (formParams != null) {
        String paramString = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        Map<String, String[]> requestParams = parseQueryString(paramString == null ? "" : paramString);
        for (String name : formParams.keySet()) {
            String[] actualValues = requestParams.get(name);
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                            + paramString + " is missing parameter '" + name + "'",
                    actualValues, notNullValue());
            String[] expectedValues = formParams.get(name);
            for (String expectedValue : expectedValues) {
                assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                        + paramString + " is missing a value " + expectedValue + " for parameter '" + name
                        + "'", Arrays.asList(actualValues), hasItem(expectedValue));
            }
        }
    }
    if (entity != null) {
        if (contentType != null && contentType.endsWith("/xml")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            assertThat(the(actual), isEquivalentTo(the(expect)));
        } else if (contentType != null && contentType.endsWith("/json")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            //        System.out.println( "EXPECT=" + expect );
            //        System.out.println( "ACTUAL=" + actual );
            assertThat(actual, sameJSONAs(expect));
        } else if (characterEncoding == null || request.getCharacterEncoding() == null) {
            byte[] bytes = IOUtils.toByteArray(request.getInputStream());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", bytes, is(entity));
        } else {
            String expect = new String(entity, characterEncoding);
            String actual = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", actual, is(expect));
        }
    }
}

From source file:fr.smile.liferay.EsigatePortlet.java

/**
 * Transform request to IncominqRequest//from  w w w  .j  a  v a2  s . com
 *
 * @param request
 * @param method
 * @return an incoming request
 * @throws IOException
 */
public IncomingRequest create(PortletRequest request, String method) throws IOException {

    HttpServletRequest httpServletRequest = PortalUtil
            .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));

    StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL);

    StringBuilder query = new StringBuilder();
    Enumeration<String> parameters = request.getParameterNames();
    String sep = "";
    while (parameters.hasMoreElements()) {
        String name = parameters.nextElement();
        String[] values = request.getParameterValues(name);
        if (!name.equals(ACTION_PARAMETER)) {
            for (String value : values) {
                query.append(sep);
                query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8"));
                sep = "&";
            }
        }
    }

    ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0);

    if (method.equals("GET")) {
        if (!query.toString().isEmpty()) {
            if (!uri.toString().contains("?")) {
                uri.append("?");
            } else {
                uri.append("&");
            }
            uri.append(query);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion "
                + protocolVersion);
    }
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(method, uri.toString(), protocolVersion));

    if (method.equals("POST")) {
        // create entity
        InputStream inputStream = IOUtils.toInputStream(query.toString());

        if (inputStream != null) {
            // Copy entity-related headers
            InputStreamEntity entity = new InputStreamEntity(inputStream, query.length());
            String contentTypeHeader = httpServletRequest.getContentType();
            if (contentTypeHeader != null) {
                entity.setContentType(contentTypeHeader);
            }
            String contentEncodingHeader = httpServletRequest.getCharacterEncoding();
            if (contentEncodingHeader != null) {
                entity.setContentEncoding(contentEncodingHeader);
            }
            builder.setEntity(entity);
        }
    }

    HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null);
    builder.setContext(context);
    builder.setRemoteAddr(httpServletRequest.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());
    // Copy cookies
    javax.servlet.http.Cookie[] src = request.getCookies();

    if (src != null) {
        LOG.debug("Copying " + src.length + " cookie(s) to response.");
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            dest.setSecure(c.getSecure());
            dest.setDomain(c.getDomain());
            dest.setPath(c.getPath());
            dest.setComment(c.getComment());
            dest.setVersion(c.getVersion());
            builder.addCookie(dest);
        }
    }

    builder.setSession(new HttpServletSession(httpServletRequest));

    IncomingRequest incomingRequest = builder.build();
    return incomingRequest;

}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request/*from  w w w.j  a v a2 s.c o  m*/
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        String serverUrl = request.getHeader("serverUrl");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = new PostMethod(serverUrl);

            // Transfer bytes from in to out
            log.info("HTTP POST transfering..." + serverUrl);
            String body = inputStreamAsString(request.getInputStream());

            HttpClient client = new HttpClient();

            httppost.setRequestBody(body);
            if (0 == httppost.getParameters().length) {
                log.debug("No Name/Value pairs found ... pushing as raw_post_data");
                httppost.setParameter("raw_post_data", body);
            }
            if (log.isDebugEnabled()) {
                log.debug("Body = " + body);
                NameValuePair[] nameValuePairs = httppost.getParameters();
                log.debug("NameValuePairs found: " + nameValuePairs.length);
                for (int i = 0; i < nameValuePairs.length; ++i) {
                    log.debug("parameters:" + nameValuePairs[i].toString());
                }
            }
            //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);

            client.executeMethod(httppost);
            if (log.isDebugEnabled()) {
                Header[] respHeaders = httppost.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                response.setContentType("text/xml");
                String responseBody = httppost.getResponseBodyAsString();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
            } else {
                log.error("Unexpected failure: " + httppost.getStatusLine().toString());
            }
            httppost.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

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

/**
 * Creates a new request wrapper to handle multi-part data using methods
 * adapted from Jason Pell's multipart classes (see class description).
 * //from  w ww .  j  ava2s  .  c  o  m
 * @param saveDir
 *            the directory to save off the file
 * @param servletRequest
 *            the request containing the multipart
 * @throws java.io.IOException
 *             is thrown if encoding fails.
 * @throws
 */
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {

    Integer delay = 3;
    UploadListener listener = null;
    DiskFileItemFactory fac = null;

    // Parse the request
    try {
        if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) {
            servletRequest.setAttribute("error", "size");
            FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest);
            // handle with each file:
            while (it.hasNext()) {
                FileItemStream item = it.next();
                if (item.isFormField()) {
                    List<String> values;
                    if (params.get(item.getFieldName()) != null) {
                        values = params.get(item.getFieldName());
                    } else {
                        values = new ArrayList<String>();
                    }
                    InputStream stream = item.openStream();
                    values.add(Streams.asString(stream));
                    params.put(item.getFieldName(), values);
                }
            }
            return;
        } else {
            listener = new UploadListener(servletRequest, delay);
            fac = new MonitoredDiskFileItemFactory(listener);
        }

        // Make sure that the data is written to file
        fac.setSizeThreshold(0);
        if (saveDir != null) {
            fac.setRepository(new File(saveDir));
        }
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (log.isDebugEnabled())
                log.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                log.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                log.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning
                // that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    log.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                String targetFileName = item.getName();

                if (!targetFileName.contains(":"))
                    item.write(new File(targetDirectory + targetFileName));

                //?Action
                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (Exception e) {
        log.error(e);
        errors.add(e.getMessage());
    }
}