Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:com.hypersocket.server.HypersocketServerImpl.java

public HypersocketSession setupHttpSession(List<String> cookies, boolean secure,
        HttpServletResponse servletResponse) {

    HypersocketSession session = null;//from  w w  w  .  j a v a 2s .co  m

    for (String header : cookies) {

        StringTokenizer t = new StringTokenizer(header, ";");

        while (t.hasMoreTokens()) {
            String cookie = t.nextToken();
            int idx = cookie.indexOf('=');
            if (idx == -1)
                continue;
            String name = cookie.substring(0, idx).trim();
            if (name.equals(sessionCookieName)) {
                String value = cookie.substring(idx + 1);
                session = HypersocketSessionFactory.getInstance().getSession(value,
                        servletConfig.getServletContext());
                // Check that the session exists in case we have any old
                // cookies
                if (session != null) {
                    break;
                }
            }
        }
    }
    if (session == null) {
        session = HypersocketSessionFactory.getInstance().createSession(servletConfig.getServletContext());
    }

    Cookie cookie = new Cookie(sessionCookieName, session.getId());
    cookie.setMaxAge(60 * 15);
    cookie.setPath("/");
    cookie.setSecure(secure);
    servletResponse.addCookie(cookie);

    return session;
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);//from www  .  j a  v  a2s .  co  m

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}

From source file:hudson.Functions.java

/**
 * Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
 *
 * @param noAutoRefresh//  ww w  . jav  a2 s . co  m
 *      On certain pages, like a page with forms, will have annoying interference
 *      with auto refresh. On those pages, disable auto-refresh.
 */
public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response,
        boolean noAutoRefresh) {
    if (noAutoRefresh)
        return;

    String param = request.getParameter("auto_refresh");
    boolean refresh = isAutoRefresh(request);
    if (param != null) {
        refresh = Boolean.parseBoolean(param);
        Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh));
        // Need to set path or it will not stick from e.g. a project page to the dashboard.
        // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
        // to avoid conflicts with any other web apps that might be on the same machine.
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24 * 30); // persist it roughly for a month
        response.addCookie(c);
    }
    if (refresh) {
        response.addHeader("Refresh", "10");
    }
}

From source file:org.hdiv.filter.ValidatorHelperTest.java

/**
 * Test for cookies integrity./* w  w  w .j  av  a 2 s .  co  m*/
 */
public void testValidateCookiesIntegrity() {

    MockHttpServletRequest request = (MockHttpServletRequest) HDIVUtil.getHttpServletRequest();
    RequestWrapper requestWrapper = new RequestWrapper(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    ResponseWrapper responseWrapper = new ResponseWrapper(response);

    responseWrapper.addCookie(new Cookie("name", "value"));

    this.dataComposer.beginRequest(this.targetName);
    this.dataComposer.compose("param1", "value1", false);
    String pageState = this.dataComposer.endRequest();
    assertNotNull(pageState);
    request.addParameter(hdivParameter, pageState);

    this.dataComposer.endPage();

    // Modify cookie value on client
    request.setCookies(new Cookie[] { new Cookie("name", "changedValue") });

    requestWrapper = new RequestWrapper(request);
    boolean result = helper.validate(requestWrapper).isValid();
    assertFalse(result);
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void addLogoutSessionCookie() throws UnsupportedEncodingException {
    Session session = sessionManager.get(getSessionId());
    if (session != null && session.getAuthnMethod() == AuthnMethod.TLSCLIENT) {
        // set logout session cookie
        String cookieName = Shared.getLogoutCookieName(this.getIdmAccessor().getTenant());
        java.util.Date date = new java.util.Date();
        String timestamp = new Timestamp(date.getTime()).toString();
        String encodedTimestamp = Shared.encodeString(timestamp);
        log.debug("Setting cookie " + cookieName + " value " + encodedTimestamp);
        Cookie sessionCookie = new Cookie(cookieName, encodedTimestamp);
        sessionCookie.setPath("/");
        sessionCookie.setSecure(true);//from ww  w.j a va2  s. co m
        sessionCookie.setHttpOnly(true);
        response.addCookie(sessionCookie);
    }
}

From source file:com.agiletec.plugins.jpcontentfeedback.aps.internalservlet.feedback.ContentFeedbackAction.java

protected void addCookieRating(String contentId) {
    UserDetails currentUser = this.getCurrentUser();
    String cookieName = CheckVotingUtil.getCookieName(currentUser.getUsername(), contentId);
    String cookieValue = CheckVotingUtil.getCookieValue(currentUser.getUsername(), contentId);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(365 * 24 * 60 * 60);//one year
    this.getResponse().addCookie(cookie);
}

From source file:com.bee_wkspace.labee_fw.app.base.AppBaseBlogic.java

/**
 * ??????????<br>//  w  w  w .ja  v a  2  s  .co  m
 * ?????id???<br>
 * ?????5?????????<br>
 * ????<br>
 *
 * @param idName ID??
 * @param value 
 */
protected void addPasswdSetCookie(String idName, String value) {
    Cookie cookie = new Cookie(idName, value);
    cookie.setMaxAge(5);
    bean.addPasswdSetName(idName);
    super.addCookie(cookie);
}

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

private static SpSession getSession(HttpServletRequest request, HttpServletResponse response) {
    BigInteger sessionID = new BigInteger(32, new Random(System.currentTimeMillis()));
    Cookie[] cookies = request.getCookies();
    try {//  w  w w.  jav a  2 s. c o m
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("SigSpSession")) {
                sessionID = new BigInteger(cookie.getValue());
            }
        }
    } catch (Exception ex) {
    }
    response.addCookie(new Cookie("SigSpSession", sessionID.toString()));
    return getSessionFromID(sessionID);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping(value = { "/{userParam}/loggedout", "{userParam}/j_spring_security_logout" })
public String loggedout(@PathVariable String userParam, ModelMap map, HttpSession session,
        HttpServletResponse response, HttpServletRequest request) {
    logger.debug("###Entering in loggedout(response) method");
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }/*from w  w  w  . j  a  v a2  s .  c o  m*/
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("logout", true);
    String redirect = null;
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attr = en.nextElement();
        session.removeAttribute(attr);
    }
    Cookie cookie = new Cookie("JforumSSO", "");
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    if (request.getRequestedSessionId() != null && request.isRequestedSessionIdValid()) {
        // create logout notification begins
        User user = userService.get(userParam);
        String message = "logged.out";
        String messageArgs = user.getUsername();
        eventService.createEvent(new Date(), user, message, messageArgs, Source.PORTAL, Scope.USER,
                Category.ACCOUNT, Severity.INFORMATION, true);
    }
    session.invalidate();
    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLogoutUrl()) ? null
                    : config.getCasLogoutUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }

    SecurityContextHolder.getContext().setAuthentication(null);
    // ends
    logger.debug("###Exiting loggedout(response) method");
    return redirect == null ? "redirect:/j_spring_security_logout" : "redirect:" + redirect;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private static Cookie loginSessionCookie(SessionID sessionId) {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, sessionId.getValue());
    sessionCookie.setPath("/openidconnect-sample-rp");
    sessionCookie.setSecure(true);/*  w  w  w  .  ja  v  a2s  .  co m*/
    sessionCookie.setHttpOnly(true);
    return sessionCookie;
}