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.openmrs.module.clinicalsummary.web.controller.evaluator.EvaluateRuleController.java

@RequestMapping(method = RequestMethod.POST)
public String processForm(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);
    Location location = Context.getLocationService().getLocation(NumberUtils.toInt(locationId, -1));
    Cohort cohort = Context.getService(CoreService.class).getDateCreatedCohort(location, startDate, endDate);

    Integer counter = 0;//from www  .  j a v  a  2  s  .c o m
    int firstElement = 0;
    for (Integer patientId : cohort.getMemberIds()) {
        Patient patient = Context.getPatientService().getPatient(patientId);
        SummaryService service = Context.getService(SummaryService.class);
        // reuse index that's already exists but not needed anymore
        List<Index> activeIndexes = Context.getService(IndexService.class).getIndexes(patient);
        List<Summary> summaries = service.getSummaries(patient);
        while (!activeIndexes.isEmpty()) {
            Index activeIndex = activeIndexes.remove(firstElement);
            if (CollectionUtils.isNotEmpty(summaries) && !summaries.contains(activeIndex.getSummary()))
                Context.getService(IndexService.class).deleteIndex(activeIndex);
        }
        counter++;
        if (counter % 20 == 0) {
            Context.flushSession();
            Context.clearSession();
        }
        ResultCacheInstance.getInstance().clearCache(patient);
    }
    session.setMaxInactiveInterval(maxInactiveInterval);
    return "redirect:evaluateRule.form";
}

From source file:fr.aliasource.webmail.server.LoginImpl.java

public boolean doLogin(String login, String password, String domain) {
    HttpSession session = getThreadLocalRequest().getSession();
    // needs to be shorter than backend session
    session.setMaxInactiveInterval(1 * 60);

    IAccount account = (IAccount) session.getAttribute("account");
    if (account == null) {
        try {/*from  ww  w. ja v a  2  s  .  c  o  m*/
            account = proxyClientFactory.newProxyClient(cfg);
            account.login(login, domain, password);
            session.setAttribute("account", account);
            return true;
        } catch (ClientException e) {
            return false;
        }
    } else {
        return true;
    }
}

From source file:modelo.AutenticacionManager.Autenticacion.java

public void doLogIn(String login, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String rol = "";
    String ip = request.getRemoteAddr();
    HttpSession sesion = request.getSession();

    variablesSession(sesion, response, login, rol, ip);
    //Tiempo en que expira la sesion
    sesion.setMaxInactiveInterval(Integer.parseInt(ActiveDirectory.getString("sesionTimeOut")));
}

From source file:com.martin.zkedit.controller.Login.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Login Post Action!");
    try {/*from  ww  w .j  a v  a  2 s .c  o  m*/
        Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
        Map<String, Object> templateParam = new HashMap<>();
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout")));
        //TODO: Implement custom authentication logic if required.
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = null;
        Boolean authenticated = false;
        //if ldap is provided then it overrides roleset.
        if (globalProps.getProperty("ldapAuth").equals("true")) {
            authenticated = new LdapAuth().authenticateUser(globalProps.getProperty("ldapUrl"), username,
                    password, globalProps.getProperty("ldapDomain"));
            if (authenticated) {
                JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                        .parse(globalProps.getProperty("ldapRoleSet"))).get("users");
                for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                    JSONObject jsonUser = (JSONObject) it.next();
                    if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) {
                        role = (String) jsonUser.get("role");
                    }
                    if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) {
                        role = (String) jsonUser.get("role");
                    }
                }
                if (role == null) {
                    role = ZooKeeperUtil.ROLE_USER;
                }

            }
        } else {
            JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                    .parse(globalProps.getProperty("userSet"))).get("users");
            for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                JSONObject jsonUser = (JSONObject) it.next();
                if (jsonUser.get("username").equals(username) && jsonUser.get("password").equals(password)) {
                    authenticated = true;
                    role = (String) jsonUser.get("role");
                }
            }
        }
        if (authenticated) {
            logger.info("Login successfull: " + username);
            session.setAttribute("authName", username);
            session.setAttribute("authRole", role);
            response.sendRedirect("/home");
        } else {
            session.setAttribute("flashMsg", "Invalid Login");
            ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.html.ftl");
        }

    } catch (ParseException | TemplateException ex) {
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}

