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.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request//from w  w  w.ja v a 2 s  .  c o m
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Retrieves all of the headers from the servlet request and sets them on the proxy request
 * /*w  ww.ja v a2s  .  co 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
 * @return ProxyInfo
 */
@SuppressWarnings("rawtypes")
private ProxyInfo setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest,
        HttpMethod httpMethodProxyRequest) {

    final String proxyHost = url.getHost();
    final int proxyPort = url.getPort();
    final String proxyPath = url.getPath();
    final ProxyInfo proxyInfo = new ProxyInfo(proxyHost, proxyPath, proxyPort);

    // ////////////////////////////////////////
    // Get an Enumeration of all of the header
    // names sent by the client.
    // ////////////////////////////////////////

    Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames();

    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();

        if (stringHeaderName.equalsIgnoreCase(Utils.CONTENT_LENGTH_HEADER_NAME))
            continue;

        // ////////////////////////////////////////////////////////////////////////
        // 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 enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);

        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = (String) 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(Utils.HOST_HEADER_NAME)) {
                stringHeaderValue = Utils.getProxyHostAndPort(proxyInfo);
            }

            // ////////////////////////
            // Skip GZIP Responses
            // ////////////////////////

            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;

            Header header = new Header(stringHeaderName, stringHeaderValue);

            // /////////////////////////////////////////////
            // Set the same header on the proxy request
            // /////////////////////////////////////////////

            httpMethodProxyRequest.setRequestHeader(header);
        }
    }

    return proxyInfo;
}

From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java

