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.codelibs.fess.api.gsa.GsaApiManager.java

protected void processSearchRequest(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) {
    final SearchService searchService = ComponentUtil.getComponent(SearchService.class);
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final boolean xmlDtd = OUTPUT_XML.equals(request.getParameter("output"));

    if (!fessConfig.isAcceptedSearchReferer(request.getHeader("referer"))) {
        writeXmlResponse(99, xmlDtd, StringUtil.EMPTY, "Referer is invalid.");
        return;//from  www.j  a va  2s  . com
    }

    int status = 0;
    String errMsg = StringUtil.EMPTY;
    String query = null;
    final StringBuilder buf = new StringBuilder(1000);
    request.setAttribute(Constants.SEARCH_LOG_ACCESS_TYPE, Constants.SEARCH_LOG_ACCESS_TYPE_GSA);
    try {
        final SearchRenderData data = new SearchRenderData();
        final GsaRequestParams params = new GsaRequestParams(request, fessConfig);
        query = params.getQuery();
        searchService.search(params, data, OptionalThing.empty());
        final String execTime = data.getExecTime();
        final long allRecordCount = data.getAllRecordCount();
        final List<Map<String, Object>> documentItems = data.getDocumentItems();

        final List<String> getFields = new ArrayList<>();
        // meta tags should be returned
        final String getFieldsParam = request.getParameter("getfields");
        if (StringUtil.isNotBlank(getFieldsParam)) {
            getFields.addAll(Arrays.asList(getFieldsParam.split("\\.")));
        }
        final StringBuilder requestUri = new StringBuilder(request.getRequestURI());
        if (request.getQueryString() != null) {
            requestUri.append("?").append(request.getQueryString());
        }
        final String uriQueryString = requestUri.toString();
        // Input/Output encoding
        final String ie = request.getCharacterEncoding();
        final String oe = "UTF-8";
        // IP address
        final String ip = ComponentUtil.getViewHelper().getClientIp(request);

        buf.append("<TM>");
        buf.append(execTime);
        buf.append("</TM>");
        buf.append("<Q>");
        buf.append(escapeXml(query));
        buf.append("</Q>");
        for (final Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            final String[] values = entry.getValue();
            if (values == null) {
                continue;
            }
            final String key = entry.getKey();
            if ("sort".equals(key)) {
                continue;
            }
            for (final String value : values) {
                appendParam(buf, key, value);
            }
        }
        appendParam(buf, "ie", ie);
        if (request.getParameter("oe") == null) {
            appendParam(buf, "oe", oe);
        }
        final String[] langs = params.getLanguages();
        if (langs.length > 0) {
            appendParam(buf, "inlang", langs[0]);
            appendParam(buf, "ulang", langs[0]);
        }
        appendParam(buf, "ip", ip);
        appendParam(buf, "access", "p");
        appendParam(buf, "sort", params.getSortParam(), params.getSortParam());
        appendParam(buf, "entqr", "3");
        appendParam(buf, "entqrm", "0");
        appendParam(buf, "wc", "200");
        appendParam(buf, "wc_mc", "1");
        if (!documentItems.isEmpty()) {
            buf.append("<RES SN=\"");
            buf.append(data.getCurrentStartRecordNumber());
            buf.append("\" EN=\"");
            buf.append(data.getCurrentEndRecordNumber());
            buf.append("\">");
            buf.append("<M>");
            buf.append(allRecordCount);
            buf.append("</M>");
            if (data.isExistPrevPage() || data.isExistNextPage()) {
                buf.append("<NB>");
                if (data.isExistPrevPage()) {
                    long s = data.getCurrentStartRecordNumber() - data.getPageSize() - 1;
                    if (s < 0) {
                        s = 0;
                    }
                    buf.append("<PU>");
                    buf.append(escapeXml(uriQueryString.replaceFirst("start=([0-9]+)", "start=" + s)));
                    buf.append("</PU>");
                }
                if (data.isExistNextPage()) {
                    buf.append("<NU>");
                    buf.append(escapeXml(uriQueryString.replaceFirst("start=([0-9]+)",
                            "start=" + data.getCurrentEndRecordNumber())));
                    buf.append("</NU>");
                }
                buf.append("</NB>");
            }
            long recordNumber = data.getCurrentStartRecordNumber();
            for (final Map<String, Object> document : documentItems) {
                buf.append("<R N=\"");
                buf.append(recordNumber);
                buf.append("\">");
                final String url = DocumentUtil.getValue(document, fessConfig.getIndexFieldUrl(), String.class);
                document.put("UE", url);
                document.put("U", URLDecoder.decode(url, Constants.UTF_8));
                document.put("T", DocumentUtil.getValue(document, fessConfig.getResponseFieldContentTitle(),
                        String.class));
                final float score = DocumentUtil.getValue(document, Constants.SCORE, Float.class, Float.NaN);
                int rk = 10;
                if (!Float.isNaN(score)) {
                    if (score < 0.0) {
                        rk = 0;
                    } else if (score > 1.0) {
                        rk = 10;
                    } else {
                        rk = (int) (score * 10.0);
                    }
                }
                document.put("RK", rk);
                document.put("S", DocumentUtil.getValue(document,
                        fessConfig.getResponseFieldContentDescription(), String.class, StringUtil.EMPTY));
                final String lang = DocumentUtil.getValue(document, fessConfig.getIndexFieldLang(),
                        String.class);
                if (StringUtil.isNotBlank(lang)) {
                    document.put("LANG", lang);
                    document.remove(fessConfig.getIndexFieldLang());
                }
                final String gsaMetaPrefix = fessConfig.getQueryGsaMetaPrefix();
                for (final Map.Entry<String, Object> entry : document.entrySet()) {
                    final String name = entry.getKey();
                    if (StringUtil.isNotBlank(name) && entry.getValue() != null
                            && fessConfig.isGsaResponseFields(name)) {
                        if (name.startsWith(gsaMetaPrefix)) {
                            final String tagName = name.replaceFirst("^" + gsaMetaPrefix, StringUtil.EMPTY);
                            if (getFields.contains(tagName)) {
                                buf.append("<MT N=\"");
                                buf.append(tagName);
                                buf.append("\" V=\"");
                                buf.append(escapeXml(entry.getValue()));
                                buf.append("\"/>");
                            }
                        } else {
                            final String tagName = name;
                            buf.append('<');
                            buf.append(tagName);
                            buf.append('>');
                            buf.append(escapeXml(entry.getValue()));
                            buf.append("</");
                            buf.append(tagName);
                            buf.append('>');
                        }
                    }
                }
                buf.append("<ENT_SOURCE>").append(escapeXml("FESS")).append("</ENT_SOURCE>");
                String lastModified = DocumentUtil.getValue(document, fessConfig.getIndexFieldLastModified(),
                        String.class);
                if (StringUtil.isBlank(lastModified)) {
                    lastModified = StringUtil.EMPTY;
                }
                lastModified = lastModified.split("T")[0];
                buf.append("<FS NAME=\"date\" VALUE=\"").append(escapeXml(lastModified)).append("\"/>");

                buf.append("<HAS>");
                buf.append("<L/>");
                buf.append("<C SZ=\"");
                buf.append(DocumentUtil.getValue(document, fessConfig.getIndexFieldContentLength(), Long.class,
                        Long.valueOf(0)).longValue() / 1000);
                document.remove(fessConfig.getIndexFieldContentLength());
                buf.append("k\" CID=\"");
                buf.append(DocumentUtil.getValue(document, fessConfig.getIndexFieldDocId(), String.class));
                document.remove(fessConfig.getIndexFieldDocId());
                buf.append("\" ENC=\"");
                final String charsetField = fessConfig.getQueryGsaIndexFieldCharset();
                String charset = DocumentUtil.getValue(document, charsetField, String.class);
                document.remove(charsetField);
                if (StringUtil.isBlank(charset)) {
                    final String contentTypeField = fessConfig.getQueryGsaIndexFieldContentType();
                    charset = DocumentUtil.getValue(document, contentTypeField, String.class);
                    document.remove(contentTypeField);
                    if (StringUtil.isNotBlank(charset)) {
                        final Matcher m = Pattern.compile(".*;\\s*charset=(.+)").matcher(charset);
                        if (m.matches()) {
                            charset = m.group(1);
                        }
                    }
                    if (StringUtil.isBlank(charset)) {
                        charset = Constants.UTF_8;
                    }
                }
                buf.append(charset);
                buf.append("\"/>");
                buf.append("</HAS>");
                buf.append("</R>");
                recordNumber++;
            }
            buf.append("</RES>");
        }
    } catch (final Exception e) {
        status = 1;
        errMsg = e.getMessage();
        if (errMsg == null) {
            errMsg = e.getClass().getName();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to process a search request.", e);
        }
        if (e instanceof InvalidAccessTokenException) {
            final InvalidAccessTokenException iate = (InvalidAccessTokenException) e;
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Bearer error=\"" + iate.getType() + "\"");
        }
    }

    writeXmlResponse(status, xmlDtd, buf.toString(), errMsg);
}

