Example usage for javax.servlet.http HttpSession setMaxInactiveInterval

List of usage examples for javax.servlet.http HttpSession setMaxInactiveInterval

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession setMaxInactiveInterval.

Prototype

public void setMaxInactiveInterval(int interval);

Source Link

Document

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Usage

From source file:org.polymap.service.fs.webdav.WebDavServer.java

/**
 * Initializes a new session for the given user.
 * <p/>//  ww w.  jav a 2 s.c o m
 * This method is called by {@link SecurityManagerAdapter}
 * 
 * @param user
 * @return The specified user.
 */
public static Principal createNewSession(final Principal user) {
    HttpServletRequest req = com.bradmcevoy.http.ServletRequest.getRequest();
    final HttpSession session = req.getSession();

    // HTTP session timeout: 30min
    session.setMaxInactiveInterval(30 * 60);

    FsPlugin.getDefault().sessionContextProvider.mapContext(user.getName(), true);
    final SessionContext sessionContext = SessionContext.current();

    // ContentManager
    Locale locale = req.getLocale();
    sessionContext.setAttribute("contentManager",
            ContentManager.forUser(user.getName(), locale, sessionContext));

    // invalidate HTTP session when context is destroyed
    sessionContext.addSessionListener(new ISessionListener() {
        public void beforeDestroy() {
            log.info("SessionContext is destroyed -> invalidating HTTP session");
            try {
                //sessionContext.removeSessionListener( this );
                session.invalidate();
            } catch (Exception e) {
                log.warn("HTTP session already invalidated: " + e);
            }
        }
    });
    // session destroy listener
    session.setAttribute("sessionListener", new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent ev) {
        }

        public void valueUnbound(HttpSessionBindingEvent ev) {
            //
            sessionContext.execute(new Runnable() {
                public void run() {
                    ContentManager.releaseSession(user.getName());
                }
            });
            // prevent life-lock
            if (!sessionContext.isDestroyed() && sessionContext.getAttribute("destroying") == null) {
                sessionContext.setAttribute("destroying", true);
                FsPlugin.getDefault().sessionContextProvider.destroyContext(sessionContext.getSessionKey());
                log.info("HTTP Session destroyed: " + session.getId() + ", user: " + user);
            }
        }
    });
    log.info("New HTTP session: " + session.getId() + ", user: " + user);
    return user;
}

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

public static void terminateSession(HttpSession httpSession) {
    if (httpSession != null) {
        if ("true".equals("" + httpSession.getAttribute("administration"))) {
            httpSession.setMaxInactiveInterval(1);
        }/* w w w.j  a  v  a2s.com*/
    }
}

From source file:org.structr.core.auth.AuthHelper.java

public static HttpSession newSession(final HttpServletRequest request) {

    HttpSession session = request.getSession(true);
    if (session == null) {

        // try again
        session = request.getSession(true);

    }//w  w w . j  av  a2 s  .  co  m

    if (session != null) {

        session.setMaxInactiveInterval(Services.getGlobalSessionTimeout());

    } else {

        logger.log(Level.SEVERE, "Unable to create new session after two attempts");

    }

    return session;

}

From source file:com.mnt.base.web.DigestAuthenticator.java

public static boolean authenticate(HttpServletRequest req, HttpServletResponse resp) {

    boolean result = false;

    HttpSession session = req.getSession();

    if (session != null) {

        result = session.getAttribute(AUTHENTICATED_FLAG_KEY) != null;

        if (!result) {

            session.setMaxInactiveInterval(60);

            Map<String, Object> authInfoMap = CommonUtil.uncheckedMapCast(session.getAttribute(AUTH_INFO_MAP));

            if (authInfoMap == null) {
                authInfoMap = new HashMap<String, Object>();
                session.setAttribute(AUTH_INFO_MAP, authInfoMap);
            }//from   w ww  . ja v a 2  s .c om

            String authentication = req.getHeader("Authorization");

            if (CommonUtil.isEmpty(authentication) || !authentication.startsWith("Digest ")) {

                postAuthRequired(req, resp, authInfoMap);

            } else {
                result = authenticate(req.getMethod(), authentication, authInfoMap);

                if (result) {

                    if (authProvider != null) {
                        try {
                            authProvider.authenticated(authUser.get(), true);
                        } catch (Exception e) {
                            log.error("error while invoke the authProvider.authenticated: " + authUser.get(),
                                    e);
                        }
                    }
                    session.setAttribute(AUTHENTICATED_FLAG_KEY, true);
                    session.removeAttribute(AUTH_INFO_MAP);
                    authInfoMap.clear();
                    authInfoMap = null;

                    session.setMaxInactiveInterval(1800);
                } else {
                    authProvider.authenticated(authUser.get(), false);
                    authInfoMap.clear();
                    postAuthRequired(req, resp, authInfoMap);
                }
            }
        }
    } else {
        System.err.println("Just support session available authentication.");
    }

    return result;
}

