Example usage for javax.servlet.http HttpServletRequest getHeaders

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

Introduction

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

Prototype

public Enumeration<String> getHeaders(String name);

Source Link

Document

Returns all the values of the specified request header as an Enumeration of String objects.

Usage

From source file:com.fujitsu.dc.engine.rs.StatusResource.java

/**
 * Service.//from www  .  j a  v a  2s.  c  o m
 * @param path ??
 * @param req Request
 * @param res Response
 * @param is 
 * @return Response
 */
public final Response run(final String path, final HttpServletRequest req, final HttpServletResponse res,
        final InputStream is) {
    StringBuilder msg = new StringBuilder();
    msg.append(">>> Request Started ");
    msg.append(" method:");
    msg.append(req.getMethod());
    msg.append(" method:");
    msg.append(req.getRequestURL());
    msg.append(" url:");
    log.info(msg);

    // ? ????
    Enumeration<String> multiheaders = req.getHeaderNames();
    for (String headerName : Collections.list(multiheaders)) {
        Enumeration<String> headers = req.getHeaders(headerName);
        for (String header : Collections.list(headers)) {
            log.debug("RequestHeader['" + headerName + "'] = " + header);
        }
    }
    try {
        DcEngineConfig.reload();
    } catch (Exception e) {
        log.warn(" unknown Exception(" + e.getMessage() + ")");
        return errorResponse(new DcEngineException("500 Internal Server Error (Unknown Error)",
                DcEngineException.STATUSCODE_SERVER_ERROR));
    }
    return Response.status(HttpStatus.SC_NO_CONTENT).build();
}

From source file:io.personium.engine.rs.StatusResource.java

/**
 * Service.//from   ww  w .  j a  v  a 2 s  .  c om
 * @param path ??
 * @param req Request
 * @param res Response
 * @param is 
 * @return Response
 */
public final Response run(final String path, final HttpServletRequest req, final HttpServletResponse res,
        final InputStream is) {
    StringBuilder msg = new StringBuilder();
    msg.append(">>> Request Started ");
    msg.append(" method:");
    msg.append(req.getMethod());
    msg.append(" method:");
    msg.append(req.getRequestURL());
    msg.append(" url:");
    log.info(msg);

    // ? ????
    Enumeration<String> multiheaders = req.getHeaderNames();
    for (String headerName : Collections.list(multiheaders)) {
        Enumeration<String> headers = req.getHeaders(headerName);
        for (String header : Collections.list(headers)) {
            log.debug("RequestHeader['" + headerName + "'] = " + header);
        }
    }
    try {
        PersoniumEngineConfig.reload();
    } catch (Exception e) {
        log.warn(" unknown Exception(" + e.getMessage() + ")");
        return errorResponse(new PersoniumEngineException("500 Internal Server Error (Unknown Error)",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR));
    }
    return Response.status(HttpStatus.SC_NO_CONTENT).build();
}

From source file:org.getobjects.servlets.WOServletRequest.java

protected void loadHeadersFromServletRequest(final HttpServletRequest _rq) {
    final Enumeration e = _rq.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();

        final Enumeration ve = _rq.getHeaders(name);
        name = name.toLowerCase();//from w w w.j a  v  a2 s .  co m

        while (ve.hasMoreElements()) {
            final String v = (String) ve.nextElement();
            this.appendHeader(v, name);
        }
    }
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);//from  w ww .  ja  v a 2  s  .  co m
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

        connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length));

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}

From source file:org.mule.transport.servlet.MockHttpServletRequestBuilder.java

private void addHeaderExpectations(HttpServletRequest mockRequest) {
    Enumeration<String> nameEnum = null;
    if (headers != null) {
        nameEnum = keyEnumeration(headers);

        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            Enumeration<String> valueAsEnumeration = null;
            if (value instanceof Enumeration) {
                valueAsEnumeration = (Enumeration<String>) value;
            } else {
                valueAsEnumeration = new SingleElementEnumeration((String) value);
            }/*from w  ww .j  a v  a 2s  .c o  m*/

            when(mockRequest.getHeaders(eq(key))).thenReturn(valueAsEnumeration);
        }
    }

    when(mockRequest.getHeaderNames()).thenReturn(nameEnum);
}