From source file:org.georchestra.security.Proxy.java

private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL)
        throws IOException {
    HttpRequestBase targetRequest;//from  www .  ja  va  2 s  .  com
    try {
        // Split URL
        URL url = new URL(sURL);
        URI uri = buildUri(url);

        switch (requestType) {
        case GET: {
            logger.debug("New request is: " + sURL + "\nRequest is GET");

            HttpGet get = new HttpGet(uri);
            targetRequest = get;
            break;
        }
        case POST: {
            logger.debug("New request is: " + sURL + "\nRequest is POST");

            HttpPost post = new HttpPost(uri);
            HttpEntity entity;
            request.setCharacterEncoding("UTF8");
            if (isFormContentType(request)) {
                logger.debug("Post is recognized as a form post.");
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                    String name = (String) e.nextElement();
                    String[] v = request.getParameterValues(name);
                    for (String value : v) {
                        NameValuePair nv = new BasicNameValuePair(name, value);
                        parameters.add(nv);
                    }
                }
                String charset = request.getCharacterEncoding();
                try {
                    Charset.forName(charset);
                } catch (Throwable t) {
                    charset = null;
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                entity = new UrlEncodedFormEntity(parameters, charset);
                post.setEntity(entity);

            } else {
                logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
                int contentLength = request.getContentLength();
                ServletInputStream inputStream = request.getInputStream();
                entity = new InputStreamEntity(inputStream, contentLength);
            }
            post.setEntity(entity);
            targetRequest = post;
            break;
        }
        case TRACE: {
            logger.debug("New request is: " + sURL + "\nRequest is TRACE");

            HttpTrace post = new HttpTrace(uri);

            targetRequest = post;
            break;
        }
        case OPTIONS: {
            logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");

            HttpOptions post = new HttpOptions(uri);

            targetRequest = post;
            break;
        }
        case HEAD: {
            logger.debug("New request is: " + sURL + "\nRequest is HEAD");

            HttpHead post = new HttpHead(uri);

            targetRequest = post;
            break;
        }
        case PUT: {
            logger.debug("New request is: " + sURL + "\nRequest is PUT");

            HttpPut put = new HttpPut(uri);

            put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));

            targetRequest = put;
            break;
        }
        case DELETE: {
            logger.debug("New request is: " + sURL + "\nRequest is DELETE");

            HttpDelete delete = new HttpDelete(uri);

            targetRequest = delete;
            break;
        }
        default: {
            String msg = requestType + " not yet supported";
            logger.error(msg);
            throw new IllegalArgumentException(msg);
        }

        }
    } catch (URISyntaxException e) {
        logger.error("ERROR creating URI from " + sURL, e);
        throw new IOException(e);
    }

    return targetRequest;
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the
 * request.//from  w w w  . jav a2  s . c  o  m
 *
 * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed
 *         file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files
 *         are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId");
 */
protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp,
        List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException {
    if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req)
            || req.getAttribute(ATTR_UPLOADS_DONE) != null) {
        return req;
    }

    // mark that the uploads have been parsed, so they aren't parsed again on this request
    req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE);

    // Result - map that will be created of request parameters,
    // parsed parameters, and uploaded files
    Map map = new HashMap();

    // parse using commons-fileupload

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold
    if (m_uploadTempDir != null)
        factory.setRepository(new File(m_uploadTempDir));
    if (m_uploadThreshold > 0)
        factory.setSizeThreshold(m_uploadThreshold);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // set the encoding
    String encoding = req.getCharacterEncoding();
    if (encoding != null && encoding.length() > 0)
        upload.setHeaderEncoding(encoding);

    // set the max upload size
    long uploadMax = -1;
    if (m_uploadMaxSize > 0)
        uploadMax = m_uploadMaxSize;

    // check for request-scoped override to upload.max (value in megs)
    String override = req.getParameter(CONFIG_UPLOAD_MAX);
    if (override != null) {
        try {
            // get the max in bytes
            uploadMax = Long.parseLong(override) * 1024L * 1024L;
        } catch (NumberFormatException e) {
            M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override);
        }
    }

    // limit to the ceiling
    if (uploadMax > m_uploadCeiling) {
        /**
         * KNL-602 This is the expected behaviour of the request filter honouring the globaly configured
         * value -DH
         */
        M_log.debug("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > "
                + ((m_uploadCeiling / 1024L) / 1024L) + " megs");

        uploadMax = m_uploadCeiling;
    }

    // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields
    if (!m_uploadContinue) {
        // TODO: when we switch to commons-fileupload 1.2
        // // either per file or overall request, as configured
        // if (m_uploadMaxPerFile)
        // {
        // upload.setFileSizeMax(uploadMax);
        // }
        // else
        // {
        // upload.setSizeMax(uploadMax);
        // }

        upload.setSizeMax(uploadMax);
    }

    try {
        // parse multipart encoded parameters
        boolean uploadOk = true;
        List list = upload.parseRequest(req);
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);

            if (item.isFormField()) {
                String str = item.getString(encoding);

                Object obj = map.get(item.getFieldName());
                if (obj == null) {
                    map.put(item.getFieldName(), new String[] { str });
                } else if (obj instanceof String[]) {
                    String[] old_vals = (String[]) obj;
                    String[] values = new String[old_vals.length + 1];
                    for (int i1 = 0; i1 < old_vals.length; i1++) {
                        values[i1] = old_vals[i1];
                    }
                    values[values.length - 1] = str;
                    map.put(item.getFieldName(), values);
                } else if (obj instanceof String) {
                    String[] values = new String[2];
                    values[0] = (String) obj;
                    values[1] = str;
                    map.put(item.getFieldName(), values);
                }
            } else {
                // collect it for delete at the end of the request
                tempFiles.add(item);

                // check the max, unless we are letting commons-fileupload throw exception on max exceeded
                // Note: the continue option assumes the max is per-file, not overall.
                if (m_uploadContinue && (item.getSize() > uploadMax)) {
                    uploadOk = false;

                    M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L));

                    req.setAttribute("upload.status", "size_limit_exceeded");
                    // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException
                    req.setAttribute("upload.exception",
                            new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax));
                    req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L));
                } else {
                    req.setAttribute(item.getFieldName(), item);
                }
            }
        }

        // unless we had an upload file that exceeded max, set the upload status to "ok"
        if (uploadOk) {
            req.setAttribute("upload.status", "ok");
        }
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L));

        // DON'T throw an exception, instead note the exception
        // so that the tool down-the-line can handle the problem
        req.setAttribute("upload.status", "size_limit_exceeded");
        req.setAttribute("upload.exception", ex);
        req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L));
    }
    // TODO: put in for commons-fileupload 1.2
    // catch (FileUploadBase.FileSizeLimitExceededException ex)
    // {
    // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L));
    //
    // // DON'T throw an exception, instead note the exception
    // // so that the tool down-the-line can handle the problem
    // req.setAttribute("upload.status", "size_limit_exceeded");
    // req.setAttribute("upload.exception", ex);
    // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L));
    // }
    catch (FileUploadException ex) {
        M_log.info("Unexpected exception in upload parsing", ex);
        req.setAttribute("upload.status", "exception");
        req.setAttribute("upload.exception", ex);
    }

    // add any parameters that were in the URL - make sure to get multiples
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        String[] values = req.getParameterValues(name);
        map.put(name, values);
    }

    // return a wrapped response that exposes the parsed parameters and files
    return new WrappedRequestFileUpload(req, map);
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Handles HTTP POST requests.// w  w w  . ja  va2 s .  c  o  m
 * <p>
 * An HTTP POST request specifies parameters in the request body. OGC service specifications use three different
 * ways to encode the parameters:
 * <ul>
 * <li><b>KVP</b>: Parameters are given as <code>key=value</code> pairs which are separated using the &amp;
 * character. This is equivalent to standard HTTP GET requests, except that the parameters are not part of the query
 * string, but the POST body. In this case, the <code>content-type</code> field in the header must be
 * <code>application/x-www-form-urlencoded</code>.</li>
 * <li><b>XML</b>: The POST body contains an XML document. In this case, the <code>content-type</code> field in the
 * header has to be <code>text/xml</code>, but the implementation does not rely on this in order to be more tolerant
 * to clients.</li>
 * <li><b>SOAP</b>: TODO</li>
 * <li><b>Multipart</b>: TODO</li>
 * </ul>
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response);

    try {
        logHeaders(request);
        addHeaders(responseBuffer);
        responseBuffer = handleCompression(responseBuffer);

        LOG.debug("doPost(), contentType: '" + request.getContentType() + "'");

        long entryTime = System.currentTimeMillis();
        try {
            // check if content-type implies that it's a KVP request
            String contentType = request.getContentType();
            boolean isKVP = false;
            if (contentType != null) {
                isKVP = request.getContentType().startsWith("application/x-www-form-urlencoded");
            }
            List<FileItem> multiParts = checkAndRetrieveMultiparts(request);
            InputStream is = request.getInputStream();

            if (isKVP) {
                String queryString = readPostBodyAsString(is);
                LOG.debug("Treating POST input stream as KVP parameters. Raw input: '" + queryString + "'.");
                Map<String, String> normalizedKVPParams = null;
                String encoding = request.getCharacterEncoding();
                if (encoding == null) {
                    LOG.debug("Request has no further encoding information. Defaulting to '" + DEFAULT_ENCODING
                            + "'.");
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, DEFAULT_ENCODING);
                } else {
                    LOG.debug("Client encoding information :" + encoding);
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, encoding);
                }
                dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime);
            } else {
                // if( handle multiparts, get first body from multipart (?)
                // body->requestDoc

                InputStream requestInputStream = null;
                if (multiParts != null && multiParts.size() > 0) {
                    for (int i = 0; i < multiParts.size() && requestInputStream == null; ++i) {
                        FileItem item = multiParts.get(i);
                        if (item != null) {
                            LOG.debug("Using multipart item: " + i + " with contenttype: "
                                    + item.getContentType() + " as the request.");
                            requestInputStream = item.getInputStream();
                        }
                    }
                } else {
                    requestInputStream = is;
                }
                if (requestInputStream == null) {
                    String msg = "Could not create a valid inputstream from request "
                            + ((multiParts != null && multiParts.size() > 0) ? "without" : "with")
                            + " multiparts.";
                    LOG.error(msg);
                    throw new IOException(msg);
                }

                String dummySystemId = "HTTP Post request from " + request.getRemoteAddr() + ":"
                        + request.getRemotePort();
                XMLStreamReader xmlStream = XMLInputFactoryUtils.newSafeInstance()
                        .createXMLStreamReader(dummySystemId, requestInputStream);
                // skip to start tag of root element
                XMLStreamUtils.nextElement(xmlStream);
                if (isSOAPRequest(xmlStream)) {
                    dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts);
                } else {
                    dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts);
                }
            }
        } catch (Throwable e) {
            LOG.debug("Handling HTTP-POST request took: " + (System.currentTimeMillis() - entryTime)
                    + " ms before sending exception.");
            LOG.debug(e.getMessage(), e);
            OWSException ex = new OWSException(e.getLocalizedMessage(), "InvalidRequest");
            OWS ows = null;
            try {
                ows = determineOWSByPath(request);
            } catch (OWSException e2) {
                sendException(ows, e2, responseBuffer, null);
                return;
            }
            sendException(ows, ex, responseBuffer, null);
        }
        LOG.debug("Handling HTTP-POST request with status 'success' took: "
                + (System.currentTimeMillis() - entryTime) + " ms.");
    } finally {
        instance.CONTEXT.remove();
        responseBuffer.flushBuffer();
        if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) {
            validateResponse(responseBuffer);
        }
    }
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information.//from   w  ww. ja v a2  s . c  o  m
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request/*w w  w . j a  va 2s.  c  o  m*/
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