From source file:org.itracker.web.util.LoginUtilities.java

public static User setupSession(User user, String encPassword, HttpServletRequest request,
        HttpServletResponse response) {//from www . java 2s . c o  m
    if (user == null) {
        logger.warn("setupSession: null user", (logger.isDebugEnabled() ? new RuntimeException() : null));
        throw new IllegalArgumentException("null user");
    }

    UserService userService = ServletContextUtils.getItrackerServices().getUserService();

    if (logger.isDebugEnabled()) {
        logger.debug("Creating new session");
    }
    HttpSession session = request.getSession(true);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session timeout to " + getConfiguredSessionTimeout() + " minutes");
    }
    session.setMaxInactiveInterval(getConfiguredSessionTimeout() * 60);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session tracker");
    }
    session.setAttribute(Constants.SESSION_TRACKER_KEY, new SessionTracker(user.getLogin(), session.getId()));

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user information");
    }
    session.setAttribute(Constants.USER_KEY, user);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting preferences for user " + user.getLogin());
    }
    UserPreferences userPrefs = user.getPreferences();
    // TODO : this is a hack, remove when possible
    if (userPrefs == null) {
        logger.warn("setupSession: got user with no preferences!: " + user + " (prefs: " + user.getPreferences()
                + ")");
        userPrefs = new UserPreferences();
    }
    session.setAttribute(Constants.PREFERENCES_KEY, userPrefs);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user " + user + " locale to "
                + ITrackerResources.getLocale(userPrefs.getUserLocale()));
    }
    session.setAttribute(Constants.LOCALE_KEY, ITrackerResources.getLocale(userPrefs.getUserLocale()));

    // TODO: cookie could be removed
    Cookie cookie = new Cookie(Constants.COOKIE_NAME, "");
    cookie.setPath(request.getContextPath());

    cookie.setValue("");
    cookie.setMaxAge(0);

    response.addCookie(cookie);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting permissions for user " + user.getLogin());
    }
    Map<Integer, Set<PermissionType>> usersMapOfProjectIdsAndSetOfPermissionTypes = userService
            .getUsersMapOfProjectIdsAndSetOfPermissionTypes(user, AuthenticationConstants.REQ_SOURCE_WEB);
    session.setAttribute(Constants.PERMISSIONS_KEY, usersMapOfProjectIdsAndSetOfPermissionTypes);

    // Reset some session forms
    session.setAttribute(Constants.SEARCH_QUERY_KEY, null);

    SessionManager.clearSessionNeedsReset(user.getLogin());
    if (logger.isDebugEnabled()) {
        logger.debug("User session data updated.");
    }
    return user;
}

From source file:com.sentinel.web.controllers.LoginController.java

/**
 * api to set session timeout for current HttpSession. timeoutInSeconds is
 * optional parameter. If not set, will be defaulted to 24 hours (86400s)
 * // w  w w .ja v a  2  s  . c om
 * @param timeoutInSeconds
 * @param httpSession
 * @return
 */
@RequestMapping(method = RequestMethod.PUT, value = "/loginsession/timeout")
public @ResponseBody String setSessionTimeout(
        @RequestParam(value = "timeoutInSeconds", defaultValue = "86400") int timeoutInSeconds,
        HttpSession httpSession) {
    httpSession.setMaxInactiveInterval(timeoutInSeconds);
    return "httpSession timeout set to:" + httpSession.getMaxInactiveInterval();
}

From source file:org.openmrs.module.clinicalsummary.web.controller.evaluator.EvaluateReminderController.java

@RequestMapping(method = RequestMethod.POST)
public String processForm(final @RequestParam(required = false, value = "cohort") Integer cohortId,
        final HttpSession session) {
    int maxInactiveInterval = session.getMaxInactiveInterval();
    session.setMaxInactiveInterval(-1);
    Cohort cohort = Context.getCohortService().getCohort(cohortId);
    ReminderCohortEvaluatorInstance.getInstance().evaluate(new Cohort(cohort.getMemberIds()));
    session.setMaxInactiveInterval(maxInactiveInterval);
    return "redirect:evaluateReminder.form";
}

