Example usage for javax.servlet.http Cookie setValue

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

Introduction

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

Prototype

public void setValue(String newValue) 

Source Link

Document

Assigns a new value to this Cookie.

Usage

From source file:wicket.protocol.http.WebResponse.java

/**
 * Convenience method for clearing a cookie.
 * /*from w  ww .j a v  a 2s .co m*/
 * @param cookie
 *            The cookie to set
 * @see WebResponse#addCookie(Cookie)
 */
public void clearCookie(final Cookie cookie) {
    if (httpServletResponse != null) {
        cookie.setMaxAge(0);
        cookie.setValue(null);
        addCookie(cookie);
    }
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?cookie/*from   w  ww . ja v a  2 s . c o m*/
 * 
 * @param req
 *            
 * @param names
 *            cookie??
 */
public static void purgeCookies(HttpServletRequest req, HttpServletResponse resp, String... names) {
    Set<String> nameSet = ValidationUtils.isEmpty(names) ? null : new HashSet<String>(Arrays.asList(names));
    boolean removeAll = ValidationUtils.isEmpty(nameSet);
    for (Cookie cookie : req.getCookies()) {
        if (removeAll || nameSet.contains(cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            if (!removeAll)
                nameSet.remove(cookie.getName());
            ;
        }
    }
}

From source file:contestWebsite.MainPage.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates");
    ve.init();//  w  w  w.  j  a  va2s .  com
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    Entity user = userCookie != null ? userCookie.authenticateUser() : null;
    boolean loggedIn = (boolean) context.get("loggedIn");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    if (loggedIn && !userCookie.isAdmin()) {
        Entity contestInfo = infoAndCookie.x;
        String endDateStr = (String) contestInfo.getProperty("editEndDate");
        String startDateStr = (String) contestInfo.getProperty("editStartDate");

        Date endDate = new Date();
        Date startDate = new Date();
        try {
            endDate = new SimpleDateFormat("MM/dd/yyyy").parse(endDateStr);
            startDate = new SimpleDateFormat("MM/dd/yyyy").parse(startDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format");
        }

        if (new Date().after(endDate) || new Date().before(startDate)) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Registration editing deadline passed.");
        } else {
            Query query = new Query("registration")
                    .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id")));
            Entity registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);

            String studentData = req.getParameter("studentData");

            JSONArray regData = null;
            try {
                regData = new JSONArray(studentData);
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }

            long price = (Long) infoAndCookie.x.getProperty("price");
            int cost = (int) (0 * price);

            for (int i = 0; i < regData.length(); i++) {
                try {
                    JSONObject studentRegData = regData.getJSONObject(i);
                    for (Subject subject : Subject.values()) {
                        cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    return;
                }
            }

            registration.setProperty("cost", cost);
            registration.setProperty("studentData", new Text(studentData));

            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                datastore.put(registration);
                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }

            resp.sendRedirect("/?updated=1");
        }
    } else if (loggedIn && userCookie.isAdmin()) {
        String username = req.getParameter("email").toLowerCase();
        Query query = new Query("user")
                .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, username));
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
        if (users.size() >= 1) {
            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                query = new Query("authToken").setKeysOnly();
                Filter tokenFilter = new FilterPredicate("token", FilterOperator.EQUAL,
                        URLDecoder.decode(userCookie.getValue(), "UTF-8"));
                Filter expiredFilter = new FilterPredicate("expires", FilterOperator.LESS_THAN, new Date());
                query.setFilter(CompositeFilterOperator.or(tokenFilter, expiredFilter));
                datastore.delete(
                        datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0).getKey());

                userCookie.setMaxAge(0);
                userCookie.setValue("");
                resp.addCookie(userCookie);

                SecureRandom random = new SecureRandom();
                String authToken = new BigInteger(130, random).toString(32);
                Entity token = new Entity("authToken");
                token.setProperty("user-id", username);
                token.setProperty("token", authToken);

                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, 60);
                token.setProperty("expires", new Date(calendar.getTimeInMillis()));

                Cookie cookie = new Cookie("authToken", authToken);
                cookie.setValue(authToken);
                resp.addCookie(cookie);

                datastore.put(token);
                datastore.put(user);
                resp.sendRedirect("/");

                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }
        } else {
            resp.sendRedirect("/?error=1");
        }
    } else {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation");
    }
}

From source file:com.adito.core.CoreUtil.java

