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.jahia.ajax.gwt.content.server.JahiaContentManagementServiceImpl.java

@Override
public SessionValidationResult isValidSession() throws GWTJahiaServiceException {
    // >0 : schedule poll repeating for this value
    // 0 : session expire
    // <0 : polling deactivated
    final String loginUrl = getLogingUrl();
    final HttpSession session = getRequest().getSession(false);
    if (session != null) {
        Long date = (Long) session.getAttribute("lastPoll");
        long lastAccessed = session.getLastAccessedTime();
        long now = System.currentTimeMillis();
        boolean invalidated = false;
        if (date != null && (date / 1000 == lastAccessed / 1000)) {
            // last call was (probably) a poll call
            long first = (Long) session.getAttribute("firstPoll");
            if (logger.isDebugEnabled()) {
                logger.debug("Inactive since : " + (now - first));
            }/*from   w w  w .  j  av  a 2 s.  com*/
            if (now - first < session.getMaxInactiveInterval() * 1000) {
                session.setMaxInactiveInterval(session.getMaxInactiveInterval() - (int) ((now - first) / 1000));
            } else {
                session.invalidate();
                invalidated = true;
            }
        } else {
            session.setAttribute("firstPoll", now);
        }

        if (!invalidated) {
            session.setAttribute("lastPoll", now);
        }
        return new SessionValidationResult(loginUrl, sessionPollingFrequency);
    } else {
        return new SessionValidationResult(loginUrl, 0);
    }
}

