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:it.greenvulcano.gvesb.adapter.http.formatters.handlers.ExtendedInboundParamHandlerFormatter.java

/**
 * @see it.greenvulcano.gvesb.adapter.http.formatters.Formatter#marshall(java.util.Map)
 *//*  w w w. ja v a 2 s  .  co  m*/
@Override
public void marshall(Map<String, Object> environment) throws FormatterExecutionException {
    String operationType = null;
    GVBuffer inputGVBuffer = null;

    logger.debug("ExtendedInboundParamHandlerFormatter: BEGIN marshall");
    String requestContent = null;
    Properties requestParam = new Properties();

    try {
        environment.put(AdapterHttpConstants.ENV_KEY_MARSHALL_ENCODING, reqCharacterEncoding);
        inputGVBuffer = setDefaultGVBufferFields(inputGVBuffer);

        HttpServletRequest httpRequest = (HttpServletRequest) environment
                .get(AdapterHttpConstants.ENV_KEY_HTTP_SERVLET_REQUEST);
        if (httpRequest == null) {
            logger.error(
                    "ExtendedInboundParamHandlerFormatter - Error: HttpServletRequest object received is null");
            throw new FormatterExecutionException("GVHTTP_HTTP_SERVLET_REQUEST_MISSING");
        }
        logger.debug("Reading header: " + getFromRequestHeader);
        if (getFromRequestHeader) {
            Enumeration<?> e = httpRequest.getHeaderNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                logger.debug("header: " + key);
                requestParam.put(key, httpRequest.getHeader(key));
            }
        }

        Enumeration<?> pNames = httpRequest.getParameterNames();
        while (pNames.hasMoreElements()) {
            String paramName = (String) pNames.nextElement();
            String paramValue = httpRequest.getParameter(paramName);
            logger.debug("manageRequest - paramName: " + paramName + " - paramValue: " + paramValue);
            requestParam.put(paramName, paramValue);
        }

        String reqMethod = httpRequest.getMethod();
        if (reqMethod.equals("POST") || reqMethod.equals("PUT")) {
            byte[] requestContentBytes = IOUtils.toByteArray(httpRequest.getInputStream());
            logger.debug("INPUT - HTTP request content:\n");
            logger.debug(new Dump(requestContentBytes).toString());

            requestContent = convertContentToString(requestContentBytes, reqCharacterEncoding);

            /*if (!httpRequest.getContentType().equals(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)
                && handlePostBodyAsParams) {*/
            if (httpRequest.getContentType().equals(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)
                    || handlePostBodyAsParams) {
                List<String> entriesList = TextUtils.splitByStringSeparator(requestContent,
                        reqParamEntrySeparator);
                for (String element : entriesList) {
                    int indexSeparator = element.indexOf(reqParamNameValueSeparator);
                    String paramName = element.substring(0, indexSeparator);
                    String paramValue = URLDecoder.decode(
                            element.substring(indexSeparator + reqParamNameValueSeparator.length()),
                            reqCharacterEncoding);
                    logger.debug("manageRequest - paramName: " + paramName + " - paramValue: " + paramValue);
                    requestParam.put(paramName, paramValue);
                }
            }
        }

        if (reqParamHandlers.size() > 0) {
            for (Entry<String, List<InterfaceParametersHandler>> entry : reqParamHandlers.entrySet()) {
                String currParamName = entry.getKey();
                List<InterfaceParametersHandler> currParamHandlerList = entry.getValue();
                String reqParamValue = requestParam.getProperty(currParamName);
                logger.debug(
                        "manageRequest - request parameter " + currParamName + " = [" + reqParamValue + "]");
                if ((reqParamValue != null) && !reqParamValue.equals("")) {
                    for (InterfaceParametersHandler currHandler : currParamHandlerList) {
                        currHandler.setCharEncoding(reqCharacterEncoding);
                        if (currHandler.getHandlerType() == InterfaceParametersHandler.OPTYPE_HANDLER) {
                            operationType = (String) currHandler.build(reqParamValue, null);
                            logger.debug("manageRequest - current handler is an OpType handler"
                                    + "- operationType = " + operationType);
                            operationType = (String) currHandler.build(reqParamValue, null);
                        } else if (currHandler
                                .getHandlerType() == InterfaceParametersHandler.GVBUFFER_HANDLER) {
                            logger.debug("manageRequest - current handler is an GVBuffer handler");
                            inputGVBuffer = (GVBuffer) currHandler.build(reqParamValue, inputGVBuffer);
                        }
                    }
                } else if (reqParamRequired.contains(currParamName)) {
                    logger.error("manageRequest - Required request parameter missing: " + currParamName);
                    throw new FormatterExecutionException("GVHTTP_MISSING_HTTP_REQUEST_PARAMETER_ERROR",
                            new String[][] { { "paramName", currParamName } });
                } else {
                    logger.debug("manageRequest - not required request parameter missing: " + currParamName);
                }
            }
        }
        if (reqContentHandlers.size() > 0) {
            String reqParamValue = requestContent;

            if ((reqParamValue != null) && !reqParamValue.equals("")) {
                for (InterfaceParametersHandler currHandler : reqContentHandlers) {
                    currHandler.setCharEncoding(reqCharacterEncoding);

                    if (currHandler.getHandlerType() == InterfaceParametersHandler.OPTYPE_HANDLER) {
                        logger.debug("manageRequest - operationType = " + operationType);
                        operationType = (String) currHandler.build(reqParamValue, null);
                    } else if (currHandler.getHandlerType() == InterfaceParametersHandler.GVBUFFER_HANDLER) {
                        logger.debug("manageRequest - current handler is an GVBuffer handler");
                        inputGVBuffer = (GVBuffer) currHandler.build(reqParamValue, inputGVBuffer);
                    }
                }
            } else {
                logger.error("manageRequest - request content missing.");
                throw new FormatterExecutionException("GVHTTP_BAD_HTTP_REQUEST_ERROR",
                        new String[][] { { "errorName", "http request content missing" } });
            }
        }

        if (inputGVBuffer == null) {
            logger.error("manageRequest - input data missing.");
            throw new FormatterExecutionException("GVHTTP_HANDLER_ERROR",
                    new String[][] { { "errorName", "input GVBuffer not generated" } });
        }

        GVTransactionInfo transInfo = null;
        transInfo = (GVTransactionInfo) environment.get(AdapterHttpConstants.ENV_KEY_TRANS_INFO);
        if (transInfo == null) {
            transInfo = new GVTransactionInfo();
            environment.put(AdapterHttpConstants.ENV_KEY_TRANS_INFO, transInfo);
        }
        transInfo.setSystem(inputGVBuffer.getSystem());
        transInfo.setService(inputGVBuffer.getService());
        transInfo.setId(inputGVBuffer.getId());

        environment.put(AdapterHttpConstants.ENV_KEY_GVBUFFER_INPUT, inputGVBuffer);

        if ((operationType == null) || operationType.equals("")) {
            if ((defaultOperationType != null) && !defaultOperationType.equals("")) {
                operationType = defaultOperationType;
            } else {
                logger.error("manageRequest - Operation type information missing.");
                throw new FormatterExecutionException("GVHTTP_UNDEFINED_OPERATION_TYPE");

            }
        }

        environment.put(AdapterHttpConstants.ENV_KEY_OP_TYPE, operationType);
        logger.debug("ExtendedInboundParamHandlerFormatter: END marshall");
    } catch (FormatterExecutionException exc) {
        throw exc;
    } catch (HttpParamHandlerException exc) {
        if (requestContent != null) {
            logger.error(new Dump(requestContent.getBytes(), -1).toString());
        } else {
            logger.error("ExtendedInboundParamHandlerFormatter - Unable to decode the http request body");
        }
        throw new FormatterExecutionException("GVHTTP_CHARACTER_ENCODING_ERROR",
                new String[][] { { "encName", reqCharacterEncoding }, { "errorName", "" + exc } }, exc);
    } catch (UnsupportedEncodingException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while converting inbound request content to string: "
                        + exc);
        throw new FormatterExecutionException("GVHTTP_CHARACTER_ENCODING_ERROR",
                new String[][] { { "encName", reqCharacterEncoding }, { "errorName", "" + exc } }, exc);
    } catch (IOException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while reading inbound request content: " + exc);
        throw new FormatterExecutionException("GVHTTP_BAD_HTTP_REQUEST_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (HandlerException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while building input GVBuffer object or retrieving operation type: "
                        + exc);
        throw new FormatterExecutionException("GVHTTP_HANDLER_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (GVException exc) {
        logger.error("manageRequest - Error while setting GVBuffer fields with default values: " + exc);
        throw new FormatterExecutionException("GVHTTP_GVBUFFER_SETTING_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (Throwable exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Runtime error while managing inbound request: " + exc);
        throw new FormatterExecutionException("GVHTTP_RUNTIME_ERROR",
                new String[][] { { "phase", "managing inbound request" }, { "errorName", "" + exc } }, exc);
    }
}

