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:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

/**
 * Log out request - the format should be close to Apache access log format
 * /*from   w  w w .  j a v a  2  s.c o m*/
 * @param req
 * @param session
 */
private void logRequest(HttpServletRequest req, Session session) {
    StringBuilder buf = new StringBuilder();
    buf.append(req.getRemoteAddr()).append(" ");
    if (session != null && session.getUser() != null) {
        buf.append(session.getUser().getUserId()).append(" ");
    } else {
        buf.append(" - ").append(" ");
    }

    buf.append("\"");
    buf.append(req.getMethod()).append(" ");
    buf.append(req.getRequestURI()).append(" ");
    if (req.getQueryString() != null) {
        buf.append(req.getQueryString()).append(" ");
    } else {
        buf.append("-").append(" ");
    }
    buf.append(req.getProtocol()).append("\" ");

    String userAgent = req.getHeader("User-Agent");
    if (shouldLogRawUserAgent) {
        buf.append(userAgent);
    } else {
        // simply log a short string to indicate browser or not
        if (StringUtils.isFromBrowser(userAgent)) {
            buf.append("browser");
        } else {
            buf.append("not-browser");
        }
    }

    logger.info(buf.toString());
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadTemplates(HttpServletRequest request) throws ServletException {

    if (templateLodaded) {
        return;/*from  w  ww. j a v a  2  s . c om*/
    }

    templateLodadedStarted = true;

    try {
        for (TemplateBean template : TemplateConfig.templates) {
            if (template.path.startsWith(";")) {
                template.path = template.path.substring(1);
            }

            boolean firstCharIsUnecessarySeparator = template.path.startsWith("/")
                    || template.path.startsWith("\\");
            template.path = (firstCharIsUnecessarySeparator) ? template.path.substring(1) : template.path;

            loadHTMLInfo(template, request.getServerName(), request.getServerPort(),
                    request.getProtocol().contains("HTTPS"), request);

        }
    } catch (Exception e) {
        templateLodaded = false;
        templateLodadedStarted = false;

        throw new ServletException("Exception:" + e.getMessage(), e);
    }

    templateLodaded = true;
}

From source file:Properties.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>My First Servlet</title>");
    out.println("</head>");
    out.println("<h2><center>");
    out.println("Information About You</center></h2>");
    out.println("<br>");

    out.println("<center><table border>");
    out.println("<tr>");
    out.println("<td>Method</td>");
    out.println("<td>" + req.getMethod() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>User</td>");
    out.println("<td>" + req.getRemoteUser() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Client</td>");
    out.println("<td>" + req.getRemoteHost() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Protocol</td>");
    out.println("<td>" + req.getProtocol() + "</td>");
    out.println("</tr>");

    java.util.Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>Parameter '" + name + "'</td>");
        out.println("<td>" + req.getParameter(name) + "</td>");
        out.println("</tr>");
    }/*w w  w  .j  a  v a  2s.  c om*/

    out.println("</table></center><br><hr><br>");

    out.println("<h2><center>");
    out.println("Server Properties</center></h2>");
    out.println("<br>");

    out.println("<center><table border width=80%>");

    java.util.Properties props = System.getProperties();
    e = props.propertyNames();

    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>" + name + "</td>");
        out.println("<td>" + props.getProperty(name) + "</td>");
        out.println("</tr>");
    }
    out.println("</table></center>");

    out.println("</html>");
    out.flush();
}

From source file:cz.fi.muni.xkremser.editor.server.ScanImgServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.addDateHeader("Last-Modified", new Date().getTime());
    resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
    resp.addDateHeader("Expires", DateUtils.addMonths(new Date(), 1).getTime());
    boolean full = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_FULL));
    String topSpace = req.getParameter(Constants.URL_PARAM_TOP_SPACE);
    String urlHeight = req.getParameter(Constants.URL_PARAM_HEIGHT);

    String uuid = req.getParameter(Constants.URL_PARAM_UUID);

    if (uuid == null || "".equals(uuid)) {
        uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_SCANS_PREFIX)
                + Constants.SERVLET_SCANS_PREFIX.length() + 1);
    }/*from  www  . j  ava  2 s. co  m*/

    StringBuffer baseUrl = new StringBuffer();
    baseUrl.append("http");
    if (req.getProtocol().toLowerCase().contains("https")) {
        baseUrl.append('s');
    }
    baseUrl.append("://");
    if (!URLS.LOCALHOST()) {
        baseUrl.append(req.getServerName());
    } else {
        String hostname = config.getHostname();
        if (hostname.contains("://")) {
            baseUrl.append(hostname.substring(hostname.indexOf("://") + "://".length()));
        } else {
            baseUrl.append(hostname);
        }
    }
    StringBuffer sb = new StringBuffer();
    if (topSpace != null) {
        String metadata = RESTHelper.convertStreamToString(
                RESTHelper.get(baseUrl + DJATOKA_URL_GET_METADATA + uuid, null, null, true));
        String height = null;
        height = metadata.substring(metadata.indexOf("ght\": \"") + 7, metadata.indexOf("\",\n\"dw"));
        String width = metadata.substring(metadata.indexOf("dth\": \"") + 7, metadata.indexOf("\",\n\"he"));

        int intHeight = Integer.parseInt(height);
        int intUrlHeight = Integer.parseInt(urlHeight);
        int intTopSpace = Integer.parseInt(topSpace);
        boolean isLower = intTopSpace > 0 && ((intHeight - intUrlHeight) < intTopSpace);
        String region = (isLower ? intHeight - intUrlHeight : (intTopSpace < 0 ? 0 : topSpace)) + ",1,"
                + urlHeight + "," + width;

        sb.append(baseUrl.toString()).append(DJATOKA_URL_FULL_PAGE_DETAIL).append(uuid)
                .append(DJATOKA_URL_REGION).append(region);

    } else {
        sb.append(baseUrl.toString())
                .append(full ? DJATOKA_URL_FULL_IMG : DJATOKA_URL + urlHeight + DJATOKA_URL_SUFFIX)
                .append(uuid);
    }
    resp.setContentType("image/jpeg");
    resp.sendRedirect(resp.encodeRedirectURL(sb.toString()));
}

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

