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:org.owasp.dependencytrack.controller.LoginController.java

/**
 * Login action./*  w  w  w  .  j  a va  2 s . co m*/
 *
 * @param request a HttpServletRequest object
 * @param response a HttpServletResponse object
 * @return a String
 */
@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.HEAD })
public String login(HttpServletRequest request, HttpServletResponse response) {
    setLdapStatus(request, false);
    response.addCookie(new Cookie("CONTEXTPATH", getServletContext().getContextPath()));
    final String s = "loginPage";
    if (SecurityUtils.getSubject().isAuthenticated()) {
        return "redirect:/dashboard";
    }
    return s;
}

From source file:Controller.login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w  w .  j a v  a 2s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String email = request.getParameter("inputEmail");
    String password = request.getParameter("inputPassword");
    String remember = request.getParameter("remember");

    System.out.println("remember ne mnow " + email);

    LoginImplementation loginCheckObject = new LoginImplementation();

    JSONObject userData = (loginCheckObject.loginNow(email, password, remember));
    System.out.println(userData);
    if (userData.has("error")) {
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        request.setAttribute("loginError", "error");
        rd.include(request, response);

    } else {

        if ("yes".equals(remember)) {
            System.out.println("apples");
            HttpSession session = request.getSession();
            session.setAttribute("user", userData);
            //setting session to expiry in 30 mins
            session.setMaxInactiveInterval(30 * 60);
            Cookie userName = new Cookie("user", email);
            userName.setMaxAge(30 * 60);
            response.addCookie(userName);
        }
        request.setAttribute("userData", userData);
        RequestDispatcher rd = request.getRequestDispatcher("views/home.jsp");
        rd.forward(request, response);
        return;
    }

    out.close();
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void addLastLoginCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie(Constants.OPINTONI_LAST_LOGIN, timeService.nowUTCAsString());
    addCookie(response, cookie);
}

From source file:de.berlios.jhelpdesk.web.preferences.LookAndFeelEditController.java

private Cookie createCookie(HttpServletRequest req, Locale loc) {
    Cookie cookie = new Cookie("jhd_locale", loc.getLanguage());
    cookie.setMaxAge(SECONDS_BY_WEEK);//from  w  w  w . j  ava2s.  c  o  m
    cookie.setPath(req.getContextPath());
    return cookie;
}

From source file:com.google.youtube.captions.AuthSubLogin.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {//from  www.ja v a2  s. c o m
        String authSubToken = AuthSubUtil.getTokenFromReply(req.getQueryString());
        if (authSubToken == null) {
            throw new IllegalStateException("Could not parse token from AuthSub response.");
        } else {
            authSubToken = URLDecoder.decode(authSubToken, "UTF-8");
        }

        authSubToken = AuthSubUtil.exchangeForSessionToken(authSubToken, null);

        YouTubeService service = new YouTubeService(SystemProperty.applicationId.get(), Util.DEVELOPER_KEY);
        service.setAuthSubToken(authSubToken);

        UserProfileEntry profileEntry = service.getEntry(new URL(PROFILE_URL), UserProfileEntry.class);
        String username = profileEntry.getUsername();

        String authSubCookie = Util.getCookie(req, Util.AUTH_SUB_COOKIE);
        JSONObject cookieAsJSON = new JSONObject();
        if (!Util.isEmptyOrNull(authSubCookie)) {
            try {
                cookieAsJSON = new JSONObject(authSubCookie);
            } catch (JSONException e) {
                LOG.log(Level.WARNING, "Unable to parse JSON from the existing cookie: " + authSubCookie, e);
            }
        }

        try {
            cookieAsJSON.put(username, authSubToken);
        } catch (JSONException e) {
            LOG.log(Level.WARNING,
                    String.format("Unable to add account '%s' and AuthSub token '%s'" + " to the JSON object.",
                            username, authSubToken),
                    e);
        }

        Cookie cookie = new Cookie(Util.AUTH_SUB_COOKIE, cookieAsJSON.toString());
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);

        cookie = new Cookie(Util.CURRENT_AUTHSUB_TOKEN, authSubToken);
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);

        cookie = new Cookie(Util.CURRENT_USERNAME, username);
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);
    } catch (IllegalStateException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (AuthenticationException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (GeneralSecurityException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (ServiceException e) {
        LOG.log(Level.WARNING, "", e);
    }

    resp.sendRedirect("/");
}

From source file:org.jasig.cas.web.flow.SendTicketGrantingTicketActionTests.java

@Test
public void testTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String TICKET_VALUE = "test";
    request.setCookies(new Cookie[] { new Cookie("TGT", "test5") });
    WebUtils.putTicketGrantingTicketInRequestScope(this.context, TICKET_VALUE);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(TICKET_VALUE, response.getCookies()[0].getValue());
}

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);/*from   w w w. j  a v  a  2s .  c  o m*/
    response.addCookie(cookie);
}

From source file:com.companyname.services.PlatCookieService.java

public void invalidateCookie(HttpServletRequest request, HttpServletResponse response, String _cookieName) {
    logger.info("cancelling cookie named: " + _cookieName);

    // if cookie does not exist, do nothing
    Cookie cookie = getCookie(request, _cookieName);

    if (cookie == null) {
        return;//from  w w  w .  ja v  a 2s  . c  o  m
    }

    cookie = new Cookie(_cookieName, null);
    cookie.setValue("");
    cookie.setMaxAge(0);
    cookie.setPath(getCookiePath());
    cookie.setDomain(getCookieDomain());
    response.addCookie(cookie);
}

From source file:com.ms.commons.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response/* w w w.  jav a 2  s .  co  m*/
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = CookieUtils.encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDefaultPath() {
    cookieGenerator.setCookieName("guid");
    cookieGenerator.setHttpOnly(true);//server side

    BDDMockito.given(request.getContextPath()).willReturn("/some_path");

    cookieGenerator.addCookie(response, "cookie_monster");

    final Cookie expectedCookie = new Cookie("guid", "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);/*w ww. j a v a  2s .c om*/
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "guid=cookie_monster; Domain=\"what a domain\"; Path=/; HttpOnly");

}