List of usage examples for javax.servlet.http Cookie getName
public String getName()
From source file:nl.nn.adapterframework.webcontrol.action.ShowIbisstoreSummary.java
public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { IniDynaActionForm showIbisstoreSummaryForm = (IniDynaActionForm) form; // Initialize action initAction(request);/*ww w .j ava 2s . com*/ String jmsRealm = (String) showIbisstoreSummaryForm.get("jmsRealm"); String cookieName = AppConstants.getInstance().getString(SHOWIBISSTORECOOKIE, SHOWIBISSTORECOOKIE); if (StringUtils.isEmpty(jmsRealm)) { // get jmsRealm value from cookie Cookie[] cookies = request.getCookies(); if (null != cookies) { for (int i = 0; i < cookies.length; i++) { Cookie aCookie = cookies[i]; if (aCookie.getName().equals(cookieName)) { jmsRealm = aCookie.getValue(); log.debug("jmsRealm from cookie [" + jmsRealm + "]"); } } } } for (IAdapter iAdapter : ibisManager.getRegisteredAdapters()) { Adapter adapter = (Adapter) iAdapter; for (Iterator receiverIt = adapter.getReceiverIterator(); receiverIt.hasNext();) { ReceiverBase receiver = (ReceiverBase) receiverIt.next(); ITransactionalStorage errorStorage = receiver.getErrorStorage(); if (errorStorage != null) { String slotId = errorStorage.getSlotId(); if (StringUtils.isNotEmpty(slotId)) { SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null); String type = errorStorage.getType(); slotmap.put(type + "/" + slotId, sir); } } ITransactionalStorage messageLog = receiver.getMessageLog(); if (messageLog != null) { String slotId = messageLog.getSlotId(); if (StringUtils.isNotEmpty(slotId)) { SlotIdRecord sir = new SlotIdRecord(adapter.getName(), receiver.getName(), null); String type = messageLog.getType(); slotmap.put(type + "/" + slotId, sir); } } } PipeLine pipeline = adapter.getPipeLine(); if (pipeline != null) { for (int i = 0; i < pipeline.getPipeLineSize(); i++) { IPipe pipe = pipeline.getPipe(i); if (pipe instanceof MessageSendingPipe) { MessageSendingPipe msp = (MessageSendingPipe) pipe; ITransactionalStorage messageLog = msp.getMessageLog(); if (messageLog != null) { String slotId = messageLog.getSlotId(); if (StringUtils.isNotEmpty(slotId)) { SlotIdRecord sir = new SlotIdRecord(adapter.getName(), null, msp.getName()); String type = messageLog.getType(); slotmap.put(type + "/" + slotId, sir); slotmap.put(slotId, sir); } } } } } } List jmsRealms = JmsRealmFactory.getInstance().getRegisteredRealmNamesAsList(); if (jmsRealms.size() == 0) { jmsRealms.add("no realms defined"); } else { if (StringUtils.isEmpty(jmsRealm)) { jmsRealm = (String) jmsRealms.get(0); } } showIbisstoreSummaryForm.set("jmsRealms", jmsRealms); if (StringUtils.isNotEmpty(jmsRealm)) { String formQuery = AppConstants.getInstance().getProperty(SHOWIBISSTOREQUERYKEY); String result = "<none/>"; try { IbisstoreSummaryQuerySender qs; qs = (IbisstoreSummaryQuerySender) ibisManager.getIbisContext() .createBeanAutowireByName(IbisstoreSummaryQuerySender.class); qs.setSlotmap(slotmap); try { qs.setName("QuerySender"); qs.setJmsRealm(jmsRealm); qs.setQueryType("select"); qs.setBlobSmartGet(true); qs.configure(true); qs.open(); result = qs.sendMessage("dummy", formQuery); } catch (Throwable t) { error("error occured on executing jdbc query", t); } finally { qs.close(); } } catch (Exception e) { error("error occured on creating or closing connection", e); } if (log.isDebugEnabled()) log.debug("result [" + result + "]"); request.setAttribute("result", result); } if (!errors.isEmpty()) { saveErrors(request, errors); return (mapping.findForward("success")); } //Successfull: store cookie String cookieValue = jmsRealm; Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge(Integer.MAX_VALUE); log.debug("Store cookie for " + request.getServletPath() + " cookieName[" + cookieName + "] " + " cookieValue[" + cookieValue + "]"); try { response.addCookie(cookie); } catch (Throwable t) { log.warn("unable to add cookie to request. cookie value [" + cookie.getValue() + "]", t); } log.debug("forward to success"); return (mapping.findForward("success")); }
From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try {/*from ww w . j a v a 2s. c om*/ String userApprovedParamS = req.getParameter(ProxyUriUtils.PROXY_APPROVAL_PARAM); boolean userWasWarned = false; boolean userApproved = (userApprovedParamS != null && Boolean.valueOf(userApprovedParamS)); boolean securityEnabled = isSecurityEnabled(); final String remoteUser = req.getRemoteUser(); final String pathInfo = req.getPathInfo(); String parts[] = pathInfo.split("/", 3); if (parts.length < 2) { LOG.warn(remoteUser + " Gave an invalid proxy path " + pathInfo); notFound(resp, "Your path appears to be formatted incorrectly."); return; } //parts[0] is empty because path info always starts with a / String appId = parts[1]; String rest = parts.length > 2 ? parts[2] : ""; ApplicationId id = Apps.toAppID(appId); if (id == null) { LOG.warn(req.getRemoteUser() + " Attempting to access " + appId + " that is invalid"); notFound(resp, appId + " appears to be formatted incorrectly."); return; } if (securityEnabled) { String cookieName = getCheckCookieName(id); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie c : cookies) { if (cookieName.equals(c.getName())) { userWasWarned = true; userApproved = userApproved || Boolean.valueOf(c.getValue()); break; } } } } boolean checkUser = securityEnabled && (!userWasWarned || !userApproved); ApplicationReport applicationReport = null; try { applicationReport = getApplicationReport(id); } catch (ApplicationNotFoundException e) { applicationReport = null; } if (applicationReport == null) { LOG.warn(req.getRemoteUser() + " Attempting to access " + id + " that was not found"); URI toFetch = ProxyUriUtils.getUriFromTrackingPlugins(id, this.trackingUriPlugins); if (toFetch != null) { resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString())); return; } notFound(resp, "Application " + appId + " could not be found, " + "please try the history server"); return; } String original = applicationReport.getOriginalTrackingUrl(); URI trackingUri = null; // fallback to ResourceManager's app page if no tracking URI provided if (original == null || original.equals("N/A")) { resp.sendRedirect(resp.encodeRedirectURL(StringHelper.pjoin(rmAppPageUrlBase, id.toString()))); return; } else { if (ProxyUriUtils.getSchemeFromUrl(original).isEmpty()) { trackingUri = ProxyUriUtils.getUriFromAMUrl(WebAppUtils.getHttpSchemePrefix(conf), original); } else { trackingUri = new URI(original); } } String runningUser = applicationReport.getUser(); if (checkUser && !runningUser.equals(remoteUser)) { LOG.info("Asking " + remoteUser + " if they want to connect to the " + "app master GUI of " + appId + " owned by " + runningUser); warnUserPage(resp, ProxyUriUtils.getPathAndQuery(id, rest, req.getQueryString(), true), runningUser, id); return; } URI toFetch = new URI(trackingUri.getScheme(), trackingUri.getAuthority(), StringHelper.ujoin(trackingUri.getPath(), rest), req.getQueryString(), null); LOG.info(req.getRemoteUser() + " is accessing unchecked " + toFetch + " which is the app master GUI of " + appId + " owned by " + runningUser); switch (applicationReport.getYarnApplicationState()) { case KILLED: case FINISHED: case FAILED: resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString())); return; } Cookie c = null; if (userWasWarned && userApproved) { c = makeCheckCookie(id, true); } proxyLink(req, resp, toFetch, c, getProxyHost()); } catch (URISyntaxException e) { throw new IOException(e); } catch (YarnException e) { throw new IOException(e); } }
From source file:com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie.java
private void doWork(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException { as.setExecuted(true);/*from ww w. jav a 2s . c o m*/ MyVDConnection myvd = cfgMgr.getMyVD(); //HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId()); HttpSession session = ((HttpServletRequest) request).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId()); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); if (holder == null) { throw new ServletException("Holder is null"); } RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); String urlChain = holder.getUrl().getAuthChain(); AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName()); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); Attribute attr = authParams.get("cookieName"); if (attr == null) { throw new ServletException("No cookie name specified"); } String cookieName = attr.getValues().get(0); boolean useSSLSessionID; attr = authParams.get("useSSLSessionID"); if (attr == null) { useSSLSessionID = false; } else { useSSLSessionID = attr.getValues().get(0).equalsIgnoreCase("true"); } attr = authParams.get("millisToLive"); if (attr == null) { throw new ServletException("No milliseconds to live specified"); } long millisToLive = Long.parseLong(attr.getValues().get(0)); attr = authParams.get("keyAlias"); if (attr == null) { throw new ServletException("No key name specified"); } String keyAlias = attr.getValues().get(0); Cookie authCookie = null; if (request.getCookies() == null) { as.setSuccess(false); holder.getConfig().getAuthManager().nextAuth(request, response, session, false); return; } for (Cookie cookie : request.getCookies()) { if (cookie.getName().equalsIgnoreCase(cookieName)) { authCookie = cookie; break; } } if (authCookie == null) { as.setSuccess(false); holder.getConfig().getAuthManager().nextAuth(request, response, session, false); return; } com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile(); SecretKey key = this.cfgMgr.getSecretKey(keyAlias); if (key == null) { throw new ServletException("Secret key '" + keyAlias + "' does not exist"); } try { String cookieVal = authCookie.getValue(); if (cookieVal.startsWith("\"")) { cookieVal = cookieVal.substring(1, cookieVal.length() - 1); } lastmile.loadLastMielToken(cookieVal, key); } catch (Exception e) { logger.warn("Could not decrypt cookie", e); as.setSuccess(false); holder.getConfig().getAuthManager().nextAuth(request, response, session, false); return; } if (!lastmile.isValid()) { logger.warn("Cookie no longer valid"); as.setSuccess(false); holder.getConfig().getAuthManager().nextAuth(request, response, session, false); return; } boolean found = false; boolean validip = false; boolean validSslSessionId = !useSSLSessionID; String dn = null; for (Attribute attrib : lastmile.getAttributes()) { if (attrib.getName().equalsIgnoreCase("CLIENT_IP")) { validip = attrib.getValues().get(0).equals(request.getRemoteAddr()); } else if (attrib.getName().equalsIgnoreCase("DN")) { dn = attrib.getValues().get(0); } else if (attrib.getName().equalsIgnoreCase("SSL_SESSION_ID")) { Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id"); if (sessionID instanceof byte[]) { sessionID = new String(Base64.encodeBase64((byte[]) sessionID)); } validSslSessionId = attrib.getValues().get(0).equals(sessionID); } } if (dn != null && validip && validSslSessionId) { try { LDAPSearchResults res = myvd.search(dn, 0, "(objectClass=*)", new ArrayList<String>()); if (res.hasMore()) { LDAPEntry entry = res.next(); Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator(); AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel()); ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo); while (it.hasNext()) { LDAPAttribute ldapattr = it.next(); attr = new Attribute(ldapattr.getName()); String[] vals = ldapattr.getStringValueArray(); for (int i = 0; i < vals.length; i++) { attr.getValues().add(vals[i]); } authInfo.getAttribs().put(attr.getName(), attr); } as.setSuccess(true); } else { as.setSuccess(false); } } catch (LDAPException e) { if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) { logger.error("Could not authenticate user", e); } as.setSuccess(false); } } else { as.setSuccess(false); } holder.getConfig().getAuthManager().nextAuth(request, response, session, false); }
From source file:com.bilko.controller.BlogController.java
private String getSessionCookie(final Request request) { final Cookie[] cookies = request.raw().getCookies(); if (cookies == null) { return null; }/*from w w w. j a v a 2s. c o m*/ for (final Cookie cookie : cookies) { if (cookie.getName().equals("session")) { return cookie.getValue(); } } return null; }
From source file:com.bilko.controller.BlogController.java
private Cookie getSessionCookieActual(final Request request) { final Cookie[] cookies = request.raw().getCookies(); if (cookies == null) { return null; }//from ww w. j a va2 s.c o m for (final Cookie cookie : cookies) { if (cookie.getName().equals("session")) { return cookie; } } return null; }
From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java
@Override public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t) throws IOException, ServletException { @SuppressWarnings("deprecation") Throwable unwrappedException = unwrapException(t); log.debug("handleException#in"); if (!ExceptionHelper.isSecurityError(unwrappedException) && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) { super.handleException(request, response, t); return;//from w w w . j av a 2 s . c o m } Principal principal = request.getUserPrincipal(); NuxeoPrincipal nuxeoPrincipal = null; if (principal instanceof NuxeoPrincipal) { nuxeoPrincipal = (NuxeoPrincipal) principal; // redirect to login than to requested page if (nuxeoPrincipal.isAnonymous()) { response.resetBuffer(); String urlToReach = getURLToReach(request); log.debug(String.format("handleException#urlToReach#%s", urlToReach)); Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach); cookieUrlToReach.setPath("/"); cookieUrlToReach.setMaxAge(60); response.addCookie(cookieUrlToReach); log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName())); if (!response.isCommitted()) { request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response); } FacesContext.getCurrentInstance().responseComplete(); } } // go back to default handler super.handleException(request, response, t); }
From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java
@Override public String getPortalSessionId(final HttpServletRequest request) { String portalSessionId = null; // Put sessionId in current Http request final Object attrValue = request.getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME); if (attrValue != null && attrValue instanceof String) { portalSessionId = (String) attrValue; }// ww w . j a va 2 s . co m if (!StringUtils.hasText(portalSessionId)) { final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { if (cookie != null && IPortal.PORTAL_SESSION_ID_COOKIE_NAME.equals(cookie.getName())) { portalSessionId = cookie.getValue(); } } } } if (!StringUtils.hasText(portalSessionId)) { // Search Portal Session Id in Http Session portalSessionId = (String) request.getSession(true).getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME); } if (!StringUtils.hasText(portalSessionId)) { // Search Portal Session Id in Http Request params portalSessionId = request.getParameter(IPortal.PORTAL_SESSION_ID_PARAM_NAME); } // Null is the default value if (!StringUtils.hasText(portalSessionId) || !this.sessionBucketCache.containsKey(portalSessionId)) { // If the session Id cannot be found in the cache we cannot trust the session Id found. portalSessionId = null; } return portalSessionId; }
From source file:shiver.me.timbers.spring.security.jwt.AuthenticationRequestJwtTokenParserTest.java
@Test @SuppressWarnings("unchecked") public void Can_parse_a_jwt_token_from_a_cookie() throws JwtInvalidTokenException { final HttpServletRequest request = mock(HttpServletRequest.class); final Cookie cookie = mock(Cookie.class); final String token = someString(); final Object principal = new Object(); final Authentication expected = mock(Authentication.class); // Given/*from w w w . j a va2 s .c o m*/ given(request.getCookies()).willReturn(new Cookie[] { mock(Cookie.class), cookie, mock(Cookie.class) }); given(cookie.getName()).willReturn(tokenName); given(cookie.getValue()).willReturn(token); given(principleTokenParser.parse(token)).willReturn(principal); given(authenticationConverter.convert(principal)).willReturn(expected); // When final Authentication actual = tokenParser.parse(request); // Then assertThat(actual, is(expected)); }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;/*from w w w.j ava2s .c om*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:com.appeligo.search.actions.BaseAction.java
protected String getCookieId() { Cookie[] cookies = getServletRequest().getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(BaseAction.COOKIE_ID)) { cookie.setMaxAge(Integer.MAX_VALUE); return cookie.getValue(); }/*from w w w . jav a2s .c o m*/ } } //No cookie found; String cookieValue = request.getRemoteAddr() + System.currentTimeMillis(); Cookie cookie = new Cookie(COOKIE_ID, cookieValue); cookie.setMaxAge(Integer.MAX_VALUE); response.addCookie(cookie); return cookieValue; }