From source file:org.infoscoop.web.ProxyServlet.java

public void doProcess(HttpServletRequest request, HttpServletResponse response, int methodType)
        throws ServletException, IOException {
    int statusCode = 0;
    String url = request.getParameter("url");
    ProxyRequest proxyRequest = null;/*  w  w w  . j a  v a  2 s.co m*/

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {

        String filterType = request.getParameter("filter");

        proxyRequest = new ProxyRequest(url, filterType);

        String filterEncoding = request.getParameter("filterEncoding");
        proxyRequest.setFilterEncoding(filterEncoding);

        proxyRequest.setLocales(request.getLocales());
        proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

        int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
        proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);

        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
        }

        //The certification for iframe
        String authTypeParam = request.getParameter("authType");
        if (authTypeParam != null && !"".equals(authTypeParam)) {
            proxyRequest.putRequestHeader("authType", authTypeParam);
            proxyRequest.putRequestHeader("authuserid", request.getParameter("authuserid"));
            proxyRequest.putRequestHeader("authpassword", request.getParameter("authpassword"));
        }

        for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
            String name = (String) names.nextElement();

            proxyRequest.setFilterParameter(name, request.getParameter(name));
        }

        try {
            String otherMethod = request.getHeader("MSDPortal-method");
            if (otherMethod == null)
                otherMethod = request.getParameter("method");

            if (methodType == METHOD_GET) {
                if (otherMethod != null && otherMethod.equalsIgnoreCase("delete")) {
                    statusCode = proxyRequest.executeDelete();
                } else if ("postCredential".equals(authTypeParam)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } else {
                if ("get".equalsIgnoreCase(otherMethod)) {
                    statusCode = proxyRequest.executeGet();
                } else {
                    proxyRequest.setReqeustBody(request.getInputStream());
                    if (otherMethod == null || "post".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePost();
                    } else if ("put".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePut();
                    } else if ("report".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executeReport();
                        if (statusCode == 207)
                            statusCode = 200;
                    }
                }
            }

        } catch (SocketTimeoutException ex) {
            // When the status code was 408, Firefox did not move well.
            // ABecause the cords such as 10408 are converted into 500 by Apache-GlassFish cooperation, we set it in a header.Apache-GlassFish.
            response.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        } catch (ConnectTimeoutException ex) {
            // In the case of connection-timeout,  we don't try it again.
            //response.setHeader(HttpStatusCode.HEADER_NAME,
            //      HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        }

        Map<String, List<String>> responseHeaders = proxyRequest.getResponseHeaders();
        if (statusCode == 401) {

            String wwwAuthHeader = proxyRequest.getResponseHeader("WWW-Authenticate");
            if (wwwAuthHeader == null) {
                statusCode = 403;
            } else if (wwwAuthHeader.toLowerCase().startsWith("basic")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "basic");
            } else if (wwwAuthHeader.toLowerCase().startsWith("ntlm")
                    || wwwAuthHeader.toLowerCase().startsWith("negotiate")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "ntlm");
            }
        }
        response.setStatus(statusCode);

        if (log.isInfoEnabled()) {
            log.info("Response-Status: " + statusCode);
        }

        StringBuffer headersSb = new StringBuffer();
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {

            String name = entry.getKey();
            if (name.equalsIgnoreCase("Transfer-Encoding") || name.equalsIgnoreCase("X-Powered-By")) {
                continue;
            }

            for (String value : entry.getValue()) {
                response.setHeader(entry.getKey(), value);
                headersSb.append(name + "=" + value + ",  ");
            }
        }

        if (!response.containsHeader("Connection")) {
            response.setHeader("Connection", "close");
            headersSb.append("Connection=close,  ");
        }

        if (log.isInfoEnabled())
            log.info("ResponseHeader: " + headersSb);

        String cacheHeader = request.getHeader("MSDPortal-Cache");

        InputStream responseBody = proxyRequest.getResponseBody();

        bos = new BufferedOutputStream(response.getOutputStream());

        if (responseBody != null) {

            //bis = new BufferedInputStream(
            //      new ByteArrayInputStream(bytes));
            bis = new BufferedInputStream(responseBody);

            if (log.isDebugEnabled()) {
                /*
                bis.mark(10240000);
                BufferedReader br =  new BufferedReader(new InputStreamReader(bis,"UTF-8"));
                        
                StringBuffer logStr = new StringBuffer();
                String out = null;
                while((out = br.readLine())!= null){
                   logStr.append(out);
                }
                        
                log.debug(logStr);
                bis.reset();
                */
                bis = printDebug(bis);
            }

            String cacheID = null;
            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse")) {

                //Process to save the cash
                String uid = (String) request.getSession().getAttribute("Uid");
                if (uid == null)
                    uid = request.getHeader("MSDPortal-SessionId");

                Map<String, List<String>> headerMap = proxyRequest.getResponseHeaders();

                try {
                    cacheID = CacheService.getHandle().insertCache(uid, url /*proxyRequest.getTargetURL() + "?"
                                                                            + request.getQueryString()*/, bis,
                            headerMap);
                    if (log.isInfoEnabled())
                        log.info("save cache : id = " + cacheID);
                } catch (Exception e) {
                    log.error(e);
                    //response.sendError(500, e.getMessage());
                }
            }

            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse") && cacheID != null) {
                response.setHeader("MSDPortal-Cache-ID", cacheID);
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Content-Length", "1");
                //response.setHeader("Content-Length", "0");
                //response.setHeader("Connection", "close");
                bos.write(0);
                bos.flush();
                //response.setStatus(204);
            } else {
                if (cacheHeader != null && cacheHeader.equals("No-Cache")) {
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                }
                if (!response.containsHeader("Content-Length") || statusCode == 500) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] b = new byte[1024];
                    int c = 0;
                    while ((c = bis.read(b)) != -1) {
                        baos.write(b, 0, c);
                    }

                    byte[] data = baos.toByteArray();
                    response.addHeader("Content-Length", String.valueOf(data.length));

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                }

                byte[] b = new byte[1024];
                int c = 0;
                while ((c = bis.read(b)) != -1) {
                    bos.write(b, 0, c);
                }
                bos.flush();
            }
        } else {
            if (statusCode == HttpStatus.SC_NO_CONTENT) {
                response.setHeader("Content-Length", "0");
            } else {
                response.setHeader("Content-Length", "1");
                bos.write(0);
                bos.flush();
            }
        }

        long elapsedtime = new Date().getTime() - lastDeleteCachesTime;
        if (elapsedtime > 86400000) {
            log.info("Delete old public caches.");
            lastDeleteCachesTime = new Date().getTime();
            CacheService.getHandle().deleteOldPublicCaches();
        }

    } catch (Exception e) {

        log.error("Failed to get the URL. " + buildMessage(statusCode, proxyRequest, url), e);
        response.sendError(500, e.getMessage());
    } finally {
        if (log.isInfoEnabled()) {
            log.info("Succeeded in getting the URL. " + buildMessage(statusCode, proxyRequest, url));
        }

        if (proxyRequest != null)
            proxyRequest.close();
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}

