List of usage examples for javax.servlet.http HttpSession setMaxInactiveInterval
public void setMaxInactiveInterval(int interval);
From source file:fr.aliasource.webmail.server.LoginFilter.java
private boolean doLogin(HttpSession s, String login, String password) throws InstantiationException, IllegalAccessException, ClassNotFoundException, ClientException { logger.info("Filter based login"); ProxyConfig cfg = new ProxyConfig(settings); IAccount account = proxyClientFactory.newProxyClient(cfg); try {/* w w w. java 2 s . co m*/ if (login.contains("@")) { String[] creds = login.split("@"); account.login(creds[0], creds[1], password); } else { account.login(login, null, password); } s.setAttribute("account", account); s.setMaxInactiveInterval(3 * 60); return true; } catch (Exception e) { logger.error("Error loging into backend : user without mailbox ? (" + login + ")"); return false; } }
From source file:org.sakaiproject.tool.assessment.ui.web.session.SessionUtil.java
/** * Sets the current <code>HttpSession</code> maxInactiveInterval value * @param context the faces context/*from ww w. ja v a 2s .c o m*/ * @param delivery the delivery bean * @param beginAssessment true if called from the beginning of an assessment, otherwise false * * @see org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean */ public static void setSessionTimeout(FacesContext context, DeliveryBean delivery, boolean beginAssessment) { if (!IntegrationContextFactory.getInstance().isIntegrated()) { return; } ExternalContext exContext = context.getExternalContext(); HttpSession session = (HttpSession) exContext.getSession(false); if (session == null) { return; } /** if we have a tool session then get big session (MySession) */ if (session instanceof ToolSession) { session = (HttpSession) SessionManager.getCurrentSession(); } synchronized (session) { if (beginAssessment) { /** * if we have not already set value * (ensure setSessionTimeout is called only once at beginning of assessment) */ int interval = DEFAULT_APP_INTERVAL_VAL; if (session.getAttribute(EXTERNAL_APP_INTERVAL) == null) { if (delivery != null && delivery.getHasTimeLimit()) { interval = delivery.getTimeLimit_hour() * HOURS_TO_SECONDS_MULTIPLIER; interval += delivery.getTimeLimit_minute() * MINUTES_TO_SECONDS_MULTIPLIER; } else { /** for assessments without time limit */ interval = DEFAULT_APP_INTERVAL_VAL; } } if (interval > session.getMaxInactiveInterval()) { if (log.isDebugEnabled()) { log.debug("begin_assessment: Setting session " + session.getId() + " inactive interval= " + interval + " seconds"); } /** store current interval value */ session.setAttribute(EXTERNAL_APP_INTERVAL, Integer.valueOf(session.getMaxInactiveInterval())); session.setMaxInactiveInterval(interval + INTERVAL_BUFFER); } } else { /** on assessment submission or 'save and exit' from assessment */ Integer returnVal = (Integer) session.getAttribute(EXTERNAL_APP_INTERVAL); if (returnVal == null) { return; } else { session.removeAttribute(EXTERNAL_APP_INTERVAL); if (log.isDebugEnabled()) { log.debug("end_assessment: Setting session " + session.getId() + " inactive interval= " + returnVal + " seconds"); } /** set to value of interval before taking */ session.setMaxInactiveInterval(returnVal.intValue()); } } } }
From source file:org.openmrs.module.cccgenerator.web.controller.CCCGeneratorFormController.java
@RequestMapping(method = RequestMethod.POST, value = "module/cccgenerator/cccgeneratorForm.form") public void whenPageIsPosted(ModelMap map, HttpServletRequest request, @RequestParam(required = false, value = "site") String siteId, @RequestParam(required = true, value = "cohort") String cohortdefuuid) { //lengthen the session to make sure generation is complete HttpSession httpSession = request.getSession(); Integer httpSessionvalue = httpSession.getMaxInactiveInterval(); httpSession.setMaxInactiveInterval(-1); CCCGeneratorService service = Context.getService(CCCGeneratorService.class); EncounterService encounterservice = Context.getEncounterService(); AdministrationService adminservice = Context.getAdministrationService(); PatientService pService = Context.getPatientService(); LocationService locservice = Context.getLocationService(); List<Patient> listOfHIVPatientsPerSite = new ArrayList<Patient>(); Set<Integer> patientIdsFromCohort = null; ///////try to find all the required ids for patient CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class); List<CohortDefinition> listOfCohorts = cohortDefinitionService.getAllDefinitions(false); List<Location> listOfLocations = Context.getLocationService().getAllLocations(false); map.addAttribute("listOfCohort", listOfCohorts); CohortDefinition cohortDefinition = Context.getService(CohortDefinitionService.class) .getDefinitionByUuid(cohortdefuuid); try {/* w w w . j a va 2s. c o m*/ EvaluationContext evaluationContext = new EvaluationContext(); //add loctation to be displayed here ///evaluationContext.addParameterValue("locationList",Arrays.asList(Context.getLocationService().getLocation(Integer.parseInt(siteId)))); //evaluation Cohort cohort = cohortDefinitionService.evaluate(cohortDefinition, evaluationContext); patientIdsFromCohort = new HashSet<Integer>(); patientIdsFromCohort.addAll(cohort.getMemberIds()); } catch (Exception e) { e.printStackTrace(); } ////////////////////////////////////////////////// //get the location from the jsp interface Location siteLocation = locservice.getLocation(Integer.parseInt(siteId)); map.addAttribute("location1", siteLocation.getName()); Integer CCC = 0; Integer lastcount = 0; String CCCIdentifier = ""; String glbCCC = ""; int number_of_hiv_patients_affected = 0; int number_of_hiv_patients_affected_generated = 0; //cohort to return all patient ids log.info("Get all patients who are HIV positive " + patientIdsFromCohort.size()); //get cohort of all the patient ids in the database Cohort allpatientscohort = Context.getPatientSetService().getAllPatients(); Set<Integer> allpatientscohortset = allpatientscohort.getMemberIds(); log.info("All patients in the databse are " + allpatientscohortset.size()); //get all patients to exclude from the set Set<Integer> toExclude = new HashSet<Integer>( Context.getService(CCCGeneratorService.class).excludeDiscontinued().getMemberIds()); log.info("The number of patients discontinued from care " + toExclude.size()); //remove the above from the patientIdsFromCohort to get only true matches patientIdsFromCohort.removeAll(toExclude); //get the intersection of only the patients who are present no empty slots Set<Integer> uniqueSetids = new HashSet<Integer>( CollectionUtils.intersection(allpatientscohortset, patientIdsFromCohort)); log.info("Only unique numbers selected " + uniqueSetids.size()); //get aready generated members Cohort listOfHIVPatientIdAlreadygenerated = service.getAllHIVPatients(); Set<Integer> listOfHIVPatientIdAlreadygeneratedpatientsIds = new HashSet<Integer>( listOfHIVPatientIdAlreadygenerated.getMemberIds()); log.info("Already generated ones are " + listOfHIVPatientIdAlreadygeneratedpatientsIds.size()); //get the difference in number of HIV patients uniqueSetids.removeAll(listOfHIVPatientIdAlreadygeneratedpatientsIds); log.info("Difference comes in here excluding already generated ones " + uniqueSetids.size()); Patient patients; int count = 0; for (Integer patientId : uniqueSetids) { count++; log.info("This patient Number " + patientId + " and this number " + count + " Remaining " + (uniqueSetids.size() - count)); cleanupafterCount(count); patients = pService.getPatient(patientId); List<Encounter> listOfEncounters = encounterservice.getEncountersByPatientId(patientId); Collections.sort(listOfEncounters, new SortEncountersByDateComparator()); for (Encounter encounters : listOfEncounters) { log.info("Got in the encounters loop"); if (encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ADULT_INITIAL) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ADULT_RETURN) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PEDS_INITIAL) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PEDS_RETURN) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_BASELINE_INVESTIGATION) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PMTCTANC) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PMTCTPOSTNATAL) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ECPeds) || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ECSTABLE)) { // log.info("Found a patient having HIV encounters"); // log.info("Locations are seen here if equal is when we enter the loop "); log.info(encounters.getLocation() + "==" + locservice.getLocation(Integer.parseInt(siteId))); //starts here //get all the related locations in the database Set<Integer> getAllLocations = Context.getService(CCCGeneratorService.class) .getIdsOfLocationsParentAndChildren(Integer.parseInt(siteId)); log.info("All locations and their sub sites " + getAllLocations.size()); for (Integer i : getAllLocations) { if (encounters.getLocation() == locservice.getLocation(i)) { log.info("Checking for provided location from the encounters"); CCCLocation ml = service .getCCCLocationByLocation(locservice.getLocation(Integer.parseInt(siteId))); //we pick the unique number for every facility CCC = ml.getCCC(); //using CCC above we check for the last count CCCCount mc = service.getCCCCountByCCC(CCC); lastcount = mc.getLastCount(); log.info("This the last count per the location and CCC " + lastcount); //we increament the count by one lastcount++; String pCCCIdentifier = "" + lastcount; //check for the number of digits required to be concatnated to facility number if (pCCCIdentifier.length() < 5) { int x = 5 - pCCCIdentifier.length(); String y = ""; for (int k = 0; k < x; k++) y += "0"; pCCCIdentifier = y + pCCCIdentifier; } CCCIdentifier = CCC + "-" + pCCCIdentifier; glbCCC = adminservice.getGlobalProperty("cccgenerator.CCC"); PatientIdentifierType patientIdentifierType = pService .getPatientIdentifierTypeByName(glbCCC); List<PatientIdentifier> listOfCCCIdentifier = pService.getPatientIdentifiers(null, Arrays.asList(patientIdentifierType), Arrays.asList(locservice.getLocation(i)), Arrays.asList(patients), false); log.info("Already patients ids per CCC " + listOfCCCIdentifier.size()); if (listOfCCCIdentifier.size() == 0) { //} PatientIdentifier patientIdentifier = new PatientIdentifier(); patientIdentifier.setPatient(patients); patientIdentifier.setIdentifier(CCCIdentifier); patientIdentifier.setIdentifierType(patientIdentifierType); patientIdentifier.setLocation(locservice.getLocation(i)); patientIdentifier.setPreferred(false); mc.setLastCount(lastcount); //save the count thereby rewriting the previous one service.saveCCCCount(mc); Integer thecountLast = null; Integer CCCcount = null; CCCCount thecount = service.getCCCCountByCCC(CCC); thecountLast = thecount.getCCC(); CCCcount = thecount.getLastCount(); //log.info("This is the count "+CCCcount+" and CCC is "+thecountLast); //add and save patient identserifier pService.savePatientIdentifier(patientIdentifier); number_of_hiv_patients_affected += 1; number_of_hiv_patients_affected_generated += number_of_hiv_patients_affected; //add the patients to the list so that we can use in the jsp listOfHIVPatientsPerSite.add(patients); //////////////////////////////////////////////////////////////////////// //CCCCount allCCC=new CCCCount(); //update all other related sites List<CCCCount> allCCC = service.getAllRelatedSites(thecountLast); //log.info("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu "+allCCC.size()); //log.info("This is the CCC sizes "+allCCC.getLocation()); for (CCCCount m : allCCC) { m.setLastCount(CCCcount); service.saveCCCCount(m); } // log.info("After the count has been changed "); //////////////////////////////////////////////////////////////////////// cleanupaftersaving(number_of_hiv_patients_affected); } else { continue; } } } } break; } } List<Location> locations = locservice.getAllLocations(false); map.addAttribute("siteLocations", locations); map.addAttribute("totalcccnumbersgenerated", listOfHIVPatientsPerSite.size()); httpSession.setMaxInactiveInterval(httpSessionvalue); }
From source file:org.structr.common.SecurityContext.java
public HttpSession getSession() { if (request != null) { final HttpSession session = request.getSession(false); if (session != null) { session.setMaxInactiveInterval(Services.getGlobalSessionTimeout()); }//from w ww . ja v a2 s .c om return session; } return null; }
From source file:org.forgerock.openidm.filter.AuthFilter.java
private void createSession(HttpServletRequest req, HttpSession sess, AuthData ad) { if (req.getHeader("X-OpenIDM-NoSession") == null) { sess = req.getSession();//from w ww .j a v a2s .co m sess.setAttribute(USERNAME_ATTRIBUTE, ad.username); sess.setAttribute(USERID_ATTRIBUTE, ad.userId); sess.setAttribute(ROLES_ATTRIBUTE, ad.roles); sess.setAttribute(RESOURCE_ATTRIBUTE, ad.resource); sess.setMaxInactiveInterval(authModule.sessionTimeout); if (logger.isDebugEnabled()) { logger.debug("Created session for: {} with id {}, roles {} and resource: {}", new Object[] { ad.username, ad.userId, ad.roles, ad.resource }); } } }
From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); String action = request.getParameter("Action"); String name = request.getParameter("Name"); String value = request.getParameter("Value"); String age = request.getParameter("MaxAge"); String nextUrl = getURI(request) + "?R=" + redirectCount++; if (action.equals("New Session")) { session = request.getSession(true); } else if (session != null) { if (action.equals("Invalidate")) session.invalidate();//from ww w . jav a 2s . c o m else if (action.equals("Set")) { session.setAttribute(name, value); try { int m = Integer.parseInt(age); session.setMaxInactiveInterval(m); } catch (Exception e) { LogSupport.ignore(log, e); } } else if (action.equals("Remove")) session.removeAttribute(name); } String encodedUrl = response.encodeRedirectURL(nextUrl); response.sendRedirect(encodedUrl); }
From source file:password.pwm.http.filter.RequestInitializationFilter.java
private void checkIfSessionRecycleNeeded(final PwmRequest pwmRequest) throws IOException, ServletException { if (!pwmRequest.getPwmSession().getSessionStateBean().isSessionIdRecycleNeeded()) { return;//from ww w. j a va 2s . c om } final boolean recycleEnabled = Boolean .parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.HTTP_SESSION_RECYCLE_AT_AUTH)); if (!recycleEnabled) { return; } LOGGER.debug(pwmRequest, "forcing new http session due to authentication"); final HttpServletRequest req = pwmRequest.getHttpServletRequest(); // read the old session data final HttpSession oldSession = req.getSession(true); final int oldMaxInactiveInterval = oldSession.getMaxInactiveInterval(); final Map<String, Object> sessionAttributes = new HashMap<>(); final Enumeration oldSessionAttrNames = oldSession.getAttributeNames(); while (oldSessionAttrNames.hasMoreElements()) { final String attrName = (String) oldSessionAttrNames.nextElement(); sessionAttributes.put(attrName, oldSession.getAttribute(attrName)); } for (final String attrName : sessionAttributes.keySet()) { oldSession.removeAttribute(attrName); } //invalidate the old session oldSession.invalidate(); // make a new session final HttpSession newSession = req.getSession(true); // write back all the session data for (final String attrName : sessionAttributes.keySet()) { newSession.setAttribute(attrName, sessionAttributes.get(attrName)); } newSession.setMaxInactiveInterval(oldMaxInactiveInterval); pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(false); }
From source file:com.clt.systemmanger.controller.UserAction.java
/** * @Description: /*w ww . j a v a2s. c o m*/ * @param session * @return String ?? * @author hjx * @create_date 2015910 ?3:05:04 */ @RequestMapping("/layoutByPC") @ResponseBody public Map<String, Object> layoutByPC(HttpSession session) { TUser user = (TUser) session.getAttribute("user"); if (null != user) { UserSession.set("user", null); session.setAttribute("user", null); session.setMaxInactiveInterval(0); } return AjaxUtil.getMap(true, "??"); }
From source file:com.mirth.connect.server.servlets.UserServlet.java
private LoginStatus login(HttpServletRequest request, HttpServletResponse response, UserController userController, EventController eventController, String username, String password, String version) throws ServletException { try {//from ww w .ja v a2s. c o m LoginStatus loginStatus = null; ConfigurationController configurationController = ControllerFactory.getFactory() .createConfigurationController(); // if the version of the client in is not the same as the server and // the version is not 0.0.0 (bypass) if (!version.equals(configurationController.getServerVersion()) && !version.equals("0.0.0")) { loginStatus = new LoginStatus(LoginStatus.Status.FAIL_VERSION_MISMATCH, "Mirth Connect Administrator version " + version + " cannot conect to Server version " + configurationController.getServerVersion() + ". Please clear your Java cache and relaunch the Administrator from the Server webpage."); } else { HttpSession session = request.getSession(); loginStatus = userController.authorizeUser(username, password); if ((loginStatus.getStatus() == LoginStatus.Status.SUCCESS) || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) { User user = new User(); user.setUsername(username); User validUser = userController.getUser(user).get(0); // set the sessions attributes session.setAttribute(SESSION_USER, validUser.getId()); session.setAttribute(SESSION_AUTHORIZED, true); // this prevents the session from timing out session.setMaxInactiveInterval(-1); // set the user status to logged in in the database userController.loginUser(validUser); // add the user's session to to session map UserSessionCache.getInstance().registerSessionForUser(session, validUser); } } // Manually audit the Login event with the username since the user // id has not been stored to the session yet Event event = new Event(); event.setIpAddress(getRequestIpAddress(request)); event.setLevel(Level.INFORMATION); event.setName(Operations.USER_LOGIN.getDisplayName()); // Set the outcome to the result of the login attempt event.setOutcome(((loginStatus.getStatus() == LoginStatus.Status.SUCCESS) || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) ? Outcome.SUCCESS : Outcome.FAILURE); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("username", username); event.setAttributes(attributes); eventController.addEvent(event); return loginStatus; } catch (Exception e) { throw new ServletException(e); } }
From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java
protected void removeSession(HttpServletRequest request, int interval) { if (Engine.isEngineMode()) { Engine.logContext.debug("[GenericServlet] End of session required => try to invalidate session"); try {/*from w w w . j av a 2 s .c o m*/ HttpSession httpSession = request.getSession(); boolean isAdminSession = "true".equals((String) httpSession.getAttribute("administration")); if (!isAdminSession && Engine.theApp.contextManager.isSessionEmtpy(httpSession.getId())) { Engine.logContext.debug( "[GenericServlet] The owner HTTP session is empty => invalidating HTTP session in " + interval + "s."); httpSession.setMaxInactiveInterval(interval); } } catch (Exception e) { Engine.logContext .debug("[GenericServlet] End of session required => failed to get the session: " + e); } } }