From source file:org.grails.plugins.zkui.metaclass.RedirectDynamicMethod.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from w  w  w .  j  a v a2s  .c om*/
public Object invoke(Object target, String methodName, Object[] arguments) {
    if (arguments.length == 0) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    Map argMap = arguments[0] instanceof Map ? (Map) arguments[0] : Collections.EMPTY_MAP;
    if (argMap.isEmpty()) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();

    HttpServletRequest request = webRequest.getCurrentRequest();
    if (request.getAttribute(GRAILS_REDIRECT_ISSUED) != null) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
    }

    HttpServletResponse response = webRequest.getCurrentResponse();
    if (response.isCommitted()) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
    }

    Object uri = argMap.get(ARGUMENT_URI);
    String url = argMap.containsKey(ARGUMENT_URL) ? argMap.get(ARGUMENT_URL).toString() : null;
    String actualUri;
    if (uri != null) {
        GrailsApplicationAttributes attrs = webRequest.getAttributes();
        actualUri = attrs.getApplicationUri(request) + uri.toString();
    } else if (url != null) {
        actualUri = url;
    } else {
        if (argMap.get(ARGUMENT_ACTION) == null || argMap.get(ARGUMENT_CONTROLLER) == null) {
            throw new CannotRedirectException(
                    "redirect required attribute [controller] or attribute [action] is missing");
        }
        String actionName = argMap.get(ARGUMENT_ACTION).toString();
        String controllerName = argMap.get(ARGUMENT_CONTROLLER).toString();
        controllerName = controllerName != null ? controllerName : webRequest.getControllerName();

        Map params = (Map) argMap.get(ARGUMENT_PARAMS);
        if (params == null) {
            params = new HashMap();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Dynamic method [redirect] looking up URL mapping for controller [" + controllerName
                    + "] and action [" + actionName + "] and params [" + params + "] with [" + urlMappingsHolder
                    + "]");
        }

        Object id = argMap.get(ARGUMENT_ID);
        try {
            if (id != null) {
                params.put(ARGUMENT_ID, id);
            }

            UrlCreator urlMapping = urlMappingsHolder.getReverseMapping(controllerName, actionName, params);
            if (urlMapping == null && LOG.isDebugEnabled()) {
                LOG.debug("Dynamic method [redirect] no URL mapping found for params [" + params + "]");
            }

            String frag = argMap.get(ARGUMENT_FRAGMENT) != null ? argMap.get(ARGUMENT_FRAGMENT).toString()
                    : null;
            actualUri = urlMapping.createURL(controllerName, actionName, params, request.getCharacterEncoding(),
                    frag);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Dynamic method [redirect] mapped to URL [" + actualUri + "]");
            }
        } finally {
            if (id != null) {
                params.remove(ARGUMENT_ID);
            }
        }
    }

    return redirectResponse(actualUri, request, response);
}

