Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest setAttribute.

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:org.nuxeo.ecm.platform.ui.web.rest.FancyURLFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {/*  w w w  .  j a  v  a  2s. c  om*/
        getUrlService();
        // initialize its view id manager if necessary
        urlService.initViewIdManager(servletContext, httpRequest, httpResponse);

        // check if this is an URL that needs to be parsed
        if (urlService.isCandidateForDecoding(httpRequest)) {
            DocumentView docView = urlService.getDocumentViewFromRequest(httpRequest);
            // if parse succeeded => process
            if (docView != null) {
                // put it in request
                urlService.setDocumentViewInRequest(httpRequest, docView);

                // get the view id for navigation from the stored outcome
                String jsfOutcome = docView.getViewId();

                // get target page according to navigation rules
                String target = urlService.getViewIdFromOutcome(jsfOutcome, httpRequest);

                // dispatch
                RequestDispatcher dispatcher;
                if (target != null) {
                    dispatcher = httpRequest.getRequestDispatcher(target);
                } else {
                    // Use a dummy dispatcher if the target is not needed.
                    // This comes handy for instance for nxfile url
                    dispatcher = httpRequest.getRequestDispatcher("/malformed_url_error_page.faces");
                }
                // set force encoding in case forward triggers a
                // redirect (when a seam page is processed for instance).
                request.setAttribute(URLPolicyService.FORCE_URL_ENCODING_REQUEST_KEY, Boolean.TRUE);
                // forward request to the target viewId
                dispatcher.forward(new FancyURLRequestWrapper(httpRequest, docView),
                        wrapResponse(httpRequest, httpResponse));
                return;
            }
        }

        // do not filter if it's candidate for encoding so soon : document
        // view has not been set in the request yet => always wrap
        chain.doFilter(request, wrapResponse(httpRequest, httpResponse));

    } catch (IOException e) {
        String url = httpRequest.getRequestURL().toString();
        if (DownloadHelper.isClientAbortError(e)) {
            DownloadHelper.logClientAbort(e);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Client disconnected from URL %s : %s", url, e.getMessage()));
            }
        } else {
            throw new IOException("On requestURL: " + url, e);
        }
    } catch (ServletException e) {
        String url = httpRequest.getRequestURL().toString();
        if (DownloadHelper.isClientAbortError(e)) {
            DownloadHelper.logClientAbort(e);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Client disconnected from URL %s : %s", url, e.getMessage()));
            }
        } else {
            throw new ServletException("On requestURL: " + url, e);
        }
    }

}

