Example usage for javax.servlet.http HttpServletRequest getHeaderNames

List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaderNames.

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleCopyBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String destContainerName, String destBlobName) throws IOException, S3Exception {
    String copySourceHeader = request.getHeader("x-amz-copy-source");
    copySourceHeader = URLDecoder.decode(copySourceHeader, "UTF-8");
    if (copySourceHeader.startsWith("/")) {
        // Some clients like boto do not include the leading slash
        copySourceHeader = copySourceHeader.substring(1);
    }/*from   w  w  w . j a v a  2s . c o m*/
    String[] path = copySourceHeader.split("/", 2);
    if (path.length != 2) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }
    String sourceContainerName = path[0];
    String sourceBlobName = path[1];
    boolean replaceMetadata = "REPLACE".equalsIgnoreCase(request.getHeader("x-amz-metadata-directive"));

    if (sourceContainerName.equals(destContainerName) && sourceBlobName.equals(destBlobName)
            && !replaceMetadata) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }

    CopyOptions.Builder options = CopyOptions.builder();

    String ifMatch = request.getHeader("x-amz-copy-source-if-match");
    if (ifMatch != null) {
        options.ifMatch(ifMatch);
    }
    String ifNoneMatch = request.getHeader("x-amz-copy-source-if-none-match");
    if (ifNoneMatch != null) {
        options.ifNoneMatch(ifNoneMatch);
    }
    long ifModifiedSince = request.getDateHeader("x-amz-copy-source-if-modified-since");
    if (ifModifiedSince != -1) {
        options.ifModifiedSince(new Date(ifModifiedSince));
    }
    long ifUnmodifiedSince = request.getDateHeader("x-amz-copy-source-if-unmodified-since");
    if (ifUnmodifiedSince != -1) {
        options.ifUnmodifiedSince(new Date(ifUnmodifiedSince));
    }

    if (replaceMetadata) {
        ContentMetadataBuilder contentMetadata = ContentMetadataBuilder.create();
        ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
        for (String headerName : Collections.list(request.getHeaderNames())) {
            String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
            if (headerName.equalsIgnoreCase(HttpHeaders.CACHE_CONTROL)) {
                contentMetadata.cacheControl(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_DISPOSITION)) {
                contentMetadata.contentDisposition(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) {
                contentMetadata.contentEncoding(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LANGUAGE)) {
                contentMetadata.contentLanguage(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) {
                contentMetadata.contentType(headerValue);
            } else if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) {
                userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()), headerValue);
            }
            // TODO: Expires
        }
        options.contentMetadata(contentMetadata.build());
        options.userMetadata(userMetadata.build());
    }

    String eTag;
    try {
        eTag = blobStore.copyBlob(sourceContainerName, sourceBlobName, destContainerName, destBlobName,
                options.build());
    } catch (KeyNotFoundException knfe) {
        throw new S3Exception(S3ErrorCode.NO_SUCH_KEY, knfe);
    }

    // TODO: jclouds should include this in CopyOptions
    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl != null && !cannedAcl.equalsIgnoreCase("private")) {
        handleSetBlobAcl(request, response, is, blobStore, destContainerName, destBlobName);
    }

    BlobMetadata blobMetadata = blobStore.blobMetadata(destContainerName, destBlobName);
    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("CopyObjectResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeSimpleElement(xml, "LastModified", formatDate(blobMetadata.getLastModified()));
        writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag));

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.pentaho.platform.web.servlet.GenericServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    if (showDeprecationMessage) {
        String deprecationMessage = "GenericServlet is deprecated and should no longer be handling requests. More detail below..."
                + "\n | You have issued a {0} request to {1} from referer {2} "
                + "\n | Please consider using one of the following REST services instead:"
                + "\n | * GET /api/repos/<pluginId>/<path> to read files from a plugin public dir"
                + "\n | * POST|GET /api/repos/<pathId>/generatedContent to create content resulting from execution of a "
                + "repo file"
                + "\n | * POST|GET /api/repos/<pluginId>/<contentGeneratorId> to execute a content generator by name (RPC "
                + "compatibility service)"
                + "\n \\ To turn this message off, set init-param 'showDeprecationMessage' to false in the GenericServlet "
                + "declaration" + "";
        String referer = StringUtils.defaultString(request.getHeader("Referer"), "");
        logger.warn(MessageFormat.format(deprecationMessage, request.getMethod(), request.getRequestURL(),
                referer));//from w  ww. j  a  v  a  2  s  .  c o m
    }

    PentahoSystem.systemEntryPoint();

    IOutputHandler outputHandler = null;
    // BISERVER-2767 - grabbing the current class loader so we can replace it at the end
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    try {
        InputStream in = request.getInputStream();
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String contentGeneratorId = ""; //$NON-NLS-1$
        String urlPath = ""; //$NON-NLS-1$
        SimpleParameterProvider pathParams = new SimpleParameterProvider();
        if (StringUtils.isEmpty(pathInfo)) {
            logger.error(
                    Messages.getInstance().getErrorString("GenericServlet.ERROR_0005_NO_RESOURCE_SPECIFIED")); //$NON-NLS-1$
            response.sendError(403);
            return;
        }

        String path = pathInfo.substring(1);
        int slashPos = path.indexOf('/');
        if (slashPos != -1) {
            pathParams.setParameter("path", pathInfo.substring(slashPos + 1)); //$NON-NLS-1$
            contentGeneratorId = path.substring(0, slashPos);
        } else {
            contentGeneratorId = path;
        }
        urlPath = "content/" + contentGeneratorId; //$NON-NLS-1$

        pathParams.setParameter("query", request.getQueryString()); //$NON-NLS-1$
        pathParams.setParameter("contentType", request.getContentType()); //$NON-NLS-1$
        pathParams.setParameter("inputstream", in); //$NON-NLS-1$
        pathParams.setParameter("httpresponse", response); //$NON-NLS-1$
        pathParams.setParameter("httprequest", request); //$NON-NLS-1$
        pathParams.setParameter("remoteaddr", request.getRemoteAddr()); //$NON-NLS-1$
        if (PentahoSystem.debug) {
            debug("GenericServlet contentGeneratorId=" + contentGeneratorId); //$NON-NLS-1$
            debug("GenericServlet urlPath=" + urlPath); //$NON-NLS-1$
        }
        IPentahoSession session = getPentahoSession(request);
        IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
        if (pluginManager == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0001_BAD_OBJECT", //$NON-NLS-1$
                    IPluginManager.class.getSimpleName());
            error(message);
            out.write(message.getBytes());
            return;
        }

        // TODO make doing the HTTP headers configurable per content generator
        SimpleParameterProvider headerParams = new SimpleParameterProvider();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getHeader(name);
            headerParams.setParameter(name, value);
        }

        String pluginId = pluginManager.getServicePlugin(pathInfo);

        if (pluginId != null && pluginManager.isStaticResource(pathInfo)) {
            boolean cacheOn = "true"
                    .equals(pluginManager.getPluginSetting(pluginId, "settings/cache", "false")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
            String maxAge = (String) pluginManager.getPluginSetting(pluginId, "settings/max-age", null); //$NON-NLS-1$
            allowBrowserCache(maxAge, pathParams);

            String mimeType = MimeHelper.getMimeTypeFromFileName(pathInfo);
            if (mimeType != null) {
                response.setContentType(mimeType);
            }
            OutputStream out = response.getOutputStream();

            // do we have this resource cached?
            ByteArrayOutputStream byteStream = null;

            if (cacheOn) {
                byteStream = (ByteArrayOutputStream) cache.getFromRegionCache(CACHE_FILE, pathInfo);
            }

            if (byteStream != null) {
                IOUtils.write(byteStream.toByteArray(), out);
                return;
            }
            InputStream resourceStream = pluginManager.getStaticResource(pathInfo);
            if (resourceStream != null) {
                try {
                    byteStream = new ByteArrayOutputStream();
                    IOUtils.copy(resourceStream, byteStream);

                    // if cache is enabled, drop file in cache
                    if (cacheOn) {
                        cache.putInRegionCache(CACHE_FILE, pathInfo, byteStream);
                    }

                    // write it out
                    IOUtils.write(byteStream.toByteArray(), out);
                    return;
                } finally {
                    IOUtils.closeQuietly(resourceStream);
                }
            }
            logger.error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0004_RESOURCE_NOT_FOUND", //$NON-NLS-1$
                    pluginId, pathInfo));
            response.sendError(404);
            return;
        }

        // content generators defined in plugin.xml are registered with 2 aliases, one is the id, the other is type
        // so, we can still retrieve a content generator by id, even though this is not the correct way to find
        // it. the correct way is to look up a content generator by pluginManager.getContentGenerator(type,
        // perspectiveName)
        IContentGenerator contentGenerator = (IContentGenerator) pluginManager.getBean(contentGeneratorId);
        if (contentGenerator == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR",
                    ESAPI.encoder().encodeForHTML(contentGeneratorId)); //$NON-NLS-1$
            error(message);
            out.write(message.getBytes());
            return;
        }

        // set the classloader of the current thread to the class loader of
        // the plugin so that it can load its libraries
        // Note: we cannot ask the contentGenerator class for it's classloader, since the cg may
        // actually be a proxy object loaded by main the WebAppClassloader
        Thread.currentThread().setContextClassLoader(pluginManager.getClassLoader(pluginId));

        // String proxyClass = PentahoSystem.getSystemSetting( module+"/plugin.xml" ,
        // "plugin/content-generators/"+contentGeneratorId,
        // "content generator not found");
        IParameterProvider requestParameters = new HttpRequestParameterProvider(request);
        // see if this is an upload

        // File uploading is a service provided by UploadFileServlet where appropriate protections
        // are in place to prevent uploads that are too large.

        // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // if (isMultipart) {
        // requestParameters = new SimpleParameterProvider();
        // // Create a factory for disk-based file items
        // FileItemFactory factory = new DiskFileItemFactory();
        //
        // // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        //
        // // Parse the request
        // List<?> /* FileItem */items = upload.parseRequest(request);
        // Iterator<?> iter = items.iterator();
        // while (iter.hasNext()) {
        // FileItem item = (FileItem) iter.next();
        //
        // if (item.isFormField()) {
        // ((SimpleParameterProvider) requestParameters).setParameter(item.getFieldName(), item.getString());
        // } else {
        // String name = item.getName();
        // ((SimpleParameterProvider) requestParameters).setParameter(name, item.getInputStream());
        // }
        // }
        // }

        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());

        IMimeTypeListener listener = new HttpMimeTypeListener(request, response);

        outputHandler = getOutputHandler(response, true);
        outputHandler.setMimeTypeListener(listener);

        IParameterProvider sessionParameters = new HttpSessionParameterProvider(session);
        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
        Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
        parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParameters);
        parameterProviders.put(IParameterProvider.SCOPE_SESSION, sessionParameters);
        parameterProviders.put("headers", headerParams); //$NON-NLS-1$
        parameterProviders.put("path", pathParams); //$NON-NLS-1$
        SimpleUrlFactory urlFactory = new SimpleUrlFactory(requestContext.getContextPath() + urlPath + "?"); //$NON-NLS-1$ //$NON-NLS-2$
        List<String> messages = new ArrayList<String>();
        contentGenerator.setOutputHandler(outputHandler);
        contentGenerator.setMessagesList(messages);
        contentGenerator.setParameterProviders(parameterProviders);
        contentGenerator.setSession(session);
        contentGenerator.setUrlFactory(urlFactory);
        // String contentType = request.getContentType();
        // contentGenerator.setInput(input);
        contentGenerator.createContent();
        if (PentahoSystem.debug) {
            debug("Generic Servlet content generate successfully"); //$NON-NLS-1$
        }

    } catch (Exception e) {
        StringBuffer buffer = new StringBuffer();
        error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", //$NON-NLS-1$
                request.getQueryString()), e);
        List errorList = new ArrayList();
        String msg = e.getMessage();
        errorList.add(msg);
        PentahoSystem.get(IMessageFormatter.class, PentahoSessionHolder.getSession())
                .formatFailureMessage("text/html", null, buffer, errorList); //$NON-NLS-1$
        response.getOutputStream().write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));

    } finally {
        // reset the classloader of the current thread
        Thread.currentThread().setContextClassLoader(origContextClassloader);
        PentahoSystem.systemExitPoint();
    }
}