From source file:com.telefonica.iot.cygnus.handlers.OrionRestHandler.java

@Override
public List<Event> getEvents(javax.servlet.http.HttpServletRequest request) throws Exception {
    // get a transaction id and store it in the log4j Mapped Diagnostic Context (MDC); this way it will be
    // accessible by the whole source code
    String transId = generateTransId();
    MDC.put(Constants.HEADER_TRANSACTION_ID, transId);
    LOGGER.info("Starting transaction (" + transId + ")");

    // check the method
    String method = request.getMethod().toUpperCase(Locale.ENGLISH);

    if (!method.equals("POST")) {
        LOGGER.warn("Bad HTTP notification (" + method + " method not supported)");
        throw new MethodNotSupportedException(method + " method not supported");
    } // if//from w w  w. j  a  va  2  s  .  c  o  m

    // check the notificationTarget
    String target = request.getRequestURI();

    if (!target.equals(notificationTarget)) {
        LOGGER.warn("Bad HTTP notification (" + target + " target not supported)");
        throw new HTTPBadRequestException(target + " target not supported");
    } // if

    // check the headers looking for not supported user agents, content type and tenant/organization
    Enumeration headerNames = request.getHeaderNames();
    String contentType = null;
    String service = null;
    String servicePath = null;

    while (headerNames.hasMoreElements()) {
        String headerName = ((String) headerNames.nextElement()).toLowerCase(Locale.ENGLISH);
        String headerValue = request.getHeader(headerName).toLowerCase(Locale.ENGLISH);

        if (headerName.equals(Constants.HEADER_USER_AGENT)) {
            if (!headerValue.startsWith("orion")) {
                LOGGER.warn("Bad HTTP notification (" + headerValue + " user agent not supported)");
                throw new HTTPBadRequestException(headerValue + " user agent not supported");
            } // if
        } else if (headerName.equals(Constants.HEADER_CONTENT_TYPE)) {
            if (!headerValue.contains("application/json") && !headerValue.contains("application/xml")) {
                LOGGER.warn("Bad HTTP notification (" + headerValue + " content type not supported)");
                throw new HTTPBadRequestException(headerValue + " content type not supported");
            } else {
                contentType = headerValue;
            } // if else
        } else if (headerName.equals(Constants.HEADER_SERVICE)) {
            if (headerValue.length() > Constants.SERVICE_HEADER_MAX_LEN) {
                LOGGER.warn("Bad HTTP notification ('fiware-service' header length greater than "
                        + Constants.SERVICE_HEADER_MAX_LEN + ")");
                throw new HTTPBadRequestException("'fiware-service' header length greater than "
                        + Constants.SERVICE_HEADER_MAX_LEN + ")");
            } else {
                service = Utils.encode(headerValue);
            } // if else
        } else if (headerName.equals(Constants.HEADER_SERVICE_PATH)) {
            if (headerValue.length() > Constants.SERVICE_PATH_HEADER_MAX_LEN) {
                LOGGER.warn("Bad HTTP notification ('fiware-servicePath' header length greater than "
                        + Constants.SERVICE_PATH_HEADER_MAX_LEN + ")");
                throw new HTTPBadRequestException("'fiware-servicePath' header length greater than "
                        + Constants.SERVICE_PATH_HEADER_MAX_LEN + ")");
            } else {
                servicePath = Utils.encode(headerValue);
            } // if else
        } // if else if
    } // for

    // get the data content
    String data = "";
    String line;
    BufferedReader reader = request.getReader();

    while ((line = reader.readLine()) != null) {
        data += line;
    } // while

    if (data.length() == 0) {
        LOGGER.warn("Bad HTTP notification (No content in the request)");
        throw new HTTPBadRequestException("No content in the request");
    } // if

    // data adaptation; two replacements:
    //   1. replace all the appearances of "contextValue" with "value" in order Orion versions under 0.10.0 may
    //      work (Json content type only)
    //   2. replace all the white lines between tags with nothing; the regex ">[ ]*<" means "all the white spaces
    //      between '>' and '<', e.g. "<tag1>1</tag1>      <tag2>2</tag2>" becomes "<tag1>1</tag1><tag2>2</tag2>"

    if (contentType.equals("application/json")) {
        data = data.replaceAll("contextValue", "value");
    } // if

    data = data.replaceAll(">[ ]*<", "><");
    LOGGER.info("Received data (" + data + ")");

    // create the appropiate headers
    Map<String, String> eventHeaders = new HashMap<String, String>();
    eventHeaders.put(Constants.HEADER_CONTENT_TYPE, contentType);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_CONTENT_TYPE + ", value=" + contentType
            + ")");
    eventHeaders.put(Constants.HEADER_SERVICE, service == null ? defaultService : service);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_SERVICE + ", value="
            + (service == null ? defaultService : service) + ")");
    eventHeaders.put(Constants.HEADER_SERVICE_PATH, servicePath == null ? defaultServicePath : servicePath);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_SERVICE_PATH + ", value="
            + (servicePath == null ? defaultServicePath : servicePath) + ")");
    eventHeaders.put(Constants.HEADER_TRANSACTION_ID, transId);
    LOGGER.debug(
            "Adding flume event header (name=" + Constants.HEADER_TRANSACTION_ID + ", value=" + transId + ")");
    eventHeaders.put(Constants.HEADER_TTL, eventsTTL);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_TTL + ", value=" + eventsTTL + ")");

    // create the event list containing only one event
    ArrayList<Event> eventList = new ArrayList<Event>();
    Event event = EventBuilder.withBody(data.getBytes(), eventHeaders);
    eventList.add(event);
    LOGGER.info("Event put in the channel (id=" + event.hashCode() + ", ttl=" + eventsTTL + ")");
    return eventList;
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

