Example usage for javax.servlet.http HttpServletRequest getPathTranslated

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

Introduction

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

Prototype

public String getPathTranslated();

Source Link

Document

Returns any extra path information after the servlet name but before the query string, and translates it to a real path.

Usage

From source file:org.springframework.boot.actuate.trace.WebRequestTraceFilter.java

protected Map<String, Object> getTrace(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    Principal userPrincipal = request.getUserPrincipal();
    Map<String, Object> trace = new LinkedHashMap<String, Object>();
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    trace.put("method", request.getMethod());
    trace.put("path", request.getRequestURI());
    trace.put("headers", headers);
    if (isIncluded(Include.REQUEST_HEADERS)) {
        headers.put("request", getRequestHeaders(request));
    }//  w ww  .  j ava  2  s  .c  o m
    add(trace, Include.PATH_INFO, "pathInfo", request.getPathInfo());
    add(trace, Include.PATH_TRANSLATED, "pathTranslated", request.getPathTranslated());
    add(trace, Include.CONTEXT_PATH, "contextPath", request.getContextPath());
    add(trace, Include.USER_PRINCIPAL, "userPrincipal",
            (userPrincipal == null ? null : userPrincipal.getName()));
    add(trace, Include.PARAMETERS, "parameters", request.getParameterMap());
    add(trace, Include.QUERY_STRING, "query", request.getQueryString());
    add(trace, Include.AUTH_TYPE, "authType", request.getAuthType());
    add(trace, Include.REMOTE_ADDRESS, "remoteAddress", request.getRemoteAddr());
    add(trace, Include.SESSION_ID, "sessionId", (session == null ? null : session.getId()));
    add(trace, Include.REMOTE_USER, "remoteUser", request.getRemoteUser());
    if (isIncluded(Include.ERRORS) && exception != null && this.errorAttributes != null) {
        trace.put("error",
                this.errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), true));
    }
    return trace;
}

From source file:be.fedict.eid.idp.webapp.ProtocolEntryServlet.java