From source file:controllers.controller.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww  .  j a  va 2  s  . c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {

    request.setCharacterEncoding(PageParameters.getParameter("charset").toString());
    response.setCharacterEncoding(PageParameters.getParameter("charset").toString());
    response.setContentType(PageParameters.getParameter("servletSetContentType").toString());
    response.setHeader("Cache-Control", "no-cache");
    HttpSession session;
    PrintWriter out;
    QUID quid;
    LinkedList<String> userAccess;
    quid = new QUID();
    quid.setRequest(request);
    session = request.getSession(true);
    SessionUtil.addIfNotExistSession(session);
    out = response.getWriter();
    try {
        try {
            if (PageParameters.getParameter("SiteOnMaintenance").equals("true")) {
                response.sendRedirect(PageParameters.getParameter("SiteOnMaintenanceURL").toString());
            } else // <editor-fold defaultstate="collapsed" desc="Realizando LogIn de usuario">
            //si proviene de la pgina  de login aqui se detectara y se validara al usuario
            {
                if (request.getParameter("LogInPage") != null) {
                    //aqui consulta el usuario en Base de Datos.
                    //                        if (request.getParameter("captcha").equals(session.getAttribute("captcha")) && request.getParameter("captcha").equalsIgnoreCase("") == false) {
                    if (true) {
                        if (request.getParameter("user").equalsIgnoreCase("") == false
                                && request.getParameter("pass").equalsIgnoreCase("") == false) {

                            LinkedList infoUser = null;
                            LinkedList<String> accessos = null;

                            infoUser = quid.selectIdUsuario(request.getParameter("user"),
                                    request.getParameter("pass"), "ACTIVO");

                            if (infoUser != null) {
                                session.removeAttribute("captcha");
                                SessionUtil.clearNCloseSession(session);
                                session = request.getSession(true);
                                session.setAttribute("tipoRol", infoUser.get(3));
                                session.setAttribute("userID", infoUser.get(0));
                                session.setAttribute("userName", infoUser.get(1));
                                session.setAttribute("FK_ID_Plantel", infoUser.get(2));
                                //asignacion de permisos
                                //LinkedList<String> accessos = new LinkedList();
                                accessos = quid.selectPermisosUsuarios(infoUser.get(0).toString());
                                session.setMaxInactiveInterval(3 * 60 * 60); // 2hrs * 60 min * 60 seg

                                //accesos del usaurio y parametros del mismo
                                session.setAttribute("userAccess", accessos);
                                SessionUtil.addIfNotExistSession(session);
                                request.getRequestDispatcher(PageParameters.getParameter("mainMenuServLet"))
                                        .forward(request, response);
                            } else {
                                this.getServletConfig().getServletContext().getRequestDispatcher(""
                                        + PageParameters.getParameter("msgUtil")
                                        + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Usuario o password incorrectos.&url=/"
                                        + PageParameters.getParameter("appName")
                                        + PageParameters.getParameter("LogInPage")).forward(request, response);
                            }
                        } else {
                            this.getServletConfig().getServletContext().getRequestDispatcher(""
                                    + PageParameters.getParameter("msgUtil")
                                    + "/msgNRedirectFull.jsp?title=Error&type=error&msg=El usuario y password no pueden estar vacos.&url=/"
                                    + PageParameters.getParameter("appName")
                                    + PageParameters.getParameter("LogInPage")).forward(request, response);
                        }
                    } else {
                        this.getServletConfig().getServletContext().getRequestDispatcher(""
                                + PageParameters.getParameter("msgUtil")
                                + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Cdigo de verificacin incorrecto.&url=/"
                                + PageParameters.getParameter("appName")
                                + PageParameters.getParameter("LogInPage")).forward(request, response);
                    }
                    // </editor-fold> 
                    // <editor-fold defaultstate="expanded" desc="Validando que sea un usuario logeado">
                } else if (session.getAttribute("userAccess") == null) {
                    response.sendRedirect("/" + PageParameters.getParameter("appName")
                            + PageParameters.getParameter("LogInPage"));
                    // </editor-fold> 
                } else // <editor-fold defaultstate="collapsed" desc="Cerrando sesion">
                {
                    if (request.getParameter("exit") != null) {
                        //session.invalidate();
                        this.clearNCloseSession(session, request, response, quid, out);
                        //quid.insertLog("SysLogOut", "exit", "", "", "", "");
                        response.sendRedirect(PageParameters.getParameter("mainContext")
                                + PageParameters.getParameter("LogInPage").toString());
                        // </editor-fold>
                        // <editor-fold defaultstate="collapsed" desc="Revisando de que form viene">
                    } else if (request.getParameter("FormForm") != null) {
                        switch (request.getParameter("FormForm")) {
                        case "agregaFichaTecnica":
                            this.agregaFichaTecnica(session, request, response, quid, out);
                            break;
                        case "modificaFichaTecnica":
                            this.modificaFichaTecnica(session, request, response, quid, out);
                            break;
                        case "agregaEtapaDesarrollo":
                            this.agregaEtapaDesarrollo(session, request, response, quid, out);
                            break;
                        case "modificaEtapaDesarrollo":
                            this.modificaEtapaDesarrollo(session, request, response, quid, out);
                            break;
                        case "eliminaStage":
                            this.eliminaEtapa(session, request, response, quid, out);
                            break;
                        case "agregaActivity":
                            this.agregaActividad(session, request, response, quid, out);
                            break;
                        case "modificaActivity":
                            this.modificaActividad(session, request, response, quid, out);
                            break;
                        case "eliminaActivity":
                            this.eliminaActividad(session, request, response, quid, out);
                            break;
                        case "deleteObjetoArchivo":
                            this.deleteObjetoArchivo(session, request, response, quid, out);
                            break;
                        }
                        // </editor-fold>
                    } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
                        this.subirArchivo(session, request, response, quid, out);

                    } else {
                        out.println("UPS.... Algo malo ha pasado");
                    }
                }
            }

        } catch (Exception ex) {
            Logger.getLogger(controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        quid = null;
        out.close();
    }
}

From source file:org.geoserver.geofence.gui.server.service.impl.LoginService.java

public UserModel authenticate(String userName, String password, HttpSession session)
        throws ApplicationException {
    logger.info("Authenticating '" + userName + "'");

    GrantedAuths grantedAuths = null;//w  ww  . j  av a 2  s.  c  om
    String token = null;

    try {
        URL url = Class.forName("org.geoserver.geofence.gui.client.UserUI").getResource("client.keystore");
        String path = url.getPath();
        if (logger.isDebugEnabled()) {
            logger.debug(path);
        }
        System.setProperty("javax.net.ssl.trustStore", path);
        System.setProperty("javax.net.ssl.trustStorePassword", "geosolutions");

        GFUser matchingUser = null;

        // a backdoor!?! :o
        if (userName.equals("1nt3rnAL-G30r3p0-admin")) {
            matchingUser = new GFUser();
            matchingUser.setName(userName);
            matchingUser.setPassword("2c6fe6e260312c5aa94ef0ca42b0af");
        } else {
            try {
                matchingUser = geofenceRemoteService.getGfUserAdminService().get(userName);
            } catch (NotFoundServiceEx ex) {
                logger.warn("User not found");
                throw new ApplicationException("Login failed");
            }
            //                // grantedAuthorities =
            //                List<GFUser> matchingUsers = geofenceRemoteService.getGfUserAdminService().getFullList(userName, null,
            //                        null);
            //                logger.info(matchingUsers);
            //                logger.info(matchingUsers.size());
            //
            //                if ((matchingUsers == null) || matchingUsers.isEmpty() || (matchingUsers.size() != 1))
            //                {
            //                    logger.error("Error :********** " + "Invalid username specified!");
            //                    throw new ApplicationException("Error :********** " + "Invalid username specified!");
            //                }
            //
            //                logger.info(matchingUsers.get(0).getName());
            //                logger.info(matchingUsers.get(0).getPassword());
            //                logger.info(matchingUsers.get(0).getEnabled());
            //
            //                if (!matchingUsers.get(0).getName().equals(userName) || !matchingUsers.get(0).getEnabled())
            //                {
            //                    logger.error("Error :********** " + "The specified user does not exist!");
            //                    throw new ApplicationException("Error :********** " + "The specified user does not exist!");
            //                }
            //
            //                matchingUser = matchingUsers.get(0);
        }

        token = geofenceRemoteService.getLoginService().login(userName, password, matchingUser.getPassword());
        grantedAuths = geofenceRemoteService.getLoginService().getGrantedAuthorities(token);

    } catch (ClassNotFoundException e) {
        logger.error("Error :********** " + e.getMessage());
        throw new ApplicationException(e);
    } catch (AuthException e) {
        logger.error("Login failed");
        throw new ApplicationException(e.getMessage(), e);
    }

    UserModel user = new UserModel();
    user.setName(userName);
    user.setPassword(password);

    // convert the server-side auths to client-side auths
    List<Authorization> guiAuths = new ArrayList<Authorization>();
    for (Authority auth : grantedAuths.getAuthorities()) {
        guiAuths.add(Authorization.valueOf(auth.name()));
    }
    user.setGrantedAuthorizations(guiAuths);

    if ((grantedAuths != null) && !grantedAuths.getAuthorities().isEmpty()) {
    }

    session.setMaxInactiveInterval(7200);

    session.setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(), token);
    /* session.setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(),
        grantedAuthorities_NOTUSEDANYMORE.getToken()); */

    return user;
}