From source file:org.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

    String xForwardedURL = constructForwardableURL(httpRequest);

    if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
        synchronized (httpRequest.getServletContext()) {
            if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null
                    && "locallogin".equals(httpRequest.getServletContext()
                            .getAttribute(httpRequest.getRequestedSessionId()).toString())) {
                httpRequest.getSession().setAttribute("locallogin", "true");
                httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId());
            }//from ww  w  .  j  av a  2  s .c o  m
        }
    }

    RangerSecurityContext context = RangerContextHolder.getSecurityContext();
    UserSessionBase session = context != null ? context.getUserSession() : null;
    boolean ssoEnabled = session != null ? session.isSSOEnabled()
            : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);

    String userAgent = httpRequest.getHeader("User-Agent");
    if (httpRequest.getSession() != null) {
        if (httpRequest.getSession().getAttribute("locallogin") != null) {
            servletRequest.setAttribute("ssoEnabled", false);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }
    //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication
    if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) {
        //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
        //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
        if (jwtProperties != null && !isAuthenticated()) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            String serializedJWT = getJWTFromCookie(httpRequest);
            // if we get the hadoop-jwt token from the cookies then will process it further
            if (serializedJWT != null) {
                SignedJWT jwtToken = null;
                try {
                    jwtToken = SignedJWT.parse(serializedJWT);
                    boolean valid = validateToken(jwtToken);
                    //if the public key provide is correct and also token is not expired the process token
                    if (valid) {
                        String userName = jwtToken.getJWTClaimsSet().getSubject();
                        LOG.info("SSO login user : " + userName);

                        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role",
                                "ROLE_USER");
                        //if we get the userName from the token then log into ranger using the same user
                        if (userName != null && !userName.trim().isEmpty()) {
                            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
                            final UserDetails principal = new User(userName, "", grantedAuths);
                            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                                    principal, "", grantedAuths);
                            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
                            authenticationProvider.setSsoEnabled(ssoEnabled);
                            Authentication authentication = authenticationProvider
                                    .authenticate(finalAuthentication);
                            authentication = getGrantedAuthority(authentication);
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }

                        filterChain.doFilter(servletRequest, httpServletResponse);
                    }
                    // if the token is not valid then redirect to knox sso
                    else {
                        if (isWebUserAgent(userAgent)) {
                            String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("SSO URL = " + ssourl);
                            }
                            httpServletResponse.sendRedirect(ssourl);
                        } else {
                            filterChain.doFilter(servletRequest, httpServletResponse);
                        }
                    }
                } catch (ParseException e) {
                    LOG.warn("Unable to parse the JWT token", e);
                }
            }
            // if the jwt token is not available then redirect it to knox sso
            else {
                if (isWebUserAgent(userAgent)) {
                    String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO URL = " + ssourl);
                    }
                    httpServletResponse.sendRedirect(ssourl);
                } else {
                    filterChain.doFilter(servletRequest, httpServletResponse);
                }
            }
        }
        //if property is not loaded or is already authenticated then proceed further with next filter
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL)
            && isWebUserAgent(userAgent) && isAuthenticated()) {
        //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login
        // In this scenario the user as to use separate browser
        String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", "");
        url = url.replace(LOCAL_LOGIN_URL, "");
        LOG.warn(
                "There is an active session and if you want local login to ranger, try this on a separate browser");
        ((HttpServletResponse) servletResponse).sendRedirect(url);
    }
    //if sso is not enable or the request is not from browser then proceed further with next filter
    else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.JIPortletAuthenticationProcessingFilter.java

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

    if (logger.isDebugEnabled()) {
        logger.debug("Trusted Host Authentication.");
    }//from   w ww .j a va  2s.c  o m

    String incomingIPAddress = request.getRemoteAddr();
    // if not from trusted host, skip this filter totally
    if ((incomingIPAddress == null) || (!isFromTrustedHost(incomingIPAddress))) {
        chain.doFilter(request, response);
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Requested from Trusted Host IP:" + incomingIPAddress);
    }

    List roleList = new ArrayList();

    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Credentials credentials = getUserCredentials(httpRequest);
    String userName = credentials.getUserName();
    String password = credentials.getPassword();

    if ((userName == null) || (userName.trim().length() == 0)) {
        chain.doFilter(request, response);
        return;
    }

    // skip any actions when the authentication object already exists.
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if ((existingAuth != null) && (existingAuth.getName().equals(userName))
            && (existingAuth.isAuthenticated())) {
        // if already authenticated, set the trusted host flag so that 
        // subsequent filters (such as the Basic auth filter) know it's a
        // portlet authentication
        request.setAttribute("fromTrustedHost", "true");

        chain.doFilter(request, response);
        return;
    }

    // starting the flow       
    // user exist
    if (doesUserExist(userName)) {
        // is it an internal user
        if (isInternalUser(userName)) {
            String oldPassword = getUserPaswordFromRepository(userName);
            // update password if they are different
            if (!haveSamePassword(oldPassword, password)) {
                updatePassword(userName, password);
                if (logger.isDebugEnabled()) {
                    logger.debug("Updated Password for User:" + userName);
                }
            }
        }
        // get list of role
        roleList = getUserRoleList(userName);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Created New User:" + userName);
        }
        // create an internal user
        roleList.add("ROLE_USER");
        roleList.add("ROLE_PORTLET");
        createUserWithRoles(userName, password, roleList, false);
    }
    SecurityContextHolder.getContext()
            .setAuthentication(createAuthenticationObject(userName, password, roleList, request));
    // it's authenticated thru trusted host
    request.setAttribute("fromTrustedHost", "true");

    if (logger.isDebugEnabled()) {
        logger.debug("Created Authentication Object within JIPortletAuthenticationProcessingFilter");
    }

    chain.doFilter(request, response);
}