private void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LOG.debug("handle request");
    LOG.debug("request URI: " + request.getRequestURI());
    LOG.debug("request method: " + request.getMethod());
    LOG.debug("request path info: " + request.getPathInfo());
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request query string: " + request.getQueryString());
    LOG.debug("request path translated: " + request.getPathTranslated());

    String userAgent = request.getHeader("User-Agent");
    if (invalidUserAgent(userAgent)) {
        LOG.warn("unsupported user agent: " + userAgent);
        response.sendRedirect(request.getContextPath() + this.unsupportedBrowserPageInitParam);
        return;//from  www.j  a va  2  s.c om
    }

    String protocolServiceContextPath = request.getPathInfo();
    setProtocolServiceContextPath(protocolServiceContextPath, request);

    ServletContext servletContext = request.getServletContext();
    Map<String, IdentityProviderProtocolService> protocolServices = getProtocolServices(servletContext);
    IdentityProviderProtocolService protocolService = protocolServices.get(protocolServiceContextPath);
    if (null == protocolService) {
        LOG.warn("unsupported protocol: " + protocolServiceContextPath);
        response.sendRedirect(request.getContextPath() + this.unknownProtocolPageInitParam);
        return;
    }

    /*
     Explicitamente deshabilitamos los protocolos relacionados con
     Identification debido a que la tarjeta del Banco Central
     no contiene informacion de identidad. El TLV parsing del
     archivo de identidad de Belgica esta estrictamente ligado
     a la disposicion fisica de la informacion en esa tarjeta y
     no se tiene ninguna analogia reutilizable en la tarjeta
     del Banco Central por el momento.*/
    if (request.getPathInfo().equals("/openid/ident") || request.getPathInfo().equals("/openid/auth-ident")
            || request.getPathInfo().equals("/saml2/post/ident")
            || request.getPathInfo().equals("/saml2/post/auth-ident")
            || request.getPathInfo().equals("/saml2/redirect/ident")
            || request.getPathInfo().equals("/saml2/redirect/auth-ident")
            || request.getPathInfo().equals("/saml2/artifact/ident")
            || request.getPathInfo().equals("/saml2/artifact/auth-ident")
            || request.getPathInfo().equals("/saml2/ws-federation/ident")
            || request.getPathInfo().equals("/saml2/ws-federation/auth-ident")) {
        LOG.warn("unsupported protocol: " + protocolServiceContextPath);
        response.sendRedirect(request.getContextPath() + this.unknownProtocolPageInitParam);
        return;
    }

    try {
        IncomingRequest incomingRequest = protocolService.handleIncomingRequest(request, response);
        if (null == incomingRequest) {
            LOG.debug("the protocol service handler " + "defined its own response flow");
            return;
        }

        // optionally authenticate RP
        LOG.debug("SP Domain: " + incomingRequest.getSpDomain());
        request.getSession().setAttribute(Constants.RP_DOMAIN_SESSION_ATTRIBUTE, incomingRequest.getSpDomain());
        RPEntity rp = this.rpService.find(incomingRequest.getSpDomain());
        if (null != rp) {

            if (!isValid(rp, incomingRequest, request, response)) {
                return;
            }
        }

        // set preferred language if possible
        LOG.debug("Languages: " + incomingRequest.getLanguages());
        if (null != incomingRequest.getLanguages() && !incomingRequest.getLanguages().isEmpty()) {
            request.getSession().setAttribute(SP.LANGUAGE_LIST_SESSION_ATTRIBUTE,
                    incomingRequest.getLanguages());
        }

        // check required attributes if set
        if (null != incomingRequest.getRequiredAttributes()
                && !incomingRequest.getRequiredAttributes().isEmpty()) {

            for (String attributeProtocolUri : incomingRequest.getRequiredAttributes()) {

                // lookup attribute
                AttributeEntity attribute = this.attributeService.findAttribute(protocolService.getId(),
                        attributeProtocolUri);

                if (null == attribute) {
                    redirectToErrorPage("Required attribute \"" + attributeProtocolUri + "\" not available.",
                            request, response);
                    return;
                }

                // check RP's config if necessary
                if (null != rp) {
                    boolean found = false;
                    for (RPAttributeEntity rpAttribute : rp.getAttributes()) {
                        if (rpAttribute.getAttribute().equals(attribute)) {
                            found = true;
                            break;
                        }
                    }

                    if (!found) {
                        redirectToErrorPage(
                                "Required attribute \"" + attributeProtocolUri + "\" not available.", request,
                                response);
                        return;
                    }
                }

            }
        }

        request.getSession().setAttribute(Constants.IDP_FLOW_SESSION_ATTRIBUTE, incomingRequest.getIdpFlow());

        switch (incomingRequest.getIdpFlow()) {
        case AUTHENTICATION:
        case AUTHENTICATION_WITH_IDENTIFICATION:
            response.sendRedirect(request.getContextPath() + this.authenticationPageInitParam);
            break;
        case IDENTIFICATION:
            response.sendRedirect(request.getContextPath() + this.identificationPageInitParam);
            break;
        default:
            throw new RuntimeException("cannot handle " + "IdP flow: " + incomingRequest.getIdpFlow());
        }

        // accounting
        this.accountingService.addRequest(incomingRequest.getSpDomain());

    } catch (Exception e) {
        LOG.error("protocol error: " + e.getMessage(), e);
        redirectToErrorPage(e.getMessage(), request, response);
    }
}

From source file:org.ngrinder.script.controller.SvnDavController.java

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());// w  w w  .  ja v  a 2  s.c o m
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());/*  w  ww.  ja  v a 2s. c o m*/
}

From source file:de.betterform.agent.web.servlet.XSLTServlet.java