From source file:it.geosolutions.geofence.gui.server.service.impl.LoginService.java

public User authenticate(String userName, String password, HttpSession session) throws ApplicationException {
    logger.info("Authenticating '" + userName + "'");

    GrantedAuths grantedAuths = null;// w  w w . jav a  2 s.  c om
    String token = null;

    try {
        URL url = Class.forName("it.geosolutions.geofence.gui.client.UserUI").getResource("client.keystore");
        String path = url.getPath();
        if (logger.isDebugEnabled()) {
            logger.debug(path);
        }
        System.setProperty("javax.net.ssl.trustStore", path);
        System.setProperty("javax.net.ssl.trustStorePassword", "geosolutions");

        GFUser matchingUser = null;

        // a backdoor!?! :o
        if (userName.equals("1nt3rnAL-G30r3p0-admin")) {
            matchingUser = new GFUser();
            matchingUser.setName(userName);
            matchingUser.setPassword("2c6fe6e260312c5aa94ef0ca42b0af");
        } else {
            try {
                matchingUser = geofenceRemoteService.getGfUserAdminService().get(userName);
            } catch (NotFoundServiceEx ex) {
                logger.warn("User not found");
                throw new ApplicationException("Login failed");
            }
            //                // grantedAuthorities =
            //                List<GFUser> matchingUsers = geofenceRemoteService.getGfUserAdminService().getFullList(userName, null,
            //                        null);
            //                logger.info(matchingUsers);
            //                logger.info(matchingUsers.size());
            //
            //                if ((matchingUsers == null) || matchingUsers.isEmpty() || (matchingUsers.size() != 1))
            //                {
            //                    logger.error("Error :********** " + "Invalid username specified!");
            //                    throw new ApplicationException("Error :********** " + "Invalid username specified!");
            //                }
            //
            //                logger.info(matchingUsers.get(0).getName());
            //                logger.info(matchingUsers.get(0).getPassword());
            //                logger.info(matchingUsers.get(0).getEnabled());
            //
            //                if (!matchingUsers.get(0).getName().equals(userName) || !matchingUsers.get(0).getEnabled())
            //                {
            //                    logger.error("Error :********** " + "The specified user does not exist!");
            //                    throw new ApplicationException("Error :********** " + "The specified user does not exist!");
            //                }
            //
            //                matchingUser = matchingUsers.get(0);
        }

        token = geofenceRemoteService.getLoginService().login(userName, password, matchingUser.getPassword());
        grantedAuths = geofenceRemoteService.getLoginService().getGrantedAuthorities(token);

    } catch (ClassNotFoundException e) {
        logger.error("Error :********** " + e.getMessage());
        throw new ApplicationException(e);
    } catch (AuthException e) {
        logger.error("Login failed");
        throw new ApplicationException(e.getMessage(), e);
    }

    User user = new User();
    user.setName(userName);
    user.setPassword(password);

    // convert the server-side auths to client-side auths
    List<Authorization> guiAuths = new ArrayList<Authorization>();
    for (Authority auth : grantedAuths.getAuthorities()) {
        guiAuths.add(Authorization.valueOf(auth.name()));
    }
    user.setGrantedAuthorizations(guiAuths);

    if ((grantedAuths != null) && !grantedAuths.getAuthorities().isEmpty()) {
    }

    session.setMaxInactiveInterval(7200);

    session.setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(), token);
    /* session.setAttribute(GeofenceKeySessionValues.USER_LOGGED_TOKEN.getValue(),
        grantedAuthorities_NOTUSEDANYMORE.getToken()); */

    return user;
}

