List of usage examples for javax.servlet.http Cookie getValue
public String getValue()
From source file:csns.web.filter.DepartmentFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String contextPath = request.getContextPath(); String path = request.getRequestURI().substring(contextPath.length()); Cookie cookie = WebUtils.getCookie(request, "default-dept"); if (path.startsWith("/department/")) { int beginIndex = "/department/".length(); int endIndex = path.indexOf("/", beginIndex); if (endIndex < 0) endIndex = path.length();/*from w w w. j a va2 s . com*/ String dept = path.substring(beginIndex, endIndex); request.setAttribute("dept", dept); logger.debug(path + " -> " + dept); if (cookie == null) { cookie = new Cookie("default-dept", dept); cookie.setPath("/"); cookie.setMaxAge(100000000); response.addCookie(cookie); } } else { if (cookie != null) request.setAttribute("dept", cookie.getValue()); } filterChain.doFilter(request, response); }
From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java
/** * Adds a cookie to the response.// ww w . j av a2 s . c o m * * @param response The servlet response. * @param cookie The cookie to be sent. */ private void addCookie(HttpServletResponse response, Cookie cookie) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding cookie: " + cookie.getDomain() + cookie.getPath() + " " + cookie.getName() + "=" + cookie.getValue()); } // We don't use the container's response.addCookie, since the HttpOnly cookie flag was introduced only recently // in the servlet specification, and we're still using the older 2.4 specification as a minimal requirement for // compatibility with as many containers as possible. Instead, we write the cookie manually as a HTTP header. StringBuilder cookieValue = new StringBuilder(150); cookieValue.append(cookie.getName() + "="); if (StringUtils.isNotEmpty(cookie.getValue())) { cookieValue.append("\"" + cookie.getValue() + "\""); } cookieValue.append("; Version=1"); if (cookie.getMaxAge() >= 0) { cookieValue.append("; Max-Age=" + cookie.getMaxAge()); // IE is such a pain, it doesn't understand the modern, safer Max-Age cookieValue.append("; Expires="); if (cookie.getMaxAge() == 0) { cookieValue.append(COOKIE_EXPIRE_NOW); } else { cookieValue.append(COOKIE_EXPIRE_FORMAT .format(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L))); } } if (StringUtils.isNotEmpty(cookie.getDomain())) { // IE needs toLowerCase for the domain name cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase()); } if (StringUtils.isNotEmpty(cookie.getPath())) { cookieValue.append("; Path=" + cookie.getPath()); } // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly cookieValue.append("; HttpOnly"); // Session cookies should be discarded. // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header data after the // first "Discard" encountered, so it will only see the first such cookie. Disabled for the moment until Safari // gets fixed, or a better idea comes to mind. // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a session cookie. // if (cookie.getMaxAge() < 0) { // cookieValue.append("; Discard"); // } response.addHeader("Set-Cookie", cookieValue.toString()); }
From source file:com.yaodu.framework.controller.product.ProductSearchController.java
private List<ProductBascInfo> getRecentlyViewedList(HttpServletRequest request) { List<ProductBascInfo> recentlyViewedList = null; if (null != request) { Cookie[] cookie = request.getCookies(); if (null == cookie) { return recentlyViewedList; }/*from w w w. j a va 2 s . c o m*/ for (int i = 0; i < cookie.length; i++) { Cookie cook = cookie[i]; if (cook.getName().equalsIgnoreCase("relatedProducts")) { // ? if (!"".equals(cook.getValue().toString())) { final String[] arrs = cook.getValue().split("\\|"); recentlyViewedList = productSolrjSearchService.findProductsByIds(arrs); Collections.sort(recentlyViewedList, new Comparator<ProductBascInfo>() { public int compare(ProductBascInfo p1, ProductBascInfo p2) { return Integer.valueOf(ArrayUtils.indexOf(arrs, p1.getnId())) .compareTo(ArrayUtils.indexOf(arrs, p2.getnId())); } }); } break; } } } return recentlyViewedList; }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java
/** * Resolve the user's current theme from the cookie. * /*from w w w . j a v a 2 s . c o m*/ * @param request * @param response * @return * @throws Exception */ private String resolveTheme(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME); if (c == null) { String value = this.getSettings().getParam(SysParams_Core.CORE_DEFAULT_THEME_EXTJS); c = this.createCookie(Constants.COOKIE_NAME_THEME, value, 60 * 60 * 24 * 365); response.addCookie(c); } String theme = request.getParameter(Constants.REQUEST_PARAM_THEME); if (theme == null || theme.equals("")) { theme = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_THEME, theme, 60 * 60 * 24 * 365); response.addCookie(c); } return theme; }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Retrieves all of the cookies from the servlet request and sets them on * the proxy request/* ww w.ja v a 2s . c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an array of all of all the cookies sent by the client Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (Cookie cookie : cookies) { cookie.setDomain(stringProxyHost); cookie.setPath(httpServletRequest.getServletPath()); httpMethodProxyRequest.setRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath()); } }
From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java
/** * ????/*from w w w . j a va 2 s .com*/ * @param request */ private void dealCoremailUserName(HttpServletRequest request) { Cookie[] cs = request.getCookies(); if (cs != null) { for (Cookie c : cs) { if ("passport.remember.user".equals(c.getName())) { if (StringUtils.isNotEmpty(c.getValue())) { request.setAttribute("userName", c.getValue()); } } } } }
From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java
/** * Add request cookies to the attributes map * * @param httpServletRequest Http Servlet Request * @param attributes Map of attributes to add additional attributes to from the Http Request *//*from ww w. j a va2 s . c o m*/ protected void addRequestCookies(final HttpServletRequest httpServletRequest, final Map<String, List<Object>> attributes) { final Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (final Cookie cookie : cookies) { final String cookieName = cookie.getName(); if (this.cookieAttributeMapping.containsKey(cookieName)) { for (final String attributeName : this.cookieAttributeMapping.get(cookieName)) { attributes.put(attributeName, list(cookie.getValue())); } } } }
From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java
@Override protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta) throws ServletException, IOException { String tipo = requisicao.getContentType(); if (tipo == null || tipo.isEmpty()) tipo = "text/plain"; String codificacao = requisicao.getCharacterEncoding(); if (codificacao == null || codificacao.isEmpty()) codificacao = "UTF-8"; resposta.setCharacterEncoding(codificacao); PrintWriter saida = resposta.getWriter(); try {/*ww w.ja v a 2 s.c o m*/ JSON json; if (tipo.contains("json")) { json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao)); } else { json = new JSON(); } Enumeration<String> parametros = requisicao.getParameterNames(); while (parametros.hasMoreElements()) { String chave = parametros.nextElement(); String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao); json.put(chave, valor); } if (tipo.contains("multipart")) { Collection<Part> arquivos = requisicao.getParts(); if (!arquivos.isEmpty()) { File diretorio = new File(uxiAmarelo.getDiretorio()); if (!diretorio.isAbsolute()) { diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator + uxiAmarelo.getDiretorio()); } if (!diretorio.exists()) diretorio.mkdirs(); String diretorioStr = diretorio.getAbsolutePath(); String url = uxiAmarelo.getDiretorioURL(); if (uxiAmarelo.isDiretorioURLRelativo()) { String url_esquema = requisicao.getScheme(); String url_servidor = requisicao.getServerName(); int url_porta = requisicao.getServerPort(); String url_contexto = requisicao.getContextPath(); url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url; } if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } Map<String, List<JSON>> mapa_arquivos = new HashMap<>(); for (Part arquivo : arquivos) { String chave = arquivo.getName(); String nome_original = getNome(arquivo, codificacao); String nome = nome_original; if (nome == null || nome.isEmpty()) { try (InputStream is = arquivo.getInputStream()) { String valor = IOUtils.toString(is, codificacao); valor = URLDecoder.decode(valor, codificacao); json.put(chave, valor); continue; } } if (uxiAmarelo.getArquivoNome().equals("uuid")) { nome = UUID.randomUUID().toString(); } while (new File(diretorioStr + File.separator + nome).exists()) { nome = UUID.randomUUID().toString(); } arquivo.write(diretorioStr + File.separator + nome); List<JSON> lista = mapa_arquivos.get(chave); if (lista == null) { lista = new LinkedList<>(); mapa_arquivos.put(chave, lista); } lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome)); } for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) { List<JSON> lista = entrada.getValue(); if (lista.size() > 1) { json.put(entrada.getKey(), lista); } else { json.put(entrada.getKey(), lista.get(0)); } } } } String copaiba = (String) json.remove("copaiba"); if (StringUtil.tamanho(copaiba) == 0) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String[] copaibaParam = copaiba.split("@"); if (copaibaParam.length != 3) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String comando = (String) json.remove("uxicmd"); if (StringUtil.tamanho(comando) == 0) comando = null; if (uxiAmarelo.isCookieEnviar()) { Cookie[] cookies = requisicao.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!json.has(nome)) { try { json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { json.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(json.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, json.remove(chave), json); } } } String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) { resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json.toString(); comando = null; } else { resultado = ""; } if (comando == null) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("application/json"); saida.write(resultado); } else if (comando.startsWith("redirecionar")) { resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado)); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8"))); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); try (InputStream is = con.getInputStream()) { saida.write(IOUtils.toString(is)); } con.disconnect(); } else if (comando.startsWith("html")) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); saida.write(Util.obterStringDeJSON("html", comando, resultado)); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resposta.setContentType("application/json"); saida.write(Util.gerarRespostaErro(e).toString()); } saida.flush(); }
From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java
/** * Resolve the user's current language from the cookie. * //from w w w .java 2s. c om * @param request * @param response * @return * @throws Exception */ private String resolveLang(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG); if (c == null) { String value = this.getSettings().getParam(SysParam.CORE_DEFAULT_LANGUAGE.name()); c = this.createCookie(Constants.COOKIE_NAME_LANG, value, 60 * 60 * 24 * 365); response.addCookie(c); } String lang = request.getParameter(Constants.REQUEST_PARAM_LANG); if (lang == null || lang.equals("")) { lang = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365); response.addCookie(c); } return lang; }