List of usage examples for javax.servlet.http Cookie getName
public String getName()
From source file:com.zimbra.cs.service.ExternalUserProvServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String param = req.getParameter("p"); if (param == null) { throw new ServletException("request missing param"); }//from w w w. ja v a 2 s .c o m Map<Object, Object> tokenMap = validatePrelimToken(param); Map<String, String> reqHeaders = new HashMap<String, String>(); String ownerId = (String) tokenMap.get("aid"); String folderId = (String) tokenMap.get("fid"); String extUserEmail = (String) tokenMap.get("email"); Provisioning prov = Provisioning.getInstance(); Account grantee; try { Account owner = prov.getAccountById(ownerId); Domain domain = prov.getDomain(owner); grantee = prov.getAccountByName(mapExtEmailToAcctName(extUserEmail, domain)); if (grantee == null) { // external virtual account not created yet if (prov.isOctopus() && DebugConfig.skipVirtualAccountRegistrationPage) { // provision using 'null' password and display name // UI will ask the user to set these post provisioning provisionVirtualAccountAndRedirect(req, resp, null, null, ownerId, extUserEmail); } else { resp.addCookie(new Cookie("ZM_PRELIM_AUTH_TOKEN", param)); req.setAttribute("extuseremail", extUserEmail); if (WebClientServiceUtil.isServerInSplitMode()) { reqHeaders.put("extuseremail", extUserEmail); reqHeaders.put("ZM_PRELIM_AUTH_TOKEN", param); String htmlresp = WebClientServiceUtil .sendServiceRequestToOneRandomUiNode(EXT_USER_PROV_ON_UI_NODE, reqHeaders); resp.getWriter().print(htmlresp); } else { ServletContext context = getServletContext().getContext("/zimbra"); if (context != null) { RequestDispatcher dispatcher = context.getRequestDispatcher(PUBLIC_EXTUSERPROV_JSP); dispatcher.forward(req, resp); } else { logger.warn("Could not access servlet context url /zimbra"); throw ServiceException.TEMPORARILY_UNAVAILABLE(); } } } } else { // create a new mountpoint in the external user's mailbox if not already created String[] sharedItems = owner.getSharedItem(); int sharedFolderId = Integer.valueOf(folderId); String sharedFolderPath = null; MailItem.Type sharedFolderView = null; for (String sharedItem : sharedItems) { ShareInfoData sid = AclPushSerializer.deserialize(sharedItem); if (sid.getItemId() == sharedFolderId && extUserEmail.equalsIgnoreCase(sid.getGranteeId())) { sharedFolderPath = sid.getPath(); sharedFolderView = sid.getFolderDefaultViewCode(); break; } } if (sharedFolderPath == null) { throw new ServletException("share not found"); } String mountpointName = getMountpointName(owner, grantee, sharedFolderPath); ZMailbox.Options options = new ZMailbox.Options(); options.setNoSession(true); options.setAuthToken(AuthProvider.getAuthToken(grantee).toZAuthToken()); options.setUri(AccountUtil.getSoapUri(grantee)); ZMailbox zMailbox = new ZMailbox(options); ZMountpoint zMtpt = null; try { zMtpt = zMailbox.createMountpoint(String.valueOf(getMptParentFolderId(sharedFolderView, prov)), mountpointName, ZFolder.View.fromString(sharedFolderView.toString()), ZFolder.Color.DEFAULTCOLOR, null, ZMailbox.OwnerBy.BY_ID, ownerId, ZMailbox.SharedItemBy.BY_ID, folderId, false); } catch (ServiceException e) { logger.debug("Error in attempting to create mountpoint. Probably it already exists.", e); } if (zMtpt != null) { if (sharedFolderView == MailItem.Type.APPOINTMENT) { // make sure that the mountpoint is checked in the UI by default FolderActionSelector actionSelector = new FolderActionSelector(zMtpt.getId(), "check"); FolderActionRequest actionRequest = new FolderActionRequest(actionSelector); try { zMailbox.invokeJaxb(actionRequest); } catch (ServiceException e) { logger.warn("Error in invoking check action on calendar mountpoint", e); } } HashSet<MailItem.Type> types = new HashSet<MailItem.Type>(); types.add(sharedFolderView); enableAppFeatures(grantee, types); } // check if the external user is already logged-in String zAuthTokenCookie = null; javax.servlet.http.Cookie cookies[] = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("ZM_AUTH_TOKEN")) { zAuthTokenCookie = cookie.getValue(); break; } } } AuthToken zAuthToken = null; if (zAuthTokenCookie != null) { try { zAuthToken = AuthProvider.getAuthToken(zAuthTokenCookie); } catch (AuthTokenException ignored) { // auth token is not valid } } if (zAuthToken != null && !zAuthToken.isExpired() && zAuthToken.isRegistered() && grantee.getId().equals(zAuthToken.getAccountId())) { // external virtual account already logged-in resp.sendRedirect("/"); } else if (prov.isOctopus() && !grantee.isVirtualAccountInitialPasswordSet() && DebugConfig.skipVirtualAccountRegistrationPage) { // seems like the virtual user did not set his password during his last visit, after an account was // provisioned for him setCookieAndRedirect(req, resp, grantee); } else { req.setAttribute("virtualacctdomain", domain.getName()); if (WebClientServiceUtil.isServerInSplitMode()) { reqHeaders.put("virtualacctdomain", domain.getName()); String htmlresp = WebClientServiceUtil .sendServiceRequestToOneRandomUiNode(PUBLIC_LOGIN_ON_UI_NODE, reqHeaders); resp.getWriter().print(htmlresp); } else { RequestDispatcher dispatcher = getServletContext().getContext("/zimbra") .getRequestDispatcher(PUBLIC_LOGIN_JSP); dispatcher.forward(req, resp); } } } } catch (ServiceException e) { throw new ServletException(e); } }
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:org.toobsframework.pres.component.Component.java
/** * Get the objects associated to this component * @param paramsIn - the parameters sent to the datasource to obtain th object * @param paramsOut//from w w w . j av a 2s. com * @return an array of all the objects implementing IDataSourceObject */ public IDataProviderObject[] getObjects(IRequest request, Map<String, Object> paramsIn, Map<String, Object> paramsOut, IXMLTransformerHelper transformerHelper) throws ComponentException, ComponentNotInitializedException, ParameterException { List<IDataProviderObject> allObjects = new ArrayList<IDataProviderObject>(); if (!this.initDone) { ComponentNotInitializedException ex = new ComponentNotInitializedException(); ex.setComponentId(this.id); throw ex; } int len = objectsConfig.length; for (int i = 0; i < len; i++) { Map<String, Object> params = new HashMap<String, Object>(paramsIn); GetObject thisObjDef = objectsConfig[i]; //Fix the params using the param mapping for //this configuration. if (thisObjDef.getParameters() != null) { ParameterUtil.mapParameters(request, "Component:" + this.id + ":GetObject:" + thisObjDef.getServiceProvider(), thisObjDef.getParameters().getParameter(), params, params, this.id, allObjects); } List<IDataProviderObject> theseObjects = new ArrayList<IDataProviderObject>(); //Call the appropriate action. Map<String, Object> outParams = new HashMap<String, Object>(); // TODO: JG I need to put the cookies: notations into into parameters if (thisObjDef.getAction().equals("getCookie")) { String searchCriteria = ParameterUtil.resolveParam(request, thisObjDef.getSearchCriteria(), params)[0]; String thisGuidParam = ParameterUtil.resolveParam(request, thisObjDef.getGuidParam(), params)[0]; String cookieName = (searchCriteria != null ? searchCriteria : ""); Object guidValue = params.get(thisGuidParam); if (guidValue != null && guidValue.getClass().isArray()) { cookieName += ((String[]) guidValue)[0]; } else { cookieName += guidValue; } String cookieValue = null; Cookie[] cookies = request.getHttpRequest().getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { Cookie cookie = cookies[c]; if (cookie.getName().equals(cookieName)) { cookieValue = cookie.getValue(); break; } } } if (cookieName != null && cookieValue != null) { theseObjects.add(this.createObject(new CookieVO(cookieName, cookieValue))); } } else { theseObjects.add(getDispatchedObject(request, thisObjDef, params, outParams)); } // TODO SNIP!!! ParameterUtil.mapScriptParams(outParams, paramsIn); if (thisObjDef.getOutputParameters() != null) { ParameterUtil.mapOutputParameters(request, thisObjDef.getOutputParameters().getParameter(), paramsIn, this.id, theseObjects); if (paramsOut != null) { ParameterUtil.mapOutputParameters(request, thisObjDef.getOutputParameters().getParameter(), paramsOut, this.id, theseObjects); } } allObjects.addAll(theseObjects); } IDataProviderObject[] objArray = new IDataProviderObject[allObjects.size()]; objArray = allObjects.toArray(objArray); return objArray; }
From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java
@Override protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { AuthenticationToken token = null;//from w ww . j a v a 2s .c o m String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = this.signer.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (token != null) { AuthenticationHandler authHandler = getAuthenticationHandler(); if (!token.getType().equals(authHandler.getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } } return token; }
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 www . ja v a 2s . 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.spshop.web.ShoppingController.java
@RequestMapping(value = "/logout") public String logout(Model model, HttpServletRequest request, HttpServletResponse response) { request.getSession().invalidate();//from w w w. jav a 2 s . c o m model.addAttribute(LOGOUT_ACTION, Boolean.TRUE.toString()); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { if (COOKIE_ACCOUNT.equals(cookie.getName())) { cookie = new Cookie(COOKIE_ACCOUNT, EMPTY_STR); cookie.setPath("/"); cookie.setMaxAge(30 * 24 * 60 * 60); response.addCookie(cookie); } } } return "redirect:" + getSiteView().getHost(); }
From source file:com.tremolosecurity.proxy.filter.HttpFilterRequestImpl.java
@Override public void addCookie(Cookie cookie) { ArrayList<Cookie> vals = this.cookies.get(cookie.getName()); if (vals == null) { vals = new ArrayList<Cookie>(); this.cookies.put(cookie.getName(), vals); }//from ww w.j a v a 2 s.c o m vals.add(cookie); }
From source file:com.spshop.web.ShoppingController.java
private User retrieveUserNameAndPWDFromCookie(Cookie cookies[]) { try {/* www. ja v a2s . co m*/ if (null != cookies) { for (Cookie cookie : cookies) { if (COOKIE_ACCOUNT.equals(cookie.getName())) { String value = Utils.OBJ.getDecry(cookie.getValue()); String[] mixUser = value.split(USER_NAME_PWD_SPLIT); User user = new User(); user.setEmail(mixUser[0]); user.setPassword(mixUser[1]); return user; } } } } catch (Exception e) { logger.info(e.getMessage()); } return null; }
From source file:com.google.ie.web.controller.UserController.java
/** * Retrieve the value of friend connect authorization cookie from the * request.//from w ww . j av a 2 s . c o m * * @param request * @return */ private String getAuthToken(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie != null && cookie.getName().equals(getFcauthCookieName())) { return cookie.getValue(); } } } if (isDebugEnabled) { LOGGER.debug("The cookie " + getFcauthCookieName() + " was not found "); } return null; }