private void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;//from  ww  w  .j  a  v  a2 s  .  c  o  m

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:com.groupon.odo.Proxy.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request//from  w ww .  j av a  2s  . c o  m
 *
 * @param httpServletRequest     The request object representing the client's request to the
 *                               servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest)
        throws Exception {

    String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME))
            continue;

        logger.info("Current header: {}", stringHeaderName);
        // As per the Java Servlet API 2.5 documentation:
        // Some headers, such as Accept-Language can be sent by clients
        // as several headers each with a different value rather than
        // sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the
        // client
        Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);

        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) && requestInformation.get().handle) {
                String hostValue = getHostHeaderForHost(hostName);
                if (hostValue != null) {
                    stringHeaderValue = hostValue;
                }
            }

            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.addRequestHeader(header);
        }
    }

    // bail if we aren't fully handling this request
    if (!requestInformation.get().handle) {
        return;
    }

    // deal with header overrides for the request
    processRequestHeaderOverrides(httpMethodProxyRequest);
}

From source file:io.cos.cas.authentication.handler.support.OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java

/**
 * Abstract method to implement to construct the credential from the
 * request object.//from  ww  w.j a v  a2 s. c o  m
 *
 * @param context the context for this request.
 * @return the constructed credential or null if none could be constructed
 * from the request.
 * @throws AccountException a account exception
 */
