Example usage for javax.servlet.http HttpServletRequest getProtocol

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

Introduction

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

Prototype

public String getProtocol();

Source Link

Document

Returns the name and version of the protocol the request uses in the form <i>protocol/majorVersion.minorVersion</i>, for example, HTTP/1.1.

Usage

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request// w w w .  j a v a 2 s.  c  om
 ***************************************************************************/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    boolean checkedContent = false;
    boolean legend = false;
    String strErrorMessage = "";
    String serverUrl = request.getParameter("url");
    log.info("POST param serverUrl: " + serverUrl);
    if (serverUrl.startsWith("legend")) {
        serverUrl = serverUrl.replace("legend", "");
        serverUrl = serverUrl.replace("?", "&");
        serverUrl = serverUrl.replaceFirst("&", "?");
        legend = true;
    }
    serverUrl = checkTypeRequest(serverUrl);
    // log.info("serverUrl ckecked: " + serverUrl);
    if (!serverUrl.equals("ERROR")) {
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = null;
            try {
                if (log.isDebugEnabled()) {
                    Enumeration<?> e = request.getHeaderNames();
                    while (e.hasMoreElements()) {
                        String name = (String) e.nextElement();
                        String value = request.getHeader(name);
                        log.debug("request header:" + name + ":" + value);
                    }
                }
                HttpClient client = new HttpClient();
                httppost = new PostMethod(serverUrl);
                // PATH
                httppost.setDoAuthentication(false);
                httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(3, false));
                // FIN_PATH
                // PATH_MAPEAEDITA_SECURITY - AP
                // PATCH_TICKET_MJM-20112405-POST
                String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210
                if (authorizationValue == null) {
                    // The 'Authorization' header must be in this form ->
                    // Authorization: Basic <encodedLogin>
                    // 'encodedLogin' is a string in the form 'user:pass'
                    // that has been encoded by way of the Base64 algorithm.
                    // More info on this can be found at
                    // http://en.wikipedia.org/wiki/Basic_access_authentication
                    String user = (String) request.getSession().getAttribute("user");
                    String pass = (String) request.getSession().getAttribute("pass");
                    if (user != null && pass != null) {
                        String userAndPass = user + ":" + pass;
                        String encodedLogin = new String(
                                org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes()));
                        httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                    } else { // MJM - 20110520
                        String ticketParameter = request.getParameter("ticket");
                        if (ticketParameter != null) {
                            ticketParameter = ticketParameter.trim();
                            if (!ticketParameter.isEmpty()) {
                                Ticket ticket = TicketFactory.createInstance();
                                try {
                                    Map<String, String> props = ticket.getProperties(ticketParameter);
                                    user = props.get("user");
                                    pass = props.get("pass");
                                    String userAndPass = user + ":" + pass;
                                    String encodedLogin = new String(org.apache.commons.codec.binary.Base64
                                            .encodeBase64(userAndPass.getBytes()));
                                    httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                                } catch (Exception e) {
                                    log.info("-------------------------------------------");
                                    log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS");
                                    log.info("METHOD: doPost");
                                    log.info("TICKET VALUE: " + ticketParameter);
                                    log.info("-------------------------------------------");
                                }
                            }
                        }
                    }
                } else {
                    httppost.addRequestHeader(AUTHORIZATION, authorizationValue);
                }
                // FIN_PATH_TICKET_MJM-20112405-POST
                // FIN_PATH_MAPEAEDITA_SECURITY - AP
                String body = inputStreamAsString(request.getInputStream());
                StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null);
                if (0 == httppost.getParameters().length) {
                    log.debug("No Name/Value pairs found ... pushing as received"); // PATCH
                    httppost.setRequestEntity(bodyEntity); // PATCH
                }
                if (log.isDebugEnabled()) {
                    log.debug("Body = " + body);
                    NameValuePair[] nameValuePairs = httppost.getParameters();
                    log.debug("NameValuePairs found: " + nameValuePairs.length);
                    for (int i = 0; i < nameValuePairs.length; ++i) {
                        log.debug("parameters:" + nameValuePairs[i].toString());
                    }
                }
                if (!legend)
                    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
                if (soap) {
                    httppost.addRequestHeader("SOAPAction", serverUrl);
                }
                client.executeMethod(httppost);
                // PATH_FOLLOW_REDIRECT_POST
                int j = 0;
                String redirectLocation;
                Header locationHeader = httppost.getResponseHeader("location");
                while (locationHeader != null && j < numMaxRedirects) {
                    redirectLocation = locationHeader.getValue();
                    // AGG 20111304 Aadimos el cuerpo de la peticin POST a
                    // la nueva peticin redirigida
                    // String bodyPost = httppost.getResponseBodyAsString();
                    StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null);
                    httppost.releaseConnection();
                    httppost = new PostMethod(redirectLocation);
                    // AGG 20110912 Aadidas cabeceras peticin SOAP
                    if (redirectLocation.toLowerCase().contains("wsdl")) {
                        redirectLocation = serverUrl.replace("?wsdl", "");
                        httppost.addRequestHeader("SOAPAction", redirectLocation);
                        httppost.addRequestHeader("Content-type", "text/xml");
                    }
                    httppost.setRequestEntity(bodyEntityPost);
                    client.executeMethod(httppost);
                    locationHeader = httppost.getResponseHeader("location");
                    j++;
                }
                log.info("Number of followed redirections: " + j);
                if (locationHeader != null && j == numMaxRedirects) {
                    log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed.");
                }
                // FIN_PATH_FOLLOW_REDIRECT_POST
                if (log.isDebugEnabled()) {
                    Header[] responseHeaders = httppost.getResponseHeaders();
                    for (int i = 0; i < responseHeaders.length; ++i) {
                        String headerName = responseHeaders[i].getName();
                        String headerValue = responseHeaders[i].getValue();
                        log.debug("responseHeaders:" + headerName + "=" + headerValue);
                    }
                }
                // dump response to out
                if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httppost.getResponseHeaders();
                    int compSize = httppost.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY - AG
                    if (checkedContent == true) {
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch")
                                || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) {
                            response.setContentType("application/json");
                        } else {
                            response.setContentType("text/xml");
                        }
                        if (legend) {
                            String responseBody = httppost.getResponseBodyAsString();
                            if (responseBody.contains("ServiceExceptionReport")
                                    && serverUrl.contains("LegendGraphic")) {
                                response.sendRedirect("Componente/img/blank.gif");
                            } else {
                                response.setContentLength(responseBody.length());
                                PrintWriter out = response.getWriter();
                                out.print(responseBody);
                                response.flushBuffer();
                            }
                        } else {
                            // Patch_AGG 20112505 Prevents IE cache
                            if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                                response.setHeader("Pragma", "no-cache");
                            } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                                response.setHeader("Cache-Control", "no-cache");
                            }
                            response.setDateHeader("Expires", -1);
                            // END patch
                            // Copy request to response
                            InputStream st = httppost.getResponseBodyAsStream();
                            final ServletOutputStream sos = response.getOutputStream();
                            IOUtils.copy(st, sos);
                        }
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    response.addHeader(WWW_AUTHENTICATE,
                            httppost.getResponseHeader(WWW_AUTHENTICATE).getValue());
                } else {
                    strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString())
                            .concat(" ").concat(httppost.getResponseBodyAsString());
                    log.error("Unexpected failure: " + httppost.getStatusLine().toString());
                }
                httppost.releaseConnection();
                // AGG 20110927 Avoid Throwable (change it with exceptions)
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httppost != null) {
                    httppost.releaseConnection();
                }
            }
        } else {
            strErrorMessage += "Only HTTP(S) protocol supported";
            log.error("Only HTTP(S) protocol supported");
            // throw new
            // ServletException("only HTTP(S) protocol supported");
        }
    }
    // There are errors.
    if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) {
        if (strErrorMessage.equals("") == true) {
            strErrorMessage = "Error en el parametro url de entrada";
        }
        // String errorXML = strErrorMessage;
        String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage
                + "</descripcion></error>";
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            out.print(errorXML);
            response.flushBuffer();
        } catch (Exception e) {
            log.error(e);
        }
    }
    log.info("-------- End POST method --------");
}

