Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:axiom.servlet.AbstractServletClient.java

protected void parseCookies(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws Exception {
    try {//from   w  ww . ja va 2 s  . c  o m
        Context cx = Context.enter();
        cx.setClassShutter(new ClassShutter() {
            public boolean visibleToScripts(String fullClassName) {
                return false;
            }
        });

        ImporterTopLevel scope = new ImporterTopLevel(cx, true);

        // read cookies
        Cookie[] reqCookies = request.getCookies();
        Scriptable cookies = cx.newObject(scope);

        if (reqCookies != null) {
            for (int i = 0; i < reqCookies.length; i++) {
                try {
                    // get Cookies
                    String nextKey = reqCookies[i].getName();
                    String nextPart = reqCookies[i].getValue();

                    if (sessionCookieName.equals(nextKey)) {
                        reqtrans.setSession(nextPart);
                    } else {
                        cookies.put(nextKey, cookies, nextPart);
                    }
                } catch (Exception badCookie) {
                    // ignore
                }
            }
        }

        reqtrans.setCookies(cookies);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {
        Context.exit();
    }
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

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

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/*from  www  .j a  va 2 s .  c  om*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:com.google.gsa.Kerberos.java

/**
 * Gets a cookie from the request/*ww  w  . j a v  a2s . com*/
 * 
 * @param request HTTP request
 * @param cookieName cookie name
 * 
 * @return cookie (if it exists)
 */
private Cookie getCookie(HttpServletRequest request, String cookieName) {

    Cookie cookie = null;
    Cookie[] cookies = null;

    // Retrieve cookies from the request
    cookies = request.getCookies();

    // Protection: look for auth and referer cookies
    if (cookies != null) {

        // Look for the referer cookie
        for (int i = 0; i < cookies.length; i++) {

            // Look for the referer cookie
            if ((cookies[i].getName()).equals(cookieName)) {

                // Cache cookie
                cookie = cookies[i];

                logger.debug("Cookie already exists: " + cookie.getValue());

                // Exit
                break;
            }

        }

    }

    return cookie;

}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

@RequestMapping(value = "/logout/**", method = RequestMethod.GET)
public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) {
    // clear cookies//from   www  .ja  v a 2 s . c o m
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            String ckName = cookies[i].getName();
            if (ckName.equals(loginCookie) || ckName.startsWith("_shib")) {
                log.debug("cookie to clear " + ckName);
                Cookie c = new Cookie(ckName, "void");
                c.setSecure(true);
                c.setPath("/");
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }
    /**
            try {
               log.debug("redirect to: " +  logoutUrl);
               response.sendRedirect(logoutUrl);
            } catch (IOException e) {
               log.error("redirect: " + e);
            }
            return emptyMV("configuration error");
     **/
    String view = "browser";
    Device currentDevice = DeviceUtils.getCurrentDevice(request);
    if (currentDevice != null && currentDevice.isMobile())
        view = "mobile";
    ModelAndView mv = new ModelAndView(view + "/chooser");
    mv.addObject("root", browserRootPath);
    mv.addObject("vers", request.getServletPath());
    mv.addObject("pagetype", "browser/loggedout");
    mv.addObject("pathextra", "");
    mv.addObject("uwloginpath", standardLoginPath);
    mv.addObject("googleloginpath", googleLoginPath);
    mv.addObject("incommonloginpath", incommonLoginPath);
    return (mv);
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

private void sendToLogin(HttpServletRequest request, HttpServletResponse response, String loginPath) {

    // delete any existing sessions first
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().startsWith("_shib")) {
                log.debug("clearing cookie " + cookies[i].getName());
                Cookie c = new Cookie(cookies[i].getName(), "");
                c.setSecure(true);//ww  w .  java2 s.  c  o m
                c.setPath("/");
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }

    String rp = "";
    if (request.getPathInfo() != null)
        rp = request.getPathInfo();
    String rqs = "";
    if (request.getQueryString() != null)
        rqs = "?" + request.getQueryString();
    String red = browserRootPath + request.getServletPath() + loginPath + rp + rqs;
    log.debug("no user yet: redirect for login to " + red);
    try {
        response.sendRedirect(red);
    } catch (IOException e) {
        log.error("redirect: " + e);
    }
}

From source file:org.apache.hadoop.test.mock.MockRequestMatcher.java

public void match(HttpServletRequest request) throws IOException {
    if (methods != null) {
        assertThat(//from   ww w.  j  a  v  a 2s .  c  o  m
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " is not using one of the expected HTTP methods",
                methods, hasItem(request.getMethod()));
    }
    if (pathInfo != null) {
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected pathInfo", request.getPathInfo(), is(pathInfo));
    }
    if (requestURL != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected requestURL",
                request.getRequestURL().toString(), is(requestURL));
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " does not have the expected value for header " + name,
                    request.getHeader(name), is(headers.get(name)));
        }
    }
    if (cookies != null) {
        List<Cookie> requestCookies = Arrays.asList(request.getCookies());
        for (Cookie cookie : cookies) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " does not have the expected cookie " + cookie, requestCookies, hasItem(cookie));
        }
    }
    if (contentType != null) {
        String[] requestContentType = request.getContentType().split(";", 2);
        assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                + " does not have the expected content type", requestContentType[0], is(contentType));
    }
    if (characterEncoding != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected character encoding",
                request.getCharacterEncoding(), equalToIgnoringCase(characterEncoding));
    }
    if (contentLength != null) {
        assertThat(
                "Request " + request.getMethod() + " " + request.getRequestURL()
                        + " does not have the expected content length",
                request.getContentLength(), is(contentLength));
    }
    if (attributes != null) {
        for (String name : attributes.keySet()) {
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " is missing attribute '" + name + "'", request.getAttribute(name), notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL()
                            + " has wrong value for attribute '" + name + "'",
                    request.getAttribute(name), is(request.getAttribute(name)));
        }
    }
    // Note: Cannot use any of the expect.getParameter*() methods because they will read the
    // body and we don't want that to happen.
    if (queryParams != null) {
        String queryString = request.getQueryString();
        Map<String, String[]> requestParams = parseQueryString(queryString == null ? "" : queryString);
        for (String name : queryParams.keySet()) {
            String[] values = requestParams.get(name);
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                    + queryString + " is missing parameter '" + name + "'", values, notNullValue());
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " query string "
                            + queryString + " is missing a value for parameter '" + name + "'",
                    Arrays.asList(values), hasItem(queryParams.get(name)));
        }
    }
    if (formParams != null) {
        String paramString = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        Map<String, String[]> requestParams = parseQueryString(paramString == null ? "" : paramString);
        for (String name : formParams.keySet()) {
            String[] actualValues = requestParams.get(name);
            assertThat(
                    "Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                            + paramString + " is missing parameter '" + name + "'",
                    actualValues, notNullValue());
            String[] expectedValues = formParams.get(name);
            for (String expectedValue : expectedValues) {
                assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " form params "
                        + paramString + " is missing a value " + expectedValue + " for parameter '" + name
                        + "'", Arrays.asList(actualValues), hasItem(expectedValue));
            }
        }
    }
    if (entity != null) {
        if (contentType != null && contentType.endsWith("/xml")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            assertThat(the(actual), isEquivalentTo(the(expect)));
        } else if (contentType != null && contentType.endsWith("/json")) {
            String expectEncoding = characterEncoding;
            String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding));
            String actualEncoding = request.getCharacterEncoding();
            String actual = IOUtils.toString(request.getInputStream(),
                    actualEncoding == null ? UTF8.name() : actualEncoding);
            //        System.out.println( "EXPECT=" + expect );
            //        System.out.println( "ACTUAL=" + actual );
            assertThat(actual, sameJSONAs(expect));
        } else if (characterEncoding == null || request.getCharacterEncoding() == null) {
            byte[] bytes = IOUtils.toByteArray(request.getInputStream());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", bytes, is(entity));
        } else {
            String expect = new String(entity, characterEncoding);
            String actual = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            assertThat("Request " + request.getMethod() + " " + request.getRequestURL()
                    + " content does not match the expected content", actual, is(expect));
        }
    }
}