From source file:egovframework.example.sample.web.EgovSampleController.java

@RequestMapping(value = "/login.do", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

    String id = request.getParameter("id");
    String pw = request.getParameter("pw");

    Account ac = new Account();
    ac.setA_id(id);//w w w  .  j a va 2  s  . c  o  m
    int IDCheck = sampleService.joinIdCheck(ac);

    if (IDCheck == 0) {//?  
        request.setAttribute("color", "red");
        request.setAttribute("Result", " ID.");
        model.addAttribute("login", "login.jsp");
    } else {
        Account ac2 = sampleService.getAccount(ac);
        String dBpass = ac2.getA_pw();

        System.out.println(pw + "<<  DB>>" + dBpass);
        if (pw.equals(dBpass)) {//? ?
            System.out.println(" ?");
            HttpSession hs = request.getSession();
            hs.setAttribute("userInfo", ac2);
            hs.setMaxInactiveInterval(1 * 60 * 60); //?   (1)

            // ?? ID 
            Cookie c = new Cookie("lastLoginID", id);
            c.setMaxAge(1 * 60 * 60);//  (1)
            response.addCookie(c);

            model.addAttribute("login", "loginOK.jsp");

        } else {//  
            System.out.println(" ");
            request.setAttribute("color", "red");
            request.setAttribute("Result", " .");
            model.addAttribute("login", "login.jsp");
        }

    }

    //model.addAttribute("main", "defaultMain.jsp");
    return "forward:/home.do";
}

