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.qut.middleware.esoe.authn.servlet.AuthnServlet.java

/**
 * Sets the session cookie for this principal
 * /*from   w w w.  j  a  va2  s. c  o m*/
 * @param data
 */
private void setSessionCookie(AuthnProcessorData data) {
    Cookie sessionCookie = new Cookie(this.sessionTokenName, data.getSessionID());
    sessionCookie.setDomain(this.sessionDomain);
    sessionCookie.setMaxAge(-1); // negative indicates session scope cookie
    sessionCookie.setPath("/");

    data.getHttpResponse().addCookie(sessionCookie);
}

From source file:memedb.httpd.MemeDBHandler.java

protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Credentials cred = null;/*from   ww w.j  av a 2s  .com*/

    if (request.getRequestURI().equals("/_auth")) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.debug("login attempt for {}", username);
        if (!allowAnonymous && "anonymous".equals(username)) {
            sendNoAuthError(response, "Bad username / password combination");
            return null;
        }
        if (username != null) {
            if (password == null) {
                password = "";
            }
            if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) {
                return new SACredentials("anonymous", "", timeout);
            }
            cred = memeDB.getAuthentication().authenticate(username, password);
            if (cred != null) {
                if (request.getParameter("setcookie") == null
                        || request.getParameter("setcookie").toLowerCase().equals("false")) {
                    Cookie cookie = new Cookie(COOKIE_ID, cred.getToken());
                    cookie.setMaxAge(timeout);
                    response.addCookie(cookie);
                }
                return cred;
            } else {
                log.warn("Bad login attempt for {}", username);
                sendNoAuthError(response, "Bad username / password combination");
                return null;
            }
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_ID)) {
                cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue());
                if (cred != null) {
                    log.debug("Got credentials from cookie token: {}", cookie.getValue());
                    return cred;
                }
            }
        }
    }

    String param = request.getParameter("token");
    if (param != null && !param.equals("")) {
        cred = memeDB.getAuthentication().getCredentialsFromToken(param);
        if (cred != null) {
            log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String headerparam = request.getHeader("MemeDB-Token");
    if (headerparam != null && !headerparam.equals("")) {
        log.info("Attempting authentication with token {}", headerparam);
        cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam);
        if (cred != null) {
            log.info("Got credentials!");
            log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        String[] authSplit = authHeader.split(" ");
        if (authSplit.length == 2) {
            String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes()));
            if (userpass != null) {
                String[] ar = userpass.split(":");
                if (ar.length > 0) {
                    String u = ar[0];
                    String p = "";
                    if (ar.length > 1) {
                        p = ar[1];
                    }
                    if (!allowAnonymous && "anonymous".equals(u)) {
                    } else {
                        cred = memeDB.getAuthentication().authenticate(u, p);

                        if (cred != null) {
                            log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(),
                                    cred.getToken());
                            addCredentialedCookie(response, cred);
                        }
                        return cred;
                    }
                }
            }
        }
        response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
        sendNoAuthError(response, "You need a username and password");
        return null;
    }

    if (allowAnonymous) {
        if (allowAnonymousAsSa)
            return new SACredentials("anonymous", "", timeout);
        return new AnonCredentials("", timeout);
    }

    log.warn("Error authenticating");
    response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
    sendNoAuthError(response, "You need a username and password");
    return null;
}

From source file:com.yahoo.yos.YahooFilter.java