From source file:org.openmrs.module.clinicalsummary.web.controller.evaluator.EvaluatePatientsController.java

@RequestMapping(method = RequestMethod.POST)
public String processForm(final @RequestParam(required = false, value = "cohort") Integer cohortId,
        final @RequestParam(required = false, value = "summaryId") Integer summaryId,
        final HttpSession session) {
    int maxInactiveInterval = session.getMaxInactiveInterval();
    session.setMaxInactiveInterval(-1);

    Summary summary = Context.getService(SummaryService.class).getSummary(summaryId);
    Cohort cohort = Context.getCohortService().getCohort(cohortId);

    SummaryCohortEvaluatorInstance instance = SummaryCohortEvaluatorInstance.getInstance();
    instance.evaluate(new Cohort(cohort.getMemberIds()), Arrays.asList(summary));

    session.setMaxInactiveInterval(maxInactiveInterval);
    return "redirect:evaluatePatients.form";
}

From source file:org.openmrs.module.clinicalsummary.web.controller.evaluator.EvaluateCohortController.java

@RequestMapping(method = RequestMethod.POST)
public String processForm(
        final @RequestParam(required = false, value = "patientIdentifiers") String patientIdentifiers,
        final @RequestParam(required = false, value = "locationId") String locationId,
        final @RequestParam(required = false, value = "obsStartDate") Date startDate,
        final @RequestParam(required = false, value = "obsEndDate") Date endDate, final HttpSession session) {

    int maxInactiveInterval = session.getMaxInactiveInterval();
    session.setMaxInactiveInterval(-1);

    if (StringUtils.isBlank(locationId) && StringUtils.isBlank(patientIdentifiers)) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "clinicalsummary.invalid.parameters");
    } else {/*w w  w  .  j  a v a  2 s  .com*/
        Cohort cohort = new Cohort();
        if (StringUtils.isNotBlank(patientIdentifiers)) {
            String[] patientIdentifier = StringUtils.split(patientIdentifiers);
            cohort = Context.getPatientSetService().convertPatientIdentifier(Arrays.asList(patientIdentifier));
        } else if (StringUtils.isNotBlank(locationId)) {
            Location location = Context.getLocationService().getLocation(NumberUtils.toInt(locationId, -1));
            cohort = Context.getService(CoreService.class).getDateCreatedCohort(location, startDate, endDate);
        }
        SummaryCohortEvaluatorInstance instance = SummaryCohortEvaluatorInstance.getInstance();
        instance.evaluate(cohort);
    }
    session.setMaxInactiveInterval(maxInactiveInterval);
    return "redirect:evaluateCohort.form";
}

From source file:com.liferay.tool.datamanipulator.thread.HandlerThread.java

@Override
public void run() {
    HttpSession httpSession = _requestContext.getSession();
    httpSession.setMaxInactiveInterval(-1);

    //PermissionThreadLocal.setIndexEnabled(false);
    PermissionThreadLocal.setPermissionChecker(_requestContext.getPermissionChecker());

    PrincipalThreadLocal.setName(_requestContext.getUserId());

    PortalSessionThreadLocal.setHttpSession(httpSession);

    String threadName = this.getName();

    long startTime = System.currentTimeMillis();

    StringBuilder startSB = new StringBuilder(5);
    startSB.append(threadName);//from  w  ww.j  ava  2  s.  c  o m
    startSB.append(": Started generating '");
    startSB.append(HandlerUtil.getHandlerDisplayName(_handler.getClass()));
    startSB.append("' entries at ");
    startSB.append(new java.util.Date(startTime));

    _log.info(startSB.toString());

    try {
        _handler.proceed(_requestContext);
    } catch (Exception e) {
        _log.error(e, e);
    }

    long endTime = System.currentTimeMillis();

    StringBuilder finishSB = new StringBuilder(5);
    finishSB.append(threadName);
    finishSB.append(": Finished generating '");
    finishSB.append(HandlerUtil.getHandlerDisplayName(_handler.getClass()));
    finishSB.append("' entries at ");
    finishSB.append(new java.util.Date(endTime));

    _log.info(finishSB.toString());

    StringBuilder tookSB = new StringBuilder(4);
    tookSB.append(threadName);
    tookSB.append(": The generation process took ");
    tookSB.append(DurationFormatUtils.formatDurationWords(endTime - startTime, true, true));

    _log.info(tookSB.toString());
}