/**
 * This method is only called when non-scripted mode is used to update the UI. This basically exists to support
 * the PFG (POST/FORWARD/GET) pattern that allows to use the browser back button without POSTDATA warning from the browser
 * and to re-initialize the preceding form (if any).
 * <p/>// www  . ja  v a  2 s .  com
 * To make sure that an update is requested from the XFormsSession and not by the user clicking the reload button the
 * XFormsSession holds a property XFormsSession.UPDATE_REQUEST when coming from XFormsSession. If this property exists,
 * the UI is refreshed otherwise the form is re-inited with a GET.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletContext servletContext = getServletContext();

    String stylePath = null;
    try {
        stylePath = WebFactory.getRealPath(editorHome, servletContext);
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    File styleFile = new File(stylePath, xslFile);
    if (styleFile == null) {
        throw new ServletException("XSL stylesheet cannot be found: " + styleFile);
    }

    String contentType = null;
    Document doc = null;
    String xsl = null;

    contentType = (String) request.getAttribute("contenttype");
    if (contentType == null)
        contentType = defContentType;

    // The servlet returns HTML.
    response.setContentType(contentType);
    if (cache == null)
        cache = new HashMap();
    Transformer t = null;
    // Get the XML input document and the stylesheet.
    //        Source xmlSource = new DOMSource(doc);
    String inputFile = request.getPathTranslated();
    File input = new File(inputFile);
    if (input == null) {
        throw new ServletException("XML document cannot be found: " + inputFile);
    }
    Source xmlSource = new StreamSource(new FileInputStream(input));
    // Perform the transformation, sending the output to the response.

    // XSL processing can be time consuming, but this is mainly due to the overhead
    // of compiling the XSL sheet.
    // By caching the compiled sheets, the process is speeded up dramatically.
    // Time saved on subsequent requests can be 99% or more (hundreds of milliseconds).
    try {
        // check if the XSL sheet was found in cache, and use that if available
        //            if (cache.containsKey(xsl)) t = (Transformer)cache.get(xsl);
        //            else
        //            {
        // otherwise, load the XSL sheet from disk, compile it and store the compiled
        // sheet in the cache
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xslSource = new StreamSource(new FileInputStream(styleFile));
        t = tFactory.newTransformer(xslSource);
        String contextName = request.getContextPath();

        t.setParameter("APP_CONTEXT", contextName);
        t.setParameter("EDITOR_HOME", stylePath.substring(stylePath.indexOf("/betterform/")) + "/");
        t.setParameter("filename", "file://" + inputFile);

        //                cache.put(xsl, t);
        //            }

        // perform the XSL transformation of the XML Document into the servlet outputstream
        //            t.transform(xmlSource, new StreamResult(out));
        Document resultDoc = DOMUtil.newDocument(true, false);
        t.transform(xmlSource, new DOMResult(resultDoc));
        request.setAttribute(WebFactory.XFORMS_NODE, resultDoc);
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
        throw new ServletException(e);
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
        throw new ServletException(e);
    } catch (TransformerException e) {
        e.printStackTrace();
        throw new ServletException(e);
    }
}

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 ww w.  ja  v a  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:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = rqst.getAttributeNames();
        for (; e.hasMoreElements();) {
            String attribute = e.nextElement();
            b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
        }/*  w  ww  . j  a va 2s  . co m*/

        X509Certificate[] userCerts = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");
        if (userCerts != null)
            for (X509Certificate cert : userCerts)
                b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

        b.append("\n The Scheme is " + rqst.getScheme());
        b.append("\n The Auth Type is " + rqst.getAuthType());
        b.append("\n The Path Info is " + rqst.getPathInfo());
        b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
        b.append("\n The Context Path is " + rqst.getContextPath());
        b.append("\n The Query String is " + rqst.getQueryString());
        b.append("\n The Remote User is " + rqst.getRemoteUser());
        b.append("\n The User Principal is " + rqst.getUserPrincipal());
        b.append("\n The Request URI is " + rqst.getRequestURI());
        b.append("\n The Request URL is " + rqst.getRequestURL());
        b.append("\n The Servlet Path is " + rqst.getServletPath());

        LOG.debug(b.toString());
    }

    boolean unitTest = false;
    if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null)
        unitTest = true;

    if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) {
        boolean isAuthorized = false;
        X509Certificate[] certs = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");

        if (unitTest) {
            try {
                LOG.debug("==> Entering https unit test");
                String SslPath = rqst.getParameter("SslPath");
                InputStream inStream = new FileInputStream(SslPath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                certs = new X509Certificate[] { cert };
            } catch (Exception e) {
                // do nothing here
            }
        }

        if (certs == null || certs.length == 0) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
            LOG.info("No Client SSL certificate received");
            return;
        }
        for (X509Certificate cert : certs) {
            try {
                cert.checkValidity();
            } catch (CertificateExpiredException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
                return;
            } catch (CertificateNotYetValidException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
                return;
            }
        }

        String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
        String userID = null;
        for (String s : tokens) {
            if (s.startsWith("CN=")) {
                userID = s;
                break;
            }
        }
        if (userID == null || userID.length() < 4) {
            LOG.info("Can't retrieve user ID from SSL certificate");
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
            return;
        }
        userID = userID.substring(3);

        String servletPath = rqst.getServletPath();
        if (unitTest) {
            servletPath = rqst.getParameter("TestSevletPathInfo");
            LOG.info("this is for unit test purpose only");
        }

        if (HFTP_PATTERN.matcher(servletPath).matches()) {
            // request is an HSFTP request
            if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
                // file path as part of the URL
                isAuthorized = checkPath(userID, certs[0],
                        rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
            } else {
                // file path is stored in "filename" parameter
                isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
            }
        } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
            Configuration conf = new Configuration(false);
            conf.addResource("hdfsproxy-default.xml");
            Map<String, Set<Path>> permsMap = getPermMap(conf);
            Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
            if (permsMap == null || certsMap == null) {
                LOG.warn("Permission files reloading failed");
                rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Permission files reloading failed");
                return;
            }
            ProxyFilter.permsMap = permsMap;
            ProxyFilter.certsMap = certsMap;
            LOG.info("User permissions and user certs files reloaded");
            rsp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (!isAuthorized) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
            return;
        }

        // request is authorized, set ugi for servlets
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID);
        rqst.setAttribute("authorized.ugi", ugi);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID);
    } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes
        String ugi = rqst.getParameter("ugi");
        if (ugi != null) {
            rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi));
            rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]);
        }
    }
    chain.doFilter(request, response);
}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Process HTTP HEAD and GET//from   w  ww . j  a  v  a2s.c o  m
 * 
 * @param req
 *            an HttpServletRequest object that contains the request the
 *            client has made of the servlet
 * @param resp
 *            an HttpServletResponse object that contains the response the
 *            servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet
 *             handles the GET request
 * @throws ServletException
 *             if the request for the GET could not be handled
 */
