List of usage examples for javax.servlet.http HttpSession removeAttribute
public void removeAttribute(String name);
From source file:cs544.wamp_blog_engine.controller.UserController.java
@RequestMapping(value = "/addUser", method = RequestMethod.POST) public String add(@Valid User user, BindingResult result, HttpSession session, RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) { String view = "redirect:/"; System.out.println("userController Add"); if (!result.hasErrors()) { try {//from ww w. j av a 2s . c o m user.setProfilepic(file.getBytes()); } catch (IOException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } userService.addUser(user); session.removeAttribute("credential"); flashAttr.addFlashAttribute("successfulSignup", "User signed up succesfully. please log in to proceed"); User u = (User) session.getAttribute("loggedUser"); if (u != null && u.getUserCredential().isAdmin()) { view = "redirect:/settings"; } } else { for (FieldError err : result.getFieldErrors()) { System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage()); } view = "addUser"; } return view; }
From source file:fr.paris.lutece.plugins.mylutece.web.MyLuteceApp.java
/** * This method is call by the JSP named DoMyLuteceLogin.jsp * @param request The HTTP request//w w w. j ava2 s . c o m * @return The URL to forward depending of the result of the login. * @throws UnsupportedEncodingException */ public String doLogin(HttpServletRequest request) throws UnsupportedEncodingException { String strUsername = request.getParameter(PARAMETER_USERNAME); String strPassword = request.getParameter(PARAMETER_PASSWORD); String strAuthProvider = request.getParameter(PARAMETER_AUTH_PROVIDER); String strReturn = "../../../../" + getLoginPageUrl(); Boolean bIsCaptchaEnabled = (Boolean) request.getSession(true).getAttribute(PARAMETER_IS_ACTIVE_CAPTCHA); if ((bIsCaptchaEnabled != null) && bIsCaptchaEnabled) { CaptchaSecurityService captchaService = new CaptchaSecurityService(); if (!captchaService.validate(request)) { strReturn += ("&" + PARAMETER_ERROR + "=" + PARAMETER_ERROR_CAPTCHA); } } Plugin plugin = PluginService.getPlugin(MyLutecePlugin.PLUGIN_NAME); try { SecurityService.getInstance().loginUser(request, strUsername, strPassword); } catch (LoginRedirectException ex) { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(PARAMETER_IS_ACTIVE_CAPTCHA); } return ex.getRedirectUrl(); } catch (FailedLoginException ex) { // Creating a record of connections log ConnectionLog connectionLog = new ConnectionLog(); connectionLog.setIpAddress(SecurityUtil.getRealIp(request)); connectionLog.setDateLogin(new java.sql.Timestamp(new java.util.Date().getTime())); connectionLog.setLoginStatus(ConnectionLog.LOGIN_DENIED); // will be inserted only if access denied ConnectionLogHome.addUserLog(connectionLog, plugin); strReturn += ("&" + PARAMETER_ERROR + "=" + PARAMETER_ERROR_VALUE_INVALID); if (StringUtils.isNotBlank(strAuthProvider)) { strReturn += ("&" + PARAMETER_AUTH_PROVIDER + "=" + strAuthProvider); } if (ex.getMessage() != null) { String strMessage = "&" + PARAMETER_ERROR_MSG + "=" + URLEncoder.encode(ex.getMessage(), "UTF-8"); strReturn += strMessage; } if (ex instanceof FailedLoginCaptchaException) { Boolean bEnableCaptcha = ((FailedLoginCaptchaException) ex).isCaptchaEnabled(); request.getSession(true).setAttribute(PARAMETER_IS_ACTIVE_CAPTCHA, bEnableCaptcha); } return strReturn; } catch (LoginException ex) { strReturn += ("&" + PARAMETER_ERROR + "=" + PARAMETER_ERROR_VALUE_INVALID); if (StringUtils.isNotBlank(strAuthProvider)) { strReturn += ("&" + PARAMETER_AUTH_PROVIDER + "=" + strAuthProvider); } if (ex.getMessage() != null) { String strMessage = "&" + PARAMETER_ERROR_MSG + "=" + ex.getMessage(); strReturn += strMessage; } return strReturn; } HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(PARAMETER_IS_ACTIVE_CAPTCHA); } String strNextUrl = PortalJspBean.getLoginNextUrl(request); String strCurrentUrl = getCurrentUrl(request); if (strNextUrl != null) { return strNextUrl; } else if (strCurrentUrl != null) { return strCurrentUrl; } return getDefaultRedirectUrl(); }
From source file:wqm.radio.StationManager.java
public boolean acceptCalibrationPhase(HttpSession session, boolean endsPhase, Station station, AtlasSensor sensor, int phaseID, float v1, float v2, float v3) { for (Pair<Thread, BaseStation> baseStation : baseStations) { if (baseStation.getB().hasStation(station.getCompactAddress())) { boolean toRet = calibrationSessionManager.acceptCalibrationPhase(endsPhase, baseStation.getB(), station, sensor, phaseID, v1, v2, v3); if (endsPhase) { session.removeAttribute(Phase.getLockName()); }/*from w ww . ja va 2 s . c o m*/ return toRet; } } return false; }
From source file:edu.lternet.pasta.portal.LoginServlet.java
/** * The doPost method of the servlet. <br> * // w ww .j a v a 2 s . c om * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); String from = (String) httpSession.getAttribute("from"); String uid = request.getParameter("uid"); String password = request.getParameter("password"); String forward = null; try { new LoginClient(uid, password); httpSession.setAttribute("uid", uid); if (from == null || from.isEmpty()) { forward = "./home.jsp"; } else { forward = from; httpSession.removeAttribute("from"); } } catch (PastaAuthenticationException e) { String message = "<strong><em>Login failed</em></strong> for user <kbd class=\"nis\">" + uid + "</kbd>."; forward = "./login.jsp"; request.setAttribute("message", message); } try { TokenManager tm = new TokenManager(); logger.info(tm.getCleartextToken(uid)); logger.info(tm.getUserDistinguishedName(uid)); logger.info(tm.getTokenAuthenticationSystem(uid)); logger.info(tm.getTokenTimeToLive(uid)); ArrayList<String> groups = tm.getUserGroups(uid); for (String group : groups) { logger.info(group); } logger.info(tm.getTokenSignature(uid)); // Let's try to alter the token /* String token = tm.getToken(uid); token = Escalator.addGroup(token, "super"); tm.setToken(uid, token); logger.info(tm.getCleartextToken(uid)); */ } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (java.sql.SQLException e) { e.printStackTrace(); } RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward); requestDispatcher.forward(request, response); }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * sessionnames?session// www. j a va2 s . c om * * @param req * @param names */ public static void purgeSessions(HttpServletRequest req, String... names) { HttpSession session = req.getSession(false); if (session == null) { if (LOG.isDebugEnabled()) LOG.debug("[purgeSessions] No sessions to purge"); return; } if (ValidationUtils.isEmpty(names)) { // ?session Enumeration<String> namesEnum = session.getAttributeNames(); for (; namesEnum.hasMoreElements();) { session.removeAttribute(namesEnum.nextElement()); } return; } // ??? for (String name : names) { session.removeAttribute(name); } }
From source file:aaf.vhr.idp.http.VhrRemoteUserAuthServlet.java
/** {@inheritDoc} */ @Override//from w w w. j ava 2 s .c o m protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException { try { // key to ExternalAuthentication session String key = null; boolean isVhrReturn = false; boolean isForceAuthn = false; DateTime authnStart = null; // when this authentication started at the IdP // array to use as return parameter when calling VhrSessionValidator DateTime authnInstantArr[] = new DateTime[1]; if (httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME) != null) { // we have come back from the VHR isVhrReturn = true; key = httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME); HttpSession hs = httpRequest.getSession(); if (hs != null && hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key) != null) { authnStart = (DateTime) hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key); // remove the attribute from the session so that we do not attempt to reuse it... hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME); } ; if (hs != null && hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key) != null) { isForceAuthn = ((Boolean) hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key)).booleanValue(); // remove the attribute from the session so that we do not attempt to reuse it... hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME); } ; } else { // starting a new SSO request key = ExternalAuthentication.startExternalAuthentication(httpRequest); // check if forceAuthn is set Object forceAuthnAttr = httpRequest.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM); if (forceAuthnAttr != null && forceAuthnAttr instanceof java.lang.Boolean) { log.debug("Loading foceAuthn value"); isForceAuthn = ((Boolean) forceAuthnAttr).booleanValue(); } // check if we can see when authentication was initiated final AuthenticationContext authCtx = ExternalAuthentication .getProfileRequestContext(key, httpRequest) .getSubcontext(AuthenticationContext.class, false); if (authCtx != null) { log.debug("Authentication initiation is {}", authCtx.getInitiationInstant()); authnStart = new DateTime(authCtx.getInitiationInstant(), DateTimeZone.UTC); log.debug("AuthnStart is {}", authnStart); } ; } ; log.debug("forceAuthn is {}, authnStart is {}", isForceAuthn, authnStart); if (key == null) { log.error("No ExternalAuthentication sesssion key found"); throw new ServletException("No ExternalAuthentication sesssion key found"); } ; // we now have a key - either: // * we started new authentication // * or we have returned from VHR and loaded the key from the HttpSession String username = null; // We may have a cookie - either as part of return or from previous session // Attempt to locate VHR SessionID String vhrSessionID = null; Cookie[] cookies = httpRequest.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(SSO_COOKIE_NAME)) { vhrSessionID = cookie.getValue(); break; } } if (vhrSessionID != null) { log.info("Found vhrSessionID from {}. Establishing validity.", httpRequest.getRemoteHost()); username = vhrSessionValidator.validateSession(vhrSessionID, (isForceAuthn ? authnStart : null), authnInstantArr); } ; // If we do not have a username yet (no Vhr session cookie or did not validate), // we redirect to VHR - but only if we are not returning from the VHR // Reason: (i) we do not want to loop and (ii) we do not have the full context otherwise initialized by // ExternalAuthentication.startExternalAuthentication() if (username == null && !isVhrReturn) { URLCodec codec = new URLCodec(); String relyingParty = (String) httpRequest.getAttribute("relyingParty"); String serviceName = ""; log.info("No vhrSessionID found from {}. Directing to VHR authentication process.", httpRequest.getRemoteHost()); log.debug("Relying party which initiated the SSO request was: {}", relyingParty); // try getting a RelyingPartyUIContext // we should pass on the request for consent revocation final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest); final RelyingPartyUIContext rpuiCtx = prc.getSubcontext(AuthenticationContext.class, true) .getSubcontext(RelyingPartyUIContext.class, false); if (rpuiCtx != null) { serviceName = rpuiCtx.getServiceName(); log.debug("RelyingPartyUIContext received, ServiceName is {}", serviceName); } ; // save session *key* HttpSession hs = httpRequest.getSession(true); hs.setAttribute(IS_FORCE_AUTHN_ATTR_NAME + key, new Boolean(isForceAuthn)); hs.setAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key, authnStart); try { httpResponse.sendRedirect(String.format(vhrLoginEndpoint, codec.encode(httpRequest.getRequestURL().toString() + "?" + REDIRECT_REQ_PARAM_NAME + "=" + codec.encode(key)), codec.encode(relyingParty), codec.encode(serviceName))); } catch (EncoderException e) { log.error("Could not encode VHR redirect params"); throw new IOException(e); } return; // we issued a redirect - return now } ; if (username == null) { log.warn("VirtualHome authentication failed: no username received"); httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, "VirtualHome authentication failed: no username received"); ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); return; } // check if consent revocation was requested String consentRevocationParam = httpRequest.getParameter(consentRevocationParamName); if (consentRevocationParam != null) { // we should pass on the request for consent revocation final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest); final ConsentManagementContext consentCtx = prc.getSubcontext(ConsentManagementContext.class, true); log.debug("Consent revocation request received, setting revokeConsent in consentCtx"); consentCtx.setRevokeConsent(consentRevocationParam.equalsIgnoreCase("true")); } ; // Set authnInstant to timestamp returned by VHR if (authnInstantArr[0] != null) { log.debug("Response from VHR includes authenticationInstant time {}, passing this back to IdP", authnInstantArr[0]); httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_INSTANT_KEY, authnInstantArr[0]); } ; httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username); ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); } catch (final ExternalAuthenticationException e) { throw new ServletException("Error processing external authentication request", e); } }
From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java
static void unregisterUserSession(HttpSession session) { String username = (String) session.getAttribute(USERNAME_ATTR); log.debug("HstConcurrentLoginFilter will unregister session for {}", username); if (username == null) { return;// w w w .jav a2s.com } ServletContext servletContext = session.getServletContext(); @SuppressWarnings("unchecked") Map<String, HttpSessionWrapper> map = (Map<String, HttpSessionWrapper>) servletContext .getAttribute(USERNAME_SESSIONID_MAP_ATTR); if (map != null) { HttpSessionWrapper oldHttpSessionWrapper = null; synchronized (map) { oldHttpSessionWrapper = map.get(username); if (oldHttpSessionWrapper != null) { if (oldHttpSessionWrapper.equalsTo(session)) { map.remove(username); log.debug("HstConcurrentLoginFilter kicked out session ({}) for {}.", oldHttpSessionWrapper.getId(), username); } else { log.debug( "HstConcurrentLoginFilter didn't kick out session ({}) for {} because it's logged on by other http session.", oldHttpSessionWrapper.getId(), username); } } } } else { log.error("HstConcurrentLoginFilter is in invalid state. The session ids map is not found."); } session.removeAttribute(USERNAME_ATTR); log.debug("HstConcurrentLoginFilter removed user name session attribute: {}", username); }
From source file:org.duracloud.account.app.controller.AccountGroupsController.java
@RequestMapping(value = GROUP_EDIT_PATH, method = RequestMethod.POST) @Transactional//from w w w . ja va 2 s . c o m public String editGroup(@PathVariable Long accountId, @PathVariable String groupName, @ModelAttribute(GROUP_FORM_KEY) @Valid GroupForm form, HttpServletRequest request, Model model) throws Exception { GroupForm.Action action = form.getAction(); AccountService as = getAccountService(accountId); List<DuracloudGroup> groups = getGroups(accountId); DuracloudGroup group = getGroup(groupName, groups); addGroupToModel(group, model); HttpSession session = request.getSession(); List<DuracloudUser> groupUsers = addGroupUsersIfNotAlreadyInSession(group, model, session); // handle save case if (action == GroupForm.Action.SAVE) { Set<DuracloudUser> users = new HashSet<DuracloudUser>(groupUsers); save(group, users, accountId, form); session.removeAttribute(GROUP_USERS_KEY); return formatGroupRedirect(accountId, groupName, null); } Collection<DuracloudUser> availableUsers = getAvailableUsers(as, groupUsers); if (action == GroupForm.Action.ADD) { // handle add String[] availableUsernames = form.getAvailableUsernames(); if (availableUsernames != null) { for (String username : availableUsernames) { DuracloudUser user = getUser(username, availableUsers); if (user != null) { groupUsers.add(user); } } form.setAvailableUsernames(null); form.setGroupUsernames(availableUsernames); } } else if (action == GroupForm.Action.REMOVE) { String[] groupUsernames = form.getGroupUsernames(); if (groupUsernames != null) { for (String username : groupUsernames) { DuracloudUser user = getUser(username, groupUsers); if (user != null) { groupUsers.remove(user); availableUsers.add(user); } } form.setGroupUsernames(null); form.setAvailableUsernames(groupUsernames); } } else { throw new DuraCloudRuntimeException("[" + action + "] not supported."); } model.addAttribute(GROUP_FORM_KEY, form); addAvailableUsersToModel(availableUsers, groupUsers, model); addGroupsObjectsToModel(as, groups, model); return GROUP_EDIT_VIEW_ID; }
From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.web.AliquotIdBreakdownController.java
/** * Aliquot Id Breakdown report simple handler * * @param model/* w w w . ja v a 2 s . com*/ * @param session * @param request * @return view name */ @RequestMapping(value = AliquotIdBreakdownReportConstants.ALIQUOT_ID_BREAKDOWN_REPORT_URL, method = RequestMethod.GET, params = { "!" + DatareportsCommonConstants.ALIQUOT_ID, "!" + DatareportsCommonConstants.ANALYTE_ID, "!" + DatareportsCommonConstants.SAMPLE_ID, "!" + DatareportsCommonConstants.PARTICIPANT_ID }) public String aliquotIdBreakdownReportSimpleHandler(final ModelMap model, final HttpSession session, final HttpServletRequest request) { final ModelMap bbModel = (ModelMap) session .getAttribute(AliquotIdBreakdownReportConstants.ALIQUOT_ID_BREAKDOWN_FILTER_MODEL); if (bbModel != null && bbModel.size() > 0) { model.addAllAttributes(bbModel); } final List<AliquotIdBreakdown> aliquotIdBreakdownList = service.getAliquotIdBreakdown(); commonService.processDisplayTag("aliquotIdBreakdown", aliquotIdBreakdownList, model, request); model.addAttribute(DatareportsCommonConstants.SERVER_URL, serverAddress); session.removeAttribute(AliquotIdBreakdownReportConstants.ALIQUOT_ID_BREAKDOWN_FILTER_MODEL); return AliquotIdBreakdownReportConstants.ALIQUOT_ID_BREAKDOWN_REPORT_VIEW; }
From source file:net.ontopia.topicmaps.classify.WebChew.java
public void processForm() { HttpSession session = request.getSession(true); String tmckey = getClassificationKey(); // reclassify if (request.getParameter("reclassify") != null) { session.removeAttribute(tmckey); }/*from w ww . j a v a 2 s .com*/ // black list selected terms String blacklisted = request.getParameter("blacklisted"); if (blacklisted != null && blacklisted.length() > 0) { BlackList bl = getBlackList(); bl.addStopWord(blacklisted); bl.save(); } // remove selected association String removeAssociation = request.getParameter("removeAssociation"); if (removeAssociation != null) { // process form data try { TopicMapStoreIF store = NavigatorUtils.getTopicMapRepository(session.getServletContext()) .getReferenceByKey(request.getParameter("tm")).createStore(false); try { TopicMapIF topicmap = store.getTopicMap(); AssociationIF assoc = (AssociationIF) topicmap.getObjectById(removeAssociation); if (assoc != null) assoc.remove(); store.commit(); } finally { store.close(); } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } String[] selected = request.getParameterValues("selected"); if (request.getParameter("ok") != null || request.getParameter("cancel") != null) { try { // if ok pressed process form if (request.getParameter("ok") != null) { // create associations; look up existing classified document in session TopicMapClassification tmc = (TopicMapClassification) session.getAttribute(tmckey); if (tmc == null) return; // process form data TopicMapStoreIF store = NavigatorUtils.getTopicMapRepository(session.getServletContext()) .getReferenceByKey(request.getParameter("tm")).createStore(false); try { TopicMapIF topicmap = store.getTopicMap(); TopicMapBuilderIF builder = topicmap.getBuilder(); // get document topic TopicIF dtopic = (TopicIF) topicmap.getObjectById(request.getParameter("id")); if (selected != null && selected.length > 0) { for (int i = 0; i < selected.length; i++) { String termid = selected[i]; String at = request.getParameter("at-" + termid); if (at == null || "-".equals(at)) continue; String cn = request.getParameter("cn-" + termid); String ct = request.getParameter("ct-" + termid); if (ct == null || "-".equals(ct)) continue; // create new candidate topic TopicIF ctopic; if (ct.startsWith("new:")) { String ctoid = ct.substring("new:".length()); TopicIF ctype = (TopicIF) topicmap.getObjectById(ctoid); if (ctype == null) throw new OntopiaRuntimeException( "Cannot find topic type: " + ct + " " + ctoid); ctopic = builder.makeTopic(ctype); builder.makeTopicName(ctopic, cn); } else if ("-".equals(ct)) { continue; // ignore } else { ctopic = (TopicIF) topicmap.getObjectById(ct); } // create association String[] at_data = StringUtils.split(at, ":"); if (at_data.length != 3) continue; TopicIF atype = (TopicIF) topicmap.getObjectById(at_data[0]); if (atype == null) throw new OntopiaRuntimeException("Cannot find association type: " + at); TopicIF drtype = (TopicIF) topicmap.getObjectById(at_data[1]); if (drtype == null) throw new OntopiaRuntimeException( "Cannot find document roletype: " + at_data[1]); TopicIF crtype = (TopicIF) topicmap.getObjectById(at_data[2]); if (crtype == null) throw new OntopiaRuntimeException( "Cannot find concept roletype: " + at_data[2]); AssociationIF assoc = builder.makeAssociation(atype); builder.makeAssociationRole(assoc, drtype, dtopic); builder.makeAssociationRole(assoc, crtype, ctopic); } // remove duplicate associations DuplicateSuppressionUtils.removeDuplicateAssociations(dtopic); store.commit(); } } finally { store.close(); } } // clear classication session.removeAttribute(tmckey); // redirect back to instance page response.sendRedirect(redirectURI); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } }