Example usage for javax.servlet.http HttpServletRequest getAuthType

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

Introduction

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

Prototype

public String getAuthType();

Source Link

Document

Returns the name of the authentication scheme used to protect the servlet.

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  . ja  va 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: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));
        }//from www .  java2 s  .  c o 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:org.apache.hadoop.fs.webdav.WebdavServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("/--------------------------------------------------");
    log.debug(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURI().toString());

    log.info("  RemoteHost: " + request.getRemoteHost());
    log.info("| ATTRIBUTES: ");
    Enumeration e1 = request.getAttributeNames();
    while (e1.hasMoreElements()) {
        String name = (String) e1.nextElement();
        log.info("|| " + name + ": ");
    }/*from   w ww  .  j  a  v a  2 s. c  o m*/

    log.info("| PARAMETERS: ");
    Enumeration e2 = request.getParameterNames();
    while (e2.hasMoreElements()) {
        String name = (String) e2.nextElement();
        log.info("|| " + name + ": ");
    }

    log.info("HEADERS: ");
    Enumeration e6 = request.getHeaderNames();
    while (e6.hasMoreElements()) {
        String name = (String) e6.nextElement();
        log.info("-- " + name + ": " + request.getHeader(name));
    }
    log.info("RemoteUser: " + request.getRemoteUser());
    log.info("AuthType: " + request.getAuthType());

    currentUserName = request.getRemoteUser();

    String roles = "";
    if (currentUserRoles != null) {
        for (String roleName : currentUserRoles) {
            roles += roleName + ", ";
        }
        if (roles.length() > 2) {
            roles = roles.substring(0, roles.length() - 2);
        }
    }
    log.debug("Roles: " + roles);

    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e.getCause() instanceof AccessControlException) {
            log.info("EXCEPTION: Can't access to resource. You don't have permissions.");
            MultiStatusResponse msr = new MultiStatusResponse(request.getRequestURL().toString(), 401,
                    "Can't access to resource. You don't have permissions.");

            MultiStatus ms = new MultiStatus();
            ms.addResponse(msr);

            WebdavResponse webdavResponse = new WebdavResponseImpl(response);
            webdavResponse.sendMultiStatus(ms);
        } else
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    log.info("\\--------------------------------------------------");
}