@SuppressWarnings("unchecked")
public void processHeadGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Context path: " + req.getContextPath());
        logger.debug("Path info: " + req.getPathInfo());
        logger.debug("Path translated: " + req.getPathTranslated());
        logger.debug("Query string: " + req.getQueryString());
        logger.debug("Request URI: " + req.getRequestURI());
        logger.debug("Request URL: " + req.getRequestURL());
        logger.debug("Servlet path: " + req.getServletPath());
        logger.debug("Servlet name: " + this.getServletName());

        for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            logger.debug("Header- " + headerName + ": " + headerValue);
        }
    }

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }

        if (or.getKey() != null) {
            S3Object s3Object;
            StorageService storageService;

            try {
                storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);
                s3Object = storageService.load(or.getBucket(), or.getKey());

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }
            } catch (DataAccessException e) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                return;
            }

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                String response;
                Acp acp = s3Object.getAcp();

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                // retrieve object
                InputStream in = null;
                OutputStream out = null;
                byte[] buffer = new byte[4096];
                int count;
                String value;

                try {
                    s3Object.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // headers
                resp.setContentType(s3Object.getContentType());
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                // TODO: set the Content-Range, if request includes Range
                // TODO: add "x-amz-missing-meta", if any

                // add the "x-amz-meta-" headers
                for (Iterator<String> names = s3Object.getMetadataNames(); names.hasNext();) {
                    String name = names.next();
                    String headerName = HEADER_PREFIX_USER_META + name;
                    String prefix = "";
                    StringBuffer buf = new StringBuffer();
                    for (Iterator<String> values = s3Object.getMetadataValues(name); values.hasNext();) {
                        buf.append(values.next()).append(prefix);
                        prefix = ",";
                    }
                    resp.setHeader(headerName, buf.toString());
                }

                resp.setDateHeader("Last-Modified", s3Object.getLastModified());
                if ((value = s3Object.getETag()) != null) {
                    resp.setHeader("ETag", value);
                }
                if ((value = s3Object.getContentMD5()) != null) {
                    resp.setHeader("Content-MD5", value);
                }
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                resp.setHeader("Accept-Ranges", "bytes");

                String rangeRequest = req.getHeader("Range");

                if (rangeRequest != null) {
                    // request for a range
                    RangeSet rangeSet = RangeFactory.processRangeHeader(rangeRequest);

                    // set content length
                    rangeSet.resolve(s3Object.getContentLength());

                    if (rangeSet.size() > 1) {
                        // requires multi-part response
                        // TODO: implement
                        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
                    }

                    Range[] ranges = (Range[]) rangeSet.toArray(new Range[0]);

                    resp.setHeader("Content-Range",
                            formatRangeHeaderValue(ranges[0], s3Object.getContentLength()));
                    resp.setHeader("Content-Length", Long.toString(rangeSet.getLength()));

                    in = new RangeInputStream(s3Object.getInputStream(), ranges[0]);
                    resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                } else {
                    // request for entire content
                    // Used instead of resp.setContentLength((int)); because
                    // Amazon
                    // limit is 5 gig, which is bigger than an int
                    resp.setHeader("Content-Length", Long.toString(s3Object.getContentLength()));

                    in = s3Object.getInputStream();
                    resp.setStatus(HttpServletResponse.SC_OK);
                }

                // body
                out = resp.getOutputStream();

                while ((count = in.read(buffer, 0, buffer.length)) > 0) {
                    out.write(buffer, 0, count);
                }

                out.flush(); // commit response
                out.close();
                out = null;
            }
            return;
        } else if (or.getBucket() != null) {
            // operation on a bucket
            StorageService storageService;
            String prefix;
            String marker;
            int maxKeys = Integer.MAX_VALUE;
            String delimiter;
            String response;
            String value;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                Acp acp;

                try {
                    acp = storageService.loadBucket(or.getBucket()).getAcp();
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                Bucket bucket;

                prefix = req.getParameter("prefix");
                if (prefix == null) {
                    prefix = "";
                }
                marker = req.getParameter("marker");
                value = req.getParameter("max-keys");
                if (value != null) {
                    try {
                        maxKeys = Integer.parseInt(value);
                    } catch (NumberFormatException e) {
                        logger.info("max-keys must be numeric: " + value);
                    }
                }

                delimiter = req.getParameter("delimiter");

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    bucket.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = storageService.listKeys(bucket, prefix, marker, delimiter, maxKeys);

                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                if (logger.isTraceEnabled()) {
                    logger.trace("Response: " + response);
                }
            }
            return;
        } else {
            // operation on the service
            StorageService storageService;
            List buckets;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            buckets = storageService.findBuckets("");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
            buffer.append("<Owner>");
            buffer.append("<ID/>"); // TODO: implement
            buffer.append("<DisplayName/>"); // TODO: implementF
            buffer.append("</Owner>");
            buffer.append("<Buckets>");
            for (Iterator iter = buckets.iterator(); iter.hasNext();) {
                Bucket bucket = (Bucket) iter.next();
                buffer.append("<Bucket>");
                buffer.append("<Name>").append(bucket.getName()).append("</Name>");
                buffer.append("<CreationDate>").append(iso8601.format(bucket.getCreated()))
                        .append("</CreationDate>");
                buffer.append("</Bucket>");
            }
            buffer.append("</Buckets>");
            buffer.append("</ListAllMyBucketsResult>");

            resp.setContentLength(buffer.length());
            resp.setContentType("application/xml");
            resp.setStatus(HttpServletResponse.SC_OK);

            Writer out = resp.getWriter();
            out.write(buffer.toString());
            return;
        }
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidURI");
        return;
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.inbound.HttpIdentityRequestFactory.java