private void logRequestInfo(HttpServletRequest req) {
    if (!ZimbraLog.dav.isDebugEnabled()) {
        return;/*from   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());
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data.//from   w w  w  . j  a  va  2s. c o m
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:helma.servlet.AbstractServletClient.java

protected void writeResponse(HttpServletRequest req, HttpServletResponse res, RequestTrans hopreq,
        ResponseTrans hopres) throws IOException {
    if (hopres.getForward() != null) {
        sendForward(res, req, hopres);//from  ww  w.  j  av  a 2s. co  m
        return;
    }

    if (hopres.getETag() != null) {
        res.setHeader("ETag", hopres.getETag());
    }

    if (hopres.getRedirect() != null) {
        sendRedirect(req, res, hopres.getRedirect(), hopres.getStatus());
    } else if (hopres.getNotModified()) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        if (!hopres.isCacheable() || !caching) {
            // Disable caching of response.
            if (isOneDotOne(req.getProtocol())) {
                // for HTTP 1.1
                res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
            } else {
                // for HTTP 1.0
                res.setDateHeader("Expires", System.currentTimeMillis() - 10000);
                res.setHeader("Pragma", "no-cache");
            }
        }

        if (hopres.getRealm() != null) {
            res.setHeader("WWW-Authenticate", "Basic realm=\"" + hopres.getRealm() + "\"");
        }

        if (hopres.getStatus() > 0) {
            res.setStatus(hopres.getStatus());
        }

        // set last-modified header to now
        long modified = hopres.getLastModified();
        if (modified > -1) {
            res.setDateHeader("Last-Modified", modified);
        }

        res.setContentLength(hopres.getContentLength());
        res.setContentType(hopres.getContentType());

        if (!"HEAD".equalsIgnoreCase(req.getMethod())) {
            byte[] content = hopres.getContent();
            if (content != null) {
                try {
                    OutputStream out = res.getOutputStream();
                    out.write(content);
                    out.flush();
                } catch (Exception iox) {
                    log("Exception in writeResponse: " + iox);
                }
            }
        }
    }
}

From source file:es.agrega.soporte.http.BrowserDetector.java

/**
 * Process the HttpServletRequest for client information.
 * Prosecute to the fullest extent possible ;-)
 *
 * @param request An HttpRequest used to gather client information.
 *///from  ww w.j  av a  2  s.  c  o m
public void setRequest(HttpServletRequest request) {
    // because different containers/web-servers use diffent naming conventions,
    // we need to be extra careful fetching this headers
    String tempUAS = HttpUtils.findHeader(request, "USER_AGENT");
    if (tempUAS != null) {
        this.setUserAgentString(tempUAS);
    }

    // get values from request headers
    clientIP = request.getRemoteAddr();
    clientHost = request.getRemoteHost();
    String acceptEncoding = HttpUtils.findHeader(request, "ACCEPT_ENCODING");
    if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) {
        gzipOK = true;
    }

    // acceptMIME: parse ACCEPT and place into ARRAYLIST
    String[] acceptArray = StringUtils.split(HttpUtils.findHeader(request, "ACCEPT"), ",");
    acceptMIME = java.util.Arrays.asList(acceptArray);

    String protocol = request.getProtocol();
    if (protocol != null && protocol.indexOf("/") != -1) {
        int slashLoc = protocol.indexOf("/");
        protocolType = protocol.substring(0, slashLoc);
        try {
            protocolVersion = Float.valueOf(protocol.substring(slashLoc + 1)).floatValue();
        } catch (Exception e) { // if there was an error getting protocolVersion, set to -1
            protocolVersion = (float) -1.0;
        }
        if ("HTTP".equals(protocolType) && protocolVersion > 1.0)
            keepAliveOK = true;

    }
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;//from   w  w w.  j a  va  2 s . c  o  m

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}