From source file:org.jasig.portal.url.MaxInactiveInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    final HttpSession session = request.getSession(false);
    if (session == null) {
        return true;
    }//from   w ww.  j  a  v a 2 s  . com

    // Now see if authentication was successful...
    final IPerson person = this.personManager.getPerson((HttpServletRequest) request);
    if (person == null) {
        return true;
    }

    final ISecurityContext securityContext = person.getSecurityContext();
    if (securityContext != null && securityContext.isAuthenticated()) {
        // We have an authenticated user... let's see if any MAX_INACTIVE settings apply...
        IAuthorizationPrincipal principal = authorizationService
                .newPrincipal((String) person.getAttribute(IPerson.USERNAME), IPerson.class);
        Integer rulingGrant = null;
        Integer rulingDeny = null;
        IPermission[] permissions = authorizationService.getAllPermissionsForPrincipal(principal, null,
                "MAX_INACTIVE", null);
        for (IPermission p : permissions) {
            // First be sure the record applies currently...
            long now = System.currentTimeMillis();
            if (p.getEffective() != null && p.getEffective().getTime() > now) {
                // It's *TOO EARLY* for this record... move on.
                continue;
            }
            if (p.getExpires() != null && p.getExpires().getTime() < now) {
                // It's *TOO LATE* for this record... move on.
                continue;
            }
            if (p.getType().equals(IPermission.PERMISSION_TYPE_GRANT)) {
                try {
                    Integer grantEntry = Integer.valueOf(p.getTarget());
                    if (rulingGrant == null || grantEntry.intValue() < 0 /* Any negative number trumps all */
                            || rulingGrant.intValue() < grantEntry.intValue()) {
                        rulingGrant = grantEntry;
                    }
                } catch (NumberFormatException nfe) {
                    log.warn("Invalid MAX_INACTIVE permission grant '" + p.getTarget()
                            + "';  target must be an integer value.");
                }
            } else if (p.getType().equals(IPermission.PERMISSION_TYPE_DENY)) {
                try {
                    Integer denyEntry = Integer.valueOf(p.getTarget());
                    if (rulingDeny == null || rulingDeny.intValue() > denyEntry.intValue()) {
                        rulingDeny = denyEntry;
                    }
                } catch (NumberFormatException nfe) {
                    log.warn("Invalid MAX_INACTIVE permission deny '" + p.getTarget()
                            + "';  target must be an integer value.");
                }
            } else {
                log.warn("Unknown permission type:  " + p.getType());
            }
        }

        if (rulingDeny != null && rulingDeny.intValue() < 0) {
            // Negative MaxInactiveInterval values mean the session never 
            // times out, so a negative DENY is somewhat nonsensical... just 
            // clear it.
            log.warn("A MAX_INACTIVE DENY entry improperly specified a negative target:  "
                    + rulingDeny.intValue());
            rulingDeny = null;
        }
        if (rulingGrant != null || rulingDeny != null) {
            // We only want to intervene if there's some actual value 
            // specified... otherwise we'll just let the container settings 
            //govern.
            int maxInactive = rulingGrant != null ? rulingGrant.intValue() : 0; // If rulingGrant is null, rulingDeny won't be...
            if (rulingDeny != null) {
                // Applying DENY entries is tricky b/c GRANT entries may be negative...
                int limit = rulingDeny.intValue();
                if (maxInactive >= 0) {
                    maxInactive = limit < maxInactive ? limit : maxInactive;
                } else {
                    // The best grant was negative (unlimited), so go with limit...
                    maxInactive = limit;
                }
            }
            // Apply the specified setting...
            session.setMaxInactiveInterval(maxInactive);
            if (log.isInfoEnabled()) {
                log.info("Setting maxInactive to '" + maxInactive + "' for user '"
                        + person.getAttribute(IPerson.USERNAME) + "'");
            }
        }

    }

    return true;
}

From source file:egovframework.example.sample.web.EgovSampleController.java

@RequestMapping(value = "/doModifyId.do", method = { RequestMethod.GET, RequestMethod.POST })
public String doModifyId(HttpServletRequest request, @RequestParam("j_id") String a_id,
        @RequestParam("j_pw") String a_pw, @RequestParam("j_name") String a_name,
        @RequestParam("j_adress") String a_adress, @RequestParam("j_phone") String a_phone,
        @RequestParam("j_hint") String a_hint, @RequestParam("j_respond") String a_respond, Model model,
        SessionStatus status//from  ww  w  . jav a 2  s .  co  m

) throws Exception {

    HttpSession hs = request.getSession();
    Account loginInfo = (Account) hs.getAttribute("userInfo");

    System.out.println("? ");

    System.out.println("? " + a_phone);
    System.out.println("int " + a_phone);
    Account ac = new Account(a_id, a_pw, a_name, a_adress, a_hint, a_respond, a_phone);
    ac.setA_cash(loginInfo.getA_cash());
    sampleService.modifyId(ac);
    status.setComplete();

    //HttpSession hs = request.getSession();
    //   hs.invalidate();

    hs.setAttribute("userInfo", ac);
    hs.setMaxInactiveInterval(1 * 60 * 60);

    model.addAttribute("login", "loginOK.jsp");
    //   model.addAttribute("main", "defaultMain.jsp");

    return "forward:/home.do";

}