public void create(IdentityRequest.IdentityRequestBuilder builder, HttpServletRequest request,
        HttpServletResponse response) throws FrameworkClientException {

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        builder.addHeader(headerName, request.getHeader(headerName));
    }/*ww  w  .  j  a  va2 s .co  m*/

    // We need to create a new map with the parameters sent in servlet request to avoid having a reference.
    Map<String, String[]> paramMap = new HashMap<>(request.getParameterMap());
    builder.setParameters(paramMap);

    Enumeration<String> attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = attrNames.nextElement();
        builder.addAttribute(attrName, request.getAttribute(attrName));
    }
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            builder.addCookie(cookie.getName(), cookie);
        }
    }

    String requestURI = request.getRequestURI();

    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (StringUtils.isNotBlank(tenantDomain)) {
        builder.setTenantDomain(tenantDomain);
    } else {
        builder.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    builder.setContentType(request.getContentType());
    builder.setContextPath(request.getContextPath());
    builder.setMethod(request.getMethod());
    builder.setPathInfo(request.getPathInfo());
    builder.setPathTranslated(request.getPathTranslated());
    builder.setQueryString(request.getQueryString());
    builder.setRequestURI(requestURI);
    builder.setRequestURL(request.getRequestURL());
    builder.setServletPath(request.getServletPath());

}