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.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

private void cookies(MockHttpServletRequest result) {
    String cookieHeaderValue = header("Cookie");
    Cookie[] parentCookies = result.getCookies();
    List<Cookie> cookies = new ArrayList<Cookie>();
    if (cookieHeaderValue != null) {
        StringTokenizer tokens = new StringTokenizer(cookieHeaderValue, "=;");
        while (tokens.hasMoreTokens()) {
            String cookieName = tokens.nextToken().trim();
            if (!tokens.hasMoreTokens()) {
                throw new IllegalArgumentException("Expected value for cookie name " + cookieName
                        + ". Full cookie was " + cookieHeaderValue);
            }/*from w ww . j a v  a  2  s.  c  o  m*/
            String cookieValue = tokens.nextToken().trim();
            processCookie(result, cookies, new Cookie(cookieName, cookieValue));
        }
    }

    Set<com.gargoylesoftware.htmlunit.util.Cookie> managedCookies = cookieManager
            .getCookies(webRequest.getUrl());
    for (com.gargoylesoftware.htmlunit.util.Cookie cookie : managedCookies) {
        processCookie(result, cookies, new Cookie(cookie.getName(), cookie.getValue()));
    }
    if (parentCookies != null) {
        for (Cookie cookie : parentCookies) {
            cookies.add(cookie);
        }
    }
    if (!cookies.isEmpty()) {
        result.setCookies(cookies.toArray(new Cookie[0]));
    }
}

From source file:com.duroty.application.admin.utils.AdminDefaultAction.java

/**
 * DOCUMENT ME!//from   w  w  w.ja va  2 s. com
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws LanguageControlException DOCUMENT ME!
 */
