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.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override/*ww  w .j a  v a 2  s .com*/
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:de.eod.jliki.users.utils.UserDBHelper.java

/**
 * Logs in a user returned from database after the login test was made.<br/>
 * @param dbUser the user from database (session may not be closed!)
 * @param passedLogin did the user pass the login test?
 * @param rememberMe will the user stay logged in?
 * @param userLogin the login object/*from  w ww  .ja v a 2 s.c  o m*/
 * @param session the hibernate session for further queries
 * @return true if the user was logged in
 */
private static boolean loginUser(final User dbUser, final boolean passedLogin, final boolean rememberMe,
        final LoginBean userLogin, final Session session) {
    boolean didLogin = false;
    if (passedLogin && dbUser.getActive() == ActiveState.ACTIVE) {
        didLogin = true;
        userLogin.setUserName(dbUser.getName());
        userLogin.setLoggedIn(true);
    } else {
        didLogin = false;
        userLogin.setUserName(userLogin.getUserName());
        userLogin.setLoggedIn(false);
    }

    dbUser.setLastlogin(new Date());

    final UUID loginUUID = UUID.randomUUID();
    Cookie cookie = null;
    final int tenDays = 60 * 60 * 24 * 10;
    if (rememberMe && passedLogin) {
        cookie = new Cookie("login", loginUUID.toString());
        cookie.setMaxAge(tenDays);
        dbUser.setCookieid(loginUUID.toString());
    } else {
        cookie = new Cookie("login", "");
        cookie.setMaxAge(0);
        dbUser.setCookieid("");
    }

    userLogin.clearPermissions();
    dbUser.transferPermissionsToLogin(userLogin);
    for (final UserGroup grp : dbUser.getGroups()) {
        grp.transferPermissionsToLogin(userLogin);
    }

    final HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
            .getExternalContext().getResponse();
    httpServletResponse.addCookie(cookie);

    return didLogin;
}

From source file:cn.vlabs.duckling.vwb.VWBFilter.java

public static void removeGlobalCookie(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) {/* w ww  .  j ava 2  s . c o  m*/
    Cookie oldCookie = new Cookie(COOKIE_NAME, session.getId());
    oldCookie.setPath(request.getContextPath());
    oldCookie.setMaxAge(0);
    response.addCookie(oldCookie);
}

From source file:com.ssbusy.controller.catalog.CategoryController.java

@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView model = new ModelAndView();
    MyCustomer customer = (MyCustomer) CustomerState.getCustomer();

    HttpSession session = request.getSession();
    MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode");
    Boolean w_flag = Boolean.FALSE;
    // cookies//from   w w w .  j a va 2  s  .c o m
    String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    int count = 0;// ??
    Cookie cookies[] = request.getCookies();
    Boolean uiv2 = null;
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (dateTime.equals(c.getName())) {
                count = Integer.valueOf(c.getValue());
                break;
                // } else if ("uiv2".equals(c.getName())) {
                // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie
            }
        }
    }
    if (cookies != null) {
        for (Cookie c : cookies) {
            if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) {
                model.addObject("rember", c.getValue());
                break;
            }
        }
    }
    // String uiParam = request.getParameter("uiv2");
    // if (StringUtils.isNotEmpty(uiParam)) { // 1 param
    // uiv2 = Boolean.valueOf(uiParam);
    // Cookie c = new Cookie("uiv2", uiv2.toString());
    // c.setPath("/");
    // c.setMaxAge(60 * 60 * 24 * 360);
    // response.addCookie(c);
    // } else if (uiv2 == null) {
    uiv2 = Boolean.TRUE; // 3 default. 
    // }
    session.setAttribute("uiv2", uiv2);
    // LOG.warn("uiv2=" + uiv2);

    if (myOfferCode != null) {
        if (customer.isRegistered())
            giftService.updateOwnerCustomer(customer, myOfferCode);
        else
            myOfferCode = null;
    } else if (count < maxoffercodeCount) {
        myOfferCode = giftService.getgift(customer);
        if (myOfferCode != null) {
            if (customer.isAnonymous()) {
                session.setAttribute("bonusOfferCode", myOfferCode);
                model.addObject("bonusOfferCode", myOfferCode);
                myOfferCode = null;
            }
        }
    }
    if (myOfferCode != null) {
        session.removeAttribute("bonusOfferCode");
        model.addObject("bonusOfferCode", myOfferCode);
        Cookie c = new Cookie(dateTime, String.valueOf(count + 1));
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24);
        response.addCookie(c);
        LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr());
    }

    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the
        // field to the
        // product search criteria expected format. This is used in
        // multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical
        // URLs

        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }

        parameters.remove(ProductSearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");

        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        model.setViewName("redirect:" + newUrl);
    } else {
        // Else, if we received a GET to the category URL (either the user
        // clicked this link or we redirected
        // from the POST method, we can actually process the results

        Category category = (Category) request
                .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME);
        assert (category != null);

        List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category);
        ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets);

        String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING);
        ProductSearchResult result;

        List<FulfillmentLocation> locations = null;
        try {
            // 
            if (customer != null && customer.getRegion() != null) {
                InventorySolrSearchServiceExtensionHandler.customerLocation
                        .set(locations = customer.getRegion().getFulfillmentLocations());
            }
            if (StringUtils.isNotBlank(searchTerm)) {
                result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria);
            } else {
                result = searchService.findProductsByCategory(category, searchCriteria);
            }
        } finally {
            InventorySolrSearchServiceExtensionHandler.customerLocation.remove();
        }

        facetService.setActiveFacetResults(result.getFacets(), request);
        List<Product> products = result.getProducts();

        if (products != null && products.size() > 0) {
            List<String> prodIds = new ArrayList<String>(products.size());
            for (Product product : products) {
                prodIds.add(String.valueOf(product.getId()));
            }
            model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT));

            // ?productinventories
            if (locations != null) {
                Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations);
                model.addObject("inventories", invs);
            }
        }

        model.addObject(PRODUCTS_ATTRIBUTE_NAME, products);
        model.addObject(CATEGORY_ATTRIBUTE_NAME, category);
        // facets
        List<SearchFacetDTO> facets = result.getFacets();
        if (facets != null) {
            _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) {
                SearchFacetDTO dto = itr.next();
                if (dto != null && dto.getFacetValues() != null) {
                    for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) {
                        if (searchFacetDTO != null)
                            if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0)
                                continue _nextFact;
                    }
                }
                itr.remove();
            }
            model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets());
        }
        model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);

        // TODO temp
        String view = category.getDisplayTemplate();
        if (StringUtils.isEmpty(view))
            view = getDefaultCategoryView();
        if (request.getRequestURI().startsWith("/weixin/")) {
            view = "weixin/catalog/w_category_item";
            w_flag = Boolean.TRUE;
        }
        if (uiv2) {
            if ("layout/home".equals(view))
                view = "v2/home";
            else {
                if (!view.startsWith("activity") && !view.startsWith("weixin/")) {
                    view = "v2/" + view;
                }

            }
        }
        session.setAttribute("w_flag", w_flag);
        model.setViewName(view);
    }
    // if (isAjaxRequest(request)) {
    // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM);
    // model.addObject("ajax", Boolean.TRUE);
    // }
    return model;
}

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

