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:org.osaf.cosmo.acegisecurity.providers.ticket.ExtraTicketProcessingFilter.java

/**
 * Examines HTTP servlet requests for extra ticket keys,
 * and register them with the security manager.
 *//*from  w  w  w.ja va  2 s  . co  m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (log.isDebugEnabled())
        log.debug("looking for tickets in request headers");

    Set<Ticket> tickets = new HashSet<Ticket>();

    // Look for tickets in header in the format:
    // X-Cosmo-Ticket: slkdfjsdf, slkdjfsdf, sdlfkjsfsdf
    Enumeration<String> ticketKeys = httpRequest.getHeaders(TICKET_HEADER);
    while (ticketKeys.hasMoreElements()) {
        String ticketKeyValue = ticketKeys.nextElement();
        for (String ticketKey : ticketKeyValue.split(",")) {
            Ticket ticket = contentDao.findTicket(ticketKey.trim());
            if (ticket != null)
                tickets.add(ticket);
        }
    }

    // Look for tickets in header in the format:
    // X-MorseCode-Ticket: slkdfjsdf, slkdjfsdf, sdlfkjsfsdf
    ticketKeys = httpRequest.getHeaders(MORSE_CODE_TICKET_HEADER);
    while (ticketKeys.hasMoreElements()) {
        String ticketKeyValue = ticketKeys.nextElement();
        for (String ticketKey : ticketKeyValue.split(",")) {
            Ticket ticket = contentDao.findTicket(ticketKey.trim());
            if (ticket != null)
                tickets.add(ticket);
        }
    }

    // look for tickets in request parameters
    String[] paramTicketKeys = httpRequest.getParameterValues(PARAM_TICKET);
    if (paramTicketKeys != null) {
        for (String ticketKey : paramTicketKeys) {
            Ticket ticket = contentDao.findTicket(ticketKey);
            if (ticket != null)
                tickets.add(ticket);
        }
    }

    try {
        // register tickets
        securityManager.registerTickets(tickets);
        chain.doFilter(request, response);
    } finally {
        // clear tickets
        securityManager.unregisterTickets();
    }
}

From source file:ca.uhn.fhir.jpa.provider.BaseJpaProvider.java

public void startRequest(HttpServletRequest theRequest) {
    if (theRequest == null) {
        return;//  ww w  .j av  a 2  s . co  m
    }

    Set<String> headerNames = new TreeSet<String>();
    for (Enumeration<String> enums = theRequest.getHeaderNames(); enums.hasMoreElements();) {
        headerNames.add(enums.nextElement());
    }
    ourLog.debug("Request headers: {}", headerNames);

    Enumeration<String> forwardedFors = theRequest.getHeaders("x-forwarded-for");
    StringBuilder b = new StringBuilder();
    for (Enumeration<String> enums = forwardedFors; enums != null && enums.hasMoreElements();) {
        if (b.length() > 0) {
            b.append(" / ");
        }
        b.append(enums.nextElement());
    }

    String forwardedFor = b.toString();
    String ip = theRequest.getRemoteAddr();
    if (StringUtils.isBlank(forwardedFor)) {
        org.slf4j.MDC.put(REMOTE_ADDR, ip);
        ourLog.debug("Request is from address: {}", ip);
    } else {
        org.slf4j.MDC.put(REMOTE_ADDR, forwardedFor);
        ourLog.debug("Request is from forwarded address: {}", forwardedFor);
    }

    String userAgent = StringUtils.defaultString(theRequest.getHeader("user-agent"));
    org.slf4j.MDC.put(REMOTE_UA, userAgent);

}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00260.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;/*from  w w  w.  j  a  v  a  2s . co  m*/
                    flag = false;
                }
            }
        }
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    byte[] input = new byte[1000];
    String str = "?";
    Object inputParam = param;
    if (inputParam instanceof String)
        str = ((String) inputParam);
    if (inputParam instanceof java.io.InputStream) {
        int i = ((java.io.InputStream) inputParam).read(input);
        if (i == -1) {
            response.getWriter().println(
                    "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
            return;
        }
        str = new String(input, 0, i);
    }
    javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str);

    cookie.setSecure(false);

    response.addCookie(cookie);

    response.getWriter().println("Created cookie: 'SomeCookie': with value: '"
            + org.owasp.esapi.ESAPI.encoder().encodeForHTML(str) + "' and secure flag set to: false");
}

From source file:org.olat.core.gui.control.winmgr.WindowBackOfficeImpl.java