From source file:no.sesat.search.http.servlet.SearchServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    logAccessRequest(request);/* w ww  . j a va  2  s  . c  o m*/
    LOG.trace("doGet()");

    final DataModel datamodel = (DataModel) request.getSession().getAttribute(DataModel.KEY);
    final ParametersDataObject parametersDO = datamodel.getParameters();
    final Site site = datamodel.getSite().getSite();

    // BaseContext providing SiteContext and ResourceContext.
    //  We need it casted as a SiteContext for the ResourceContext code to be happy.
    final SiteContext genericCxt = new SiteContext() {
        public PropertiesLoader newPropertiesLoader(final SiteContext siteCxt, final String resource,
                final Properties properties) {

            return UrlResourceLoader.newPropertiesLoader(siteCxt, resource, properties);
        }

        public DocumentLoader newDocumentLoader(final SiteContext siteCxt, final String resource,
                final DocumentBuilder builder) {

            return UrlResourceLoader.newDocumentLoader(siteCxt, resource, builder);
        }

        public BytecodeLoader newBytecodeLoader(SiteContext context, String className, final String jar) {
            return UrlResourceLoader.newBytecodeLoader(context, className, jar);
        }

        @Override
        public Site getSite() {
            return site;
        }
    };

    final DataModelFactory dmFactory;
    try {
        dmFactory = DataModelFactory
                .instanceOf(ContextWrapper.wrap(DataModelFactory.Context.class, genericCxt));

    } catch (SiteKeyedFactoryInstantiationException skfe) {
        throw new ServletException(skfe);
    }

    // DataModel's ControlLevel will be VIEW_CONSTRUCTION (safe setting set by DataModelFilter)
    //  Bring it back to VIEW_CONSTRUCTION.
    dmFactory.assignControlLevel(datamodel, ControlLevel.REQUEST_CONSTRUCTION);

    try {

        final String cParameter = null != parametersDO.getValue(SearchTab.PARAMETER_KEY)
                ? parametersDO.getValue(SearchTab.PARAMETER_KEY).getString()
                : null;

        final SearchTab searchTab = RunningQueryUtility.findSearchTabByKey(datamodel, cParameter, dmFactory,
                genericCxt);

        if (null != searchTab) {

            // this is legacy. shorter to write in templates than $datamodel.page.currentTab
            request.setAttribute("tab", searchTab);

            LOG.debug("Character encoding =" + request.getCharacterEncoding());

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final String ipAddr = null != request.getAttribute(REMOTE_ADDRESS_KEY)
                    ? (String) request.getAttribute(REMOTE_ADDRESS_KEY)
                    : request.getRemoteAddr();

            performFactoryReloads(request.getParameter("reload"), genericCxt, ipAddr,
                    datamodel.getSite().getSiteConfiguration());

            // If the rss is hidden, require a partnerId.
            // The security by obscurity has been somewhat improved by the
            // addition of rssPartnerId as a md5-protected parameter (MD5ProtectedParametersFilter).
            final StringDataObject layout = parametersDO.getValue("layout");
            boolean hiddenRssWithoutPartnerId = null != layout && "rss".equals(layout.getString())
                    && searchTab.isRssHidden() && null == parametersDO.getValues().get("rssPartnerId");

            if (hiddenRssWithoutPartnerId) {

                response.sendError(HttpServletResponse.SC_NOT_FOUND);

            } else if (null != layout && "rss".equals(layout.getString())
                    && "".equals(searchTab.getRssResultName())) {

                LOG.warn("RSS not supported for requested vertical " + searchTab.toString());
                response.sendError(HttpServletResponse.SC_NOT_FOUND);

            } else {
                performSearch(request, response, genericCxt, searchTab, stopWatch);
                getServletContext().getRequestDispatcher("/WEB-INF/jsp/start.jsp").forward(request, response);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

    } finally {

        // DataModel's ControlLevel will be REQUEST_CONSTRUCTION or RUNNING_QUERY_HANDLING
        //  Increment it onwards to VIEW_CONSTRUCTION.
        dmFactory.assignControlLevel(datamodel, ControlLevel.VIEW_CONSTRUCTION);
    }
}