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:in.raster.oviyam.servlet.Validator.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    /*AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
    String loginId=principal.getName();*/

    /*??*/// ww  w.j  a  v  a 2 s. co  m
    String pid = (String) request.getParameter("PatientID").trim();
    if (pid == null || "".equals(pid)) {
        out.println("??!");
        out.close();
        return;
    }

    /*?????*/
    String r = dataAccess.getReportAddress(pid);
    /*?dcmpacs?*/
    //String r=dataAccess.addDicom("x");

    /*?*/
    Boolean a = dataAccess.checsIsExist(pid);
    if (!a) {
        out.println("?!");
        out.close();
        return;
    }

    /*????*/
    //boolean b=dataAccess.checkCheckId(loginId,pid);
    //if(!b)return;

    /**/
    /*PacsQueryLogModel pqlm = new PacsQueryLogModel();
    pqlm.setApplicationId(pid);
    pqlm.setDoctorId(loginId);
    dataAccess.addPacsLog(pqlm);*/

    AE ae;
    ServletContext servletContext = getServletContext();
    ServerConfiguration serverConfiguration;
    EchoService echoService;

    String agree = request.getParameter("agree");

    if (agree != null && agree.equals("agree")) {
        Cookie agreeCookie = new Cookie("agree", "agree");
        agreeCookie.setMaxAge(60 * 60 * 24 * 365);
        response.addCookie(agreeCookie);
    }

    try {
        ae = new AE();
        //assigns the serverConfiguration instance.         
        serverConfiguration = ae.getServerConfiguration();
        /*
         * writes the serverConfiguration instance in the servletContext (application scope).
         * So all the SERVLET classes and JSP pages can access the serverConfig attribute.
         * User can use either <jsp:useBean> tag or ${applicationScope.serverConfig} EL 
         * to access the serverConfig attribute. From SERVLET classes the User can use
         * the getServletContext().getAttribute("serverConfig") to access the serverConfiguration attribute.
         */
        servletContext.setAttribute("serverConfig", serverConfiguration);

        echoService = new EchoService();
        echoService.checkEcho();
        /*If the status of EchoService is failed then the request will be forwarded to 
         * EchoFailed.jsp. Otherwise, request is forwarded to oviyam7.jsp
         * 
         */
        if (echoService.getStatus().equals("Echo failed")) {
            /*
             * writes the echoURL(dcmProtocol://aeTitle@hostName:port) attribute in request instance.
             * and forwards the request and response object to EchoFailed.jsp .
             * echoFailed attribute can be accessed through either ${request.echoURL} or 
             * <% request.getAttribute("echoURL")%>
             */
            request.setAttribute("echoURL", ae.toString());
            request.getRequestDispatcher("EchoFailed.jsp").forward(request, response);
        } else {
            // forwards the request and response to oviyam7.jsp
            String studyUID = request.getParameter("studyUID");
            String seriesUID = request.getParameter("seriesUID");
            String patientID = request.getParameter("patientID");
            if (studyUID != null && studyUID.length() <= 0) {
                request.setAttribute("param", "studyUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid studyUID parameter for Oviyam.");
            } else if (seriesUID != null && seriesUID.length() <= 0) {
                request.setAttribute("param", "seriesUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid seriesUID parameter for Oviyam.");
            } else if (patientID != null && patientID.length() <= 0) {
                request.setAttribute("param", "patientID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid patientID parameter for Oviyam.");
            } else {
                request.getRequestDispatcher("oviyam7.jsp").forward(request, response);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage());

    }
}

From source file:com.afousan.controller.RetwisController.java

private void addAuthCookie(String auth, String name, HttpServletResponse response) {
    RetwisSecurity.setUser(name, retwis.findUid(name));

    Cookie cookie = new Cookie(CookieInterceptor.RETWIS_COOKIE, auth);
    cookie.setComment("Retwis-J demo");
    // cookie valid for up to 1 week
    cookie.setMaxAge(60 * 60 * 24 * 7);
    response.addCookie(cookie);/*from  w  w  w .  ja va  2s.co  m*/
}

From source file:SettingandReadingCookies.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Web Page");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY");

    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;

    for (int loopIndex = 0; loopIndex < cookies.length; loopIndex++) {
        Cookie cookie1 = cookies[loopIndex];
        if (cookie1.getName().equals("color")) {
            out.println("bgcolor = " + cookie1.getValue());
            foundCookie = true;//from ww  w  .  j  a v a 2 s  . co  m
        }
    }

    if (!foundCookie) {
        Cookie cookie1 = new Cookie("color", "cyan");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1);
    }

    out.println(">");
    out.println("<H1>Setting and Reading Cookies</H1>");
    out.println("This page will set its background color using a cookie when reloaded.");
    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:de.hska.ld.core.config.security.AjaxLogoutSuccessHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    ///*  w w  w  .j  ava2s .co  m*/
    // To delete a cookie, we need to create a cookie that has the same
    // name with the cookie that we want to delete. We also need to set
    // the max age of the cookie to 0 and then add it to the Servlet's
    // response method.
    //
    javax.servlet.http.Cookie cookie = new Cookie("sessionID", "");
    cookie.setPath("/");
    if (!"localhost".equals(env.getProperty("module.core.oidc.server.endpoint.main.domain"))) {
        cookie.setDomain(env.getProperty("module.core.oidc.server.endpoint.main.domain"));
    }
    cookie.setMaxAge(0);
    response.addCookie(cookie);

    // TODO destory session in etherpad

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.pearson.openideas.cq5.components.page.OpenIdeasMasterTemplate.java