protected Locale languageControl(HttpServletRequest request, HttpServletResponse response)
        throws LanguageControlException {
    Preferences preferences = null;
    String language = null;
    String name = Configuration.properties.getProperty(Configuration.COOKIE_LANGUAGE);
    int maxAge = Integer.parseInt(Configuration.properties.getProperty(Configuration.COOKIE_MAX_AGE));

    Cookie cookie = CookieManager.getCookie(name, request);

    if (cookie != null) {
        language = cookie.getValue();
        cookie.setMaxAge(maxAge);
        CookieManager.setCookie("/", cookie, response);
    } else {
    }

    try {
        preferences = getPreferencesInstance(request);
        language = preferences.getPreferences().getLanguage();
    } catch (RemoteException e) {
    } catch (NamingException e) {
    } catch (CreateException e) {
    } catch (MailException e) {
    }

    Boolean b = new Boolean(Configuration.properties.getProperty(Configuration.AUTO_LOCALE));
    boolean autoLocale = b.booleanValue();

    if (language == null) {
        if (!autoLocale) {
            throw new LanguageControlException("Choose Language. The language is empty", null);
        } else {
            language = Configuration.properties.getProperty(Configuration.DEFAULT_LANGUAGE);
        }
    }

    cookie = new Cookie(name, language);
    cookie.setMaxAge(maxAge);
    CookieManager.setCookie("/", cookie, response);

    return new Locale(language);
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

/**
 * A specific method to enable file download even in a secure (SSL) environment
 * /*from  w  ww.j a v  a2 s  . c  o m*/
 * @param file
 * @param request
 * @param response
 * @throws IOException
 */
public void sendFileDownloadResponse(FileUtil file, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (file == null)
        return;

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(file.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(file.getLength());

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(file.getFile());
    os.close();

}

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

/**
 * Test of deleteCookie method, of class ProxymaResponseDataBean.
 */// www . j a v  a2  s.  c  o m
public void testDeleteCookie() {
    System.out.println("deleteCookie");
    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());

    try {
        instance.deleteCookie(null);
        fail("exception not thrown");
    } catch (NullArgumentException x) {
        assertTrue(true);
    }

    instance.deleteCookie("unexistent");
    result = instance.getCookies();
    assertEquals(2, result.size());

    instance.deleteCookie("name1");
    result = instance.getCookies();
    assertEquals(1, result.size());
}

From source file:com.spshop.web.ShoppingController.java

@RequestMapping(value = "/createAccount", method = RequestMethod.POST)
public String createAccount(Model model, HttpServletRequest request, HttpServletResponse response) {

    String email = request.getParameter(REG_USER_NAME);
    String pwd1 = request.getParameter(REG_PWD);
    String pwd2 = request.getParameter(REG_PWD_RE);

    if (null != email) {
        email = email.trim();//from ww w . j  a  v a  2  s.c om
    }

    String acceptLicense = request.getParameter(ACCEPT_LICENSE);

    User user = new User();
    user.setName(email);
    user.setEmail(email);
    user.setPassword(pwd1);
    user.setCreateDate(new Date());
    user.setUpdateDate(new Date());

    if (!TRUE.equals(acceptLicense)) {
        getUserView().getErr().put(ACCEPT_LICENSE_ERR, "Please accept license");
    }

    String landingpage = null;
    try {
        landingpage = URLDecoder.decode(request.getParameter(LOGIN_LANDING_PAGE_PARAM), "utf-8");
    } catch (Exception e) {
        logger.debug(e.getMessage());
    }

    if (null == email || !(email.contains("@"))) {
        getUserView().getErr().put(REG_USER_NAME_ERR, "Invalid user account");
    } else {
        User u = ServiceFactory.getService(UserService.class).queryUserByEmail(email);
        if (u != null) {
            getUserView().getErr().put(REG_USER_NAME_ERR, "account already exist");
        }
    }

    if (pwd1 == null || pwd1.length() < 5) {
        getUserView().getErr().put(REG_PWD_ERR, "Invalid password");
    } else {
        if (pwd2 == null || !pwd1.equals(pwd2)) {
            getUserView().getErr().put(REG_PWD_RE_ERR, "Two passwords are not same");
        }
    }

    if (getUserView().getErr().isEmpty()) {
        final User u = ServiceFactory.getService(UserService.class).saveUser(user);
        if (null != u) {
            getUserView().getMsg().put(REG_USER_NAME_SUC, "Create Account successfully");
            final Map<String, Object> root = new HashMap<String, Object>();
            root.put("user", u);
            u.setPassword(u.getPassword());

            model.addAttribute(USER_INFO, u);
            request.getSession().setAttribute(USER_INFO, u);
            getUserView().setLoginUser(u);
            Cookie cookie = new Cookie(COOKIE_ACCOUNT,
                    Utils.OBJ.getEncryString(u.getEmail() + USER_NAME_PWD_SPLIT + u.getPassword()));
            cookie.setMaxAge(99999999);
            cookie.setPath("/");
            response.addCookie(cookie);

            new Thread() {
                public void run() {
                    try {
                        EmailTools.sendMail("register", "Welcome to Honeybuy.com, New Member Registration",
                                root, u.getName());
                    } catch (Exception e) {

                    }
                };
            }.start();

        }
    }

    if (StringUtils.isNotBlank(landingpage)) {
        getUserView().setRequestPage(landingpage);
    }
    model.addAttribute(REG_USER, user);

    return "login";
}

From source file:com.hypersocket.netty.HttpRequestServletWrapper.java

@Override
public Cookie[] getCookies() {
    if (cookies == null && getHeader("COOKIE") != null) {
        String tmp = getHeader("COOKIE");
        StringTokenizer t = new StringTokenizer(tmp, ";");
        cookies = new Cookie[t.countTokens()];
        int count = 0;
        while (t.hasMoreTokens()) {
            String nextCookie = t.nextToken().trim();
            int equalsPos = nextCookie.indexOf('=');
            String cookieName = nextCookie.substring(0, equalsPos);
            String cookieValue = nextCookie.substring(equalsPos + 1);
            cookies[count++] = new Cookie(cookieName, cookieValue);
        }//from  w  w w.  j a v a  2 s  . c om
    } else if (cookies == null) {
        cookies = new Cookie[0];
    }
    return cookies;
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Cookie makeAuthTokenCookie(AuthToken attrlist, CookieUse use) {

    String cookieValue = attrlist.getTokenString();

    if (use == CookieUse.EXTERNAL) {
        // Generate digital signature and add to token string
        byte[] signature = generateSignature(cookieValue);
        cookieValue = cookieValue + "-" + Base64.encodeBase64String(signature);
    }//from w  w w .  j a v a2s.com

    logger.debug("Cookie value: " + cookieValue);

    Cookie c = new Cookie(ConfigurationListener.getTokenName(), cookieValue);
    Long expiry = attrlist.getExpirationDate() / 1000L;
    c.setMaxAge(expiry.intValue());
    return c;

}

From source file:com.expressui.core.MainApplication.java

/**
 * Adds a cookie to the HTTP response.//from  w w w  .  ja v a2  s .  co  m
 *
 * @param name  name of the cookie
 * @param value value
 */
public void addCookie(String name, String value) {
    Cookie cookie = new Cookie(name, value);
    cookie.setPath("/");
    getResponse().addCookie(cookie);
}

From source file:com.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody/*from w  w w.  j  a v a 2s .co  m*/
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerOptionalTest.java

@Test
public void testMethod17() {
    ControllerUtil.sendAndReceive(mockMvc, null, null, "remoteProviderOptional", "method17", "theDefaultValue",
            (Object[]) null);//from  w w w. j  av a  2s .com
    ControllerUtil.sendAndReceive(mockMvc, null, Collections.singletonList(new Cookie("stringCookie", "str")),
            "remoteProviderOptional", "method17", "str", (Object[]) null);
}