List of usage examples for javax.servlet.http HttpServletRequest getCookies
public Cookie[] getCookies();
Cookie
objects the client sent with this request. From source file:com.pureinfo.tgirls.servlet.TestServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("=================parameter from request===================="); Enumeration ereq = request.getParameterNames(); while (ereq.hasMoreElements()) { String name = (String) ereq.nextElement(); System.out.println(name + "[" + request.getParameter(name) + "]"); }//from w w w .j av a 2 s .c o m System.out.println("=================end===================="); String userTabaoId = request.getParameter("id"); if (StringUtils.isEmpty(userTabaoId)) { userTabaoId = "1"; } try { IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class); User _loginUser = mgr.getUserByTaobaoId(userTabaoId); addCookie(_loginUser, request, response); Cookie[] cookies = request.getCookies(); if (cookies == null) { System.out.println("=====cookie is null======="); } else { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "(" + cookie.getMaxAge() + ")]"); } } //request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, _loginUser); System.out.println("loginuser:" + _loginUser); response.sendRedirect(request.getContextPath()); return; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(System.err); } }
From source file:com.konakart.actions.BaseAction.java
/** * Utility method to get the CustomerUuid from the browser cookie and create the cookie if it * doesn't exist./*from w ww . ja v a 2 s . c o m*/ * * @param request * @return Returns the CustomerUuid */ private String getCustomerUuidFromBrowserCookie(HttpServletRequest request, HttpServletResponse response) { /* * Try to find the cookie we are looking for */ Cookie[] cookies = request.getCookies(); String uuid = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String cookieName = cookie.getName(); if (cookieName.equals(CUSTOMER_UUID)) { /* * If we find the cookie we get the value and update the max age. */ uuid = cookie.getValue(); cookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS); cookie.setPath("/"); response.addCookie(cookie); } } } /* * If the browser cookie doesn't exist then we have to create it and store a newly created * UUID string */ if (uuid == null) { UUID uuidObject = UUID.randomUUID(); uuid = uuidObject.toString(); /* * Create a browser cookie with the UUID */ Cookie uuidCookie = new Cookie(CUSTOMER_UUID, uuid); uuidCookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS); uuidCookie.setPath("/"); response.addCookie(uuidCookie); } return uuid; }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract cookies and other global fields into inData * /* ww w .j a v a2 s .co m*/ * @param req * @param inData */ @SuppressWarnings("unchecked") private void getStandardFields(HttpServletRequest req, ServiceData inData) { // log field if (suppressSqlLog) { inData.addValue(ExilityConstants.SUPPRESS_SQL_LOG, "1"); } if (AP.cookiesToBeExtracted != null) { Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (AP.cookiesToBeExtracted.contains(cookie.getName())) { Spit.out(cookie.getName() + " extracted from cookie"); inData.addValue(cookie.getName(), cookie.getValue()); } } } } this.extractParametersAndFiles(req, inData); /** * is there a sessionData object? */ HttpSession session = req.getSession(); String token = req.getHeader(CommonFieldNames.CSRF_HEADER); if (token == null) { // try form fields token = inData.getValue(CommonFieldNames.CSRF_HEADER); } if (token == null) { // for the sake of jsps that still exist in our system.. Object obj = session.getAttribute(HttpRequestHandler.SESSION_TOKEN_NAME); if (obj != null) { token = obj.toString(); } } if (token != null) { Object obj = session.getAttribute(token); if (obj != null && obj instanceof SessionData) { Spit.out("Session fields being extracted from new token based object."); ((SessionData) obj).extractAll(inData); } else { Spit.out("CSRF token found to be " + token + " but session data not found"); } } else { Spit.out("NO CSRF token. Will try old ways of session data."); Object data = session.getAttribute(HtmlRequestHandler.GLOBAL_SERVER_DATA_NAME + inData.getValue(HtmlRequestHandler.getUserIdName())); if (data != null && data instanceof Map) { Map<String, String> sessionData = (Map<String, String>) data; for (String name : sessionData.keySet()) { // Spit.out("Trying " + name + " as a global field"); String val = sessionData.get(name); if (val != null && val.length() > 0) { inData.addValue(name, val); } } } } }
From source file:com.meltmedia.cadmium.servlets.jersey.StatusService.java
@GET @Path("/health") @Produces("text/plain") public String health(@Context HttpServletRequest request) { StringBuilder builder = new StringBuilder(); builder.append("Server: " + request.getServerName() + "\n"); builder.append("Scheme: " + request.getScheme() + "\n"); builder.append("Port: " + request.getServerPort() + "\n"); builder.append("ContextPath: " + request.getContextPath() + "\n"); builder.append("ServletPath: " + request.getServletPath() + "\n"); builder.append("Uri: " + request.getRequestURI() + "\n"); builder.append("Query: " + request.getQueryString() + "\n"); Enumeration<?> headerNames = request.getHeaderNames(); builder.append("Headers:\n"); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration<?> headers = request.getHeaders(name); builder.append(" '" + name + "':\n"); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); builder.append(" -" + headerValue + "\n"); }/*from w w w .j av a2 s. c o m*/ } if (request.getCookies() != null) { builder.append("Cookies:\n"); for (Cookie cookie : request.getCookies()) { builder.append(" '" + cookie.getName() + "':\n"); builder.append(" value: " + cookie.getValue() + "\n"); builder.append(" domain: " + cookie.getDomain() + "\n"); builder.append(" path: " + cookie.getPath() + "\n"); builder.append(" maxAge: " + cookie.getMaxAge() + "\n"); builder.append(" version: " + cookie.getVersion() + "\n"); builder.append(" comment: " + cookie.getComment() + "\n"); builder.append(" secure: " + cookie.getSecure() + "\n"); } } return builder.toString(); }
From source file:com.qut.middleware.esoe.sso.impl.SSOProcessorImpl.java
private void processCookies(SSOProcessorData data) { String remoteAddr = data.getRemoteAddress(); HttpServletRequest request = data.getHttpRequest(); if (request == null) { this.logger.warn( "[SSO for {}] No HTTP request object was passed in by the SSO handler. Unable to process cookies.", remoteAddr);//from ww w.j a v a 2s . c o m return; } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { this.logger.debug("[SSO for {}] Processing cookie {} = {}", new Object[] { remoteAddr, cookie.getName(), cookie.getValue() }); if (cookie.getName().equals(this.sessionTokenName)) { this.logger.debug("[SSO for {}] Identified ESOE cookie {} = {}", new Object[] { remoteAddr, cookie.getName(), cookie.getValue() }); data.setSessionID(cookie.getValue()); // We don't need any further cookies. Remove this if that changes. return; } } } else { this.logger.debug("[SSO for {}] No cookies in HTTP request.", remoteAddr); } }
From source file:com.liferay.portal.servlet.MainServlet.java
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (!PortalInstances.matches()) { String html = ContentUtil.get("messages/en_US/init.html"); res.getOutputStream().print(html); return;//from w w w.j ava2s . c o m } if (ShutdownUtil.isShutdown()) { String html = ContentUtil.get("messages/en_US/shutdown.html"); res.getOutputStream().print(html); return; } req.setAttribute("dotcache", "no"); // Shared session HttpSession ses = req.getSession(); if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) { String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID); _log.debug("Shared session id is " + sharedSessionId); if (sharedSessionId == null) { sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12); Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId); sharedSessionIdCookie.setPath("/"); sharedSessionIdCookie.setMaxAge(86400); res.addCookie(sharedSessionIdCookie); _log.debug("Shared session id is " + sharedSessionId); } // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) { ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId); // } HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId); if ((portalSes == null) || (ses != portalSes)) { if (portalSes == null) { _log.debug("No session exists in pool"); } else { _log.debug("Session " + portalSes.getId() + " in pool is old"); } _log.debug("Inserting current session " + ses.getId() + " in pool"); SharedSessionPool.put(sharedSessionId, ses); } } // Test CAS auto login /* * ses.setAttribute( * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER, * "liferay.com.1"); */ // CTX ServletContext ctx = getServletContext(); ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX)); if (portalCtx == null) { portalCtx = ctx; } req.setAttribute(WebKeys.CTX, portalCtx); // CTX_PATH variable String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH); if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) { portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath); } if (ses.getAttribute(WebKeys.CTX_PATH) == null) { ses.setAttribute(WebKeys.CTX_PATH, ctxPath); } req.setAttribute(WebKeys.CTX_PATH, ctxPath); // CAPTCHA_PATH variable String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH); if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) { portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) { ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); // IMAGE_PATH variable String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH); if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) { portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath); } if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) { ses.setAttribute(WebKeys.IMAGE_PATH, imagePath); } req.setAttribute(WebKeys.IMAGE_PATH, imagePath); // WebKeys.COMPANY_ID variable String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID); if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) { portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId); } if (ses.getAttribute(WebKeys.COMPANY_ID) == null) { ses.setAttribute(WebKeys.COMPANY_ID, companyId); } req.setAttribute(WebKeys.COMPANY_ID, companyId); // Portlet Request Processor PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR); if (portletReqProcessor == null) { portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req)); portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor); } // Tiles definitions factory if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) { portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY, ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY)); } // Set character encoding String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING); req.setCharacterEncoding(strutsCharEncoding); /* * if (!BrowserSniffer.is_wml(req)) { res.setContentType( * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); } */ // Determine content type String contentType = req.getHeader("Content-Type"); if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) { req = new UploadServletRequest(req); } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) { try { Company company = CompanyLocalManagerUtil.getCompany(companyId); req = new EncryptedServletRequest(req, company.getKeyObj()); } catch (Exception e) { } } // Current URL String completeURL = Http.getCompleteURL(req); if (completeURL.indexOf("j_security_check") != -1) { completeURL = ctxPath; } else { completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length()); completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length()); } req.setAttribute(WebKeys.CURRENT_URL, completeURL); // Chat server // Login String userId = PortalUtil.getUserId(req); if ((userId != null)) { PrincipalThreadLocal.setName(userId); } if (userId == null) { try { User user = UserManagerUtil.getDefaultUser(companyId); if (ses.getAttribute(Globals.LOCALE_KEY) == null) ses.setAttribute(Globals.LOCALE_KEY, user.getLocale()); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } } // Process pre service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); req.setAttribute(PageContext.EXCEPTION, e); StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res); } // Struts service callParentService(req, res); // Process post service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Clear the principal associated with this thread PrincipalThreadLocal.setName(null); }
From source file:com.adito.security.DefaultLogonController.java
public int hasClientLoggedOn(HttpServletRequest request, HttpServletResponse response) throws SecurityErrorException { // Get the logon cookie String logonCookie = null;//w w w . j a v a 2 s. c om if (request.getCookies() != null) { for (int i = 0; i < request.getCookies().length; i++) { Cookie cookie = request.getCookies()[i]; if (cookie.getName().equals(Constants.LOGON_TICKET) || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) { logonCookie = cookie.getValue(); } } } // If there is a logon ticket in the requests attributes then reassign // as we've just been issued a new ticket. if (request.getAttribute(Constants.LOGON_TICKET) != null) logonCookie = (String) request.getAttribute(Constants.LOGON_TICKET); // First check the users session for a logonticket String sessionLogonTicket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET); if (sessionLogonTicket != null) { // Make sure we are still receiving the logon ticket /** * LDP - Users are having too many issues with this change. If we * still have a ticket in the session then the HTTP session must * still be alive and the the cookie has simply expired before the * HTTP session (or the browser has elected not to send it). We * should allow this to continue and refresh the cookie here. */ /* * if(logonCookie == null && * request.getAttribute(Constants.LOGON_TICKET) == null) { * * * log.warn("Lost logon ticket. It is likely that logon cookie has * expired. "); return INVALID_TICKET; } else */ if (logonCookie == null) { SessionInfo session = getSessionInfo(sessionLogonTicket); if (session == null) return NOT_LOGGED_ON; addCookies(new ServletRequestAdapter(request), new ServletResponseAdapter(response), sessionLogonTicket, session); } // Still check that the cookie is what we expect it to be if (logonCookie != null && !sessionLogonTicket.equals(logonCookie)) { log.warn("Expected a different logon ticket."); return NOT_LOGGED_ON; } if (checkRemoteAddress(sessionLogonTicket, request.getRemoteAddr())) { return LOGGED_ON; } } else { if (logonCookie != null && logons.containsKey(logonCookie)) { if (checkRemoteAddress(logonCookie, request.getRemoteAddr())) { refreshLogonTicket(request, response, logonCookie); return LOGGED_ON; } } } return NOT_LOGGED_ON; }
From source file:helma.servlet.AbstractServletClient.java
/** * Handle a request.// w w w .ja va2 s. c o m * * @param request ... * @param response ... * * @throws ServletException ... * @throws IOException ... */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request)); try { // get the character encoding String encoding = request.getCharacterEncoding(); if (encoding == null) { // no encoding from request, use the application's charset encoding = getApplication().getCharset(); } // read cookies Cookie[] reqCookies = request.getCookies(); if (reqCookies != null) { for (int i = 0; i < reqCookies.length; i++) { try { // get Cookies String key = reqCookies[i].getName(); if (sessionCookieName.equals(key)) { reqtrans.setSession(reqCookies[i].getValue()); } reqtrans.setCookie(key, reqCookies[i]); } catch (Exception badCookie) { log("Error setting cookie", badCookie); } } } // get the cookie domain to use for this response, if any. String resCookieDomain = cookieDomain; if (resCookieDomain != null) { // check if cookieDomain is valid for this response. // (note: cookieDomain is guaranteed to be lower case) // check for x-forwarded-for header, fix for bug 443 String proxiedHost = request.getHeader("x-forwarded-host"); if (proxiedHost != null) { if (proxiedHost.toLowerCase().indexOf(resCookieDomain) == -1) { resCookieDomain = null; } } else { String host = (String) reqtrans.get("http_host"); // http_host is guaranteed to be lower case if (host != null && host.indexOf(resCookieDomain) == -1) { resCookieDomain = null; } } } // check if session cookie is present and valid, creating it if not. checkSessionCookie(request, response, reqtrans, resCookieDomain); // read and set http parameters parseParameters(request, reqtrans, encoding); // read file uploads List uploads = null; ServletRequestContext reqcx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(reqcx)) { // get session for upload progress monitoring UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans); try { uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding); } catch (Exception upx) { log("Error in file upload", upx); String message; boolean tooLarge = (upx instanceof FileUploadBase.SizeLimitExceededException); if (tooLarge) { message = "File upload size exceeds limit of " + uploadLimit + " kB"; } else { message = upx.getMessage(); if (message == null || message.length() == 0) { message = upx.toString(); } } if (uploadStatus != null) { uploadStatus.setError(message); } if (uploadSoftfail || uploadStatus != null) { reqtrans.set("helma_upload_error", message); } else { int errorCode = tooLarge ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; sendError(response, errorCode, "Error in file upload: " + message); return; } } } ResponseTrans restrans = getApplication().execute(reqtrans); // delete uploads if any if (uploads != null) { for (int i = 0; i < uploads.size(); i++) { ((FileItem) uploads.get(i)).delete(); } } // if the response was already written and committed by the application // we can skip this part and return if (response.isCommitted()) { return; } // set cookies if (restrans.countCookies() > 0) { CookieTrans[] resCookies = restrans.getCookies(); for (int i = 0; i < resCookies.length; i++) try { Cookie c = resCookies[i].getCookie("/", resCookieDomain); response.addCookie(c); } catch (Exception x) { getApplication().logEvent("Error adding cookie: " + x); } } // write response writeResponse(request, response, reqtrans, restrans); } catch (Exception x) { log("Exception in execute", x); try { if (debug) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x); } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The server encountered an error while processing your request. " + "Please check back later."); } } catch (IOException iox) { log("Exception in sendError", iox); } } }
From source file:com.netflix.genie.web.controllers.JobRestController.java
private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) { // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header. final HttpHeaders headers = forwardRequest.getHeaders(); final Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (!NAME_HEADER_COOKIE.equals(headerName)) { final String headerValue = request.getHeader(headerName); log.debug("Request Header: name = {} value = {}", headerName, headerValue); headers.add(headerName, headerValue); }/*from www .ja va 2 s .c om*/ } } // Lets add the cookie as an header final Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { StringBuilder builder = null; for (final Cookie cookie : request.getCookies()) { if (builder == null) { builder = new StringBuilder(); } else { builder.append(","); } builder.append(cookie.getName()).append("=").append(cookie.getValue()); } if (builder != null) { final String cookieValue = builder.toString(); headers.add(NAME_HEADER_COOKIE, cookieValue); log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue); } } // This method only called when need to forward so add the forwarded from header headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString()); }