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.appverse.web.framework.backend.frontfacade.rest.authentication.controllers.BasicAuthenticationRESTController.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest/*from  w w  w .  j  a  va 2  s.c  om*/
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("login")
public Response login(@Context HttpServletRequest httpServletRequest,
        @Context HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    // Invalidate session if exists
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null)
        httpSession.invalidate();

    authenticationServiceFacade = (AuthenticationServiceFacade) applicationContext
            .getBean(AUTHENTICATION_SERVICE_NAME);

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return Response.status(Response.Status.UNAUTHORIZED).entity(new AuthorizationDataVO()).build();
    }

    //Create and set the cookie
    httpServletRequest.getSession(true);
    String jsessionId = httpServletRequest.getSession().getId();
    Cookie sessionIdCookie = new Cookie("JSESSIONID", jsessionId);
    httpServletResponse.addCookie(sessionIdCookie);

    // Obtain XSRFToken and add it as a response header
    String xsrfToken = SecurityHelper.createXSRFToken(httpServletRequest);
    httpServletResponse.addHeader(SecurityHelper.XSRF_TOKEN_NAME, xsrfToken);

    // Authenticate principal and return authorization data
    AuthorizationDataVO authData = authenticationServiceFacade.authenticatePrincipal(userNameAndPassword[0],
            userNameAndPassword[1]);

    // AuthorizationDataVO
    return Response.status(Response.Status.OK).entity(authData).build();
}

From source file:com.kingcore.framework.util.CookieUtils.java

/** 
 * Creates a Cookie with the specified name, value and max age,
 * and adds it to the response.//ww  w.j a v a  2 s  . c  o  m
 * cookies  cookie?Base64 ?
 *    The form of the domain name is specified by RFC 2109. A domain name begins with a dot (.foo.com) 
 *       and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone 
 *       (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to 
 *       the server that sent them.
 * @param name cookie's name.
 * @param value cookie's value.
 * @param maxAge the time cookie been keeped. the unit is second.
 *      age of the cookie in seconds,??Cookie.
 *      an integer specifying the maximum age of the cookie in seconds; 
 *      if negative, means the cookie is not stored; if zero, deletes the cookie.
 * @param res response Object.
 * @param needEncode ??Cookie?Base64?true
 * @param domain Cookie's domain
 */
public static void sendCookie(String name, String value, int maxAge, HttpServletResponse response,
        boolean needEncode, String domain) {

    try {
        if (needEncode) {
            value = Base64.encode(value.getBytes("utf-8")); //?
            //              value = new String(Base64.encode( value.getBytes("utf-8")), "utf-8" );   //utf-8
        }
        //System.out.println("value = " + value);
        Cookie cookie = new Cookie(name, value);//Hex.encode(value.getBytes()) );
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        if (domain != null) {
            cookie.setDomain(domain); // domain
        }
        response.addCookie(cookie);

    } catch (UnsupportedEncodingException e) {
        log.debug("debug", e);
        /// e.pri ntStackTrace();
    }

}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