From source file:org.apache.jena.fuseki.mgt.ActionDataset.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //        request.getRemoteUser() ;
    //        request.getUserPrincipal() ;

    String dataset = FusekiLib.safeParameter(request, "dataset");
    HttpSession session = request.getSession(true);
    session.setAttribute("dataset", dataset);
    session.setMaxInactiveInterval(15 * 60); // 10 mins

    boolean known = DatasetRegistry.get().isRegistered(dataset);
    if (!known) {
        response.sendError(HttpSC.BAD_REQUEST_400, "No such dataset: " + dataset);
        return;//from  w  w w.j  a v a2  s.  c  o  m
    }

    if (true) {
        // Redirect to GET page.
        response.setHeader(HttpNames.hLocation, PageNames.pageAfterLogin);
        response.setStatus(HttpSC.SEE_OTHER_303);
    } else {
        // Welcome style - but HTML inline :-(
        response.setContentType("text/html");
        response.setStatus(HttpSC.OK_200);
        ServletOutputStream out = response.getOutputStream();
        out.print("<p>" + dataset + "(" + known + ")</p>");

        for (String name : DatasetRegistry.get().keys()) {
            out.print("<li>");
            out.print(name);
            out.println("</li>");
        }
        out.println("</ul>");
        out.println("<p><a href=\"info\">Next</a></p>");
    }

    //        Cookie cookie = new Cookie("org.apache.jena.fuseki.session", dataset) ;
    //        // 24 hours.
    //        cookie.setMaxAge(24*60*60) ;

}

From source file:org.romaframework.web.session.HttpAbstractSessionAspect.java

public void setTimeout(int mins) {
    HttpSession sess = (HttpSession) getActiveSystemSession();
    if (sess != null)
        sess.setMaxInactiveInterval(mins * 60);

}

From source file:com.deem.zkui.controller.Login.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Login Post Action!");
    try {//from w  w w.j  av  a2  s.c o m
        Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
        Map<String, Object> templateParam = new HashMap<>();
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout")));
        //TODO: Implement custom authentication logic if required.
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = null;
        Boolean authenticated = false;

        // We're going to read this from the env
        String userenv = null;
        String passenv = null;
        String roleenv = null;

        try {
            userenv = System.getenv(ZKUI_USERNAME);
            passenv = System.getenv(ZKUI_PASSWORD);
            roleenv = System.getenv(ZKUI_ROLE);
        } catch (NullPointerException | SecurityException ex) {
            logger.error("Couldn't read credentials from env, default to ldap...");
        }

        logger.info(String.format("User env: %s, user: %s", userenv, username));

        if (userenv == null || passenv == null) {
            logger.info("Thar be no environment variables set.");
            //if ldap is provided then it overrides roleset.
            if (globalProps.getProperty("ldapAuth").equals("true")) {
                authenticated = new LdapAuth().authenticateUser(globalProps.getProperty("ldapUrl"), username,
                        password, globalProps.getProperty("ldapDomain"));
                if (authenticated) {
                    JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                            .parse(globalProps.getProperty("ldapRoleSet"))).get("users");
                    for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                        JSONObject jsonUser = (JSONObject) it.next();
                        if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) {
                            role = (String) jsonUser.get("role");
                        }
                        if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) {
                            role = (String) jsonUser.get("role");
                        }
                    }
                    if (role == null) {
                        role = ZooKeeperUtil.ROLE_USER;
                    }

                }
            } else {
                JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                        .parse(globalProps.getProperty("userSet"))).get("users");
                for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                    JSONObject jsonUser = (JSONObject) it.next();
                    if (jsonUser.get("username").equals(username)
                            && jsonUser.get("password").equals(password)) {
                        authenticated = true;
                        role = (String) jsonUser.get("role");
                    }
                }
            }
        } else {
            authenticated = (username.equals(userenv) && password.equals(passenv));
            role = roleenv;
        }

        if (authenticated) {
            logger.info("Login successful: " + username);
            session.setAttribute("authName", username);
            session.setAttribute("authRole", role);
            response.sendRedirect("/home");
        } else {
            session.setAttribute("flashMsg", "Invalid Login");
            ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html");
        }

    } catch (ParseException | TemplateException ex) {
        logger.error(Arrays.toString(ex.getStackTrace()));
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}

