List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:com.ax.utils.CookieUtils.java
/** * Stores a value in a cookie. This cookie will persist for the amount * specified in the <tt>saveTime</tt> parameter. * //from www. ja v a 2 s .co m * @see #setCookie(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,String,String) * @param request * the servlet request. * @param response * the servlet response. * @param name * a name to identify the cookie. * @param value * the value to store in the cookie. * @param maxAge * the time (in seconds) this cookie should live. * @param domain * the domain. * @param path * the path. */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge, String domain, String path) { // Check to make sure the new value is not null (appservers like Tomcat // 4 blow up if the value is null). if (value == null) { value = ""; } if (StringUtils.isEmpty(path)) { path = "/"; } Cookie cookie = new Cookie(name, value); // maxAge0cookiemaxAge // if (maxAge > 0) // { cookie.setMaxAge(maxAge); // } cookie.setPath(path); // domain?cookiedomain if (!StringUtils.isEmpty(domain)) { cookie.setDomain(domain); } response.addCookie(cookie); }
From source file:org.syncope.console.commons.PreferenceManager.java
public void set(final Request request, final Response response, final Map<String, List<String>> prefs) { Cookie prefCookie = ((WebRequest) request).getCookie(Constants.PREFS_COOKIE_NAME); final Map<String, String> current = new HashMap<String, String>(); if (prefCookie == null || !StringUtils.hasText(prefCookie.getValue())) { prefCookie = new Cookie(Constants.PREFS_COOKIE_NAME, null); } else {//from w w w . j ava 2 s. co m current.putAll(getPrefs(new String(Base64.decodeBase64(prefCookie.getValue().getBytes())))); } // after retrieved previous setting in order to overwrite the key ... for (Entry<String, List<String>> entry : prefs.entrySet()) { current.put(entry.getKey(), StringUtils.collectionToDelimitedString(entry.getValue(), ";")); } try { prefCookie.setValue(new String(Base64.encodeBase64(setPrefs(current).getBytes()))); } catch (IOException e) { LOG.error("Could not set preferences " + current, e); } prefCookie.setMaxAge(ONE_YEAR_TIME); ((WebResponse) response).addCookie(prefCookie); }
From source file:gr.abiss.calipso.userDetails.util.SecurityUtil.java
/** * Writes a cookie to the response. In case of a blank value the method will * set the max age to zero, effectively marking the cookie for immediate * deletion by the client if the <code>allowClear</code> is true or throw an exception if false. * Blank value strings mark cookie deletion. If * @param response/*from ww w . j a va 2s . co m*/ * @param cookieName * @param cookieValue * @param allowClear */ private static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean allowClear, UserDetailsConfig userDetailsConfig) { if (StringUtils.isBlank(cookieValue) && !allowClear) { throw new RuntimeException( "Was given a blank cookie value but allowClear is false for cookie name: " + cookieName); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("addCookie, cookieName: " + cookieName + ", cookie value: " + cookieValue + ", domain: " + userDetailsConfig.getCookiesDomain() + ", secure: " + userDetailsConfig.isCookiesSecure() + ", http-only: " + userDetailsConfig.isCookiesHttpOnly() + ", path: " + userDetailsConfig.getCookiesContextPath()); } Cookie cookie = new Cookie(cookieName, cookieValue); // set the cookie domain if (StringUtils.isNotBlank(userDetailsConfig.getCookiesDomain())) { cookie.setDomain('.' + userDetailsConfig.getCookiesDomain()); } // maybe not a good idea unless you can trust the proxy // else if (StringUtils.isNotBlank(request.getHeader("X-Forwarded-Host"))) { // cookie.setDomain('.' + request.getHeader("X-Forwarded-Host")); // } // else{ // cookie.setDomain('.' + request.getLocalName()); // // } // set the cookie path if (StringUtils.isNotBlank(userDetailsConfig.getCookiesContextPath())) { cookie.setPath(userDetailsConfig.getCookiesContextPath()); } // else { // cookie.setPath("/"); // } cookie.setSecure(userDetailsConfig.isCookiesSecure()); cookie.setHttpOnly(userDetailsConfig.isCookiesHttpOnly()); if (StringUtils.isBlank(cookieValue)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("addCookie, setting max-age to 0 to clear cookie: " + cookieName); } cookie.setMaxAge(0); } response.addCookie(cookie); }
From source file:ch.ralscha.extdirectspring.controller.RouterControllerSimpleNamedTest.java
@Test public void testNonStrictMethod3() { List<Cookie> cookies = new ArrayList<Cookie>(); cookies.add(new Cookie("aSimpleCookie", "cookie")); HttpHeaders headers = new HttpHeaders(); headers.add("aSimpleHeader", "header"); Map<String, Object> params = new LinkedHashMap<String, Object>(); params.put("i", 17); ControllerUtil.sendAndReceiveNamed(mockMvc, headers, cookies, "remoteProviderSimpleNamed", "nonStrictMethod3", "nonStrictMethod3() called-17-cookie-header", params); }
From source file:org.bpmscript.web.BpmScriptCookieController.java
@SuppressWarnings("unchecked") protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(contentType); String requestUri = request.getRequestURI(); String definitionName = null; String methodName = null;/*from w w w. j a v a2 s . c om*/ String split[] = request.getRequestURI().split("/"); if (requestUri.endsWith("/")) { definitionName = split[split.length - 1]; methodName = defaultIndexName; } else { definitionName = split[split.length - 2]; methodName = split[split.length - 1].split("\\.")[0]; } String correlationIdParam = null; String cookieName = cookiePrefix + StringUtils.capitalize(definitionName) + StringUtils.capitalize(methodName); Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { String name = cookie.getName(); if (cookieName.equals(name)) { correlationIdParam = cookie.getValue(); } } String timeoutParam = request.getParameter("timeout"); long timeout = defaultTimeout; if (timeoutParam != null) { try { timeout = Integer.parseInt(timeoutParam); } catch (NumberFormatException e) { log.debug(e); } } try { SerializableHttpServletRequest serializableHttpServletRequest = new SerializableHttpServletRequest( request); if (correlationIdParam == null) { Object result = null; String conversationId = null; Object message = bpmScriptFacade.call(definitionName, methodName, timeout, serializableHttpServletRequest); if (message instanceof IInvocationMessage) { IInvocationMessage conversationMessage = (IInvocationMessage) message; result = conversationMessage.getArgs()[0]; conversationId = conversationMessage.getCorrelationId(); } else { result = message; } if (result instanceof Map) { Map<String, Object> map = (Map<String, Object>) result; if (conversationId != null) { map.put("conversationId", conversationId); response.addCookie(new Cookie(cookieName, conversationId)); } ModelAndView modelAndView = new ModelAndView((String) map.get("view"), map); return modelAndView; } else { throw new Exception("result must be a map or a conversation"); } } else { IInvocationMessage conversationMessage = null; conversationMessage = (IInvocationMessage) conversationCorrelator.call(correlationIdParam, timeout, serializableHttpServletRequest); if (conversationMessage != null) { Map<String, Object> result = (Map<String, Object>) conversationMessage.getArgs()[0]; String conversationId = conversationMessage.getCorrelationId(); result.put("conversationId", conversationId); String replyTo = conversationMessage.getReplyTo(); Cookie cookie = new Cookie(cookieName, conversationId); if (replyTo == null) { cookie.setMaxAge(0); } response.addCookie(cookie); ModelAndView modelAndView = new ModelAndView((String) result.get("view"), result); return modelAndView; } else { Cookie cookie = new Cookie(cookieName, ""); cookie.setMaxAge(0); response.addCookie(cookie); throw new Exception("Did not get a response for message " + correlationIdParam); } } } catch (Throwable e) { if (e instanceof Exception) { throw (Exception) e; } else { throw new Exception(e); } } }
From source file:io.soabase.web.filters.LanguageFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; AtomicReference<String> fixedQueryString = new AtomicReference<>(); String queryStringCode = getFromQueryString(httpRequest.getQueryString(), fixedQueryString); String expectedLanguageCode = MoreObjects.firstNonNull(queryStringCode, getLanguageCode(null, getCookie(httpRequest))); HttpServletResponse httpResponse = (HttpServletResponse) response; Optional<String> foundCookie = getCookie(httpRequest); if (!foundCookie.isPresent() || !foundCookie.get().equals(expectedLanguageCode)) { Cookie cookie = new Cookie(cookieName, expectedLanguageCode); httpResponse.addCookie(cookie); }//from w w w . jav a2 s . com if (queryStringCode != null) { StringBuffer redirectUrl = httpRequest.getRequestURL(); if (!fixedQueryString.get().isEmpty()) { redirectUrl.append("?").append(fixedQueryString.get()); } ((HttpServletResponse) response).sendRedirect(redirectUrl.toString()); return; } } chain.doFilter(request, response); }
From source file:com.nominanuda.web.http.ServletHelper.java
public Cookie servletCookie(HttpCookie c) { Cookie _c = new Cookie(c.getName(), c.getValue()); if (c.getComment() != null) { _c.setComment(c.getComment());/* w w w . ja v a 2 s. com*/ } if (c.getDomain() != null) { _c.setDomain(c.getDomain()); } if (c.getPath() != null) { _c.setPath(c.getPath()); } _c.setSecure(c.getSecure()); _c.setVersion(c.getVersion()); _c.setHttpOnly(c.getDiscard()); _c.setMaxAge((int) c.getMaxAge()); return _c; }
From source file:com.xwiki.authentication.AbstractSSOAuthServiceImpl.java
protected XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException { Cookie cookie;//from w w w.j a v a2 s .c om LOG.debug("checkAuth"); LOG.debug("Action: " + context.getAction()); if (context.getAction().startsWith("logout")) { cookie = getCookie(COOKIE_NAME, context); if (cookie != null) { cookie.setMaxAge(0); context.getResponse().addCookie(cookie); } return null; } Principal principal = null; if (LOG.isDebugEnabled()) { Cookie[] cookies = context.getRequest().getCookies(); if (cookies != null) { for (Cookie c : cookies) { LOG.debug("CookieList: " + c.getName() + " => " + c.getValue()); } } } cookie = getCookie(COOKIE_NAME, context); if (cookie != null) { LOG.debug("Found Cookie"); String uname = decryptText(cookie.getValue(), context); if (uname != null) { principal = new SimplePrincipal(uname); } } XWikiUser user; // Authenticate if (principal == null) { principal = authenticate(username, password, context); if (principal == null) { return null; } LOG.debug("Saving auth cookie"); String encuname = encryptText(principal.getName().contains(":") ? principal.getName() : context.getDatabase() + ":" + principal.getName(), context); Cookie usernameCookie = new Cookie(COOKIE_NAME, encuname); usernameCookie.setMaxAge(-1); usernameCookie.setPath("/"); context.getResponse().addCookie(usernameCookie); user = new XWikiUser(principal.getName()); } else { user = new XWikiUser(principal.getName().startsWith(context.getDatabase()) ? principal.getName().substring(context.getDatabase().length() + 1) : principal.getName()); } return user; }
From source file:org.moserp.infrastructure.gateway.config.OAuthConfiguration.java
/** * Spring security offers in-built protection for cross site request forgery * (CSRF) by needing a custom token in the header for any requests that are * NOT safe i.e. modify the resources from the server e.g. POST, PUT & PATCH * etc.<br>/* w ww .ja v a 2s . c om*/ * <br> * * This protection is achieved using cookies that send a custom value (would * remain same for the session) in the first request and then the front-end * would send back the value as a custom header.<br> * <br> * * In this method we create a filter that is applied to the web security as * follows: * <ol> * <li>Spring security provides the CSRF token value as a request attribute; * so we extract it from there.</li> * <li>If we have the token, Angular wants the cookie name to be * "XSRF-TOKEN". So we add the cookie if it's not there and set the path for * the cookie to be "/" which is root. In more complicated cases, this might * have to be the context root of the api gateway.</li> * <li>We forward the request to the next filter in the chain</li> * </ol> * * The request-to-cookie filter that we add needs to be after the * <code>csrf()</code> filter so that the request attribute for CsrfToken * has been already added before we start to process it. * * @return */ private Filter createCSRFHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME); String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie(CSRF_COOKIE_NAME, token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; }