@RequestMapping(value = "/authorize", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView authorize(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = AUTH_SESSION_COOKIE, required = false) String authSessionCookie,
        @CookieValue(value = AUTHORIZATION_REQUEST_COOKIE, required = false) String authorizationRequestCookie)
        throws AuthorizationException {

    AuthorizationRequest authzRequest = null;
    String httpMethod = request.getMethod();
    String authZdecisionKey = request.getParameter(AUTHZ_DECISION_KEY);
    if (authZdecisionKey != null) {
        logger.debug("received valid authZdecisionKey:" + authZdecisionKey);
    }//from ww w .  j  av  a2  s .c o  m

    // not return from /authenticate && not authz decision post
    if (request.getParameterMap().size() > 0 && StringUtils.isEmpty(authZdecisionKey)) {
        // incoming authz request
        authzRequest = parseAuthZrequest(request);
    }

    String authenticatedBusOwner = getAuthenticatedBusOwner(request, authSessionCookie);
    if (null == authenticatedBusOwner) {
        if (null != authzRequest) {
            try {
                logger.info("Persisting authorization request for client: "
                        + authzRequest.get(AuthorizationRequest.Field.CLIENT_ID) + "["
                        + authzRequest.get(AuthorizationRequest.Field.COOKIE) + "]");
                daoFactory.getAuthorizationRequestDAO().persist(authzRequest);
                response.addCookie(new Cookie(AUTHORIZATION_REQUEST_COOKIE,
                        authzRequest.get(AuthorizationRequest.Field.COOKIE)));
            } catch (BackplaneServerException e) {
                throw new AuthorizationException(OAuth2.OAUTH2_AUTHZ_SERVER_ERROR, e.getMessage(), request, e);
            }
        }
        logger.info("Bus owner not authenticated, redirecting to /authenticate");
        return new ModelAndView("redirect:https://" + request.getServerName() + "/v2/authenticate");
    }

    if (StringUtils.isEmpty(authZdecisionKey)) {
        // authorization request
        if (null == authzRequest) {
            // return from /authenticate
            try {
                logger.debug("bp2.authorization.request cookie = " + authorizationRequestCookie);
                authzRequest = daoFactory.getAuthorizationRequestDAO().get(authorizationRequestCookie);
                logger.info("Retrieved authorization request for client:"
                        + authzRequest.get(AuthorizationRequest.Field.CLIENT_ID) + "["
                        + authzRequest.get(AuthorizationRequest.Field.COOKIE) + "]");
            } catch (BackplaneServerException e) {
                throw new AuthorizationException(OAuth2.OAUTH2_AUTHZ_SERVER_ERROR, e.getMessage(), request, e);
            }
        }
        return processAuthZrequest(authzRequest, authSessionCookie, authenticatedBusOwner);
    } else {
        // authZ decision from bus owner, accept only on post
        if (!"POST".equals(httpMethod)) {
            throw new InvalidRequestException(
                    "Invalid HTTP method for authorization decision post: " + httpMethod);
        }
        return processAuthZdecision(authZdecisionKey, authSessionCookie, authenticatedBusOwner,
                authorizationRequestCookie, request);
    }
}

From source file:com.geeksanon.AppController.java

/**
 * Initialise the routes with get and post.
 * //ww w  . j  ava2  s  .co m
 * @throws IOException
 *             when not found
 */
