List of usage examples for javax.servlet.http Cookie getName
public String getName()
From source file:eu.trentorise.smartcampus.permissionprovider.controller.CookieCleaner.java
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { for (String s : cookieNames) { Cookie cookie = new Cookie(s, null); cookie.setPath("/"); cookie.setMaxAge(0);/* w w w .j a va 2s .co m*/ response.addCookie(cookie); cookie = new Cookie(s, null); cookie.setPath(request.getContextPath() + "/eauth/"); cookie.setMaxAge(0); response.addCookie(cookie); } if (request.getCookies() != null) { for (int i = 0; i < request.getCookies().length; i++) { Cookie cookie = request.getCookies()[i]; for (String s : cookieNames) { if (cookie.getName().startsWith(s)) { cookie = new Cookie(cookie.getName(), null); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); cookie = new Cookie(cookie.getName(), null); cookie.setPath(request.getContextPath() + "/eauth/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } } request.getSession().invalidate(); if (authentication != null) authentication.setAuthenticated(false); response.sendRedirect(request.getContextPath() + redirect); }
From source file:com.xpn.xwiki.stats.impl.StatsUtil.java
/** * Create a new visit cookie and return it. * /*from w w w . ja va2 s . c o m*/ * @param context the XWiki context. * @return the newly created cookie. * @since 1.4M1 */ protected static Cookie addCookie(XWikiContext context) { Cookie cookie = new Cookie(COOKPROP_VISITID, RandomStringUtils.randomAlphanumeric(32).toUpperCase()); cookie.setPath("/"); int time = (int) (getCookieExpirationDate().getTime() - (new Date()).getTime()) / 1000; cookie.setMaxAge(time); String cookieDomain = null; getCookieDomains(context); if (cookieDomains != null) { String servername = context.getRequest().getServerName(); for (int i = 0; i < cookieDomains.length; i++) { if (servername.indexOf(cookieDomains[i]) != -1) { cookieDomain = cookieDomains[i]; break; } } } if (cookieDomain != null) { cookie.setDomain(cookieDomain); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Setting cookie " + cookie.getValue() + " for name " + cookie.getName() + " with domain " + cookie.getDomain() + " and path " + cookie.getPath() + " and maxage " + cookie.getMaxAge()); } context.getResponse().addCookie(cookie); return cookie; }
From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE); HttpServletRequest httpRequest = (HttpServletRequest) request; if (isSpnegoEnable(authtype)) { KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); String userName = null;// www .j a v a 2 s . c om Cookie[] cookie = httpRequest.getCookies(); if (cookie != null) { for (Cookie c : cookie) { String cname = c.getName(); if (cname != null && cname.equalsIgnoreCase("u")) { int ustr = cname.indexOf("u="); if (ustr != -1) { int andStr = cname.indexOf("&", ustr); if (andStr != -1) { userName = cname.substring(ustr + 2, andStr); } } } else if (cname != null && cname.equalsIgnoreCase(AUTH_COOKIE_NAME)) { int ustr = cname.indexOf("u="); if (ustr != -1) { int andStr = cname.indexOf("&", ustr); if (andStr != -1) { userName = cname.substring(ustr + 2, andStr); } } } } } if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) { //--------------------------- To Create Ranger Session -------------------------------------- String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); //if we get the userName from the token then log into ranger using the same user final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, "", grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider(); Authentication authentication = authenticationProvider.authenticate(finalAuthentication); authentication = getGrantedAuthority(authentication); SecurityContextHolder.getContext().setAuthentication(authentication); request.setAttribute("spnegoEnabled", true); LOG.info("Logged into Ranger as = " + userName); } else { try { super.doFilter(request, response, filterChain); } catch (Exception e) { throw restErrorUtil .createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage()); } } } else { filterChain.doFilter(request, response); } }
From source file:com.jolira.testing.CachingRESTProxy.java
private boolean cacheResponse(final String query, final File queryDir, final HttpServletRequest request) throws IOException { if (backend == null) { return false; }/*from w w w. j a v a 2 s . c o m*/ final String protocol = ssl ? "https" : "http"; final String _url = protocol + "://" + backend + query; final URL url = new URL(_url); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); final Cookie[] cookies = request.getCookies(); if (cookies != null) { final StringBuilder cookieVal = new StringBuilder(); for (final Cookie cookie : cookies) { final String value = cookie.getValue(); final String name = cookie.getName(); cookieVal.append(name); cookieVal.append('='); cookieVal.append(value); cookieVal.append(';'); } connection.setRequestProperty("Cookie", cookieVal.toString()); } final InputStream in = connection.getInputStream(); try { cacheResponse(queryDir, connection, in); } finally { in.close(); } return true; }
From source file:com.qut.middleware.spep.filter.SPEPFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$ }//from w w w .j a v a 2 s . co m if (!(servletResponse instanceof HttpServletResponse)) { throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$ } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String resource, decodedResource, requested, redirectURL; URL serviceHost; ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName); // Get servlet context. if (spepContext == null) { throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$ } // Establish SPEPProxy object. SPEPProxy spep; try { spep = Initializer.init(spepContext); } catch (Exception e) { this.logger.error( "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n" + e.getLocalizedMessage()); throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$ } // Ensure SPEP startup. if (!spep.isStarted()) { // Don't allow anything to occur if SPEP hasn't started correctly. this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty "); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$ } // Get SPEP cookie. Cookie spepCookie = null; Cookie globalESOECookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(spep.getTokenName())) { spepCookie = cookie; this.logger.debug("Located spep cookie with value of " + spepCookie.getValue()); } if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) { globalESOECookie = cookie; this.logger .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue()); } } } // value for re-determining session status after Authz request boolean validSession = false; // Check SPEP session is valid. if (spepCookie != null) { String sessionID = spepCookie.getValue(); this.logger.info("Attempting to retrieve data for session with ID of " + sessionID); PrincipalSession PrincipalSession = spep.verifySession(sessionID); if (PrincipalSession != null) { this.logger.info("Located session with ID of " + sessionID); if (request.getSession().getAttribute(ATTRIBUTES) == null) { // over write with new data if it exists WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>(); attributeMap.putAll(PrincipalSession.getAttributes()); attributeMap.close(); request.getSession().setAttribute(ATTRIBUTES, attributeMap); request.getSession().setAttribute(SPEP_SESSIONID, sessionID); } /* * This section of code is critical, we must pass the PEP an exact representation of what the user is * attempting to access additionally the PEP expects that the string is not in encoded form as it will * do exact matching, so we decode before passing our request to it. */ resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource); // the authz processor may destroy the session if the PDP determines that the client // session is no longer valid, so we have to check it again if ((PrincipalSession = spep.verifySession(sessionID)) != null) validSession = true; if (validSession) { if (authzDecision == SPEPProxy.decision.permit) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was permissable"); chain.doFilter(request, response); return; } else if (authzDecision == SPEPProxy.decision.deny) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was denied, forcing response of" + HttpServletResponse.SC_FORBIDDEN); response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else if (authzDecision == SPEPProxy.decision.error) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was in error, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$ } else { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was undetermined, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$ } } } /* Clear the local session object the supplied request is invalid */ this.logger.debug("Invalidating session for ID of " + sessionID); request.getSession().invalidate(); } /* * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have * come back to the SPEP since logging out. */ List<Cookie> clearCookies = new Vector<Cookie>(); if (cookies != null) { for (Cookie cookie : cookies) { if (spep.getLogoutClearCookies() != null) { for (Cookie clearCookie : spep.getLogoutClearCookies()) { if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) { Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone(); clearCookieCloneInsecure.setMaxAge(0); clearCookieCloneInsecure.setSecure(false); clearCookies.add(clearCookieCloneInsecure); // Don't need to process the inner loop again for this cookie. break; } } } } } /* Add the cookies to be cleared into the response object. */ for (Cookie c : clearCookies) response.addCookie(c); /* * Remove any principal object details which may be in the session, this state can occur if the user has removed * their spepSession cookie but retained their jsessionid cookie */ request.getSession().removeAttribute(ATTRIBUTES); /* * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the * logical reasons below they will be forced to authenticate. */ if (spep.isLazyInit()) { this.logger.info( "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP"); /* * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out * if user is accessing something that has been configured to force a session to be established before it is * accessible */ if (globalESOECookie == null) { this.logger.debug("globalESOECookie was not set for this request"); boolean matchedLazyInitResource = false; resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); for (String lazyInitResource : spep.getLazyInitResources()) { if (decodedResource.matches(lazyInitResource)) { matchedLazyInitResource = true; this.logger.info("Lazy session init attempt matched initialization query of " + lazyInitResource + " from request of " + decodedResource); } else this.logger.debug("Lazy session init attempt failed to match initialization query of " + lazyInitResource + " from request of " + decodedResource); } // If we still have no reason to engage spep functionality for this request let the request pass if (matchedLazyInitResource) { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } else { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } } } /* * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically */ this.logger.debug("Failed all avenues to provide access to content"); if (request.getQueryString() != null) requested = request.getRequestURI() + "?" + request.getQueryString(); else requested = request.getRequestURI(); /* * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to * the local node. */ serviceHost = new URL(spep.getServiceHost()); String ssoRedirect = spep.getSsoRedirect(); String timestampParameter; if (ssoRedirect.indexOf('?') > -1) { timestampParameter = "&ts=" + System.currentTimeMillis(); } else { timestampParameter = "?ts=" + System.currentTimeMillis(); } if (request.getServerName().equals(serviceHost.getHost())) { /* Ensures that SSL offloading in Layer 7 environments is correctly handled */ requested = spep.getServiceHost() + requested; String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } else { String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } this.logger.debug("Redirecting to " + redirectURL + " to establish secure session"); response.sendRedirect(redirectURL); }
From source file:UploadImageEdit.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a2s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException, IOException_Exception { // Check that we have a file upload request PrintWriter writer = response.getWriter(); String productName = ""; String description = ""; String price = ""; String pictureName = ""; String productId = ""; Cookie cookie = null; Cookie[] cookies = null; String selectedCookie = ""; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().equals("JuraganDiskon")) { selectedCookie = cookie.getValue(); } } } else { writer.println("<h2>No cookies founds</h2>"); } if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent() + "/web/" + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields int k = 0; for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { k++; writer.println("if = " + k); String fileName = new File(item.getName()).getName(); pictureName = fileName; String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("message", "Upload has been done successfully!"); writer.println("pictureName = " + pictureName); } else { k++; writer.println("else = " + k); // Get the field name String fieldName = item.getName(); // Get the field value String value = item.getString(); if (k == 0) { } else if (k == 1) { productId = value.trim(); writer.println("productId = " + productId); } else if (k == 2) { productName = value; writer.println("productName = " + productName); } else if (k == 3) { description = value; writer.println("description = " + description); } else if (k == 4) { price = value; writer.println("price = " + price); } } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName, selectedCookie); writer.println(update); //redirects client to message page getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response); }
From source file:fr.smile.liferay.EsigatePortlet.java
/** * Transform request to IncominqRequest/*from ww w . j a v a 2 s. co m*/ * * @param request * @param method * @return an incoming request * @throws IOException */ public IncomingRequest create(PortletRequest request, String method) throws IOException { HttpServletRequest httpServletRequest = PortalUtil .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request)); StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL); StringBuilder query = new StringBuilder(); Enumeration<String> parameters = request.getParameterNames(); String sep = ""; while (parameters.hasMoreElements()) { String name = parameters.nextElement(); String[] values = request.getParameterValues(name); if (!name.equals(ACTION_PARAMETER)) { for (String value : values) { query.append(sep); query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8")); sep = "&"; } } } ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0); if (method.equals("GET")) { if (!query.toString().isEmpty()) { if (!uri.toString().contains("?")) { uri.append("?"); } else { uri.append("&"); } uri.append(query); } } if (LOG.isDebugEnabled()) { LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion " + protocolVersion); } IncomingRequest.Builder builder = IncomingRequest .builder(new BasicRequestLine(method, uri.toString(), protocolVersion)); if (method.equals("POST")) { // create entity InputStream inputStream = IOUtils.toInputStream(query.toString()); if (inputStream != null) { // Copy entity-related headers InputStreamEntity entity = new InputStreamEntity(inputStream, query.length()); String contentTypeHeader = httpServletRequest.getContentType(); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } String contentEncodingHeader = httpServletRequest.getCharacterEncoding(); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } builder.setEntity(entity); } } HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null); builder.setContext(context); builder.setRemoteAddr(httpServletRequest.getRemoteAddr()); builder.setRemoteUser(request.getRemoteUser()); HttpSession session = httpServletRequest.getSession(false); if (session != null) { builder.setSessionId(session.getId()); } builder.setUserPrincipal(request.getUserPrincipal()); // Copy cookies javax.servlet.http.Cookie[] src = request.getCookies(); if (src != null) { LOG.debug("Copying " + src.length + " cookie(s) to response."); for (int i = 0; i < src.length; i++) { javax.servlet.http.Cookie c = src[i]; BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue()); dest.setSecure(c.getSecure()); dest.setDomain(c.getDomain()); dest.setPath(c.getPath()); dest.setComment(c.getComment()); dest.setVersion(c.getVersion()); builder.addCookie(dest); } } builder.setSession(new HttpServletSession(httpServletRequest)); IncomingRequest incomingRequest = builder.build(); return incomingRequest; }
From source file:org.apache.jsp.communities_jsp.java
public static String getBrowserInfiniteCookie(HttpServletRequest request) { Cookie[] cookieJar = request.getCookies(); if (cookieJar != null) { for (Cookie cookie : cookieJar) { if (cookie.getName().equals("infinitecookie")) { return cookie.getValue() + ";"; }/*ww w.ja v a2s. com*/ } } return null; }
From source file:com.medallia.spider.SpiderServlet.java
private void addCookie(final Map<String, String> m, Cookie c) { m.put(c.getName(), c.getValue()); }
From source file:com.novartis.opensource.yada.plugin.AbstractPreprocessor.java
@Override public String getCookie(String cookie) { Cookie[] cookies = getYADARequest().getRequest().getCookies(); if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals(cookie)) { return c.getValue(); }/*from w ww .j a v a 2 s .c o m*/ } } return null; }