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.kievguide.controller.UserController.java

@RequestMapping(value = "/settingssave", method = RequestMethod.POST)
public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail,
        @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname,
        @RequestParam("email") String email, @RequestParam("password") String password,
        @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request)
        throws FileNotFoundException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    SecureRandom random = new SecureRandom();
    String photoname = new BigInteger(130, random).toString(32);
    Place place = new Place();

    User user = userService.searchUser(useremail);
    user.setFirstname(firstname);//from   w  w w .ja  va 2 s .c  o  m
    user.setLastname(lastname);
    user.setPassword(password);
    user.setEmail(email);
    if (!file.isEmpty()) {
        String folder = request.getSession().getServletContext().getRealPath("");
        folder = folder.substring(0, 30);
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg")));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        user.setPhotosrc("img/" + photoname + ".jpg");
    }

    userService.addUser(user);
    Cookie userCookie = new Cookie("userstatus", user.getEmail());
    response.addCookie(userCookie);
    String userStatus = Util.userPanel(user.getEmail());
    modelAndView.addObject("userstatus", userStatus);
    return new ModelAndView("redirect:" + "firstrequest");
}

From source file:hudson.plugins.timestamper.TimestampFormatterTest.java

private MarkupText markup(MarkupText markupText) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    Cookie[] cookies = null;/*from  w  w w .ja  v  a  2 s  .c o  m*/
    if (cookieValues != null) {
        cookies = new Cookie[cookieValues.size()];
        for (int i = 0; i < cookieValues.size(); i++) {
            cookies[i] = new Cookie("jenkins-timestamper", cookieValues.get(i));
        }
    }
    when(request.getCookies()).thenReturn(cookies);
    TimestampFormatter formatter = new TimestampFormatter("HH:mm:ss ", "ss.S ", request);
    if (serialize) {
        formatter = (TimestampFormatter) SerializationUtils.clone(formatter);
    }
    formatter.markup(markupText, new Timestamp(123, 42000));
    return markupText;
}

From source file:com.shirokumacafe.archetype.common.utilities.Servlets.java

/**
 * cookie/* w ww. j av a 2  s. c  o  m*/
 */
public static void setCookie(String name, String value, HttpServletResponse response) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge((int) ONE_YEAR_SECONDS);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:com.jredrain.session.HttpSessionFilter.java

private Cookie generateCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie sessionIdCookie;//from w  ww . ja va  2  s  . com
    String sid = null;
    if (StringUtils.isBlank(sid)) {
        sid = CommonUtils.uuid();
    }
    sessionIdCookie = new Cookie(sessionIdCookieName, sid);

    String domain = request.getServerName();

    if (domain != null) {
        sessionIdCookie.setDomain(domain);
    }

    sessionIdCookie.setPath("/");
    response.addCookie(sessionIdCookie);
    return sessionIdCookie;
}

From source file:de.metas.procurement.webui.service.impl.LoginRememberMeService.java

private void removeRememberMeCookie() {
    try {//ww w .j  a v  a  2s. co m
        Cookie cookie = getRememberMeCookie();
        if (cookie == null) {
            return;
        }

        cookie = new Cookie(COOKIENAME_RememberMe, null);
        cookie.setValue(null);
        cookie.setMaxAge(0); // by setting the cookie maxAge to 0 it will deleted immediately
        cookie.setPath("/");
        VaadinService.getCurrentResponse().addCookie(cookie);

        logger.debug("Cookie removed");
    } catch (final Exception e) {
        logger.warn("Failed removing the cookie", e);
    }
}

From source file:com.persistent.cloudninja.web.security.CNAuthenticationProcessingFilter.java

private Cookie createCookie(User user, String currentCookie) {
    String newCookieValue = userDetailsService.createCookieValueFromUser(user);
    String cookieToUse = currentCookie;
    if (!currentCookie.equals(newCookieValue))
        cookieToUse = newCookieValue;/*from  ww  w .ja v  a2  s. co  m*/
    Cookie cookie = new Cookie(cookieName, cookieToUse);
    cookie.setMaxAge(-1);
    cookie.setPath("/");
    return cookie;
}

From source file:iddb.web.security.service.CommonUserService.java

protected void createUserSession(HttpServletRequest request, HttpServletResponse response, Subject subject,
        boolean persistent) {
    HttpSession session = request.getSession(true);
    session.setAttribute(UserService.SUBJECT, subject);
    saveLocal(subject);//  w w w  .java  2s. c  o  m
    String sessionKey = HashUtils.generate(subject.getLoginId());
    session.setAttribute(UserService.SESSION_KEY, sessionKey);
    Cookie cookieKey = new Cookie("iddb-k", sessionKey);
    Cookie cookieUser = new Cookie("iddb-u", subject.getKey().toString());
    cookieKey.setPath(request.getContextPath() + "/");
    cookieUser.setPath(request.getContextPath() + "/");
    if (persistent) {
        cookieKey.setMaxAge(COOKIE_EXPIRE_REMEMBER);
        cookieUser.setMaxAge(COOKIE_EXPIRE_REMEMBER);
    } else {
        cookieKey.setMaxAge(-1);
        cookieUser.setMaxAge(-1);
    }
    response.addCookie(cookieKey);
    response.addCookie(cookieUser);

    log.trace("Create new session {}, {}, {}",
            new String[] { sessionKey, subject.getKey().toString(), request.getRemoteAddr() });
    createSession(sessionKey, subject.getKey(), request.getRemoteAddr());

}

From source file:com.hypersocket.session.json.SessionUtils.java

public void addAPISession(HttpServletRequest request, HttpServletResponse response, Session session) {

    Cookie cookie = new Cookie(HYPERSOCKET_API_SESSION, session.getId());
    cookie.setMaxAge(60 * session.getTimeout());
    cookie.setSecure(request.getProtocol().equalsIgnoreCase("https"));
    cookie.setPath("/");
    //cookie.setDomain(request.getServerName());
    response.addCookie(cookie);//from   www .ja  v  a2 s  . co  m
}

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

@Test
public void testLogoutRequestBack() throws Exception {
    final Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(new Cookie[] { cookie });
    LogoutRequest logoutRequest = new LogoutRequest("", null);
    logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FINISH_EVENT, event.getId());
}

From source file:com.mhe.imagebanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = AmazonServiceUtilTag.getImageThumbnailURL();
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;/*w ww  . j a  v a 2 s.  c o m*/
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId, ASSETBANK_TYPE);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");

        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}