public void pushCommands(HttpServletRequest request, HttpServletResponse response) {
    Writer w = null;/*from  w ww. ja va2s  . co m*/
    try {
        boolean acceptJson = false;
        for (Enumeration<String> headers = request.getHeaders("Accept"); headers.hasMoreElements();) {
            String accept = headers.nextElement();
            if (accept.contains("application/json")) {
                acceptJson = true;
            }
        }

        //first set the headers with the content-type
        //and after get the writer with the encoding
        //fixed by the content-type
        if (acceptJson) {
            ServletUtil.setJSONResourceHeaders(response);
            w = response.getWriter();
            ajaxC.pushJSONAndClear(w);
        } else {
            ServletUtil.setStringResourceHeaders(response);
            w = response.getWriter();
            ajaxC.pushResource(w, true);
        }
    } catch (IOException e) {
        log.error("Error pushing commans to the AJAX canal.", e);
    } finally {
        IOUtils.closeQuietly(w);
    }
}

From source file:org.unitedinternet.cosmo.acegisecurity.providers.ticket.ExtraTicketProcessingFilter.java

/**
 * Examines HTTP servlet requests for extra ticket keys,
 * and register them with the security manager.
 * @param request The servlet request.//from  w  w w.  j a  va 2 s . c  om
 * @param response The servlet response.
 * @param chain The filter chain.
 * @throws IOException - if something is wrong this exception is thrown.
 * @throws ServletException - if something is wrong this exception is thrown.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new IllegalStateException("Received request is of type [" + request.getClass().getName()
                + "]. Expected type: [" + HttpServletRequest.class.getName() + "].");
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (LOG.isDebugEnabled()) {
        LOG.debug("looking for tickets in request headers");
    }

    Set<Ticket> tickets = new HashSet<Ticket>();

    // Look for tickets in header in the format:
    // X-Cosmo-Ticket: slkdfjsdf, slkdjfsdf, sdlfkjsfsdf
    Enumeration<String> ticketKeys = httpRequest.getHeaders(TICKET_HEADER);
    while (ticketKeys.hasMoreElements()) {
        String ticketKeyValue = ticketKeys.nextElement();
        for (String ticketKey : ticketKeyValue.split(",")) {
            Ticket ticket = contentDao.findTicket(ticketKey.trim());
            if (ticket != null) {
                tickets.add(ticket);
            }
        }
    }

    // Look for tickets in header in the format:
    // X-MorseCode-Ticket: slkdfjsdf, slkdjfsdf, sdlfkjsfsdf
    ticketKeys = httpRequest.getHeaders(MORSE_CODE_TICKET_HEADER);
    while (ticketKeys.hasMoreElements()) {
        String ticketKeyValue = ticketKeys.nextElement();
        for (String ticketKey : ticketKeyValue.split(",")) {
            Ticket ticket = contentDao.findTicket(ticketKey.trim());
            if (ticket != null) {
                tickets.add(ticket);
            }
        }
    }

    // look for tickets in request parameters
    String[] paramTicketKeys = httpRequest.getParameterValues(PARAM_TICKET);
    if (paramTicketKeys != null) {
        for (String ticketKey : paramTicketKeys) {
            Ticket ticket = contentDao.findTicket(ticketKey);
            if (ticket != null) {
                tickets.add(ticket);
            }
        }
    }

    try {
        // register tickets
        securityManager.registerTickets(tickets);
        chain.doFilter(request, response);
    } finally {
        // clear tickets
        securityManager.unregisterTickets();
    }
}

From source file:org.codehaus.enunciate.modules.rest.RESTContentTypeRoutingController.java

/**
 * Get the content type for the specified request.
 *
 * @param request The request./*w ww  . ja  va  2 s  .c o  m*/
 * @return The content type.
 */