From source file:org.apereo.portal.url.MaxInactiveInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    final HttpSession session = request.getSession(false);
    if (session == null) {
        return true;
    }//w ww . ja  va2 s  .c o m

    // Now see if authentication was successful...
    final IPerson person = this.personManager.getPerson((HttpServletRequest) request);
    if (person == null) {
        return true;
    }

    // Check if the session max inactive value has already been set
    Boolean isAlreadySet = (Boolean) person.getAttribute(this.SESSION_MAX_INACTIVE_SET_ATTR);
    if (isAlreadySet != null && isAlreadySet.equals(Boolean.TRUE)) {
        if (log.isDebugEnabled()) {
            log.debug("Session.setMaxInactiveInterval() has already been determined for user '"
                    + person.getAttribute(IPerson.USERNAME) + "'");
        }
        return true;
    }

    final ISecurityContext securityContext = person.getSecurityContext();
    if (securityContext != null && securityContext.isAuthenticated()) {
        // We have an authenticated user... let's see if any MAX_INACTIVE settings apply...
        IAuthorizationPrincipal principal = authorizationService
                .newPrincipal((String) person.getAttribute(IPerson.USERNAME), IPerson.class);
        Integer rulingGrant = null;
        Integer rulingDeny = null;
        IPermission[] permissions = authorizationService.getAllPermissionsForPrincipal(principal,
                IPermission.PORTAL_SYSTEM, "MAX_INACTIVE", null);
        assert (permissions != null);
        if (permissions.length == 0) {
            // No max inactive permission set for this user
            if (log.isInfoEnabled()) {
                log.info("No MAX_INACTIVE permissions apply to user '" + person.getAttribute(IPerson.USERNAME)
                        + "'");
            }
            person.setAttribute(this.SESSION_MAX_INACTIVE_SET_ATTR, Boolean.TRUE);
            return true;
        }
        for (IPermission p : permissions) {
            // First be sure the record applies currently...
            long now = System.currentTimeMillis();
            if (p.getEffective() != null && p.getEffective().getTime() > now) {
                // It's *TOO EARLY* for this record... move on.
                continue;
            }
            if (p.getExpires() != null && p.getExpires().getTime() < now) {
                // It's *TOO LATE* for this record... move on.
                continue;
            }
            if (p.getType().equals(IPermission.PERMISSION_TYPE_GRANT)) {
                try {
                    Integer grantEntry = Integer.valueOf(p.getTarget());
                    if (rulingGrant == null || grantEntry.intValue() < 0 /* Any negative number trumps all */
                            || rulingGrant.intValue() < grantEntry.intValue()) {
                        rulingGrant = grantEntry;
                    }
                } catch (NumberFormatException nfe) {
                    log.warn("Invalid MAX_INACTIVE permission grant '" + p.getTarget()
                            + "';  target must be an integer value.");
                }
            } else if (p.getType().equals(IPermission.PERMISSION_TYPE_DENY)) {
                try {
                    Integer denyEntry = Integer.valueOf(p.getTarget());
                    if (rulingDeny == null || rulingDeny.intValue() > denyEntry.intValue()) {
                        rulingDeny = denyEntry;
                    }
                } catch (NumberFormatException nfe) {
                    log.warn("Invalid MAX_INACTIVE permission deny '" + p.getTarget()
                            + "';  target must be an integer value.");
                }
            } else {
                log.warn("Unknown permission type:  " + p.getType());
            }
        }

        if (rulingDeny != null && rulingDeny.intValue() < 0) {
            // Negative MaxInactiveInterval values mean the session never
            // times out, so a negative DENY is somewhat nonsensical... just
            // clear it.
            log.warn("A MAX_INACTIVE DENY entry improperly specified a negative target:  "
                    + rulingDeny.intValue());
            rulingDeny = null;
        }
        if (rulingGrant != null || rulingDeny != null) {
            // We only want to intervene if there's some actual value
            // specified... otherwise we'll just let the container settings
            //govern.
            int maxInactive = rulingGrant != null ? rulingGrant.intValue() : 0; // If rulingGrant is null, rulingDeny won't be...
            if (rulingDeny != null) {
                // Applying DENY entries is tricky b/c GRANT entries may be negative...
                int limit = rulingDeny.intValue();
                if (maxInactive >= 0) {
                    maxInactive = limit < maxInactive ? limit : maxInactive;
                } else {
                    // The best grant was negative (unlimited), so go with limit...
                    maxInactive = limit;
                }
            }
            // Apply the specified setting...
            session.setMaxInactiveInterval(maxInactive);
            person.setAttribute(this.SESSION_MAX_INACTIVE_SET_ATTR, Boolean.TRUE);
            if (log.isInfoEnabled()) {
                log.info("Setting maxInactive to '" + maxInactive + "' for user '"
                        + person.getAttribute(IPerson.USERNAME) + "'");
            }
        }

    }

    return true;
}

