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:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Copy HTTP request headers to the endpoint.
 * @param context the context//from w w w.ja va2 s .  c om
 */
public static void copyHeadersToEndpoint(ProxyContext context) {
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    if (clientRequest != null) {
        Enumeration headerNames = clientRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            if (RequestUtil.ignoreHeader(headerName, context)) {
                continue;
            }

            Enumeration headers = clientRequest.getHeaders(headerName);
            while (headers.hasMoreElements()) {
                String value = (String) headers.nextElement();
                context.getHttpMethod().addRequestHeader(headerName, value);

                if (Log.isInfo()) {
                    Log.getLogger(HTTPProxyService.LOG_CATEGORY)
                            .debug("-- Header in request: " + headerName + " : " + value);
                }
            }
        }
    }
}

From source file:org.olat.core.gui.media.ServletUtil.java

public static void printOutRequestHeaders(HttpServletRequest request) {
    for (Enumeration<String> headers = request.getHeaderNames(); headers.hasMoreElements();) {
        String header = headers.nextElement();
        log.info(header + " :: " + request.getHeader(header));
    }/*from  w ww. jav a 2  s . c o m*/
}

From source file:by.stub.yaml.stubs.StubRequest.java

public static StubRequest createFromHttpServletRequest(final HttpServletRequest request) throws IOException {
    final StubRequest assertionRequest = StubRequest.newStubRequest(request.getPathInfo(),
            HandlerUtils.extractPostRequestBody(request, "stubs"));
    assertionRequest.addMethod(request.getMethod());

    final Enumeration<String> headerNamesEnumeration = request.getHeaderNames();
    final List<String> headerNames = ObjectUtils.isNotNull(headerNamesEnumeration)
            ? Collections.list(request.getHeaderNames())
            : new LinkedList<String>();
    for (final String headerName : headerNames) {
        final String headerValue = request.getHeader(headerName);
        assertionRequest.getHeaders().put(StringUtils.toLower(headerName), headerValue);
    }//from   www . jav a2  s.  c  om

    assertionRequest.getQuery().putAll(CollectionUtils.constructParamMap(request.getQueryString()));
    ConsoleUtils.logAssertingRequest(assertionRequest);

    return assertionRequest;
}

From source file:org.frontcache.core.FCUtils.java

public static Map<String, List<String>> buildRequestHeaders(HttpServletRequest request) {

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (isIncludedHeader(name)) {
                Enumeration<String> values = request.getHeaders(name);
                while (values.hasMoreElements()) {
                    String value = values.nextElement();

                    List<String> hValues = headers.get(name);
                    if (null == hValues) {
                        hValues = new ArrayList<String>();
                        headers.put(name, hValues);
                    }//from   w w  w  .j a  va  2  s .  com
                    hValues.add(value);
                }
            }
        }
    }

    return headers;
}

From source file:org.openlaszlo.utils.LZHttpUtils.java

/** Add request headers into method. 
 *
 * @param req http servlet request object
 * @param method method to insert request headers into 
 */// w  ww . j a  va 2 s .co  m
static public void proxyRequestHeaders(HttpServletRequest req, HttpMethodBase method) {
    mLogger.debug("proxyRequestHeaders");

    // Copy all headers, if the servlet container allows, otherwise just
    // copy the cookie header and log a message.
    Enumeration<?> headerNames = req.getHeaderNames();
    if (headerNames != null) {

        // Connection header tokens not to forward
        Enumeration<?> connEnum = req.getHeaders(CONNECTION);

        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            if (allowForward(key, connEnum)) {
                String val = (String) req.getHeader(key);
                method.addRequestHeader(key, val);
                mLogger.debug("  " + key + "=" + val);
            }
        }

    } else {
        mLogger.warn(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="Can't get header names to proxy request headers"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(LZHttpUtils.class.getName(), "051018-237"));

        Enumeration<?> cookieEnum = req.getHeaders(COOKIE);
        if (cookieEnum != null) {
            while (cookieEnum.hasMoreElements()) {
                String val = (String) cookieEnum.nextElement();
                method.addRequestHeader(COOKIE, val);
                mLogger.debug("  Cookie=" + val);
            }
        }

        Enumeration<?> authEnum = req.getHeaders(AUTHORIZATION);
        if (authEnum != null) {
            while (authEnum.hasMoreElements()) {
                String val = (String) authEnum.nextElement();
                method.addRequestHeader(AUTHORIZATION, val);
                mLogger.debug("  Authorization=" + val);
            }
        }
    }
}

From source file:org.encuestame.core.util.EnMeUtils.java

/**
 * Extract the {@link InetAddress} from {@link HttpServletRequest}.
 * @param request {@link HttpServletRequest}
 * @param proxy define if the server is behind a proxy server.
 * @return//from  w w  w  .j  a v  a2 s .c o m
 * @throws UnknownHostException
 */
public static String getIP(HttpServletRequest request, boolean proxy) throws UnknownHostException {
    log.trace("getIP Force Proxy Pass [" + proxy + "]");
    log.trace("getIP request [" + request + "]");
    String ip = "";
    //FIXME: if your server use ProxyPass you need get IP from x-forwarder-for, we need create
    // a switch change for ProxyPass to normal get client Id.
    // Solution should be TOMCAT configuration.
    log.trace("X-getHeaderNames [" + request.getHeaderNames() + "]");
    if (proxy) {
        ip = XFordwardedInetAddressUtil.getAddressFromRequest(request);
        log.trace("X-FORWARDED-FOR [" + ip + "]");
    } else {
        String _ip = request.getRemoteAddr();
        log.trace("NON XFORWARDEDddddddd IP [" + _ip + "]");
        InetAddress sip = InetAddress.getByName(_ip);
        log.trace("NON XFORWARDED IP sip [" + sip + "]");
        ip = sip.getHostAddress();
    }
    return ip;
}