protected List<String> getContentTypesByPreference(HttpServletRequest request) {
    String contentTypeParam = request.getParameter(getContentTypeParameter());
    if (contentTypeParam != null) {
        return Arrays.asList(contentTypeParam);
    } else {
        Set<MimeType> mimeTypes = new TreeSet<MimeType>();
        Enumeration acceptHeaders = request.getHeaders("Accept");
        if (acceptHeaders != null && acceptHeaders.hasMoreElements()) {
            Float defaultQuality = null;
            while (acceptHeaders.hasMoreElements()) {
                String acceptHeader = (String) acceptHeaders.nextElement();
                for (StringTokenizer acceptTokens = new StringTokenizer(acceptHeader, ","); acceptTokens
                        .hasMoreTokens();) {
                    String token = acceptTokens.nextToken();
                    try {
                        MimeType acceptType = MimeType.parse(token.trim());
                        mimeTypes.add(acceptType);
                        if (acceptType.isAcceptable(this.defaultMimeType)
                                && (defaultQuality == null || defaultQuality < acceptType.getQuality())) {
                            defaultQuality = acceptType.getQuality();
                        }
                    } catch (Exception e) {
                        //ignore the invalid type in the "Accept" header
                        LOG.info(e.getMessage());
                    }
                }
            }

            if (defaultQuality != null) {
                mimeTypes.add(
                        new MimeType(defaultMimeType.getType(), defaultMimeType.getSubtype(), defaultQuality));
            }
        } else {
            //add the default content types at the end.
            mimeTypes.add(this.defaultMimeType);
        }

        ArrayList<String> values = new ArrayList<String>();
        for (MimeType mimeType : mimeTypes) {
            values.add(mimeType.toString());
        }
        return values;
    }
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00248.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;/*from  ww  w .j av  a 2 s.  c o  m*/
                    flag = false;
                }
            }
        }
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        java.util.Properties benchmarkprops = new java.util.Properties();
        benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
        String algorithm = benchmarkprops.getProperty("hashAlg2", "SHA5");
        java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
        byte[] input = { (byte) '?' };
        Object inputParam = bar;
        if (inputParam instanceof String)
            input = ((String) inputParam).getBytes();
        if (inputParam instanceof java.io.InputStream) {
            byte[] strInput = new byte[1000];
            int i = ((java.io.InputStream) inputParam).read(strInput);
            if (i == -1) {
                response.getWriter().println(
                        "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
                return;
            }
            input = java.util.Arrays.copyOf(strInput, i);
        }
        md.update(input);

        byte[] result = md.digest();
        java.io.File fileTarget = new java.io.File(
                new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
        java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data
        fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
        fw.close();
        response.getWriter()
                .println("Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                        + "' hashed and stored<br/>");
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing hash - TestCase");
        throw new ServletException(e);
    }

    response.getWriter()
            .println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Pasa los headers de un request a otro. Copia todos salvo algunos
 * prohibidos que no tienen sentido./*from  www  .java2  s  .  c om*/
 */
// CHECKSTYLE:DESIGN:OFF
protected void proxyHeaders(final HttpServletRequest request, final HttpMethod method) {

    Enumeration<String> names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = names.nextElement().toLowerCase();
        Enumeration<String> headers = request.getHeaders(name);
        if (!forbiddenHeader.contains(name)) {
            while (headers.hasMoreElements()) {
                method.addRequestHeader(name, headers.nextElement());

            }
        }
    }
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest02056.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;//from ww  w  . ja v  a2  s  .c  o  m
                    flag = false;
                }
            }
        }
    }

    String bar = doSomething(param);

    long l = new java.util.Random().nextLong();
    String rememberMeKey = Long.toString(l);

    String user = "Logan";
    String fullClassName = this.getClass().getName();
    String testCaseNumber = fullClassName
            .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
        javax.servlet.http.Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
            if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                foundUser = true;
            }
        }
    }

    if (foundUser) {
        response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
        javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
        rememberMe.setSecure(true);
        request.getSession().setAttribute(cookieName, rememberMeKey);
        response.addCookie(rememberMe);
        response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                + " whose value is: " + rememberMe.getValue() + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextLong() executed");
}

From source file:org.wso2.carbon.identity.oauth.ui.endpoints.token.OAuth2TokenEndpoint.java

private void logAccessTokenRequest(HttpServletRequest request) {
    log.debug("Received a request : " + request.getRequestURI());
    // log the headers.
    log.debug("----------logging request headers.----------");
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        Enumeration headers = request.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            log.debug(headerName + " : " + headers.nextElement());
        }/*from w  w w  .ja va 2  s.c  o  m*/
    }
    // log the parameters.
    log.debug("----------logging request parameters.----------");
    log.debug(OAuth.OAUTH_GRANT_TYPE + " - " + request.getParameter(OAuth.OAUTH_GRANT_TYPE));
    log.debug(OAuth.OAUTH_CLIENT_ID + " - " + request.getParameter(OAuth.OAUTH_CLIENT_ID));
    log.debug(OAuth.OAUTH_CODE + " - " + request.getParameter(OAuth.OAUTH_CODE));
    log.debug(OAuth.OAUTH_REDIRECT_URI + " - " + request.getParameter(OAuth.OAUTH_REDIRECT_URI));
}