From source file:controllers.AuthFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Cookie[] cookies = httpRequest.getCookies();
    String status = "No cookie";
    // Check cookie with name auth
    if (cookies != null) {
        String token = null;/*from  w w  w  .j a va  2 s  .com*/
        for (Cookie cookie : cookies) {
            status = "No token cookie";
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
                break;
            }
        }

        // Check whether the auth token hasn't expired yet
        if (token != null) {
            status = "Token cookie exists";
            JSONObject obj = ISConnector.validateToken(token);
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            if (obj != null && obj.containsKey("error")) { //Authorization failed, expired access token
                status = "Authentication failed";
                String uri = req.getRequestURI();
                this.context.log("Requested Resource:: " + uri);

                // Get session and set session
                HttpSession session = req.getSession(false);
                this.context.log("Unauthorized access request");
                res.sendRedirect(req.getContextPath() + "/login");
                return;
            } else {
                status = "Authentication succeed";
                if (obj != null && obj.containsKey("id")) {
                    long id = (long) obj.get("id");
                    int u_id = (int) id;
                    UserWS.UserWS_Service service = new UserWS.UserWS_Service();
                    UserWS.UserWS port = service.getUserWSPort();
                    User user = (User) port.getUser(u_id);
                    if (user != null) {
                        req.setAttribute("user", user);
                    }
                }
            }
        }
    }
    request.setAttribute("status", status);
    // Pass the request along the filter chain
    chain.doFilter(request, response);
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Sends an email to the user asking they follow a link to validate their email address
 * @param id DB key to be embedded in response link
 * @param email Address target//from   w  w  w .j a  va  2s .co m
 */
private void sendVerificationEmail(String id, String email, ServletRequest req) {
    m_logger.debug("sending mail");
    String from = "admin@" + m_serverName;
    Properties props = new Properties();
    props.put("mail.smpt.host", m_serverName);
    props.put("mail.from", from);
    Session session = Session.getInstance(props, null);
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, email);
        msg.setSubject("Verify your PaperMiner email address");
        msg.setSentDate(new Date());
        // FIXME: the verify address needs to be more robust
        msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n"
                + "PaperMiner has sent you this message to validate that the email address which you "
                + "supplied is able to receive notifications from our server.\n"
                + "To complete the verification process, please click the link below.\n\n" + "http://"
                + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n"
                + "If you are unable to click the link above, verification can be completed by copying "
                + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is "
                + email + ". Use this to log in when returning to the PaperMiner site.\n"
                + "You can update your email address, or change your TROVE API key at any time through the "
                + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n"
                + "Paper Miner Administrator");
        Transport.send(msg);
        m_logger.info("Verifcation mail sent to " + email);
    } catch (MessagingException ex) {
        m_logger.error("Email verification to " + email + " failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109");
    }
}