private void intialiseRoutes() throws IOException {

    /**
     * Handle the login of the user.
     */
    Spark.get(new Routes("/login", "login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", "");
            rootMap.put("login_error", "");
            template.process(rootMap, writer);
        }
    });

    Spark.post(new Routes("/login", "login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            LOGGER.info("Username:" + username + "\n" + "Password: " + password);

            DBObject user = userDAO.validateLoginCred(username, password);

            if (user != null) {
                LOGGER.info("Valid user: " + username);
                String sessionID = sessionDAO.startSession(user.get("_id").toString());
                if (sessionID == null) {
                    LOGGER.error("SessionID is null");
                    response.redirect("/_error");
                } else {
                    LOGGER.info("Session ID added to cookie for user:" + username);
                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                HashMap<String, String> rootMap = new HashMap<String, String>();
                rootMap.put("username", StringEscapeUtils.escapeHtml4(username));
                rootMap.put("password", "");
                rootMap.put("login_error", "Invalid Login! Try Again.");
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Handle the signup of the user to create an account.
     */
    Spark.get(new Routes("/signup", "signup.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", "");
            rootMap.put("password", "");
            rootMap.put("email", "");
            rootMap.put("username_error", "");
            rootMap.put("password_error", "");
            rootMap.put("verify_error", "");
            rootMap.put("email_error", "");
            template.process(rootMap, writer);
        }
    });

    Spark.post(new Routes("/signup", "signup.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verifyPassword = request.queryParams("verify");
            String email = request.queryParams("email");

            HashMap<String, String> rootMap = new HashMap<String, String>();
            rootMap.put("username", StringEscapeUtils.escapeHtml4(username));
            rootMap.put("email", StringEscapeUtils.escapeHtml4(email));
            boolean isValid = Helper.validateForm(username, password, verifyPassword, email, rootMap);
            if (isValid) {
                LOGGER.info("Creating user with Username : " + username + "and Password :" + password);
                boolean isAdded = userDAO.addUser(username, password, email);
                if (!isAdded) {
                    rootMap.put("username_error", "Username already exist! Please try another");
                    template.process(rootMap, writer);
                } else {
                    String sessionID = sessionDAO.startSession(username);
                    LOGGER.info("Session ID : " + sessionID);
                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/welcome");
                }
            } else {
                LOGGER.error("Validation failed!!");
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Welcome note to either ask a question, go-home or logout! Handle
     * welcome page.
     */
    Spark.get(new Routes("/welcome", "/welcome_note.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String cookie = Helper.getSessionCookie(request);
            String username = sessionDAO.getUserSessionID(cookie);
            if (username == null) {
                LOGGER.error("Username not found. May be Signup?");
                response.redirect("/signup");
            } else {
                HashMap<String, String> rootMap = new HashMap<String, String>();
                rootMap.put("username", username);
                template.process(rootMap, writer);
            }
        }
    });

    /**
     * Logout from the current session.
     */
    Spark.get(new Routes("/logout", "/login.ftl") {

        @Override
        protected void doHandle(Request request, Response response, StringWriter writer)
                throws IOException, TemplateException {
            String sessionID = Helper.getSessionCookie(request);
            if (sessionID == null) {
                response.redirect("/login");
            } else {
                sessionDAO.stopSession(sessionID);
                Cookie cookie = Helper.getSessionCookieActual(request);
                cookie.setMaxAge(0);
                response.raw().addCookie(cookie);
                response.redirect("/login");
            }
        }
    });

}

From source file:com.laxser.blitz.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }/*  w w  w .  ja  va  2  s.  co m*/
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

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

protected void registerUser(String userId, @SuppressWarnings("hiding") HttpServletResponse response) {
    // cookie token
    byte[] bytes = new byte[8];
    rand.nextBytes(bytes);//from   w ww .j ava 2 s  .  co  m
    String token = Base64.encodeBase64URLSafeString(bytes);

    // FIXME Leak: entries are never removed (allow just one cookie/session per user?)
    if (loggedIn.putIfAbsent(token, userId) != null) {
        throw new IllegalStateException("Token already exists: " + token);
    }

    // set cookie
    Cookie newCookie = new Cookie(COOKIE_NAME, token);
    newCookie.setHttpOnly(true);
    newCookie.setPath(COOKIE_PATH);
    newCookie.setSecure(false); // XXX
    newCookie.setMaxAge(COOKIE_MAX_AGE);
    response.addCookie(newCookie);
}

From source file:com.byd.test.actions.OrderAction.java

License:asdf

@RequestMapping("createCookie")
public void createCookie(HttpServletResponse response) {
    System.out.println("cookie start");
    Cookie cookie = new Cookie("cookie_name", "whatisthis");
    cookie.setHttpOnly(Boolean.TRUE);
    cookie.setDomain("chengangxiong");
    cookie.setVersion(1);//w w  w .j  av a  2s.  c om
    cookie.setMaxAge(15);//15
    response.addCookie(cookie);

}

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }/*from ww  w.  jav a 2s  .  c  o m*/
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        // cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

From source file:csns.web.controller.SectionController.java

@RequestMapping("/section/taken")
public String taken(@RequestParam(required = false) Quarter quarter, ModelMap models, HttpSession session,
        HttpServletResponse response) {//w ww.j a v a  2 s  . c  o  m
    Cookie cookie = new Cookie("default-home", "/section/taken");
    cookie.setPath("/");
    cookie.setMaxAge(100000000);
    response.addCookie(cookie);

    return list("taken", quarter, models, session);
}

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

private void createRememberMeCookie(final User user) {
    try {/* ww  w.j  a  va2s .co  m*/
        final String rememberMeToken = createRememberMeToken(user);
        final Cookie rememberMeCookie = new Cookie(COOKIENAME_RememberMe, rememberMeToken);

        final int maxAge = (int) TimeUnit.SECONDS.convert(cookieMaxAgeDays, TimeUnit.DAYS);
        rememberMeCookie.setMaxAge(maxAge);

        final String path = "/"; // (VaadinService.getCurrentRequest().getContextPath());
        rememberMeCookie.setPath(path);
        VaadinService.getCurrentResponse().addCookie(rememberMeCookie);
        logger.debug("Cookie added for {}: {} (maxAge={}, path={})", user, rememberMeToken, maxAge, path);
    } catch (final Exception e) {
        logger.warn("Failed creating cookie for user: {}. Skipped.", user, e);
    }
}