private void accessTokenExpired(OAuthAccessor accessor, HttpServletRequest request,
        HttpServletResponse response, AccessToken accessToken, FilterChain filterChain)
        throws IOException, ServletException, JSONException, OAuthException, URISyntaxException {
    if (logger.isDebugEnabled()) {
        logger.debug("access token expired, attempting to renew");
    }//from w w w .jav  a 2s . com
    long now = System.currentTimeMillis() / 1000;
    if (accessToken.getHandleExpires() == -1 || (now < accessToken.getHandleExpires())) {
        RequestToken requestToken = new RequestToken();
        requestToken.setKey(accessToken.getKey());
        requestToken.setSessionHandle(accessToken.getSessionHandle());
        accessor.tokenSecret = accessToken.getSecret();
        AccessToken at = fetchAccessToken(accessor, requestToken, null);
        Cookie yosdk_at = at.getCookie();
        yosdk_at.setMaxAge(30 * 24 * 60 * 60);
        response.addCookie(yosdk_at);
        String appId = oauthConfig.getProperty("yos.appid");
        YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
        request.setAttribute("yahooSession", yahooSession);
        filterChain.doFilter(request, response);
    } else {
        Cookie at = new Cookie("yosdk_at", "");
        at.setMaxAge(0);
        at.setMaxAge(0);
        response.addCookie(at);
        request.setAttribute("yahooSession", null);
        request.setAttribute("yahooRedirect", null);
        filterChain.doFilter(request, response);
        if (redirect) {
            redirectForAuthorization(accessor, request, response);
        }
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.ShowIbisstoreSummary.java

public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    IniDynaActionForm showIbisstoreSummaryForm = (IniDynaActionForm) form;
    // Initialize action
    initAction(request);/*from  ww w.j  a v a2  s . co  m*/

    String jmsRealm = (String) showIbisstoreSummaryForm.get("jmsRealm");
    String cookieName = AppConstants.getInstance().getString(SHOWIBISSTORECOOKIE, SHOWIBISSTORECOOKIE);

    if (StringUtils.isEmpty(jmsRealm)) {
        // get jmsRealm value from cookie
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie aCookie = cookies[i];

                if (aCookie.getName().equals(cookieName)) {
                    jmsRealm = aCookie.getValue();
                    log.debug("jmsRealm from cookie [" + jmsRealm + "]");
                }
            }
        }
    }

    for (IAdapter iAdapter : ibisManager.getRegisteredAdapters()) {
        Adapter adapter = (Adapter) iAdapter;
        for (Iterator receiverIt = adapter.getReceiverIterator(); receiverIt.hasNext();) {
            ReceiverBase receiver = (ReceiverBase) receiverIt.next();
            ITransactionalStorage errorStorage = receiver.getErrorStorage();
            if (errorStorage != null) {
                String slotId = errorStorage.getSlotId();
                if (StringUtils.isNotEmpty(slotId)) {
                    SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null);
                    String type = errorStorage.getType();
                    slotmap.put(type + "/" + slotId, sir);
                }
            }
            ITransactionalStorage messageLog = receiver.getMessageLog();
            if (messageLog != null) {
                String slotId = messageLog.getSlotId();
                if (StringUtils.isNotEmpty(slotId)) {
                    SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null);
                    String type = messageLog.getType();
                    slotmap.put(type + "/" + slotId, sir);
                }
            }
        }
        PipeLine pipeline = adapter.getPipeLine();
        if (pipeline != null) {
            for (int i = 0; i < pipeline.getPipeLineSize(); i++) {
                IPipe pipe = pipeline.getPipe(i);
                if (pipe instanceof MessageSendingPipe) {
                    MessageSendingPipe msp = (MessageSendingPipe) pipe;
                    ITransactionalStorage messageLog = msp.getMessageLog();
                    if (messageLog != null) {
                        String slotId = messageLog.getSlotId();
                        if (StringUtils.isNotEmpty(slotId)) {
                            SlotIdRecord sir = new SlotIdRecord(adapter.getName(), null, msp.getName());
                            String type = messageLog.getType();
                            slotmap.put(type + "/" + slotId, sir);
                            slotmap.put(slotId, sir);
                        }
                    }
                }
            }
        }
    }

    List jmsRealms = JmsRealmFactory.getInstance().getRegisteredRealmNamesAsList();
    if (jmsRealms.size() == 0) {
        jmsRealms.add("no realms defined");
    } else {
        if (StringUtils.isEmpty(jmsRealm)) {
            jmsRealm = (String) jmsRealms.get(0);
        }
    }
    showIbisstoreSummaryForm.set("jmsRealms", jmsRealms);

    if (StringUtils.isNotEmpty(jmsRealm)) {

        String formQuery = AppConstants.getInstance().getProperty(SHOWIBISSTOREQUERYKEY);

        String result = "<none/>";

        try {
            IbisstoreSummaryQuerySender qs;
            qs = (IbisstoreSummaryQuerySender) ibisManager.getIbisContext()
                    .createBeanAutowireByName(IbisstoreSummaryQuerySender.class);
            qs.setSlotmap(slotmap);
            try {
                qs.setName("QuerySender");
                qs.setJmsRealm(jmsRealm);
                qs.setQueryType("select");
                qs.setBlobSmartGet(true);
                qs.configure(true);
                qs.open();
                result = qs.sendMessage("dummy", formQuery);
            } catch (Throwable t) {
                error("error occured on executing jdbc query", t);
            } finally {
                qs.close();
            }
        } catch (Exception e) {
            error("error occured on creating or closing connection", e);
        }
        if (log.isDebugEnabled())
            log.debug("result [" + result + "]");
        request.setAttribute("result", result);

    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (mapping.findForward("success"));
    }

    //Successfull: store cookie
    String cookieValue = jmsRealm;
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(Integer.MAX_VALUE);
    log.debug("Store cookie for " + request.getServletPath() + " cookieName[" + cookieName + "] "
            + " cookieValue[" + cookieValue + "]");
    try {
        response.addCookie(cookie);
    } catch (Throwable t) {
        log.warn("unable to add cookie to request. cookie value [" + cookie.getValue() + "]", t);
    }

    log.debug("forward to success");
    return (mapping.findForward("success"));

}

From source file:com.yahoo.yos.YahooFilter.java