From source file:com.tremolosecurity.proxy.filter.HttpFilterRequestImpl.java

public HttpFilterRequestImpl(HttpServletRequest request, AuthInfo authInfo) {
    this.request = request;

    this.headers = new HashMap<String, Attribute>();
    this.cookies = new HashMap<String, ArrayList<Cookie>>();
    this.params = new HashMap<String, Attribute>();
    this.paramNames = new ArrayList<String>();

    Enumeration enumer = request.getParameterNames();
    while (enumer.hasMoreElements()) {
        String name = (String) enumer.nextElement();
        this.paramNames.add(name);
    }//from  w  w w .  j av  a2 s .  c om

    this.authInfo = authInfo;

    boolean first = true;

    ProxyUtil.loadParams(request, this.params);

    enumer = request.getHeaderNames();
    while (enumer.hasMoreElements()) {
        String name = (String) enumer.nextElement();
        Enumeration enumerVals = request.getHeaders(name);
        Attribute attrib = new Attribute(name);
        this.headers.put(attrib.getName().toLowerCase(), attrib);
        while (enumerVals.hasMoreElements()) {
            attrib.getValues().add((String) enumerVals.nextElement());
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        cookies = new Cookie[0];
    }
    for (int i = 0; i < cookies.length; i++) {
        ArrayList<Cookie> cookieList = this.cookies.get(cookies[i].getName());
        if (cookieList == null) {
            cookieList = new ArrayList<Cookie>();
            this.cookies.put(cookies[i].getName(), cookieList);
        }
        cookieList.add(cookies[i]);

    }

}

From source file:com.mhe.imagebanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = AmazonServiceUtilTag.getImageThumbnailURL();
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;//from   ww  w  . j av  a2s .c o m
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId, ASSETBANK_TYPE);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");

        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {//w  ww  . j a  v  a 2  s .  com
        String userApprovedParamS = req.getParameter(ProxyUriUtils.PROXY_APPROVAL_PARAM);
        boolean userWasWarned = false;
        boolean userApproved = (userApprovedParamS != null && Boolean.valueOf(userApprovedParamS));
        boolean securityEnabled = isSecurityEnabled();
        final String remoteUser = req.getRemoteUser();
        final String pathInfo = req.getPathInfo();

        String parts[] = pathInfo.split("/", 3);
        if (parts.length < 2) {
            LOG.warn(remoteUser + " Gave an invalid proxy path " + pathInfo);
            notFound(resp, "Your path appears to be formatted incorrectly.");
            return;
        }
        //parts[0] is empty because path info always starts with a /
        String appId = parts[1];
        String rest = parts.length > 2 ? parts[2] : "";
        ApplicationId id = Apps.toAppID(appId);
        if (id == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + appId + " that is invalid");
            notFound(resp, appId + " appears to be formatted incorrectly.");
            return;
        }

        if (securityEnabled) {
            String cookieName = getCheckCookieName(id);
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (cookieName.equals(c.getName())) {
                        userWasWarned = true;
                        userApproved = userApproved || Boolean.valueOf(c.getValue());
                        break;
                    }
                }
            }
        }

        boolean checkUser = securityEnabled && (!userWasWarned || !userApproved);

        ApplicationReport applicationReport = null;
        try {
            applicationReport = getApplicationReport(id);
        } catch (ApplicationNotFoundException e) {
            applicationReport = null;
        }
        if (applicationReport == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + id + " that was not found");

            URI toFetch = ProxyUriUtils.getUriFromTrackingPlugins(id, this.trackingUriPlugins);
            if (toFetch != null) {
                resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
                return;
            }

            notFound(resp, "Application " + appId + " could not be found, " + "please try the history server");
            return;
        }
        String original = applicationReport.getOriginalTrackingUrl();
        URI trackingUri = null;
        // fallback to ResourceManager's app page if no tracking URI provided
        if (original == null || original.equals("N/A")) {
            resp.sendRedirect(resp.encodeRedirectURL(StringHelper.pjoin(rmAppPageUrlBase, id.toString())));
            return;
        } else {
            if (ProxyUriUtils.getSchemeFromUrl(original).isEmpty()) {
                trackingUri = ProxyUriUtils.getUriFromAMUrl(WebAppUtils.getHttpSchemePrefix(conf), original);
            } else {
                trackingUri = new URI(original);
            }
        }

        String runningUser = applicationReport.getUser();
        if (checkUser && !runningUser.equals(remoteUser)) {
            LOG.info("Asking " + remoteUser + " if they want to connect to the " + "app master GUI of " + appId
                    + " owned by " + runningUser);
            warnUserPage(resp, ProxyUriUtils.getPathAndQuery(id, rest, req.getQueryString(), true), runningUser,
                    id);
            return;
        }
        URI toFetch = new URI(trackingUri.getScheme(), trackingUri.getAuthority(),
                StringHelper.ujoin(trackingUri.getPath(), rest), req.getQueryString(), null);

        LOG.info(req.getRemoteUser() + " is accessing unchecked " + toFetch + " which is the app master GUI of "
                + appId + " owned by " + runningUser);

        switch (applicationReport.getYarnApplicationState()) {
        case KILLED:
        case FINISHED:
        case FAILED:
            resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
            return;
        }
        Cookie c = null;
        if (userWasWarned && userApproved) {
            c = makeCheckCookie(id, true);
        }
        proxyLink(req, resp, toFetch, c, getProxyHost());

    } catch (URISyntaxException e) {
        throw new IOException(e);
    } catch (YarnException e) {
        throw new IOException(e);
    }
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to populate new user authentication 
 * credentials from the LDAP server.//from  ww w .  ja  v a 2  s . com
 * <p>
 * It also authenticates the user against the LDAP server, so that only 
 * priviledged users are able to read the LDAP attributes. These multiple 
 * credentials are stored in the directory server and populate them in the 
 * user's credential container. It enables the other AuthN/AuthZ modules to 
 * use them when securely accessing the backend systems.
 * <p>
 * If the LDAP authentication result is OK, it creates an 
 * authentication cookie. Anyway, the HTTP response code is returned in this 
 * method to inform the caller on the status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    logger.debug("Start LDAPSSO AuthN process");

    //protection
    repositories.clear();
    ldapAttributes.clear();

    //Insert LDAP attributes from the config file
    getLDAPAttributes(id);

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("LDAPSSO: trying to get creds from repository ID: " + id);
    Credential cred = null;
    try {
        cred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (cred == null) {
        cred = creds.getCredential("root");
        if (cred != null) {
            logger.info("LDAPSSO: credential ID used is \"root\"");
        } else {
            logger.error("LDAPSSO: No credentials available for " + id);
        }
    }

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    //If the required cookie was not found need to authenticate.
    logger.info("Authenticating root user with LDAP");
    try {

        //Check if the LDAP credentials are OK                       
        Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain,
                rdnAttr);
        try {
            logger.debug("Connecting to LDAP");
            DirContext ctx = ldapconn.openConnection();
            if (ctx == null) {
                //Just send a comment  
                logger.debug("The user(" + cred.getUsername() + ")/password doesn't match");
                ldapconn.closeConnection(ctx);
                return (HttpServletResponse.SC_UNAUTHORIZED);
            }

            //Fetching credentials
            logger.debug("Fetching credentials from the LDAP");

            fetchingCredentials(ldapconn, ctx, cred.getUsername(), creds);

            //Close the connection
            ldapconn.closeConnection(ctx);

        } catch (Exception ex) {
            logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex);
            return (HttpServletResponse.SC_UNAUTHORIZED);
        } finally {
        }

        Cookie extAuthCookie = null;

        extAuthCookie = settingCookie();

        //add sendCookies support
        logger.debug("Setting session");
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        //This would be set to OK or 401 in a real AuthN module
        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("LDAP SSO authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // Debug
    logger.debug("Sample Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}