@SuppressWarnings("unchecked")
@Test//ww  w . jav  a  2  s.  c o  m
public void testLogoutRequestFront() throws Exception {
    final Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(new Cookie[] { cookie });
    final LogoutRequest logoutRequest = new LogoutRequest("", null);
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FRONT_EVENT, event.getId());
    List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, logoutRequests.size());
    assertEquals(logoutRequest, logoutRequests.get(0));
}

From source file:com.traffitruck.web.HtmlController.java

private void setSessionCookie(HttpServletResponse response, String regid, int expiry) {
    Cookie cookie = new Cookie(DEVICE_REGISTRATION_COOKIE_NAME, regid);
    cookie.setMaxAge(expiry);//from ww w  .  ja v a2s.  c om
    cookie.setHttpOnly(true);
    // cookie.setSecure(true);
    response.addCookie(cookie);
}

From source file:com.vmm.storefront.controllers.pages.ProductPageController.java

@RequestMapping(value = PRODUCT_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
public String productDetail(@PathVariable("productCode") final String productCode, final Model model,
        final HttpServletRequest request, final HttpServletResponse response,
        @CookieValue(value = "lastBrowsedProducts", defaultValue = "") String lastBrowsedProducts)
        throws CMSItemNotFoundException, UnsupportedEncodingException {

    // Count of products to be maintained in Cookie
    final int countOfProducts = 20;

    System.out.println("praveen cookie value======" + lastBrowsedProducts);

    if (lastBrowsedProducts.equalsIgnoreCase("")) {
        lastBrowsedProducts = productCode;
    } else {/*from  w ww.  ja va  2  s  .c o m*/
        lastBrowsedProducts = listLatestBrowsedProducts(lastBrowsedProducts, productCode, countOfProducts);
    }
    final Cookie foo = new Cookie("lastBrowsedProducts", lastBrowsedProducts);
    foo.setMaxAge(9999999);
    foo.setPath("/");
    response.addCookie(foo);

    System.out.println("praveen cookie added value------------------" + lastBrowsedProducts);

    final List<ProductOption> extraOptions = Arrays.asList(ProductOption.VARIANT_MATRIX_BASE,
            ProductOption.VARIANT_MATRIX_URL, ProductOption.VARIANT_MATRIX_MEDIA);

    final ProductData productData = productFacade.getProductForCodeAndOptions(productCode, extraOptions);

    final String redirection = checkRequestUrl(request, response, productDataUrlResolver.resolve(productData));
    if (StringUtils.isNotEmpty(redirection)) {
        return redirection;
    }

    updatePageTitle(productCode, model);

    populateProductDetailForDisplay(productCode, model, request, extraOptions);

    model.addAttribute(new ReviewForm());
    model.addAttribute("pageType", PageType.PRODUCT.name());
    model.addAttribute("futureStockEnabled", Boolean.valueOf(Config.getBoolean(FUTURE_STOCK_ENABLED, false)));

    final String metaKeywords = MetaSanitizerUtil.sanitizeKeywords(productData.getKeywords());
    final String metaDescription = MetaSanitizerUtil.sanitizeDescription(productData.getDescription());
    setUpMetaData(model, metaKeywords, metaDescription);
    return getViewForPage(model);
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnResponse(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    String remoteAddress = request.getRemoteAddr();
    this.logger.debug("[Authn for {}] Going to process authentication response.", remoteAddress);

    String base64SAMLDocument = request.getParameter("SAMLResponse");
    if (base64SAMLDocument == null || base64SAMLDocument.length() == 0) {
        throw new AuthenticationException(
                "SAMLResponse request parameter was null. Unable to process response.");
    }//from   w w w  .  ja v a2 s  .co m

    byte[] samlDocument;
    try {
        samlDocument = Base64.decodeBase64(base64SAMLDocument.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationException(
                "Unable to complete authentication because a required character encoding is not supported.", e);
    }
    // Use the AuthnProcessor to unmarshal the response document.
    Response responseObject = spep.getAuthnProcessor().unmarshalResponse(samlDocument);
    this.logger.info(
            "[Authn for {}] Got an authentication response, going to process. Response ID: {}  InResponseTo: {}",
            new Object[] { remoteAddress, responseObject.getID(), responseObject.getInResponseTo() });

    spep.getAuthnProcessor().processAuthnResponse(data, responseObject);

    String sessionID = data.getSessionID();
    if (sessionID == null) {
        throw new AuthenticationException(
                "Session identifier from AuthnProcessor was null. Unable to process SSO event");
    }

    Cookie cookie = new Cookie(spep.getTokenName(), sessionID);

    cookie.setPath("/");
    response.addCookie(cookie);

    try {
        String redirectURL = null;
        String base64RequestURL = data.getRequestURL();
        if (base64RequestURL != null) {
            redirectURL = new String(Base64.decodeBase64(base64RequestURL.getBytes()));
        } else {
            redirectURL = spep.getDefaultUrl();
        }

        this.logger.info(
                "[Authn for {}] Processed response ID: {} .. Created local session with session ID: {}  Redirecting user to requested content: {}",
                new Object[] { remoteAddress, responseObject.getID(), sessionID, redirectURL });

        response.sendRedirect(redirectURL);
    } catch (IOException e) {
        throw new AuthenticationException(
                "Unable to send redirect back to authenticated content as an I/O error occurred", e);
    }
}

From source file:m.c.m.proxyma.resource.ProxymaResponseDataBeanTest.java

/**
 * Test of getCookies method, of class ProxymaResponseDataBean.
 *//*  w w  w  .jav a 2s . c  om*/
public void testGetCookies() {
    System.out.println("getCookies");
    ProxymaResponseDataBean instance = new ProxymaResponseDataBean();
    instance.addCookie(new Cookie("name1", "value1"));
    instance.addCookie(new Cookie("name2", "value2"));
    instance.addCookie(new Cookie("name1", "value3"));

    Collection<Cookie> result = instance.getCookies();
    assertEquals(2, result.size());

    //Test multi values header
    Iterator<Cookie> iter = result.iterator();
    Cookie cookie = iter.next();
    if ("name1".equals(cookie.getName())) {
        assertEquals("value3", cookie.getValue());
        assertEquals("value2", iter.next().getValue());
    } else {
        assertEquals("name2", cookie.getName());
        assertEquals("value2", cookie.getValue());
        assertEquals("value3", iter.next().getValue());
    }

    instance = new ProxymaResponseDataBean();
    result = instance.getCookies();
    assertEquals(0, result.size());
}

From source file:com.pureinfo.tgirls.sns.servlet.SNSEntryServlet.java

private void addCookie(User _loginUser, HttpServletRequest _request, HttpServletResponse _response)
        throws UnsupportedEncodingException {
    Cookie name = new Cookie(CookieUtils.NAME, URLEncoder.encode(_loginUser.getName(), "utf-8"));
    Cookie nickName = new Cookie(CookieUtils.NICK_NAME, URLEncoder.encode(_loginUser.getNickname(), "utf-8"));
    Cookie taobaoId = new Cookie(CookieUtils.TAOBAO_ID, URLEncoder.encode(_loginUser.getTaobaoID(), "utf-8"));
    Cookie img = new Cookie(CookieUtils.HEAD_IMG, URLEncoder.encode(_loginUser.getHeadImg(), "utf-8"));
    Cookie topsession = new Cookie(CookieUtils.TOP_SESSION_ID,
            _request.getParameter(APPConstants.REQ_PARAMETER_SESSION));

    _response.addCookie(name);/*from w  w w.j av  a2 s  . com*/
    _response.addCookie(nickName);
    _response.addCookie(taobaoId);
    _response.addCookie(img);
    _response.addCookie(topsession);

}