protected Credential constructCredentialsFromRequest(final RequestContext context) throws AccountException {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final OpenScienceFrameworkCredential credential = (OpenScienceFrameworkCredential) context.getFlowScope()
            .get("credential");

    // WARNING: Do not assume this works w/o acceptance testing in a Production environment.
    // The call is made to trust these headers only because we assume the Apache Shibboleth Service Provider module
    // rejects any conflicting / forged headers.
    final String shibbolethSession = request.getHeader(SHIBBOLETH_SESSION_HEADER);
    if (StringUtils.hasText(shibbolethSession)) {
        final String remoteUser = request.getHeader(REMOTE_USER);
        if (StringUtils.isEmpty(remoteUser)) {
            logger.error("Invalid Remote User specified as Empty");
            throw new RemoteUserFailedLoginException("Invalid Remote User specified as Empty");
        }

        logger.info("Remote User from HttpServletRequest '{}'", remoteUser);
        credential.setRemotePrincipal(Boolean.TRUE);

        for (final String headerName : Collections.list(request.getHeaderNames())) {
            if (headerName.startsWith(ATTRIBUTE_PREFIX)) {
                final String headerValue = request.getHeader(headerName);
                logger.debug("Remote User [{}] Auth Header '{}': '{}'", remoteUser, headerName, headerValue);

                credential.getAuthenticationHeaders().put(headerName.substring(ATTRIBUTE_PREFIX.length()),
                        headerValue);
            }
        }

        // Notify the OSF of the remote principal authentication.
        final PrincipalAuthenticationResult remoteUserInfo = notifyRemotePrincipalAuthenticated(credential);
        credential.setUsername(remoteUserInfo.getUsername());
        credential.setInstitutionId(remoteUserInfo.getInstitutionId());

        return credential;
    } else if (request.getParameter("username") != null && request.getParameter("verification_key") != null) {
        // Construct credential if presented with (username, verification_key)
        // This is used when:
        //      1. User creates an account
        //      2. User resets the password through forgot_password
        //      3. User sets password when added as an unregistered contribution
        // Note: Two-factor sign in works and remain unchanged
        credential.setUsername(request.getParameter("username"));
        credential.setVerificationKey(request.getParameter("verification_key"));
        return credential;
    }

    return null;
}

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

