Example usage for javax.servlet.http Cookie setMaxAge

List of usage examples for javax.servlet.http Cookie setMaxAge

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setMaxAge.

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:com.spshop.web.ShoppingController.java

@RequestMapping(value = "/createAccount", method = RequestMethod.POST)
public String createAccount(Model model, HttpServletRequest request, HttpServletResponse response) {

    String email = request.getParameter(REG_USER_NAME);
    String pwd1 = request.getParameter(REG_PWD);
    String pwd2 = request.getParameter(REG_PWD_RE);

    if (null != email) {
        email = email.trim();/*from  w  ww.ja  v  a 2s . c o m*/
    }

    String acceptLicense = request.getParameter(ACCEPT_LICENSE);

    User user = new User();
    user.setName(email);
    user.setEmail(email);
    user.setPassword(pwd1);
    user.setCreateDate(new Date());
    user.setUpdateDate(new Date());

    if (!TRUE.equals(acceptLicense)) {
        getUserView().getErr().put(ACCEPT_LICENSE_ERR, "Please accept license");
    }

    String landingpage = null;
    try {
        landingpage = URLDecoder.decode(request.getParameter(LOGIN_LANDING_PAGE_PARAM), "utf-8");
    } catch (Exception e) {
        logger.debug(e.getMessage());
    }

    if (null == email || !(email.contains("@"))) {
        getUserView().getErr().put(REG_USER_NAME_ERR, "Invalid user account");
    } else {
        User u = ServiceFactory.getService(UserService.class).queryUserByEmail(email);
        if (u != null) {
            getUserView().getErr().put(REG_USER_NAME_ERR, "account already exist");
        }
    }

    if (pwd1 == null || pwd1.length() < 5) {
        getUserView().getErr().put(REG_PWD_ERR, "Invalid password");
    } else {
        if (pwd2 == null || !pwd1.equals(pwd2)) {
            getUserView().getErr().put(REG_PWD_RE_ERR, "Two passwords are not same");
        }
    }

    if (getUserView().getErr().isEmpty()) {
        final User u = ServiceFactory.getService(UserService.class).saveUser(user);
        if (null != u) {
            getUserView().getMsg().put(REG_USER_NAME_SUC, "Create Account successfully");
            final Map<String, Object> root = new HashMap<String, Object>();
            root.put("user", u);
            u.setPassword(u.getPassword());

            model.addAttribute(USER_INFO, u);
            request.getSession().setAttribute(USER_INFO, u);
            getUserView().setLoginUser(u);
            Cookie cookie = new Cookie(COOKIE_ACCOUNT,
                    Utils.OBJ.getEncryString(u.getEmail() + USER_NAME_PWD_SPLIT + u.getPassword()));
            cookie.setMaxAge(99999999);
            cookie.setPath("/");
            response.addCookie(cookie);

            new Thread() {
                public void run() {
                    try {
                        EmailTools.sendMail("register", "Welcome to Honeybuy.com, New Member Registration",
                                root, u.getName());
                    } catch (Exception e) {

                    }
                };
            }.start();

        }
    }

    if (StringUtils.isNotBlank(landingpage)) {
        getUserView().setRequestPage(landingpage);
    }
    model.addAttribute(REG_USER, user);

    return "login";
}

From source file:cn.tiup.httpproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *///from w  ww . j  av  a 2  s  . c o  m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(cookie.getPath()); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private void attachCookies(String name, HashMap<String, String> attrs, HttpServletResponse response,
        boolean outdated) throws ServletException {
    String maxAge = "0";
    Cookie lcook = null;
    if (!outdated) {
        lcook = new Cookie(name, cipher.encode(name, generateCookie(attrs, outdated)));
    } else {/*from w w w  .j  av a 2  s .com*/
        lcook = new Cookie(name, "");
        lcook.setMaxAge(Integer.parseInt(maxAge));
    }
    lcook.setPath(this.location);
    response.addCookie(lcook);
}

From source file:com.activecq.experiments.redis.impl.RedisSessionUtilImpl.java

@Override
public Cookie createSessionCookie() {
    final Cookie cookie = new Cookie(this.getSessionCookieName(), java.util.UUID.randomUUID().toString());

    cookie.setPath("/");
    cookie.setSecure(this.secureCookie);

    // Expire with browser session
    cookie.setMaxAge(-1);

    return cookie;
}