From source file:org.fenixedu.bennu.struts.servlet.RequestWrapperFilter.java

private void setSessionTimeout(final HttpServletRequest request) {
    final HttpSession session = request.getSession(false);
    if (session != null) {
        session.setMaxInactiveInterval(7200);
    }/*w  w w  . j a  v a  2s  .  com*/
}

From source file:Controller.login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w  w  .ja va  2  s .  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String email = request.getParameter("inputEmail");
    String password = request.getParameter("inputPassword");
    String remember = request.getParameter("remember");

    System.out.println("remember ne mnow " + email);

    LoginImplementation loginCheckObject = new LoginImplementation();

    JSONObject userData = (loginCheckObject.loginNow(email, password, remember));
    System.out.println(userData);
    if (userData.has("error")) {
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        request.setAttribute("loginError", "error");
        rd.include(request, response);

    } else {

        if ("yes".equals(remember)) {
            System.out.println("apples");
            HttpSession session = request.getSession();
            session.setAttribute("user", userData);
            //setting session to expiry in 30 mins
            session.setMaxInactiveInterval(30 * 60);
            Cookie userName = new Cookie("user", email);
            userName.setMaxAge(30 * 60);
            response.addCookie(userName);
        }
        request.setAttribute("userData", userData);
        RequestDispatcher rd = request.getRequestDispatcher("views/home.jsp");
        rd.forward(request, response);
        return;
    }

    out.close();
}

From source file:in.raster.oviyam.servlet.UserConfiguration.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request//from  w  w  w. jav  a2  s.  c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = null;
    try {
        String settings = request.getParameter("settings");
        String actionToDo = request.getParameter("todo");
        String settingsValue = request.getParameter("settingsValue");

        //Get user details
        /*InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        List<Principal> prinList = new ArrayList<Principal>(subject.getPrincipals());
        Principal p = prinList.get(0);
        String userName = p.getName();
        System.out.println("User name: " + userName);*/

        String userName = request.getUserPrincipal().getName();

        //File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
        UserHandler uh = new UserHandler();
        String str = null;
        out = response.getWriter();
        User user = uh.findUserByName(userName);

        if (user == null) {
            user = new User();
            user.setUserName(userName);
            Button btn = new Button();
            btn.setLabel("Today CT");
            btn.setDateCrit("t");
            btn.setModality("CT");
            btn.setAutoRefresh("0");
            uh.addNewUser(btn, userName);
        }

        if (user != null) {
            if (actionToDo.equalsIgnoreCase("READ")) {
                if (settings.equals("theme")) {
                    str = user.getTheme();
                } else if (settings.equals("sessTimeout")) {
                    str = user.getSessTimeout();
                } else if (settings.equals("userName")) {
                    str = user.getUserName();
                    String sessTimeout = user.getSessTimeout();
                    if (sessTimeout != null) {
                        HttpSession session = request.getSession(false);
                        session.setMaxInactiveInterval(Integer.parseInt(sessTimeout));
                    }
                } else if (settings.equals("viewerSlider")) {
                    str = user.getViewerSlider();
                } else if (settings.equals("roles")) {
                    //Principal pTmp = prinList.get(1);
                    //str = pTmp.toString();
                    if (request.isUserInRole("WebAdmin") || request.isUserInRole("admin")) {
                        str = "Admin";
                    } else {
                        str = "Other";
                    }
                } else if (settings.equals("buttons")) {
                    QueryParamHandler qph = new QueryParamHandler();
                    List<Button> butList = qph.getAllButtons(userName);
                    JSONArray jsonArray = new JSONArray(butList);
                    str = jsonArray.toString();
                }
                out.print(str);
            } else if (actionToDo.equalsIgnoreCase("UPDATE")) {
                if (settings.equals("theme")) {
                    user.setTheme(settingsValue);
                } else if (settings.equals("sessTimeout")) {
                    user.setSessTimeout(settingsValue);
                } else if (settings.equals("viewerSlider")) {
                    user.setViewerSlider(settingsValue);
                }
                uh.updateUser(user);
                out.println("Success");
            }
        }

    } catch (Exception ex) {
        log.error("Exception occured in User Configuration servlet", ex);
        //out.println("Failure");
    }
}