From source file:net.xy.jcms.shared.adapter.HttpRequestDataAccessContext.java

/**
 * default constructor//w w  w.  j a  v  a2  s. c om
 * 
 * @param request
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public HttpRequestDataAccessContext(final HttpServletRequest request)
        throws MalformedURLException, URISyntaxException {
    // gets cappsubrand default locale and various other jj related
    // informations mendatory to retrieve jj configuration
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (final UnsupportedEncodingException e) {
    }
    contextPath = request.getContextPath() + "/";
    requestPath = request.getPathInfo().length() > 0 && request.getPathInfo().charAt(0) == '/'
            ? request.getPathInfo().substring(1)
            : request.getPathInfo();
    rootUrl = new URI(request.getProtocol().split("/", 2)[0], null, request.getLocalName(),
            request.getLocalPort(), "/", null, null);

    // properties
    if (request.getParameter("flushConfig") != null) {
        properties.put("flushConfig", true);
    }
}

From source file:nl.strohalm.cyclos.http.RestFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    // If Rest is disabled by configuration, always send a 404 error
    if (restDisabled) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//w  w  w.ja va 2  s .  c o  m
    }

    // Check if the application is online
    if (!applicationService.isOnline()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    // Add no cache control
    response.setHeader("Cache-control", "no-cache, no-store, must-revalidate");

    // Check non-secure access when HTTP is enabled
    if (Boolean.TRUE.equals(getServletContext().getAttribute("cyclos.httpEnabled"))) {
        if (!"https".equalsIgnoreCase(request.getProtocol())) {
            response.sendError(HttpStatus.UPGRADE_REQUIRED.value(),
                    HttpStatus.UPGRADE_REQUIRED.getReasonPhrase());
            response.addHeader("Upgrade", "TLS/1.0, HTTP/1.1");
            response.addHeader("Connection", "Upgrade");
            return;
        }
    }

    // When logging REST parameters, we need to wrap the request with StringBodyRequest in order to have the body available
    final boolean logParameters = loggingHandler.isRestParametersLogEnabled();
    super.execute(logParameters ? new StringBodyRequest(request) : request, response, chain);
}

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

public void init() throws ServletException {
    try {/*from w ww  . java 2  s  .  c o  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:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information.//from w w  w . ja v  a 2s. co  m
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./* w ww  .ja  v a  2s.c  o  m*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from   ww  w .jav a 2 s.  c o m*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:org.apache.ofbiz.content.data.DataEvents.java

/** Streams any binary content data to the browser */
public static String serveObjectData(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    HttpSession session = request.getSession();
    Locale locale = UtilHttp.getLocale(request);

    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    String userAgent = request.getHeader("User-Agent");

    Map<String, Object> httpParams = UtilHttp.getParameterMap(request);
    String contentId = (String) httpParams.get("contentId");
    if (UtilValidate.isEmpty(contentId)) {
        String errorMsg = "Required parameter contentId not found!";
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }//from  ww  w. j  a v a 2  s  .c  o  m

    // get the permission service required for streaming data; default is always the genericContentPermission
    String permissionService = EntityUtilProperties.getPropertyValue("content", "stream.permission.service",
            "genericContentPermission", delegator);

    // get the content record
    GenericValue content;
    try {
        content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }

    // make sure content exists
    if (content == null) {
        String errorMsg = "No content found for Content ID: " + contentId;
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }

    // make sure there is a DataResource for this content
    String dataResourceId = content.getString("dataResourceId");
    if (UtilValidate.isEmpty(dataResourceId)) {
        String errorMsg = "No Data Resource found for Content ID: " + contentId;
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }

    // get the data resource
    GenericValue dataResource;
    try {
        dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId)
                .queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }

    // make sure the data resource exists
    if (dataResource == null) {
        String errorMsg = "No Data Resource found for ID: " + dataResourceId;
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }

    // see if data resource is public or not
    String isPublic = dataResource.getString("isPublic");
    if (UtilValidate.isEmpty(isPublic)) {
        isPublic = "N";
    }

    // not public check security
    if (!"Y".equalsIgnoreCase(isPublic)) {
        // do security check
        Map<String, ? extends Object> permSvcCtx = UtilMisc.toMap("userLogin", userLogin, "locale", locale,
                "mainAction", "VIEW", "contentId", contentId);
        Map<String, Object> permSvcResp;
        try {
            permSvcResp = dispatcher.runSync(permissionService, permSvcCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            return "error";
        }
        if (ServiceUtil.isError(permSvcResp)) {
            String errorMsg = ServiceUtil.getErrorMessage(permSvcResp);
            Debug.logError(errorMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errorMsg);
            return "error";
        }

        // no service errors; now check the actual response
        Boolean hasPermission = (Boolean) permSvcResp.get("hasPermission");
        if (!hasPermission.booleanValue()) {
            String errorMsg = (String) permSvcResp.get("failMessage");
            Debug.logError(errorMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errorMsg);
            return "error";
        }
    }

    // get objects needed for data processing
    String contextRoot = (String) request.getAttribute("_CONTEXT_ROOT_");
    String webSiteId = (String) session.getAttribute("webSiteId");
    String dataName = dataResource.getString("dataResourceName");

    // get the mime type
    String mimeType = DataResourceWorker.getMimeType(dataResource);

    // hack for IE and mime types
    if (userAgent.indexOf("MSIE") > -1) {
        Debug.logInfo("Found MSIE changing mime type from - " + mimeType, module);
        mimeType = "application/octet-stream";
    }

    // for local resources; use HTTPS if we are requested via HTTPS
    String https = "false";
    String protocol = request.getProtocol();
    if ("https".equalsIgnoreCase(protocol)) {
        https = "true";
    }

    // get the data resource stream and content length
    Map<String, Object> resourceData;
    try {
        resourceData = DataResourceWorker.getDataResourceStream(dataResource, https, webSiteId, locale,
                contextRoot, false);
    } catch (IOException e) {
        Debug.logError(e, "Error getting DataResource stream", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    } catch (GeneralException e) {
        Debug.logError(e, "Error getting DataResource stream", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        return "error";
    }

    // get the stream data
    InputStream stream = null;
    Long length = null;

    if (resourceData != null) {
        stream = (InputStream) resourceData.get("stream");
        length = (Long) resourceData.get("length");
    }
    Debug.logInfo("Got resource data stream: " + length + " bytes", module);

    // stream the content to the browser
    if (stream != null && length != null) {
        try {
            UtilHttp.streamContentToBrowser(response, stream, length.intValue(), mimeType, dataName);
        } catch (IOException e) {
            Debug.logError(e, "Unable to write content to browser", module);
            request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
            // this must be handled with a special error string because the output stream has been already used and we will not be able to return the error page;
            // the "io-error" should be associated to a response of type "none"
            return "io-error";
        }
    } else {
        String errorMsg = "No data is available.";
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }

    return "success";
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);//from   w  w  w. j av  a2s  .co m
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

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

/**
 *
 * @param request/*from w  ww . jav a  2 s . c  o  m*/
 * @return
 */
public static Boolean isSecure(final HttpServletRequest request) {
    Boolean secure = false;
    final String protocol = request.getProtocol();
    if (protocol.indexOf("HTTPS") > -1) {
        secure = true;
    } else {
        secure = false;
    }
    return secure;
}