From source file:com.bilko.controller.BlogController.java

private void initRoutes() throws IOException {

    get("/", new FreemarkerBasedRoute("blog_template.ftl") {

        @Override/*from w ww .j  a v a  2  s. c o m*/
        public void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request));
            final List<Document> posts = blogPostDao.findByDateDescending(10);
            final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
            if (isNotBlank(username)) {
                root.put("username", username);
            }
            root.put("myposts", posts);

            template.process(root, writer);
        }
    });

    get("/welcome", new FreemarkerBasedRoute("welcome.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request));
            if (isBlank(username)) {
                System.out.println("welcome() CAN'T IDENTIFY THE USER, REDIRECTING TO signup");
                response.redirect("/signup");
            } else {
                final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                root.put("username", username);
                template.process(root, writer);
            }
        }
    });

    get("/signup", new FreemarkerBasedRoute("signup.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    post("/signup", new FreemarkerBasedRoute("signup.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String email = request.queryParams("email");
            final String username = request.queryParams("username");
            final String password = request.queryParams("password");
            final String verify = request.queryParams("verify");
            final HashMap<String, String> root = new HashMap<String, String>() {
                {
                    put("username", escapeHtml4(username));
                    put("email", escapeHtml4(email));
                }
            };

            if (validateSignup(username, password, verify, email, root)) {
                System.out.println("SIGNUP: CREATING USER WITH: " + username + " " + password);
                if (!userDao.addUser(username, password, email)) {
                    root.put("username_error", "USERNAME ALREADY IN USE, PLEASE CHOOSE ANOTHER");
                    template.process(root, writer);
                } else {
                    final String sessionId = sessionDao.startSession(username);
                    System.out.println("SESSION ID IS: " + sessionId);
                    response.raw().addCookie(new Cookie("session", sessionId));
                    response.redirect("/welcome");
                }
            } else {
                System.out.println("USER REGISTRATION DIDN'T VALIDATE");
                template.process(root, writer);
            }
        }
    });

    get("/login", new FreemarkerBasedRoute("login.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
            root.put("username", "");
            root.put("login_error", "");
            template.process(root, writer);
        }
    });

    post("/login", new FreemarkerBasedRoute("login.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String username = request.queryParams("username");
            final String password = request.queryParams("password");
            final Document user = userDao.validateLogin(username, password);
            System.out.println("LOGIN: USER SUBMITTED: " + username + " " + password);

            if (user != null) {
                final String sessionId = sessionDao.startSession(user.get("_id").toString());
                if (sessionId == null) {
                    response.redirect("/internal_error");
                } else {
                    response.raw().addCookie(new Cookie("session", sessionId));
                    response.redirect("/welcome");
                }
            } else {
                final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                root.put("username", escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    get("/newpost", new FreemarkerBasedRoute("newpost_template.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request));
            if (isBlank(username)) {
                response.redirect("/login");
            } else {
                SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                root.put("username", username);
                template.process(root, writer);
            }
        }
    });

    post("/newpost", new FreemarkerBasedRoute("newpost_template.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String title = escapeHtml4(request.queryParams("subject"));
            final String post = escapeHtml4(request.queryParams("body"));
            final String tags = escapeHtml4(request.queryParams("tags"));
            final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request));
            if (isBlank(username)) {
                response.redirect("/login");
            } else if (isBlank(title) || isBlank(post)) {
                HashMap<String, String> root = new HashMap<String, String>() {
                    {
                        put("errors", "post must contain a title and blog entry.");
                        put("subject", title);
                        put("username", username);
                        put("tags", tags);
                        put("body", post);
                    }
                };
                template.process(root, writer);
            } else {
                final String permalink = blogPostDao.addPost(title, post.replaceAll("\\r?\\n", "<p>"),
                        extractTags(tags), username);
                response.redirect("/post/" + permalink);
            }
        }
    });

    get("/post/:permalink", new FreemarkerBasedRoute("entry_template.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String permalink = request.params(":permalink");
            System.out.println("/post: GET " + permalink);

            final Document post = blogPostDao.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            } else {
                final SimpleHash comment = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                comment.put("name", "");
                comment.put("email", "");
                comment.put("body", "");

                final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                root.put("post", post);
                root.put("comments", comment);

                template.process(root, writer);
            }
        }
    });

    post("/newcomment", new FreemarkerBasedRoute("entry_template.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String name = escapeHtml4(request.queryParams("commentName"));
            final String email = escapeHtml4(request.queryParams("commentEmail"));
            final String body = escapeHtml4(request.queryParams("commentBody"));
            final String permalink = request.queryParams("permalink");
            final Document post = blogPostDao.findByPermalink(permalink);
            if (post == null) {
                response.redirect("/post_not_found");
            } else if (isBlank(name) || isBlank(body)) {
                final SimpleHash comment = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                comment.put("name", name);
                comment.put("email", email);
                comment.put("body", body);

                final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
                root.put("comments", comment);
                root.put("post", post);
                root.put("errors", "POST MUST CONTAIN YOUR NAME AND AN ACTUAL COMMENT");

                template.process(root, writer);
            } else {
                blogPostDao.addPostComment(name, email, body, permalink);
                response.redirect("/post/" + permalink);
            }
        }
    });

    get("/tag/:thetag", new FreemarkerBasedRoute("blog_template.ftl") {
        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request));
            final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
            final String tag = escapeHtml4(request.params(":thetag"));
            final List<Document> posts = blogPostDao.findByTagDateDescending(tag);

            if (isNotBlank(username)) {
                root.put("username", username);
            }
            root.put("myposts", posts);

            template.process(root, writer);
        }
    });

    get("/logout", new FreemarkerBasedRoute("signup.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final String sessionId = getSessionCookie(request);
            if (sessionId == null) {
                response.redirect("/login");
            } else {
                sessionDao.endSession(sessionId);
                final Cookie cookie = getSessionCookieActual(request);
                if (cookie != null) {
                    cookie.setMaxAge(0);
                    response.raw().addCookie(cookie);
                    response.redirect("/login");
                }
            }
        }
    });

    get("/post_not_found", new FreemarkerBasedRoute("post_not_found.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            template.process(new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())), writer);
        }
    });

    get("/internal_error", new FreemarkerBasedRoute("error_template.ftl") {

        @Override
        protected void doHandle(final Request request, final Response response, final Writer writer)
                throws IOException, TemplateException {

            final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion()));
            root.put("error", "SYSTEM HAS ENCOUNTERED AN ERROR");
            template.process(root, writer);
        }
    });
}