From source file:com.mimp.controllers.main.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login_GET(ModelMap map, HttpSession session) {

    String email = "";
    String pass = "";

    String pagina = "login";

    if (session.getAttribute("email") != null) {

        email = (String) session.getAttribute("email");
        pass = (String) session.getAttribute("password");

        String mensaje = "El usuario se encuentra Deshabilitado. Favor contactar a la Direccin General de Adopciones para ms informacin";

        ArrayList aux = ServicioMain.usuario(email, pass);
        if (aux.get(0) == "personal") {
            Personal personal = (Personal) aux.get(1);
            if (!personal.getRol().equals("Inactivo")) {
                session.setAttribute("usuario", personal);
                session.setMaxInactiveInterval(900);
                pagina = "/Personal/inicio_personal";

                String mensaje_log = "El usuario, " + personal.getUser() + " con ID: "
                        + personal.getIdpersonal() + ". Ingres al sistema.";
                String Tipo_registro = "Login";

                try {
                    String Numero_registro = String.valueOf(personal.getIdpersonal());

                    ServicioPersonal.InsertLog(personal, Tipo_registro, Numero_registro, mensaje_log);
                } catch (Exception ex) {
                }// w  w w  .j  a  v  a 2s .com

            } else {
                map.addAttribute("mensaje", mensaje);
                pagina = "login";
            }
        } else if (aux.get(0) == "familia") {
            Familia familia = (Familia) aux.get(1);
            if (familia.getHabilitado() == 0) {
                session.setAttribute("usuario", familia);
                session.setMaxInactiveInterval(900);
                pagina = "/Familia/inicio_familia";
            } else {
                map.addAttribute("mensaje", mensaje);
                pagina = "login";
            }
        } else if (aux.get(0) == "representante" || aux.get(0) == "autoridad") {
            Entidad entidad = (Entidad) aux.get(1);
            session.setAttribute("usuario", entidad);
            session.setMaxInactiveInterval(900);
            pagina = "/Entidad/inicio_ent";
        } else if (email.equals("") || pass.equals("")) {
            mensaje = "Por favor llenar ambos campos";
            map.addAttribute("mensaje", mensaje);
            pagina = "login";
        } else {
            mensaje = "Usuario y/o contrasea incorrectos";
            map.addAttribute("mensaje", mensaje);
            pagina = "login";
        }

    } else {
        String mensaje = "La sesin ha finalizado. Favor identificarse nuevamente";
        map.addAttribute("mensaje", mensaje);
        pagina = "login";

    }

    session.removeAttribute("email");
    session.removeAttribute("password");

    return new ModelAndView(pagina, map);
}

From source file:onl.netfishers.netshot.RestService.java

/**
 * Login./*  w  ww  .j  a v a  2s .  co  m*/
 *
 * @param request the request
 * @param rsLogin the rs login
 * @return the user
 * @throws WebApplicationException the web application exception
 */
@POST
@PermitAll
@Path("user")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public User login(@Context HttpServletRequest request, RsLogin rsLogin) throws WebApplicationException {
    logger.debug("REST authentication request, username {}.", rsLogin.getUsername());

    User user = null;

    Session session = Database.getSession();
    try {
        user = (User) session.bySimpleNaturalId(User.class).load(rsLogin.getUsername());
    } catch (HibernateException e) {
        logger.error("Unable to retrieve the user {}.", rsLogin.getUsername(), e);
        throw new NetshotBadRequestException("Unable to retrieve the user.",
                NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR);
    } finally {
        session.close();
    }

    if (user != null && user.isLocal()) {
        if (!user.checkPassword(rsLogin.getPassword())) {
            user = null;
        }
    } else {
        User remoteUser = Radius.authenticate(rsLogin.getUsername(), rsLogin.getPassword());
        if (remoteUser != null && user != null) {
            remoteUser.setLevel(user.getLevel());
        }
        user = remoteUser;
    }
    if (user == null) {
        HttpSession httpSession = request.getSession();
        httpSession.invalidate();
    } else {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("user", user);
        httpSession.setMaxInactiveInterval(User.MAX_IDLE_TIME);
        return user;
    }
    throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());
}