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:com.qualogy.qafe.web.upload.DatagridUploadServlet.java

@SuppressWarnings("unchecked")
private void writeUploadInfo(HttpServletRequest request) {
    writeLog("Document Upload!");

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        Object name = headerNames.nextElement();
        if (name != null) {
            writeLog("Header - " + name + " : " + request.getHeader((String) name));
        }//  w  ww  . j av  a2s  .  co m
    }

    writeLog("ServletRemoteAddr: " + request.getRemoteAddr());
    writeLog("Remote Host: " + request.getRemoteHost());
    writeLog("Remote User: " + request.getRemoteUser());
    writeLog("Protocol: " + request.getProtocol());
    writeLog("Server Name: " + request.getServerName());
    writeLog("Server Port: " + request.getServerPort());
    writeLog("Request URL: " + request.getRequestURL());

}

From source file:com.sangupta.httpd.HttpdHandler.java

/**
 * Log the request details to screen//from ww  w.j a  v  a2  s  . com
 * 
 * @param request
 * @param response
 * @param requestTime 
 */
private void logRequest(HttpServletRequest request, HttpServletResponse response, long requestTime) {
    SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss");

    StringBuilder builder = new StringBuilder(1024);
    builder.append(request.getRemoteAddr());
    builder.append(" - [");
    builder.append(format.format(new Date(requestTime)));
    builder.append("] \"");
    builder.append(request.getMethod());
    builder.append(' ');
    builder.append(request.getRequestURI());
    builder.append(' ');
    builder.append(request.getProtocol());
    builder.append(" - ");
    builder.append(response.getStatus());
    builder.append(" - ");

    String length = response.getHeader("Content-Length");
    if (length == null) {
        length = "0";
    }

    builder.append(length);

    System.out.println(builder.toString());
}

From source file:net.yacy.http.ProxyHandler.java

/**
 * adds specific header elements for the connection of the internal
 * httpclient to the remote server according to local config
 *
 * @param header header for http client (already preset with headers from
 * original ServletRequest)/*w w w .  jav a  2 s . co m*/
 * @param origServletRequest original request/header
 */
private void setProxyHeaderForClient(final HttpServletRequest origServletRequest,
        final HeaderFramework header) {

    header.remove(RequestHeader.KEEP_ALIVE);
    header.remove(HeaderFramework.CONTENT_LENGTH);

    // setting the X-Forwarded-For header
    if (sb.getConfigBool("proxy.sendXForwardedForHeader", true)) {
        String ip = origServletRequest.getRemoteAddr();
        if (!Domains.isThisHostIP(ip)) { // if originator is local host no user ip to forward (= request from localhost)
            header.put(HeaderFramework.X_FORWARDED_FOR, origServletRequest.getRemoteAddr());
        }
    }

    String httpVersion = origServletRequest.getProtocol();
    HTTPDProxyHandler.modifyProxyHeaders(header, httpVersion);
}

From source file:com.zimbra.soap.SoapServlet.java

private void sendResponse(HttpServletRequest req, HttpServletResponse resp, Element envelope)
        throws IOException {
    SoapProtocol soapProto = SoapProtocol.determineProtocol(envelope);
    int statusCode = soapProto.hasFault(envelope) ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
            : HttpServletResponse.SC_OK;

    boolean chunkingEnabled = LC.soap_response_chunked_transfer_encoding_enabled.booleanValue();

    if (chunkingEnabled) {
        // disable chunking if proto < HTTP 1.1
        String proto = req.getProtocol();
        try {/*from ww  w . j  a  v  a2s .co  m*/
            HttpVersion httpVer = HttpVersion.parse(proto);
            chunkingEnabled = !httpVer.lessEquals(HttpVersion.HTTP_1_0);
        } catch (ProtocolException e) {
            ZimbraLog.soap.warn(
                    "cannot parse http version in request: %s, http chunked transfer encoding disabled", proto,
                    e);
            chunkingEnabled = false;
        }
    }

    // use jetty default if the LC key is not set
    int responseBufferSize = soapResponseBufferSize();
    if (responseBufferSize != -1)
        resp.setBufferSize(responseBufferSize);

    resp.setContentType(soapProto.getContentType());
    resp.setStatus(statusCode);
    resp.setHeader("Cache-Control", "no-store, no-cache");

    if (chunkingEnabled) {
        // Let jetty chunk the response if applicable.
        ZimbraServletOutputStream out = new ZimbraServletOutputStream(resp.getOutputStream());
        envelope.output(out);
        out.flush();
    } else {
        // serialize the envelope to a byte array and send the response with Content-Length header.
        byte[] soapBytes = envelope.toUTF8();
        resp.setContentLength(soapBytes.length);
        resp.getOutputStream().write(soapBytes);
        resp.getOutputStream().flush();
    }
    envelope.destroy();
}

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

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();//from ww  w .  ja v a2 s . c o  m
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:net.sf.j2ep.requesthandlers.RequestHandlerBase.java

/**
 * Will write the proxy specific headers such as Via and x-forwarded-for.
 * /*  ww w.  j a  v  a  2 s .c o  m*/
 * @param method Method to write the headers to
 * @param request The incoming request, will need to get virtual host.
 * @throws HttpException 
 */
private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    String serverHostName = "jEasyExtensibleProxy";
    try {
        serverHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
    }

    String originalVia = request.getHeader("via");
    StringBuffer via = new StringBuffer("");
    if (originalVia != null) {
        if (originalVia.indexOf(serverHostName) != -1) {
            log.error("This proxy has already handled the request, will abort.");
            throw new HttpException("Request has a cyclic dependency on this proxy.");
        }
        via.append(originalVia).append(", ");
    }
    via.append(request.getProtocol()).append(" ").append(serverHostName);

    method.setRequestHeader("via", via.toString());
    method.setRequestHeader("x-forwarded-for", request.getRemoteAddr());
    method.setRequestHeader("x-forwarded-host", request.getServerName());
    method.setRequestHeader("x-forwarded-server", serverHostName);

    method.setRequestHeader("accept-encoding", "");
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*ww w.j av a  2 s . co m*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:org.n52.iceland.service.Service.java

private long logRequest(HttpServletRequest request) {
    long count = counter.incrementAndGet();
    this.serviceEventBus.submit(new IncomingRequestEvent(request, count));

    if (LOGGER.isDebugEnabled()) {
        Enumeration<?> headerNames = request.getHeaderNames();
        StringBuilder headers = new StringBuilder();
        while (headerNames.hasMoreElements()) {
            String name = (String) headerNames.nextElement();
            headers.append("> ").append(name).append(": ").append(request.getHeader(name)).append("\n");
        }//from w  ww.j  a  v  a 2  s. c  o m
        LOGGER.debug("Incoming request No. {}:\n> [{} {} {}] from {} {}\n{}", count, request.getMethod(),
                request.getRequestURI(), request.getProtocol(), request.getRemoteAddr(),
                request.getRemoteHost(), headers);
    }
    return count;
}

From source file:org.apache.hadoop.gateway.service.test.ServiceTestResource.java

private String buildXForwardBaseURL(HttpServletRequest req) {
    final String X_Forwarded = "X-Forwarded-";
    final String X_Forwarded_Context = X_Forwarded + "Context";
    final String X_Forwarded_Proto = X_Forwarded + "Proto";
    final String X_Forwarded_Host = X_Forwarded + "Host";
    final String X_Forwarded_Port = X_Forwarded + "Port";
    final String X_Forwarded_Server = X_Forwarded + "Server";

    String baseURL = "";

    //    Get Protocol
    if (req.getHeader(X_Forwarded_Proto) != null) {
        baseURL += req.getHeader(X_Forwarded_Proto) + "://";
    } else {/*  w  w w. java  2  s. c o m*/
        baseURL += req.getProtocol() + "://";
    }

    //    Handle Server/Host and Port Here
    if (req.getHeader(X_Forwarded_Host) != null && req.getHeader(X_Forwarded_Port) != null) {
        //        Double check to see if host has port
        if (req.getHeader(X_Forwarded_Host).contains(req.getHeader(X_Forwarded_Port))) {
            baseURL += req.getHeader(X_Forwarded_Host);
        } else {
            //        If there's no port, add the host and port together;
            baseURL += req.getHeader(X_Forwarded_Host) + ":" + req.getHeader(X_Forwarded_Port);
        }
    } else if (req.getHeader(X_Forwarded_Server) != null && req.getHeader(X_Forwarded_Port) != null) {
        //      Tack on the server and port if they're available. Try host if server not available
        baseURL += req.getHeader(X_Forwarded_Server) + ":" + req.getHeader(X_Forwarded_Port);
    } else if (req.getHeader(X_Forwarded_Port) != null) {
        //      if we at least have a port, we can use it.
        baseURL += req.getServerName() + ":" + req.getHeader(X_Forwarded_Port);
    } else {
        //      Resort to request members
        baseURL += req.getServerName() + ":" + req.getLocalPort();
    }

    //    Handle Server context
    if (req.getHeader(X_Forwarded_Context) != null) {
        baseURL += req.getHeader(X_Forwarded_Context);
    } else {
        baseURL += req.getContextPath();
    }

    return baseURL;
}