From source file:com.portfolio.rest.RestServicePortfolio.java

public void logRestRequest(HttpServletRequest httpServletRequest, String inBody, String outBody, int httpCode) {

    try {// w  ww . j  a v  a 2s .  c  o m
        if (logRestRequests == 1) {
            String httpHeaders = "";
            Enumeration headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = (String) headerNames.nextElement();
                httpHeaders += headerName + ": " + httpServletRequest.getHeader(headerName) + "\n";
            }
            String url = httpServletRequest.getRequestURL().toString();
            if (httpServletRequest.getQueryString() != null)
                url += "?" + httpServletRequest.getQueryString().toString();
            dataProvider.writeLog(url, httpServletRequest.getMethod().toString(), httpHeaders, inBody, outBody,
                    httpCode);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();/*w  w  w.ja  v  a 2 s  . co  m*/
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:org.wings.session.PortletSessionServlet.java

/**
 * Verarbeitet Informationen vom Browser:
 * <UL>/*from  w  ww .  j ava 2  s .  c o m*/
 * <LI> setzt Locale
 * <LI> Dispatch Get Parameter
 * <LI> feuert Form Events
 * </UL>
 * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet
 * werden kann.
 */
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) {
    // Special case: You double clicked i.e. a "logout button"
    // First request arrives, second is on hold. First invalidates session and sends redirect as response,
    // but browser ignores and expects response in second request. But second request has longer a valid session.
    if (session == null) {
        try {
            response.sendRedirect(exitSessionWorkaround != null ? exitSessionWorkaround : "");
            return;
        } catch (IOException e) {
            log.info("Session exit workaround failed to to IOException (triple click?)");
        }
    }

    SessionManager.setSession(session);
    session.setServletRequest(req);
    session.setServletResponse(response);

    session.fireRequestEvent(SRequestEvent.REQUEST_START);

    // in case, the previous thread did not clean up.
    SForm.clearArmedComponents();

    Device outputDevice = null;

    ReloadManager reloadManager = session.getReloadManager();

    try {
        /*
         * The tomcat 3.x has a bug, in that it does not encode the URL
         * sometimes. It does so, when there is a cookie, containing some
         * tomcat sessionid but that is invalid (because, for instance,
         * we restarted the tomcat in-between).
         * [I can't think of this being the correct behaviour, so I assume
         *  it is a bug. ]
         *
         * So we have to workaround this here: if we actually got the
         * session id from a cookie, but it is not valid, we don't do
         * the encodeURL() here: we just leave the requestURL as it is
         * in the properties .. and this is url-encoded, since
         * we had set it up in the very beginning of this session
         * with URL-encoding on  (see WingServlet::newSession()).
         *
         * Vice versa: if the requestedSessionId is valid, then we can
         * do the encoding (which then does URL-encoding or not, depending
         * whether the servlet engine detected a cookie).
         * (hen)
         */
        RequestURL portletRequestURL = null;
        // get the renderResponse
        RenderResponse renderResponse = (RenderResponse) req.getAttribute(Const.REQUEST_ATTR_RENDER_RESPONSE);
        if (renderResponse == null) {
            log.error("WingS-Portlet-Bridge: cant get the request attribute "
                    + Const.REQUEST_ATTR_RENDER_RESPONSE);
        }
        PortletURL actionURL = renderResponse.createActionURL();
        if (req.isRequestedSessionIdValid()) {
            portletRequestURL = new PortletRequestURL(actionURL.toString(),
                    response.encodeURL(actionURL.toString()));
            log.debug("WingS-Portlet-Bridge: created PortletRequestURL " + actionURL.toString());
            // this will fire an event, if the encoding has changed ..
            session.setProperty("request.url", portletRequestURL);
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_RESPONSE, renderResponse);

            // get the RenderRequest
            RenderRequest renderRequest = (RenderRequest) req.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST);
            if (renderRequest == null) {
                log.error("WingS-Portlet-Bridge: cant get the request attribute "
                        + Const.REQUEST_ATTR_RENDER_REQUEST);
            }
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_REQUEST, renderRequest);
        }

        if (log.isDebugEnabled()) {
            log.debug("Request URL: " + portletRequestURL);
            log.debug("HTTP header:");
            for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) {
                String header = (String) en.nextElement();
                log.debug("    " + header + ": " + req.getHeader(header));
            }
        }
        handleLocale(req);

        // WingS-Portlet-Bridge: get the Parameter from the map in the request
        // set by the portlet
        Map params = (Map) req.getAttribute(Const.REQUEST_ATTR_PARAMETERS_FROM_ACTION_MAP);

        // The externalizer is able to handle static and dynamic resources
        ExternalizeManager extManager = getSession().getExternalizeManager();
        //WingS-Portlet-Bridge:
        //String pathInfo = req.getPathInfo();                    // Note: Websphere returns <code>null</code> here!
        String pathInfo = null;
        if (params != null) {
            String[] path = (String[]) params.get(Const.REQUEST_PARAM_RESOURCE_AS_PARAM);
            if (path != null)
                pathInfo = path[0];
        }

        if (pathInfo != null && pathInfo.length() > 0) {
            // strip of leading /
            // WingS-Portlet-Bridge:
            // pathInfo = pathInfo.substring(1);
        }

        log.info("WingS-Portlet-Bridge: pathInfo: " + pathInfo);

        // If we have no path info, or the special '_' path info (that should be explained
        // somewhere, Holger), then we deliver the top-level frame of this application.
        String externalizeIdentifier = null;
        if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) {
            externalizeIdentifier = retrieveCurrentRootFrameResource().getId();
            firstRequest = false;
        } else {
            externalizeIdentifier = pathInfo;
        }

        // Retrieve externalized resource
        ExternalizedResource extInfo = extManager.getExternalizedResource(externalizeIdentifier);

        // Special case handling: We request a .html resource of a session which is not accessible.
        // This happens some times and leads to a 404, though it should not be possible.
        if (extInfo == null && pathInfo != null && pathInfo.endsWith(".html")) {
            log.info("Found a request to an invalid .html during a valid session. Redirecting to root frame.");
            response.sendRedirect(retrieveCurrentRootFrameResource().getURL().toString());
            return;
        }

        if (extInfo != null && extInfo.getObject() instanceof UpdateResource) {
            reloadManager.setUpdateMode(true);
        } else {
            reloadManager.setUpdateMode(false);
        }

        // Prior to dispatching the actual events we have to detect
        // their epoch and inform the dispatcher which will then be
        // able to check if the request is valid and processed. If
        // this is not the case, we force a complete page reload.
        String ee = "";
        if (params != null) {
            String[] eeArray = (String[]) params.get("event_epoch");
            if (eeArray != null)
                ee = eeArray[0];
        }
        session.getDispatcher().setEventEpoch(ee);

        // WingS-Portlet-Bridge: Map for the parameters 
        // set by a SPortletAnchor or set in the Portlet
        Map portletParameters = new HashMap();

        // Enumeration en = req.getParameterNames();
        if (params != null) {
            Set paramNames = params.keySet();
            Iterator paramNamesIter = paramNames.iterator();

            Cookie[] cookies = req.getCookies();

            // are there parameters/low level events to dispatch
            if (paramNamesIter.hasNext()) {
                // only fire DISPATCH_START if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_START);

                if (cookies != null) {
                    //dispatch cookies
                    for (int i = 0; i < cookies.length; i++) {
                        Cookie cookie = cookies[i];
                        String paramName = cookie.getName();
                        String value = cookie.getValue();

                        if (log.isDebugEnabled())
                            log.debug("dispatching cookie " + paramName + " = " + value);

                        session.getDispatcher().dispatch(paramName, new String[] { value });
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug("Parameters:");
                    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                        String paramName = (String) e.nextElement();
                        StringBuilder param = new StringBuilder();
                        param.append("    ").append(paramName).append(": ");
                        final String[] values = req.getParameterValues(paramName);
                        param.append(values != null ? Arrays.toString(values) : "null");
                        log.debug(param);
                    }
                }

                while (paramNamesIter.hasNext()) {
                    String paramName = (String) paramNamesIter.next();
                    String[] values = (String[]) params.get(paramName);

                    // We do not need to dispatch the event epoch and the XHR request ID
                    if (paramName.equals("event_epoch") || paramName.equals("_xhrID")) {
                        continue;
                    }

                    String value = values[0];

                    // Split the values of the event trigger
                    if (paramName.equals("event_trigger")) {
                        int pos = value.indexOf('|');
                        paramName = value.substring(0, pos);
                        values = new String[] { value.substring(pos + 1) };
                    }

                    // Handle form submit via default button
                    if (paramName.equals("default_button")) {
                        if (value.equals("undefined")) {
                            continue;
                        } else {
                            paramName = values[0];
                            values = new String[] { "1" };
                        }
                    }

                    // WingS-Portlet-Bridge: get the portlet parameters
                    if (paramName.startsWith(Const.WINGS_PORTLET_URL_CODE_STRING)) {
                        log.info("WingS-Portlet-Bridge: getting portlet parameter " + paramName + " = "
                                + Arrays.asList(values));
                        portletParameters.put(PortletParameterCodec.decode(paramName), values);
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("dispatching " + paramName + " = " + Arrays.asList(values));
                        session.getDispatcher().dispatch(paramName, values);
                    }

                }

                SForm.fireEvents();

                // only fire DISPATCH DONE if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_DONE);
            }
        }

        //WingS-Portlet-Bridge: store the portlet parameters in the session
        session.setProperty(Const.WINGS_SESSION_PROPERTY_PORTLET_PARAMETER_MAP, portletParameters);

        session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST);
        session.getDispatcher().invokeRunnables();

        // WingS-Portlet-Bridge: fires events if the window state has changed
        session.fireWindowStateEvents();
        // WingS-Portlet-Bridge: fires events for the new portlet parameters
        session.fireNewPortletParameters();

        // if the user chose to exit the session as a reaction on an
        // event, we got an URL to redirect after the session.
        /*
         * where is the right place?
         * The right place is
         *    - _after_ we processed the events
         *        (e.g. the 'Pressed Exit-Button'-event or gave
         *         the user the chance to exit this session in the custom
         *         processRequest())
         *    - but _before_ the rendering of the page,
         *      because otherwise an redirect won't work, since we must
         *      not have sent anything to the output stream).
         */
        if (session.getExitAddress() != null) {

            try {
                session.firePrepareExit();
                session.fireRequestEvent(SRequestEvent.REQUEST_END);

                String redirectAddress;
                if (session.getExitAddress().length() > 0) {
                    // redirect to user requested URL.
                    redirectAddress = session.getExitAddress();
                } else {
                    // redirect to a fresh session.
                    redirectAddress = req.getRequestURL().toString();
                }
                req.getSession().invalidate(); // calls destroy implicitly
                response.sendRedirect(redirectAddress);
                exitSessionWorkaround = redirectAddress;
                return;
            } catch (ExitVetoException ex) {
                session.exit(null);
            } // end of try-catch
        }

        if (session.getRedirectAddress() != null) {
            handleRedirect(response);
            return;
        }

        reloadManager.notifyCGs();
        reloadManager.invalidateFrames();

        // TODO ResourceMapper
        ResourceMapper mapper = session.getResourceMapper();
        if (extInfo == null && mapper != null) {
            //wings-Portlet-Bridge:
            //                Resource res = mapper.mapResource(req.getPathInfo());
            Resource res = mapper.mapResource(pathInfo);
            if (res != null) {
                extInfo = extManager.getExternalizedResource(res.getId());
            }
        }

        if (extInfo != null) {
            outputDevice = DeviceFactory.createDevice(extInfo);
            session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo);

            long startTime = System.currentTimeMillis();
            extManager.deliver(extInfo, response, outputDevice);
            long endTime = System.currentTimeMillis();
            log.debug("------------------------- Time needed for rendering: " + (endTime - startTime)
                    + " ms -------------------------\n");

            session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo);
        } else {
            handleUnknownResourceRequested(req, response);
        }

    } catch (Throwable e) {
        log.error("Uncaught Exception", e);
        handleException(response, e);
    } finally {
        if (session != null) {
            session.fireRequestEvent(SRequestEvent.REQUEST_END);
        }

        if (outputDevice != null) {
            try {
                outputDevice.close();
            } catch (Exception e) {
            }
        }

        /*
         * the session might be null due to destroy().
         */
        if (session != null) {
            reloadManager.clear();
            session.setServletRequest(null);
            session.setServletResponse(null);
        }

        // make sure that the session association to the thread is removed
        // from the SessionManager
        SessionManager.removeSession();
        SForm.clearArmedComponents();
    }
}