/**
 * Store the provided user interface state name / value pair in a cookie
 * /*from  ww w . j  a va 2  s .  c om*/
 * @param name ui state cookie name
 * @param value ui state cookie value
 * @param request request
 * @param response response
 */
public static void storeUIState(String name, String value, HttpServletRequest request,
        HttpServletResponse response) {
    Cookie c = getCookie(name, request);
    if (c != null) {
        c.setValue(value);
    } else {
        c = new Cookie(name, value);
    }
    c.setMaxAge(-1);
    response.addCookie(c);
}

From source file:org.sonar.server.authentication.CsrfVerifier.java

public void verifyState(HttpServletRequest request, HttpServletResponse response) {
    Cookie stateCookie = null;
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (CSRF_STATE_COOKIE.equals(cookie.getName())) {
            stateCookie = cookie;/*from w ww . j a  v a2 s.c om*/
        }
    }
    if (stateCookie == null) {
        throw new UnauthorizedException();
    }
    String hashInCookie = stateCookie.getValue();

    // remove cookie
    stateCookie.setValue(null);
    stateCookie.setMaxAge(0);
    stateCookie.setPath("/");
    response.addCookie(stateCookie);

    String stateInRequest = request.getParameter("state");
    if (isBlank(stateInRequest) || !sha256Hex(stateInRequest).equals(hashInCookie)) {
        throw new UnauthorizedException();
    }
}

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

/**
 * Adds the specified cookie to the response. It can be called multiple times to
 * set more than one cookie.//  ww  w .  j a va2  s. c o  m
 * 
 * @param cookie The <code>Cookie</code> to return to the client
 * @see javax.servlet.http.HttpServletResponse#addCookie
 */
public void addCookie(Cookie cookie) {

    SavedCookie savedCookie = new SavedCookie(cookie);

    this.cookies.put(savedCookie.getName(), savedCookie);
    this.updateSessionCookies();

    if (this.confidentiality && !this.avoidCookiesConfidentiality) {
        cookie.setValue("0");
    }

    super.addCookie(cookie);
}

From source file:wicket.markup.html.form.persistence.CookieValuePersister.java

/**
 * Convenience method for deleting a cookie by name. Delete the cookie by
 * setting its maximum age to zero.//from w  ww.j a  va  2s  .  c  o  m
 * 
 * @param cookie
 *            The cookie to delete
 */
private void clear(final Cookie cookie) {
    if (cookie != null) {
        // Delete the cookie by setting its maximum age to zero
        cookie.setMaxAge(0);
        cookie.setValue(null);

        save(cookie);
    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   ww  w  . j  a v a  2  s .c  o m*/
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}

From source file:controllers.UrlController.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies2 = request.getCookies();
    user_detail = null;//w w  w.j a v  a 2  s  . c om
    if (cookies2 != null) {
        for (Cookie cookie : cookies2) {

            cookie.setValue(null);
            cookie.setMaxAge(0);

            response.addCookie(cookie);

        }
    }
    return "index";
}

From source file:org.orcid.frontend.web.controllers.HomeController.java

@RequestMapping(value = "/userStatus.json")
@Produces(value = { MediaType.APPLICATION_JSON })
public @ResponseBody Object getUserStatusJson(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "logUserOut", required = false) Boolean logUserOut)
        throws NoSuchRequestHandlingMethodException {

    String orcid = getCurrentUserOrcid();

    if (logUserOut != null && logUserOut.booleanValue()) {
        SecurityContextHolder.clearContext();

        if (request.getSession(false) != null) {
            request.getSession().invalidate();
        }//from  w  ww  .  ja  v a  2s  . c om

        logoutCurrentUser(request, response);

        UserStatus us = new UserStatus();
        us.setLoggedIn(false);
        return us;
    } else {
        UserStatus us = new UserStatus();
        us.setLoggedIn((orcid != null));
        if (internalSSOManager.enableCookie()) {
            Cookie[] cookies = request.getCookies();
            //Update cookie 
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (InternalSSOManager.COOKIE_NAME.equals(cookie.getName())) {
                        //If there are no user, just delete the cookie and token
                        if (PojoUtil.isEmpty(orcid)) {
                            cookie.setMaxAge(0);
                            cookie.setValue(StringUtils.EMPTY);
                            response.addCookie(cookie);
                        } else if (internalSSOManager.verifyToken(orcid, cookie.getValue())) {
                            internalSSOManager.updateCookie(orcid, request, response);
                        }
                        break;
                    }
                }
            }
        }
        return us;
    }
}