From source file:password.pwm.http.PwmHttpRequestWrapper.java

public Map<String, List<String>> readHeaderValuesMap() {
    final int maxChars = Integer
            .parseInt(configuration.readAppProperty(AppProperty.HTTP_PARAM_MAX_READ_LENGTH));
    final HttpServletRequest req = this.getHttpServletRequest();
    final Map<String, List<String>> returnObj = new LinkedHashMap<>();

    for (final Enumeration<String> headerNameEnum = req.getHeaderNames(); headerNameEnum.hasMoreElements();) {
        final String headerName = headerNameEnum.nextElement();
        final List<String> valueList = new ArrayList<>();
        for (final Enumeration<String> headerValueEnum = req.getHeaders(headerName); headerValueEnum
                .hasMoreElements();) {/*from ww  w .  j  a v a 2  s.c o  m*/
            final String headerValue = headerValueEnum.nextElement();
            final String sanitizedInputValue = Validator.sanitizeInputValue(configuration, headerValue,
                    maxChars);
            final String sanitizedHeaderValue = Validator.sanitizeHeaderValue(configuration,
                    sanitizedInputValue);
            if (sanitizedHeaderValue != null && !sanitizedHeaderValue.isEmpty()) {
                valueList.add(sanitizedHeaderValue);
            }
        }
        if (!valueList.isEmpty()) {
            returnObj.put(headerName, Collections.unmodifiableList(valueList));
        }
    }
    return Collections.unmodifiableMap(returnObj);
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException {
    URI targetUri;/*from   ww w.j a  v a  2 s  .  c om*/
    try {
        targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerVals = request.getHeaders(headerName);
        while (headerVals.hasMoreElements()) {
            String headerValue = headerVals.nextElement();
            headerValue = headerFilter.processRequestHeader(headerName, headerValue);
            if (headerValue != null) {
                commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
            }

        }
    }

    return commonsHttpMethod;
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
public void copyHeaders(HttpServletRequest req, HttpRequestBase method) {
    Enumeration names = req.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();

        if (name.equalsIgnoreCase(HEADER_CONTENT_LENTH)) {
            continue;
        }/*  w w  w.  j  a  v a2s.  c  o  m*/

        Enumeration values = req.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            LOG.log(Level.FINER, "{0} : {1}", new Object[] { name, value });

            if (name.equalsIgnoreCase(HEADER_HOST) || name.equalsIgnoreCase(HEADER_X_FORWARDED_FOR)) {
                continue;
            } else {
                method.addHeader(name, value);
            }
        }

        setVHost(req.getHeader("Host"));
    }
    method.addHeader(HEADER_REMOTE_HOST, req.getRemoteAddr());
    String xff = req.getHeader(HEADER_X_FORWARDED_FOR);

    if (xff == null) {
        xff = "";
    } else {
        xff = xff + ", ";
    }

    method.addHeader(HEADER_X_FORWARDED_FOR, xff + req.getRemoteHost());

    if (req.getHeader(HEADER_X_ORIGINAL_REQUEST_URL) == null) {
        method.addHeader(HEADER_X_ORIGINAL_REQUEST_URL, req.getRequestURL().toString());
    }
}

From source file:org.yes.cart.shoppingcart.support.headerdriven.impl.RequestHeaderTuplizerImpl.java

private Map<String, List<String>> createHeadersMap(final HttpServletRequest httpRequest) {

    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Enumeration headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String nextKey = (String) headerNames.nextElement();
        if (!headers.containsKey(nextKey)) {
            headers.put(nextKey, new ArrayList<String>());
        }//  w w w  .jav  a  2  s  . c o  m
        final List<String> values = headers.get(nextKey);
        final Enumeration headerValues = httpRequest.getHeaders(nextKey);
        while (headerValues.hasMoreElements()) {
            final String nextValue = (String) headerValues.nextElement();
            values.add(nextValue);
        }
    }
    return headers;
}

From source file:com.temenos.interaction.core.web.RequestContextFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI = StringUtils.removeStart(requestURI,
            servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
            headersMap.put(headerName, valuesList);
        }/*from w  ww .j  a v  a  2s  .com*/
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap);
    } else {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}