From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();//from   w w  w .  jav a2s  . co  m
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie")
                            || header.getName().equalsIgnoreCase("set-cookie2")) {
                        //System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
                           cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                        }
                                
                        //System.out.println(cookieVal);*/

                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];//from ww  w  .  j a  v  a  2s  .  co m
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:com.traffitruck.web.HtmlController.java

private void setSessionCookie(HttpServletResponse response, String regid, int expiry) {
    Cookie cookie = new Cookie(DEVICE_REGISTRATION_COOKIE_NAME, regid);
    cookie.setMaxAge(expiry);
    cookie.setHttpOnly(true);// w  w w .  j  ava2 s.com
    // cookie.setSecure(true);
    response.addCookie(cookie);
}

From source file:org.guanxi.idp.service.AuthHandler.java

/**
 * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after
 * a successful authentication at the IdP, either via the login page or an application cookie handler,
 * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value.
 * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet
 * context under GuanxiPrincipal.id/* w  w  w. j a  va2s  .  c o  m*/
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true 
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    request.setCharacterEncoding("UTF-8");

    String missingParams = checkRequestParameters(request);
    if (missingParams != null) {
        logger.info("Missing param(s) : " + missingParams);
        request.setAttribute("message",
                messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG);

    boolean spSupported = false;
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam));
    if (manager != null) {
        SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam));
        // Apply the trust rules to the SP
        if (metadata != null) {
            if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) {
                spSupported = true;
            } else {
                logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> "
                        + request.getParameter("shire"));
            }
        } else {
            logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam));
        }
    } else {
        logger.error("No Metadata Manager");
    }

    // Check the locally registered SPs
    if (!spSupported) {
        ServiceProvider[] spList = idpConfig.getServiceProviderArray();
        for (int c = 0; c < spList.length; c++) {
            if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) {
                // If it's in here, we trust it explicitly
                spSupported = true;
            }
        }
    }

    // Did we find the service provider?
    if (!spSupported) {
        logger.error(
                "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported");
        request.setAttribute("message", messageSource.getMessage("sp.not.supported",
                new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    }

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    request.getRequestDispatcher(authPage).forward(request, response);

    return false;
}