/**
 * init method doesn't do a whole lot right now.
 *//*from  w ww .ja va2 s. c o m*/
public void init() {
    log.debug("master page template init called for page {}", getCurrentPage().getPath());
    CookieUtils cookieUtils = new CookieUtils();

    String logout = getRequestParameter("logout");
    log.debug("Should we try to logout? " + logout);

    if (StringUtils.isNotBlank(logout)) {
        Cookie cookie = cookieUtils.getCookie(getSlingRequest(), "login-token");
        cookie.setPath("/");
        cookie.setMaxAge(0);

        Cookie nameCookie = cookieUtils.getCookie(getSlingRequest(), "login-name");
        if (nameCookie != null) {
            nameCookie.setPath("/");
            nameCookie.setMaxAge(0);
            getSlingResponse().addCookie(nameCookie);
        }
        getSlingResponse().addCookie(cookie);

        UrlUtils.logoutRedirect(getCurrentPage(), getSlingScriptHelper(), getSlingRequest(), getSlingResponse(),
                true);

        loggedIn = false;
    } else {
        log.debug(
                "cookie value for this page: " + cookieUtils.getCookieValue(getSlingRequest(), "login-token"));
        if (StringUtils.isNotBlank(cookieUtils.getCookieValue(getSlingRequest(), "login-token"))) {
            loggedIn = true;
        }

        log.debug("Are we logged in? " + loggedIn);
    }

    pageTitle = PAGETITLEPREFIX + getProperties().get("jcr:title", "");
    accounts = getPageProperties().getInherited("accounts", String[].class);

    if (loggedIn) {
        UserProperties props = getSlingRequest().adaptTo(UserProperties.class);

        try {
            loggedInName = props.getProperty("givenName");
            log.debug("Who is logged in? " + loggedInName);

        } catch (RepositoryException e) {
            log.error("error pulling first name", e);
        }
    } else {
        UrlUtils.logoutRedirect(getCurrentPage(), getSlingScriptHelper(), getSlingRequest(), getSlingResponse(),
                false);
    }

    if (StringUtils.isNotBlank(getRequestParameter("j_reason"))) {
        error = "Login failed, please try again";
    }
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//from   ww  w  .  jav  a 2  s.c  o m
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:com.concursive.connect.web.modules.login.auth.session.SessionValidator.java

/**
 * Follow the current session validation schema and determine if there is a
 * valid session for the user. If there is a valid session, return the
 * <code>User</code> associated with that session, otherwise, return
 * <i>null</i>./*ww w .  j av a 2 s  .c o m*/
 *
 * @param request -
 *                The servlet request as provided by the
 *                <code>ControllerServlet</code>.
 * @return A valid <code>User</code> upon successful validation.<br>
 *         <code>Null</code> upon validation failure
 */
public User validateSession(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    User thisUser = (User) request.getSession(false).getAttribute(Constants.SESSION_USER);
    LOG.debug("Has user session: " + (thisUser != null));
    if (thisUser == null || !thisUser.isLoggedIn()) {
        LOG.debug("Checking for cookie...");
        // Check cookie for session info and generate a logged in user
        String guid = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_GUID);
        if (guid == null) {
            LOG.debug("No cookie found.");
            return (thisUser == null ? null : thisUser);
        }
        LOG.debug("Cookie found with guid: " + guid);
        // Retrieve prefs to see if user with guid exists
        ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
        // Connection info
        ConnectionElement ce = new ConnectionElement();
        ce.setDriver(prefs.get("SITE.DRIVER"));
        ce.setUrl(prefs.get("SITE.URL"));
        ce.setUsername(prefs.get("SITE.USER"));
        ce.setPassword(prefs.get("SITE.PASSWORD"));
        ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
        Connection db = null;
        try {
            db = sqlDriver.getConnection(ce);
            // Load the user record from the guid
            thisUser = UserUtils.loadUserFromGuid(db, guid);
            if (thisUser != null) {
                // Track the login
                thisUser.updateLogin(db, request, prefs, null);
                thisUser.setBrowserType(request.getHeader("USER-AGENT"));
                // Apply defaults
                UserUtils.createLoggedInUser(thisUser, db, prefs, context);
                // Extend the cookie
                Cookie userCookie = new Cookie(Constants.COOKIE_USER_GUID, UserUtils.generateGuid(thisUser));
                userCookie.setPath("/");
                // 14 day cookie
                userCookie.setMaxAge(14 * 24 * 60 * 60);
                response.addCookie(userCookie);
            }
        } catch (Exception e) {
            thisUser = null;
            e.printStackTrace();
        } finally {
            if (db != null) {
                sqlDriver.free(db);
            }
        }
        // Add to session
        request.getSession().setAttribute(Constants.SESSION_USER, thisUser);
        request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ce);
    }
    return thisUser;
}

From source file:com.music.web.AuthenticationController.java

@RequestMapping("/logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    session.invalidate();//from ww  w.  j av a 2  s  .c  om
    Cookie cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_SERIES_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return "redirect:/";
}

From source file:org.apache.unomi.plugins.baseplugin.actions.MergeProfilesOnPropertyAction.java

public void sendProfileCookie(Profile profile, ServletResponse response) {
    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        Cookie profileIdCookie = new Cookie(profileIdCookieName, profile.getItemId());
        profileIdCookie.setPath("/");
        profileIdCookie.setMaxAge(cookieAgeInSeconds);
        httpServletResponse.addCookie(profileIdCookie);
    }/*from w  w  w. ja v a 2 s.  c  o  m*/
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *///from ww w .  jav  a2  s. c o  m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

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