public void init() throws ServletException {
    try {/*from w w  w.jav  a2 s.co m*/
        String bs = getInitParameter("bufferSize");
        if (logger.isDebugEnabled())
            logger.debug("Upgrade ws, create factory:");
        this._webSocketFactory = new WebSocketFactory(this, (bs == null) ? 8192 : Integer.parseInt(bs)) {
            private WebSocketBuffers _buffers = new WebSocketBuffers(8192);
            private Map<WebSocketServletConnection, String> sessionMap = new HashMap<WebSocketServletConnection, String>();

            public void upgrade(HttpServletRequest request, HttpServletResponse response, WebSocket websocket,
                    String protocol) throws IOException {
                String sessionId = request.getRequestedSessionId();
                if (logger.isDebugEnabled())
                    logger.debug("Upgrade ws, requested sessionId:" + sessionId);
                if (StringUtils.isBlank(sessionId)) {
                    sessionId = request.getSession().getId();
                    if (logger.isDebugEnabled())
                        logger.debug("Request.sessionId:" + sessionId);

                }
                if (StringUtils.isBlank(sessionId)) {
                    sessionId = ((DefaultWebsocket) websocket).getConnectionKey();
                    if (logger.isDebugEnabled())
                        logger.debug("Request.wsSessionId:" + sessionId);

                }

                if (!("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))))
                    throw new IllegalStateException("!Upgrade:websocket");
                if (!("HTTP/1.1".equals(request.getProtocol()))) {
                    throw new IllegalStateException("!HTTP/1.1");
                }
                int draft = request.getIntHeader("Sec-WebSocket-Version");
                if (draft < 0) {
                    draft = request.getIntHeader("Sec-WebSocket-Draft");
                }

                int requestedVersion = draft;
                AbstractHttpConnection http = AbstractHttpConnection.getCurrentConnection();
                if (http instanceof BlockingHttpConnection)
                    throw new IllegalStateException("Websockets not supported on blocking connectors");
                ConnectedEndPoint endp = (ConnectedEndPoint) http.getEndPoint();

                List<String> extensions_requested = new ArrayList<>();

                Enumeration<String> e = request.getHeaders("Sec-WebSocket-Extensions");
                while (e.hasMoreElements()) {
                    QuotedStringTokenizer tok = new QuotedStringTokenizer((String) e.nextElement(), ",");
                    while (tok.hasMoreTokens()) {
                        extensions_requested.add(tok.nextToken());
                    }

                }

                if (draft < getMinVersion())
                    draft = 2147483647;

                WebSocketServletConnection connection;
                switch (draft) {
                case -1:
                case 0:
                    connection = new WebSocketServletConnectionD00(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol);
                    break;
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                    connection = new WebSocketServletConnectionD06(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol);
                    break;
                case 7:
                case 8:
                    List<Extension> extensions = initExtensions(extensions_requested, 5, 5, 3);
                    connection = new WebSocketServletConnectionD08(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions, draft);
                    break;
                case 13:
                    List<Extension> extensions1 = initExtensions(extensions_requested, 5, 5, 3);
                    connection = new WebSocketServletConnectionRFC6455(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions1, draft);
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                default:
                    String versions = "13";
                    if (getMinVersion() <= 8)
                        versions = new StringBuilder().append(versions).append(", 8").toString();
                    if (getMinVersion() <= 6)
                        versions = new StringBuilder().append(versions).append(", 6").toString();
                    if (getMinVersion() <= 0) {
                        versions = new StringBuilder().append(versions).append(", 0").toString();
                    }
                    response.setHeader("Sec-WebSocket-Version", versions);

                    StringBuilder err = new StringBuilder();
                    err.append("Unsupported websocket client version specification ");
                    if (requestedVersion >= 0)
                        err.append("[").append(requestedVersion).append("]");
                    else {
                        err.append("<Unspecified, likely a pre-draft version of websocket>");
                    }
                    err.append(", configured minVersion [").append(getMinVersion()).append("]");
                    err.append(", reported supported versions [").append(versions).append("]");
                    // LOG.warn(err.toString(), new Object[0]);

                    throw new HttpException(400, "Unsupported websocket version specification");
                }

                addConnection(connection);

                connection.getConnection().setMaxBinaryMessageSize(getMaxBinaryMessageSize());
                connection.getConnection().setMaxTextMessageSize(getMaxTextMessageSize());

                connection.handshake(request, response, protocol);
                response.flushBuffer();

                connection.fillBuffersFrom(((HttpParser) http.getParser()).getHeaderBuffer());
                connection.fillBuffersFrom(((HttpParser) http.getParser()).getBodyBuffer());
                String wsSession = ((DefaultWebsocket) websocket).getConnectionKey();
                //if(logger.isDebugEnabled())logger.debug("Upgraded session " + request.getSession().getId() + " to ws " + ((DefaultWebsocket) websocket).getConnectionKey());
                if (logger.isDebugEnabled())
                    logger.debug("Upgraded session " + sessionId + " to ws " + wsSession + " from remote ip:"
                            + request.getRemoteAddr());
                try {
                    sessionMap.put(connection, wsSession);
                    SubscriptionManagerFactory.getInstance().add(sessionId, wsSession,
                            ConfigConstants.OUTPUT_WS, request.getLocalAddr(), request.getRemoteAddr());
                    //add default sub, or specific sub here, all instant policy
                    String subscribe = request.getParameter("subscribe");
                    if (StringUtils.isBlank(subscribe) || "self".equals(subscribe)) {
                        //subscribe to self
                        String sub = "{\"context\":\"vessels.self\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}";
                        sendSub(request, sub, wsSession);
                    } else if ("all".equals(subscribe)) {
                        //subscribe to all
                        String sub = "{\"context\":\"vessels.*\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}";
                        sendSub(request, sub, wsSession);
                    } else if ("none".equals(subscribe)) {
                        //subscribe to none - do nothing
                    }

                } catch (Exception e1) {
                    logger.error(e1.getMessage(), e1);
                    throw new IOException(e1);
                }
                // LOG.debug("Websocket upgrade {} {} {} {}", new Object[] { request.getRequestURI(), Integer.valueOf(draft), protocol, connection });
                request.setAttribute("org.eclipse.jetty.io.Connection", connection);
                connection.getConnection().sendMessage(Util.getWelcomeMsg().toString());
            }

            private void sendSub(HttpServletRequest request, String sub, String wsSession) throws Exception {
                Map<String, Object> headers = new HashMap<>();
                headers.put(MSG_SRC_IP, request.getRemoteAddr());
                headers.put(MSG_SRC_IP_PORT, request.getRemotePort());

                if (Util.sameNetwork(request.getLocalAddr(), request.getRemoteAddr())) {
                    headers.put(MSG_TYPE, INTERNAL_IP);
                } else {
                    headers.put(MSG_TYPE, EXTERNAL_IP);
                }
                headers.put(WebsocketConstants.CONNECTION_KEY, wsSession);
                if (logger.isDebugEnabled())
                    logger.debug("Sending connection sub:" + sub);
                producer.sendBodyAndHeaders(RouteManager.SEDA_INPUT, sub, headers);

            }

            @Override
            protected boolean removeConnection(WebSocketServletConnection connection) {
                //unsubscribe and remove websocket session
                String wsSession = sessionMap.get(connection);
                if (logger.isDebugEnabled())
                    logger.debug("Ended wsSession " + wsSession);
                try {
                    SubscriptionManagerFactory.getInstance().removeWsSession(wsSession);
                } catch (Exception e1) {
                    logger.error(e1.getMessage(), e1);
                }
                return super.removeConnection(connection);
            }

        };
        this._webSocketFactory.setMaxTextMessageSize(256 * 1024);
        this._webSocketFactory.start();

        String max = getInitParameter("maxIdleTime");
        if (max != null) {
            this._webSocketFactory.setMaxIdleTime(Integer.parseInt(max));
        }
        max = getInitParameter("maxTextMessageSize");
        if (max != null) {
            this._webSocketFactory.setMaxTextMessageSize(Integer.parseInt(max));
        }
        max = getInitParameter("maxBinaryMessageSize");
        if (max != null) {
            this._webSocketFactory.setMaxBinaryMessageSize(Integer.parseInt(max));
        }
        String min = getInitParameter("minVersion");
        if (min != null)
            this._webSocketFactory.setMinVersion(Integer.parseInt(min));
    } catch (ServletException x) {
        throw x;
    } catch (Exception x) {
        throw new ServletException(x);
    }
}

From source file:at.gv.egiz.bku.online.webapp.WebRequestHandler.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {

    BindingProcessorManager bindingProcessorManager = (BindingProcessorManager) getServletContext()
            .getAttribute("bindingProcessorManager");
    if (bindingProcessorManager == null) {
        String msg = "Configuration error: BindingProcessorManager missing!";
        log.error(msg);//  w w  w . ja v a 2  s . co m
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    Configuration conf = ((BindingProcessorManagerImpl) bindingProcessorManager).getConfiguration();
    if (conf == null)
        log.error("No configuration");
    else
        MoccaParameterBean.setP3PHeader(conf, resp);

    Id id = (Id) req.getAttribute("id");
    if (id == null) {
        String msg = "No request id! Configuration error: ServletFilter missing?";
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    // if binding processor with same id is present: remove
    bindingProcessorManager.removeBindingProcessor(id);

    Locale locale = AcceptLanguage.getLocale(req.getHeader("Accept-Language"));
    if (log.isInfoEnabled()) {
        log.info("Received request (Accept-Language locale: {}).", locale);
    }

    // create new binding processor
    String protocol = MoccaParameterBean.getInitParameter("protocol", getServletConfig(), getServletContext());
    if (protocol == null || protocol.isEmpty()) {
        protocol = req.getScheme();
    }
    HTTPBindingProcessor bindingProcessor = (HTTPBindingProcessor) bindingProcessorManager
            .createBindingProcessor(protocol, locale);

    // set headers
    LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
    if (req.getHeaderNames() != null) {
        for (Enumeration<?> headerName = req.getHeaderNames(); headerName.hasMoreElements();) {
            String name = (String) headerName.nextElement();
            // Account for multiple headers with the same field-name, but
            // they are very rare, so we are not using a StringBuffer.
            Enumeration<?> headers = req.getHeaders(name);
            String value = null;
            while (headers.hasMoreElements()) {
                value = (value == null) ? (String) headers.nextElement() : value + ", " + headers.nextElement();
            }
            headerMap.put(name, value);
        }
    }

    // set request stream 
    InputStream inputStream;
    if (req.getMethod().equals("POST")) {
        inputStream = req.getInputStream();
    } else {
        headerMap.put(HttpUtil.HTTP_HEADER_CONTENT_TYPE, InputDecoderFactory.URL_ENCODED);
        String queryString = req.getQueryString();
        if (queryString != null) {
            inputStream = new ByteArrayInputStream(queryString.getBytes("UTF-8"));
        } else {
            inputStream = new ByteArrayInputStream(new byte[] {});
        }
    }

    bindingProcessor.setHTTPHeaders(headerMap);
    bindingProcessor.consumeRequestStream(req.getRequestURL().toString(), inputStream);
    inputStream.close();

    // process
    bindingProcessorManager.process(id, bindingProcessor);

    log.debug("Sending redirect to user interface.");
    resp.sendRedirect(resp.encodeRedirectURL(uiRedirectUrl));

}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*w w  w.j  a  v a2 s . co m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:io.datenwelt.cargo.rest.Request.java

public Request(HttpServletRequest servletRequest, List<ContentType> supportedContentTypes,
        List<ContentEncoding> supportedContentEncodings) throws APIException {
    this.servletRequest = servletRequest;
    this.supportedContentTypes = supportedContentTypes;
    this.supportedContentEncodings = supportedContentEncodings;
    this.method = servletRequest.getMethod();
    this.path = Segment.normalize(servletRequest.getPathInfo());

    StringBuffer url = servletRequest.getRequestURL();
    String query = servletRequest.getQueryString();
    if (query != null && !query.isEmpty()) {
        url.append("?").append(query);
    }// ww  w  .  j  av  a2 s  .com

    // Parse request URI and construct the base URI.
    try {
        requestURI = new URI(url.toString());
        String basePath = (servletRequest.getContextPath() == null ? "" : servletRequest.getContextPath())
                + (servletRequest.getServletPath() == null ? "" : servletRequest.getServletPath());
        baseURI = URI.create(new StringBuffer().append(requestURI.getScheme()).append("://")
                .append(requestURI.getRawAuthority()).append("/").append(basePath).toString());
        path = Segment.normalize(requestURI.getPath());
        if (path.startsWith(basePath)) {
            path = path.substring(basePath.length());
        }
    } catch (URISyntaxException ex) {
        throw new APIException(new InternalServerError(), "Unable to parse request URI from string '"
                + requestURI + "'. Using defaut value for base URI. Error: " + ex.getMessage(), ex);
    }

    // Parse query string.
    String queryString = servletRequest.getQueryString();
    this.queries.addAll(Query.parseQueryString(queryString));

    // Parse header values
    Enumeration headerNames = servletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement().toString();
        Enumeration values = servletRequest.getHeaders(name);
        while (values.hasMoreElements()) {
            Header header = headers.get(name);
            if (header == null) {
                header = new Header(name);
                headers.put(header.getName(), header);
            }
            String value = values.nextElement().toString();
            header.add(Header.decode(name, value));
        }
    }

    // Collect infos about the remote end.
    remoteAddress = servletRequest.getRemoteAddr();
    remoteHost = servletRequest.getRemoteHost();
    remotePort = servletRequest.getRemotePort();

}

From source file:airlift.servlet.rest.RestServlet.java

/**
 * Apply security checks.//from  www  .  j av a 2  s  .c o m
 *
 * @param _request the _request
 * @param _response the _response
 * @param _method the _method
 * @return the rest context
 */
protected RestContext applySecurityChecks(HttpServletRequest _request, HttpServletResponse _response,
        Method _method) {
    //Deal with COR headers
    _response.addHeader("Access-Control-Allow-Origin", "*");
    _response.addHeader("Access-Control-Allow-Headers",
            "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
    _response.addHeader("Access-Control-Allow-Credentials", "true");
    _response.addHeader("Access-Control-Max-Age", "86400");
    _response.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");

    java.util.Enumeration<String> headerNames = _request.getHeaderNames();

    logInfo("reporting request header info ...");
    while (headerNames.hasMoreElements() == true) {
        String headerName = headerNames.nextElement();
        logInfo(headerName + ":" + _request.getHeader(headerName));
    }

    String namespace = this.getServletConfig().getInitParameter("a.namespace");
    if (namespace != null && org.apache.commons.lang.StringUtils.isWhitespace(namespace) == false) {
        com.google.appengine.api.NamespaceManager.set(namespace);
    }
    com.google.appengine.api.quota.QuotaService quotaService = com.google.appengine.api.quota.QuotaServiceFactory
            .getQuotaService();
    logInfo("RestServlet START " + quotaService.getCpuTimeInMegaCycles());

    java.util.List<String> acceptValueList = new java.util.ArrayList<String>();
    java.util.Enumeration<String> acceptHeaderValues = _request.getHeaders("Accept");

    while (acceptHeaderValues.hasMoreElements() == true) {
        String acceptHeaderValue = acceptHeaderValues.nextElement();

        String[] tokenArray = acceptHeaderValue.split(",");

        for (int i = 0; i < tokenArray.length; i++) {
            //For now we ignore q and other parameters 
            String acceptValue = tokenArray[i].replaceAll(";.*$", "");

            if (acceptValue.contains("*") == false) {
                acceptValueList.add(acceptValue.toLowerCase());
            }
        }
    }

    String method = determineMethod(_method, _request);
    Map uriParameterMap = new java.util.HashMap();
    RestContext restContext = prepareRestContext(method, acceptValueList, _request, uriParameterMap,
            getServletName());

    if (restContext.getHandlerPathList().isEmpty() == true) {
        sendCodedPage("404", "Not Found", _response);
    }

    UserService userService = getUserService(_request, restContext, _response);
    AbstractUser user = userService.getCurrentUser();

    RestfulSecurityContext securityContext = new RestfulSecurityContext(userService.getUserKind(),
            this.cachingContextMap.get("user.session"),
            this.getServletConfig().getInitParameter("a.roleset.manager"),
            "true".equalsIgnoreCase(this.getServletConfig().getInitParameter("a.verbose.log")));
    restContext.setSecurityContext(securityContext);
    securityContext.populate(user);
    restContext.setUser(user);

    boolean success = allowed(user, restContext, securityContext);

    logInfo("User is: " + user);

    if (!success && user == null) {
        boolean loginSuccessful = requestLogin(_request, _response, userService);

        if (loginSuccessful == false) {
            sendCodedPage("401", "UnAuthorized - you must log in to " + method + " access this resource.",
                    _response);
        }
    } else if (!success && user != null) {
        sendCodedPage("401",
                "UnAuthorized - User " + user.getEmail() + " does not have " + method
                        + " access to this resource. You may <a href=\""
                        + userService.createLogoutURL(_request.getRequestURI())
                        + "\">logout</a> and login as another user.",
                _response);
    } else if (success && timedOut(user) == true) {
        logInfo("Timed out user is now: " + user);

        boolean logoutSuccessful = logUserOut(_request, _response, userService);

        if (logoutSuccessful == false) {
            logInfo("Time out incepted log out failed");
            sendCodedPage("408", "Request Timeout", _response);
        }
    } else if (success) {
        //User is not timed out and the user can access this page.
        //Not being timed out means that your time out date time is null
        //or your time out date time is greater than the current date
        //time.

        proceedToProcessRequest(user, securityContext, _request, _response, method, restContext,
                uriParameterMap);
    }

    long totalMegaCycles = quotaService.getCpuTimeInMegaCycles();
    logInfo("RestServlet Megacycles: " + totalMegaCycles);
    logInfo("RestServlet CPU Seconds: " + quotaService.convertMegacyclesToCpuSeconds(totalMegaCycles));

    return restContext;
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

private void logRequestInfo(HttpServletRequest req) {
    if (!ZimbraLog.dav.isDebugEnabled()) {
        return;/*w  ww  .  j  a v  a 2  s  . c  o  m*/
    }
    StringBuilder hdrs = new StringBuilder();
    hdrs.append("DAV REQUEST:\n");
    hdrs.append(req.getMethod()).append(" ").append(req.getRequestURL().toString()).append(" ")
            .append(req.getProtocol());
    Enumeration<String> paramNames = req.getParameterNames();
    if (paramNames != null && paramNames.hasMoreElements()) {
        hdrs.append("\nDAV REQUEST PARAMS:");
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            if (paramName.contains("Auth")) {
                hdrs.append("\n").append(paramName).append("=*** REPLACED ***");
                continue;
            }
            String params[] = req.getParameterValues(paramName);
            if (params != null) {
                for (String param : params) {
                    hdrs.append("\n").append(paramName).append("=").append(param);
                }
            }
        }
    }
    /* Headers can include vital information which affects the request like "If-None-Match" headers,
     * so useful to be able to log them, skipping authentication related headers to avoid leaking passwords
     */
    Enumeration<String> namesEn = req.getHeaderNames();
    if (namesEn != null && namesEn.hasMoreElements()) {
        hdrs.append("\nDAV REQUEST HEADERS:");
        while (namesEn.hasMoreElements()) {
            String hdrName = namesEn.nextElement();
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                hdrs.append("\n").append(hdrName).append(": *** REPLACED ***");
                continue;
            }
            Enumeration<String> vals = req.getHeaders(hdrName);
            while (vals.hasMoreElements()) {
                hdrs.append("\n").append(hdrName).append(": ").append(vals.nextElement());
            }
        }
    }
    ZimbraLog.dav.debug(hdrs.toString());
}