From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

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

    String ips = request.getHeader("X-Forwarded-For");

    boolean isTUintern = false;
    boolean isUBintern = false;
    boolean is52bIBA = false;

    try {/* www  . j  av  a2  s  .com*/
        if (ips != null) {

            String[] ranges = config.getProperty("service.iprange.tu").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isTUintern = true;
                    break;
                }
            }

            String[] exceptions = config.getProperty("service.iprange.tu.exceptions").split("\\|");
            if (isTUintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isTUintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isUBintern = true;
                    break;
                }
            }
            exceptions = config.getProperty("service.iprange.ub.exceptions").split("\\|");
            if (isUBintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isUBintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub.52bIBAs").split("\\|");
            exceptions = config.getProperty("service.iprange.ub.52bIBAs.exceptions").split("\\|");
            String tmp[] = ips.split(", ");

            for (int i = 1; i < 3; i++) {

                try {
                    String ip = tmp[tmp.length - i];

                    for (String range : ranges) {

                        if (ip.matches(range)) {

                            is52bIBA = true;
                            break;
                        }
                    }

                    if (exceptions.length > 0) {

                        if (is52bIBA) {

                            for (String exception : exceptions) {

                                if (ip.matches(exception)) {

                                    is52bIBA = false;
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }

        }
    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }
    this.logger.info("[" + this.config.getProperty("service.name") + "] " + "Where is it from? "
            + request.getHeader("X-Forwarded-For") + ", " + isTUintern + ", " + isUBintern + ", " + is52bIBA);

    // format
    String format = "html";

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerNameKey = headerNames.nextElement();

        if (headerNameKey.equals("Accept")) {

            if (request.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (request.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (request.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
    }

    // read query
    this.logger.debug("TEST 'getQueryString': " + request.getQueryString());

    String queryString = null;
    if (request.getQueryString() == null || request.getQueryString().equals("")) {

        if (format.equals("html")) {

            try {

                JAXBContext context = JAXBContext.newInstance(Daia.class);
                Marshaller m = context.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                // Write to HttpResponse
                org.jdom2.Document doc = new org.jdom2.Document();
                doc.setRootElement(new Element("daia"));

                HashMap<String, String> parameters = new HashMap<String, String>();
                parameters.put("lang", "de");
                parameters.put("isTUintern", Boolean.toString(isTUintern));
                parameters.put("isUBintern", Boolean.toString(isUBintern));
                parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters);

                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().println(html);
            } catch (PropertyException e) {
                this.logger.error(e.getMessage(), e.getCause());
            } catch (JAXBException e) {
                this.logger.error(e.getMessage(), e.getCause());
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Query is empty.");
        }
    } else {

        if (request.getQueryString().contains("%26")) {
            this.logger.debug("TEST 'getQueryString': " + request.getQueryString());

            queryString = request.getQueryString().replaceAll("%26", "xXx");
            this.logger.debug("TEST 'getQueryString': " + queryString);

        } else {
            queryString = request.getQueryString();
        }

        if (queryString.contains("%0A")) {

            queryString = queryString.replaceAll("%0A", "");
            this.logger.debug("TEST 'queryString': " + queryString);
        }

        if ((queryString.contains("__char_set=latin1") && !queryString.contains("sid=semantics"))
                || queryString.contains("sid=GBI:wiwi")) {

            queryString = URLDecoder.decode(queryString, "ISO-8859-1");
        } else if (queryString.contains("__char_set=latin1") && queryString.contains("sid=semantics")) {

            // Tue erstmal nix
            this.logger.debug("semantics?");
        } else {
            queryString = URLDecoder.decode(queryString, "UTF-8");
        }

        HashMap<String, String> latinParameters = new HashMap<String, String>();

        for (String param : queryString.split("&")) {

            String[] tmp = param.split("=");
            try {

                if (tmp[1].contains("xXx")) {
                    latinParameters.put(tmp[0], tmp[1].replaceAll("xXx", "&"));
                } else {
                    latinParameters.put(tmp[0], tmp[1]);
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                latinParameters.put(tmp[0], "");
            }

        }

        if (latinParameters.get("format") != null && !latinParameters.get("format").equals("")) {

            format = latinParameters.get("format");
        }

        this.logger.debug("format = " + format);

        // build response
        response.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin"));

        if (format.equals("")) {

            if (format.equals("html")) {

                try {

                    JAXBContext context = JAXBContext.newInstance(Daia.class);
                    Marshaller m = context.createMarshaller();
                    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    // Write to HttpResponse
                    org.jdom2.Document doc = new org.jdom2.Document();
                    doc.setRootElement(new Element("daia"));

                    HashMap<String, String> parameters = new HashMap<String, String>();
                    parameters.put("lang", "de");
                    parameters.put("isTUintern", Boolean.toString(isTUintern));
                    parameters.put("isUBintern", Boolean.toString(isUBintern));
                    parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                    String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                            parameters);

                    response.setContentType("text/html;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println(html);
                } catch (PropertyException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                } catch (JAXBException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                }
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {FORMAT} requested.");
            }

        } else {

            this.provideService(request, response, format, latinParameters, isTUintern, isUBintern, is52bIBA);
        }
    }
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

private StreamInfo getStreamInfoKickstart(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String path) throws Exception {

    Map params = (Map) request.getAttribute(PARAMS);
    path = (String) params.get(FILENAME);
    if (log.isDebugEnabled()) {
        log.debug("getStreamInfo KICKSTART type, path: " + path);
    }//from  w w  w  . jav  a2 s .  c  om
    String diskPath = null;
    String kickstartMount = Config.get().getString(ConfigDefaults.MOUNT_POINT);
    String fileName;
    KickstartSession ksession = (KickstartSession) params.get(SESSION);
    KickstartSessionState newState = null;
    KickstartableTree tree = (KickstartableTree) params.get(TREE);
    Package rpmPackage = null;
    Channel child = (Channel) params.get(CHILD);

    if (tree.getBasePath().indexOf(kickstartMount) == 0) {
        log.debug("Trimming mount because tree is" + " explicitly rooted to the mount point");
        kickstartMount = "";
    }
    // If the tree is rooted somewhere other than
    // /var/satellite then no need to prepend it.
    if (tree.getBasePath().startsWith("/")) {
        log.debug("Tree isnt rooted at /var/satellite, lets just use basepath");
        kickstartMount = "";
    }
    // Searching for RPM
    if (path.endsWith(".rpm")) {
        String[] split = StringUtils.split(path, '/');
        fileName = split[split.length - 1];
        if (log.isDebugEnabled()) {
            log.debug("RPM filename: " + fileName);
        }
        Channel channel = tree.getChannel();
        if (child != null) {
            channel = child;
        }

        rpmPackage = ChannelFactory.lookupPackageByFilename(channel, fileName);
        if (rpmPackage != null) {
            diskPath = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + rpmPackage.getPath();
            if (log.isDebugEnabled()) {
                log.debug("found package :: diskPath path: " + diskPath);
            }
            newState = KickstartFactory.lookupSessionStateByLabel(KickstartSessionState.IN_PROGRESS);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Package was not in channel, looking in distro path.");
            }
        }
    }
    // either it's not an rpm, or we didn't find it in the channel
    // check for dir pings, virt manager or install, bz #345721
    if (diskPath == null) {
        // my $dp = File::Spec->catfile($kickstart_mount, $tree->base_path, $path);

        if (child == null) {
            diskPath = kickstartMount + "/" + tree.getBasePath() + path;
        } else if (path.endsWith("/comps.xml")) {
            diskPath = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/"
                    + child.getComps().getRelativeFilename();
        } else {
            String[] split = StringUtils.split(path, '/');
            if (split[0].equals("repodata")) {
                split[0] = child.getLabel();
            }
            diskPath = "/var/cache/" + Config.get().getString("repomd_path_prefix", "rhn/repodata/") + "/"
                    + StringUtils.join(split, '/');
        }

        if (log.isDebugEnabled()) {
            log.debug("DirCheck path: " + diskPath);
        }
        File actualFile = new File(diskPath);
        if (actualFile.exists() && actualFile.isDirectory()) {
            log.debug("Directory hit.  just return 200");
            response.setContentLength(0);
            response.setStatus(HttpServletResponse.SC_OK);
            return getStreamForText("".getBytes());
        } else if (actualFile.exists()) {
            log.debug("Looks like it is an actual file and it exists.");
            newState = KickstartFactory.lookupSessionStateByLabel(KickstartSessionState.STARTED);

        } else {
            log.error(diskPath + " Not Found .. 404!");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return getStreamForText("".getBytes());
        }

    }
    if (log.isDebugEnabled()) {
        log.debug("Final path before returning getStreamForBinary(): " + diskPath);
    }
    if (log.isDebugEnabled()) {
        Enumeration e = request.getHeaderNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            log.debug("header: [" + name + "]: " + request.getHeader(name));
        }
    }
    if (request.getMethod().equals("HEAD")) {
        log.debug("Method is HEAD .. serving checksum");
        return manualServeChecksum(response, rpmPackage, diskPath);
    } else if (request.getHeader("Range") != null) {
        log.debug("range detected.  serving chunk of file");
        String range = request.getHeader("Range");
        return manualServeByteRange(request, response, diskPath, range);
    }
    // Update kickstart session
    if (ksession != null) {
        ksession.setState(newState);
        if (ksession.getPackageFetchCount() == null) {
            ksession.setPackageFetchCount(new Long(0));
        }
        if (ksession.getState().getLabel().equals(KickstartSessionState.IN_PROGRESS)) {
            log.debug("Incrementing counter.");
            ksession.setPackageFetchCount(ksession.getPackageFetchCount().longValue() + 1);
            ksession.setLastFileRequest(path);
        }
        log.debug("Saving session.");
        KickstartFactory.saveKickstartSession(ksession);
    }
    log.debug("returning getStreamForBinary");

    File actualFile = new File(diskPath);
    Date mtime = new Date(actualFile.lastModified());
    SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    setBinaryContentInfo(response, (int) actualFile.length());
    response.addHeader("last-modified", formatter.format(mtime));
    log.debug("added last-modified and content-length values");
    return getStreamForBinary(diskPath);
}

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

/**
 * Show HTTP header information.// w w  w  .java 2 s. co 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.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request./* w w w .java  2s.  c o  m*/
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}