From source file:com.pliu.azuremgmtsdk.BasicFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {//from  w  w  w .j av a  2s .  c  o m
            String subscriptionId = httpRequest.getParameter("subscriptionId");
            if (subscriptionId != null)
                httpRequest.getSession().setAttribute("subscriptionId", subscriptionId);

            String currentUri = httpRequest.getRequestURL().toString();
            String queryStr = httpRequest.getQueryString();
            String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : "");

            // check if user has a AuthData in the session
            if (!AuthHelper.isAuthenticated(httpRequest)) {
                if (AuthHelper.containsAuthenticationData(httpRequest)) {
                    processAuthenticationData(httpRequest, currentUri, fullUrl);
                } else {
                    // not authenticated
                    // we can get the tenant id for the subscription first
                    getTenantIdForSubscription(httpRequest);

                    // then authenticate
                    sendAuthRedirect(httpRequest, httpResponse);
                    return;
                }
            }
            if (isAuthDataExpired(httpRequest)) {
                updateAuthDataUsingRefreshToken(httpRequest);
            }
        } catch (AuthenticationException authException) {
            // something went wrong (like expiration or revocation of token)
            // we should invalidate AuthData stored in session and redirect to Authorization server
            removePrincipalFromSession(httpRequest);
            sendAuthRedirect(httpRequest, httpResponse);
            return;
        } catch (Throwable exc) {
            httpResponse.setStatus(500);
            request.setAttribute("error", exc.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {
        @Override// w ww. j  a  v a  2s.  c om
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);

                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }

                if ((existingAuth == null || !existingAuth.isAuthenticated())
                        && (!StringUtils.isEmpty(userName))) {

                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider
                            .getAuthoritiesFromUGI(userName);

                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                            principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser,
                            Servlets.getRequestURI(httpRequest));

                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };

    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");

        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}

From source file:com.credit.common.web.servlet.filter.csrf.CsrfPreventionFilter.java

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

    ServletResponse wResponse = null;/*from   www .j a va 2 s.  c om*/

    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        boolean skipNonceCheck = false;
        String path = req.getServletPath();
        if (req.getPathInfo() != null) {
            path = path + req.getPathInfo();
        }

        for (String entr : entryPoints) {
            if (entr.equalsIgnoreCase(path) || path.endsWith("jsp") || path.endsWith("list")
                    || path.endsWith("List")) // TODO
            {
                skipNonceCheck = true;
                break;
            }
            if (entr.indexOf("*") > 0) {
                entr = entr.replace("*", "");
                if (path.startsWith(entr)) {
                    skipNonceCheck = true;
                    break;
                }
            }

        }

        HttpSession session = getSession(req);

        @SuppressWarnings("unchecked")
        LruCache<String> nonceCache = (session == null) ? null
                : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);

        if (!skipNonceCheck) {
            String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM);

            if (nonceCache == null || previousNonce == null || !nonceCache.contains(previousNonce)) {
                res.sendError(denyStatus);
                return;
            }
        }

        if (nonceCache == null) {
            nonceCache = new LruCache<String>(nonceCacheSize);
            if (session == null) {
                session = req.getSession(true);
            }
            session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache);
        }

        String newNonce = generateNonce();

        nonceCache.add(newNonce);
        request.setAttribute(Constants.CSRF_NONCE_REQUEST_PARAM, newNonce);
        wResponse = new CsrfResponseWrapper(res, newNonce);
    } else {
        wResponse = response;
    }

    chain.doFilter(request, wResponse);
}

From source file:org.j2free.invoker.ServiceChain.java

/**
 * Recursively processes any filters until arriving at, and processing
 * the end-point./*  w w  w  .  j  ava  2  s . co  m*/
 *
 * @param request a Servlet request
 * @param response a Servlet response
 * @param mapping The last FilterMaping to be processes, may be null to start
 *
 * @throws IOException
 * @throws ServletException
 */