From source file:com.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(request.getMethod() + " for '" + request.getRequestURI() + "' from " + request.getRemoteUser()
                + " at " + request.getRemoteAddr());
    }/*from  w w  w . j  ava2 s  .  c o m*/
    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e instanceof AccessControlException || e.getCause() instanceof AccessControlException) {
            LOG.info("Insufficient permissions for request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr());
            if (request.getMethod().equalsIgnoreCase("GET")) {
                // Provide a plain 401 response for GETs
                new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // Otherwise send a multistatus response
                MultiStatus ms = new MultiStatus();
                ms.addResponse(new MultiStatusResponse(request.getRequestURL().toString(), 401,
                        "You do not have permission to access this resource."));
                new WebdavResponseImpl(response).sendMultiStatus(ms);
            }
        } else {
            LOG.warn("Exception processing request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr() + " authType "
                    + request.getAuthType(), e);
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Log the request for debug purpose//  w  ww . j a va  2 s .  c  om
 * 
 * @param request
 *            the HTTP Servlet Request
 */
private void debugRequest(HttpServletRequest request) {

    if (this.debug || LOG.isLoggable(Level.FINE)) {
        final StringBuffer sb = new StringBuffer();
        sb.append("\n");
        try {
            sb.append("Request: ").append(request.getRequestURL()).append("\n");
            sb.append("UserPrincipal: ").append(request.getUserPrincipal()).append("\n");
            sb.append("AuthType: ").append(request.getAuthType()).append("\n");
            sb.append("Headers:\n");
            @SuppressWarnings("rawtypes")
            final Enumeration names = request.getHeaderNames();
            while (names.hasMoreElements()) {
                final String name = (String) names.nextElement();
                sb.append("\t").append(name).append("\t").append(request.getHeader(name)).append("\n");
            }
            LOG.log(this.debugLevel, "HTTP Request is : {0}", sb);

        } catch (final Throwable t) {
            LOG.log(Level.WARNING, "An unexpected problem has occured during log : {0}", t);
        }
    }
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request.//from ww w  .  j  a va2s.c om
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}

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)
 */// www .j  a v a 2  s.com
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.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java

private UserGroupInformation createKerberosUserGroupInformation(HttpServletRequest hsr)
        throws AuthorizationException, YarnException {

    UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
    if (callerUGI == null) {
        String msg = "Unable to obtain user name, user not authenticated";
        throw new AuthorizationException(msg);
    }//from w  w  w. j a v  a2s .com

    String authType = hsr.getAuthType();
    if (!KerberosAuthenticationHandler.TYPE.equalsIgnoreCase(authType)) {
        String msg = "Delegation token operations can only be carried out on a "
                + "Kerberos authenticated channel. Expected auth type is " + KerberosAuthenticationHandler.TYPE
                + ", got type " + authType;
        throw new YarnException(msg);
    }
    if (hsr.getAttribute(DelegationTokenAuthenticationHandler.DELEGATION_TOKEN_UGI_ATTRIBUTE) != null) {
        String msg = "Delegation token operations cannot be carried out using delegation"
                + " token authentication.";
        throw new YarnException(msg);
    }

    callerUGI.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    return callerUGI;
}

From source file:org.sakaiproject.util.Web.java

public static String snoop(PrintWriter out, boolean html, ServletConfig config, HttpServletRequest req) {
    // if no out, send to system out
    ByteArrayOutputStream ostream = null;
    if (out == null) {
        ostream = new ByteArrayOutputStream();
        out = new PrintWriter(ostream);
        html = false;//  w w w. ja  v  a2s . c  o  m
    }

    String h1 = "";
    String h1x = "";
    String pre = "";
    String prex = "";
    String b = "";
    String bx = "";
    String p = "";
    if (html) {
        h1 = "<h1>";
        h1x = "</h1>";
        pre = "<pre>";
        prex = "</pre>";
        b = "<b>";
        bx = "</b>";
        p = "<p>";
    }

    Enumeration<?> e = null;

    out.println(h1 + "Snoop for request" + h1x);
    out.println(req.toString());

    if (config != null) {
        e = config.getInitParameterNames();
        if (e != null) {
            boolean first = true;
            while (e.hasMoreElements()) {
                if (first) {
                    out.println(h1 + "Init Parameters" + h1x);
                    out.println(pre);
                    first = false;
                }
                String param = (String) e.nextElement();
                out.println(" " + param + ": " + config.getInitParameter(param));
            }
            out.println(prex);
        }
    }

    out.println(h1 + "Request information:" + h1x);
    out.println(pre);

    print(out, "Request method", req.getMethod());
    String requestUri = req.getRequestURI();
    print(out, "Request URI", requestUri);
    displayStringChars(out, requestUri);
    print(out, "Request protocol", req.getProtocol());
    String servletPath = req.getServletPath();
    print(out, "Servlet path", servletPath);
    displayStringChars(out, servletPath);
    String contextPath = req.getContextPath();
    print(out, "Context path", contextPath);
    displayStringChars(out, contextPath);
    String pathInfo = req.getPathInfo();
    print(out, "Path info", pathInfo);
    displayStringChars(out, pathInfo);
    print(out, "Path translated", req.getPathTranslated());
    print(out, "Query string", req.getQueryString());
    print(out, "Content length", req.getContentLength());
    print(out, "Content type", req.getContentType());
    print(out, "Server name", req.getServerName());
    print(out, "Server port", req.getServerPort());
    print(out, "Remote user", req.getRemoteUser());
    print(out, "Remote address", req.getRemoteAddr());
    // print(out, "Remote host", req.getRemoteHost());
    print(out, "Authorization scheme", req.getAuthType());

    out.println(prex);

    e = req.getHeaderNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Request headers:" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + ": " + req.getHeader(name));
        }
        out.println(prex);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Servlet parameters (Single Value style):" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + " = " + req.getParameter(name));
        }
        out.println(prex);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Servlet parameters (Multiple Value style):" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String vals[] = (String[]) req.getParameterValues(name);
            if (vals != null) {
                out.print(b + " " + name + " = " + bx);
                out.println(vals[0]);
                for (int i = 1; i < vals.length; i++)
                    out.println("           " + vals[i]);
            }
            out.println(p);
        }
        out.println(prex);
    }

    e = req.getAttributeNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Request attributes:" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + ": " + req.getAttribute(name));
        }
        out.println(prex);
    }

    if (ostream != null) {
        out.flush();
        return ostream.toString();
    }

    return "";
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }//from  ww w  . j av  a 2  s  .  c o  m

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}