private static void addContentMetdataFromHttpRequest(BlobBuilder.PayloadBlobBuilder builder,
        HttpServletRequest request) {/*from   ww w .  ja  v  a2s .  c  om*/
    ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) {
            userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()),
                    Strings.nullToEmpty(request.getHeader(headerName)));
        }
    }
    builder.cacheControl(request.getHeader(HttpHeaders.CACHE_CONTROL))
            .contentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION))
            .contentEncoding(request.getHeader(HttpHeaders.CONTENT_ENCODING))
            .contentLanguage(request.getHeader(HttpHeaders.CONTENT_LANGUAGE))
            .userMetadata(userMetadata.build());
    String contentType = request.getContentType();
    if (contentType != null) {
        builder.contentType(contentType);
    }
    long expires = request.getDateHeader(HttpHeaders.EXPIRES);
    if (expires != -1) {
        builder.expires(new Date(expires));
    }
}

From source file:com.bosch.iot.things.example.historian.Controller.java

/**
 * Check access on specific property by doing a callback to the Things service.
 *//*  w w  w .  ja va  2s .c  o m*/
private boolean checkAccess(String thingId, String feature, String path)
        throws UnsupportedEncodingException, IOException {
    HttpServletRequest httpReq = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();
    HttpServletResponse httpRes = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getResponse();

    // enforce BASIC auth
    String auth = httpReq.getHeader("Authorization");
    if (auth == null) {
        httpRes.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }

    String httpid = URLEncoder.encode(thingId, "UTF-8") + "/features/" + URLEncoder.encode(feature, "UTF-8")
            + "/properties/" + path;
    HttpGet thingsRequest = new HttpGet(
            getConfig().getProperty("thingsServiceEndpointUrl") + "/cr/1/things/" + httpid);

    // fill in apiToken if not provided
    String apiToken = getConfig().getProperty("apiToken");
    if (apiToken != null && httpReq.getHeader("x-cr-api-token") == null) {
        thingsRequest.addHeader("x-cr-api-token", apiToken);
    }

    // forward all other Headers to Things service
    Enumeration<String> headerNames = httpReq.getHeaderNames();
    if (headerNames != null) {
        final Set<String> headersToIgnore = new HashSet(Arrays.asList(new String[] { "host" }));
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (!headersToIgnore.contains(name)) {
                thingsRequest.addHeader(name, httpReq.getHeader(name));
            }
        }
    }

    LOGGER.debug("Callback to Things service: {}", thingsRequest);

    try (CloseableHttpResponse response = getHttpClient().execute(thingsRequest)) {
        LOGGER.debug("... retured {}", response.getStatusLine());

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < 200 || statusCode > 299) {
            httpRes.setStatus(statusCode);
            return false;
        }
    }

    return true;
}

From source file:org.josso.gl2.agent.SSOAgentValve.java

/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException//from ww  w.j a v a2s  .co  m
 */
private void saveRequest(HttpRequest request, Session session) {

    // Create and populate a SavedRequest object for this request
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++)
            saved.addCookie(cookies[i]);
    }
    Enumeration names = hreq.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = hreq.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration locales = hreq.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        saved.addLocale(locale);
    }
    Map parameters = hreq.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();
    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        String paramValues[] = (String[]) parameters.get(paramName);
        saved.addParameter(paramName, paramValues);
    }
    saved.setMethod(hreq.getMethod());
    saved.setQueryString(hreq.getQueryString());
    saved.setRequestURI(hreq.getRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(org.apache.catalina.authenticator.Constants.FORM_REQUEST_NOTE, saved);

}