protected void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    // Try to get the next filter on the current depth (we're overwriting
    // the param, since we only need it in the call to mappings.ceiting(mapping).
    FilterMapping next = filters.hasNext() ? filters.next() : null;

    // If we found one, skip past any that don't apply to this path
    while (next != null && !next.appliesTo(path)) {
        if (log.isTraceEnabled()) {
            log.trace("Skipping filter [name=" + next.getName() + ", path=" + path + "]");
        }
        next = filters.hasNext() ? filters.next() : null;
    }

    // Set the link to be either the found filter or the endPoint,
    // if there were no more filters remaining, since the two are
    // polymorphically referencable as a Servicable.
    final Servicable link = next == null ? endPoint : next;

    boolean release = false; // Holds whether we need to release the Controller here
    try {
        if (link.requiresController()) // If the next Servicable requires a Controller
        {
            log.trace("Next link requires Controller");

            Controller controller = Controller.get(false); // Try to get an existing one
            if (controller == null) // If there wasn't one already
            {
                log.trace("No Controller associated with Thread, creating...");
                controller = Controller.get(); // Create a new one
                release = true; // And take responsibility for closing it
            }

            // If the Servicable requires a Controller and we don't have one,
            // then blow up loudly because all resources futher down the chain
            // will be expecting a Controller and we can't provide that.
            if (controller == null) {
                throw new ServletException(
                        String.format("Error providing required Controller to %s, [cause=NULL, release=%b]",
                                link.getName(), release));
            } else if (!controller.isTransactionOpen()) {
                throw new ServletException(
                        String.format("Error providing required Controller to %s, [cause=NO TX, release=%b]",
                                link.getName(), release));
            } else
                request.setAttribute(Controller.ATTRIBUTE_KEY, controller); // But if we got it, set it as a req attribute
        }

        if (log.isTraceEnabled())
            log.trace("Servicing link [name=" + link.getName() + "]");

        link.service(request, response, this);
    } catch (Exception e) {
        throw new ServletException("Error servicing chain", e); // Wrap any exceptions as ServletException
    } finally {
        // If this Servicable has the responsibility to release a Controller
        // Don't need to check requiresController() again, since release can ONLY
        // be true if requiresController() was true.
        if (release) {
            log.trace("Releasing Controller");
            Controller.release();
        }
    }
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception {
    final Authenticator authenticator = authenticatorProvider.getAuthenticator();

    final String authMethod;
    switch (authProps.getAuthType()) {
    case BASIC:/*from ww  w.j a va  2s  . c  o m*/
        authMethod = Constraint.__BASIC_AUTH;
        break;
    case DIGEST:
        authMethod = Constraint.__DIGEST_AUTH;
        break;
    default:
        authMethod = "customauth";
    }

    Constraint constraint = new Constraint();
    constraint.setName(authMethod);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() {
        @Override
        public void setConfiguration(AuthConfiguration configuration) {
        }

        @Override
        public String getAuthMethod() {
            return authMethod;
        }

        @Override
        public void prepareRequest(ServletRequest request) {
        }

        @Override
        public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory)
                throws ServerAuthException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr());
            int remotePort = request.getRemotePort();
            String localAddress = StringUtils.trimToEmpty(request.getLocalAddr());
            int localPort = request.getLocalPort();
            String protocol = StringUtils.trimToEmpty(request.getProtocol());
            String method = StringUtils.trimToEmpty(request.getMethod());
            String requestURI = StringUtils.trimToEmpty(request.getRequestURI());
            Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request);

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
                queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(req.getInputStream());
                        req.setAttribute(ATTRIBUTE_NAME, entity);
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider,
                    configuration.getRequestInformation(request));

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                response.setHeader(entry.getKey(), entry.getValue().get(i));
                            } else {
                                response.addHeader(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_CONTINUE;
                case SUCCESS:
                    Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()),
                            null);
                    Subject subject = new Subject();
                    subject.getPrincipals().add(userPrincipal);
                    return new UserAuthentication(getAuthMethod(),
                            new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" }));
                case FAILURE:
                default:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_FAILURE;
                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                throw new ServerAuthException(t);
            }
        }

        @Override
        public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory,
                User validatedUser) throws ServerAuthException {
            return true;
        }
    });
    securityHandler.addConstraintMapping(constraintMapping);

    securityHandler.setHandler(handler);
    return securityHandler;
}