From source file:io.apiman.test.common.mock.EchoServlet.java

/**
 * Create an echo response from the inbound information in the http server
 * request./*from  w  w w .ja va 2  s. c  o  m*/
 * @param request the request
 * @param withBody if request is with body
 * @return a new echo response
 */
public static EchoResponse response(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    if (request.getQueryString() != null) {
        String[] normalisedQueryString = request.getQueryString().split("&");
        Arrays.sort(normalisedQueryString);
        response.setResource(
                request.getRequestURI() + "?" + SimpleStringUtils.join("&", normalisedQueryString));
    } else {
        response.setResource(request.getRequestURI());
    }
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            byte[] data = new byte[1024];
            int read;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}

From source file:com.lm.lic.manager.util.GenUtil.java

/**
 * @param request//w  w w.j  av a2s.  com
 */
@SuppressWarnings("unchecked")
public static void debugRequestParams(HttpServletRequest request) {
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String p = en.nextElement();
        String v = request.getParameter(p);
        System.out.println("\nPARAM: " + p);
        System.out.println("VALUE: " + v);
    }

    en = request.getHeaderNames();
    while (en.hasMoreElements()) {
        String p = en.nextElement();
        String v = request.getParameter(p);
        System.out.println("\nPHEADER: " + p);
        System.out.println("VALUE: " + v);
    }

    String qs = request.getQueryString();
    System.out.println("QueryString: " + qs);
    String method = request.getMethod();
    System.out.println("Method: " + method);
}

From source file:org.apache.openaz.xacml.rest.XACMLRest.java

/**
 * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
 *
 * @param request - Servlet request (from a POST/GET/PUT/etc.)
 *///from  ww  w . j ava  2s . c o m
public static void dumpRequest(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        // special-case for receiving heartbeat - don't need to repeatedly output all of the information
        // in multiple lines
        if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
            logger.debug("GET type=hb : heartbeat received");
            return;
        }
        logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
                + request.getRemotePort());
        logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
        Enumeration<String> en = request.getHeaderNames();
        logger.debug("Headers:");
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            Enumeration<String> values = request.getHeaders(element);
            while (values.hasMoreElements()) {
                String value = values.nextElement();
                logger.debug(element + ":" + value);
            }
        }
        logger.debug("Attributes:");
        en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            logger.debug(element + ":" + request.getAttribute(element));
        }
        logger.debug("ContextPath: " + request.getContextPath());
        if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
            // POST and PUT are allowed to have parameters in the content, but in our usage the parameters
            // are always in the Query string.
            // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it
            // might contain a Policy file).
            // Unfortunately the request.getParameterMap method reads the content to see if there are any
            // parameters,
            // and once the content is read it cannot be read again.
            // Thus for PUT and POST we must avoid reading the content here so that the main code can read
            // it.
            logger.debug("Query String:" + request.getQueryString());
            try {
                if (request.getInputStream() == null) {
                    logger.debug("Content: No content inputStream");
                } else {
                    logger.debug("Content available: " + request.getInputStream().available());
                }
            } catch (Exception e) {
                logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
            }
        } else {
            logger.debug("Parameters:");
            Map<String, String[]> params = request.getParameterMap();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String[] values = params.get(key);
                logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
            }
        }
        logger.debug("Request URL:" + request.getRequestURL());
    }
}

From source file:org.sakaiproject.entitybroker.util.request.RequestUtils.java

/**
 * This method will correctly extract the format constant from a request 
 * (extension first and then Accepts header) and then set it in the response
 * as the correct return type, if none is found then the default will be used
 * @param req the Servlet request//  w w w  .j a  v a 2 s  . com
 * @param res the Servlet response
 * @param defaultFormat (OPTIONAL) if this is set then it will be the default format assigned when none can be found,
 * otherwise the default format is {@link Formats#HTML}
 * @return the extracted format (will never be null), e.g {@link Formats#XML}
 */
@SuppressWarnings("unchecked")
public static String findAndHandleFormat(HttpServletRequest req, HttpServletResponse res,
        String defaultFormat) {
    if (defaultFormat == null) {
        defaultFormat = Formats.HTML;
    }
    String path = req.getPathInfo();
    String format = TemplateParseUtil.findExtension(path)[2];
    if (format == null) {
        // try to get it from the Accept header
        for (Enumeration<String> enumHeader = req.getHeaderNames(); enumHeader.hasMoreElements();) {
            String headerName = enumHeader.nextElement();
            if ("accept".equalsIgnoreCase(headerName)) {
                ArrayList<String> accepts = new ArrayList<String>();
                for (Enumeration<String> enumAccepts = req.getHeaders(headerName); enumAccepts
                        .hasMoreElements();) {
                    String mimeType = enumAccepts.nextElement();
                    if (mimeType == null) {
                        continue;
                    }
                    mimeType = mimeType.trim();
                    // trim out the optional stuff
                    int pos = mimeType.indexOf(';');
                    if (pos > 0) {
                        mimeType = mimeType.substring(0, pos).trim();
                    }
                    accepts.add(mimeType);
                }
                // sort the list to longest first and shortest last
                Collections.sort(accepts, new ShortestStringLastComparator());
                for (String mimeType : accepts) {
                    String f = mimeTypeToFormat.get(mimeType);
                    if (f != null) {
                        format = f;
                        break; // FOUND A MIME MATCH
                    }
                }
                break; // STOP CHECKING HEADERS
            }
        }
    }
    if (format == null || "".equals(format)) {
        // set the default value
        format = defaultFormat;
    }
    RequestUtils.setResponseEncoding(format, res);
    return format;
}