private void redirectForAuthorization(OAuthAccessor accessor, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    try {//from  www  .  j  a v a2  s  .  co m
        // get the request token
        List<OAuth.Parameter> callback = OAuth.newList(OAuth.OAUTH_CALLBACK, callbackUrl);
        //client.getRequestToken(accessor, null, callback);
        OAuthMessage message = client.getRequestTokenResponse(accessor, null, callback);
    } catch (URISyntaxException ex) {
        throw new ServletException(ex);
    } catch (OAuthException ex) {
        throw new ServletException(ex);
    }
    if (accessor.requestToken != null) {
        try {
            RequestToken rt = new RequestToken();
            rt.setKey(accessor.requestToken);
            rt.setSecret(accessor.tokenSecret);
            Cookie yosdk_rt = rt.getCookie();
            yosdk_rt.setMaxAge(600);
            response.addCookie(yosdk_rt);
        } catch (JSONException ex) {
            throw new ServletException(ex);
        }
    } else {
        throw new ServletException("Failed to create request token");
    }
    String redirectUrl = OAuth.addParameters(provider.userAuthorizationURL, "oauth_token",
            accessor.requestToken, "oauth_callback", callbackUrl);
    request.setAttribute("yahooRedirect", redirectUrl);
    response.sendRedirect(redirectUrl);
}

From source file:com.appeligo.search.actions.BaseAction.java

protected void setLineup(String lineup) {
    getServletRequest().getSession().setAttribute(LINEUP_ID, lineup);
    Cookie cookie = new Cookie(LINEUP_ID, lineup);
    cookie.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(cookie);/*from   w  ww .j a  v  a 2s  . c o m*/
}

From source file:com.mxgraph.online.drive.FileServlet.java

protected void endSession(HttpServletRequest request, HttpServletResponse response, CredentialMediator mediator)
        throws NoRefreshTokenException, IOException {
    mediator.deleteActiveCredential();/* w w w .  j a v a  2s . c  om*/
    request.getSession().invalidate();
    Cookie cookie = new Cookie("drive", "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    throw new NoRefreshTokenException();
}

From source file:com.duroty.application.admin.utils.AdminDefaultAction.java

/**
 * DOCUMENT ME!//from  ww  w  .j av  a  2s.c  o m
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws LanguageControlException DOCUMENT ME!
 */
protected Locale languageControl(HttpServletRequest request, HttpServletResponse response)
        throws LanguageControlException {
    Preferences preferences = null;
    String language = null;
    String name = Configuration.properties.getProperty(Configuration.COOKIE_LANGUAGE);
    int maxAge = Integer.parseInt(Configuration.properties.getProperty(Configuration.COOKIE_MAX_AGE));

    Cookie cookie = CookieManager.getCookie(name, request);

    if (cookie != null) {
        language = cookie.getValue();
        cookie.setMaxAge(maxAge);
        CookieManager.setCookie("/", cookie, response);
    } else {
    }

    try {
        preferences = getPreferencesInstance(request);
        language = preferences.getPreferences().getLanguage();
    } catch (RemoteException e) {
    } catch (NamingException e) {
    } catch (CreateException e) {
    } catch (MailException e) {
    }

    Boolean b = new Boolean(Configuration.properties.getProperty(Configuration.AUTO_LOCALE));
    boolean autoLocale = b.booleanValue();

    if (language == null) {
        if (!autoLocale) {
            throw new LanguageControlException("Choose Language. The language is empty", null);
        } else {
            language = Configuration.properties.getProperty(Configuration.DEFAULT_LANGUAGE);
        }
    }

    cookie = new Cookie(name, language);
    cookie.setMaxAge(maxAge);
    CookieManager.setCookie("/", cookie, response);

    return new Locale(language);
}

From source file:com.persistent.cloudninja.controller.TenantTaskListController.java

private Cookie getTenantLogoCookieInResponse(String tenantId, String cookieName) {
    String logoUrl = "";
    Tenant tenant = hibernateTemplate.get(Tenant.class, tenantId);
    String logoFilename = tenant.getLogoFileName();
    if (null == logoFilename || logoFilename.trim().length() == 0) {
        logoUrl = "";
    } else {//w  w  w  . ja va 2  s . c o m

        //create logo URL from config property file
        logoUrl = getLogoUrlFromConfig(logoFilename, tenantId);
    }
    Cookie logoCokie = new Cookie("CLOUDNINJALOGO", logoUrl);
    logoCokie.setMaxAge(-1);
    logoCokie.setPath("/");
    return logoCokie;

}

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

/**
 * Creates a new pxt cookie with the specified session id and timeout.
 *
 * @param pxtSessionId The id of the pxt session for which the cookie is being created.
 *
 * @param request The current request./* www.  j  ava2  s.c  o  m*/
 *
 * @param timeout The max age of the cookie in seconds.
 *
 * @return a new pxt cookie.
 */
public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request, int timeout) {

    String cookieName = getCookieName(request);
    String cookieValue = pxtSessionId + "x" + SessionManager.generateSessionKey(pxtSessionId.toString());

    Cookie pxtCookie = new Cookie(cookieName, cookieValue);
    // BZ #454876
    // when not using setDomain, default "Host" will be set for the cookie
    // there's no need to use domain and besides that it causes trouble,
    //  when accessing the server within the local network (without FQDN)
    // pxtCookie.setDomain(request.getServerName());
    pxtCookie.setMaxAge(timeout);
    pxtCookie.setPath(DEFAULT_PATH);
    pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable());

    return pxtCookie;
}