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:SessionTimer.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
    out.println("<BODY><H1>Session Timer</H1>");

    out.println("The previous timeout was " + session.getMaxInactiveInterval());
    out.println("<BR>");

    session.setMaxInactiveInterval(2 * 60 * 60); // two hours

    out.println("The newly assigned timeout is " + session.getMaxInactiveInterval());

    out.println("</BODY></HTML>");
}

From source file:org.rhq.enterprise.gui.coregui.server.gwt.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession();
    session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL);

    if (ServletFileUpload.isMultipartContent(req)) {

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        //fileItemFactory.setSizeThreshold(0);

        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        List<FileItem> fileItemsList;
        try {// w  ww.j av a2 s.c  om
            fileItemsList = (List<FileItem>) servletFileUpload.parseRequest(req);
        } catch (FileUploadException e) {
            writeExceptionResponse(resp, "File upload failed", e);
            return;
        }

        List<FileItem> actualFiles = new ArrayList<FileItem>();
        Map<String, String> formFields = new HashMap<String, String>();
        boolean retrieve = false;
        Subject authenticatedSubject = null;

        for (FileItem fileItem : fileItemsList) {
            if (fileItem.isFormField()) {
                if (fileItem.getFieldName() != null) {
                    formFields.put(fileItem.getFieldName(), fileItem.getString());
                }
                if ("retrieve".equals(fileItem.getFieldName())) {
                    retrieve = true;
                } else if ("sessionid".equals(fileItem.getFieldName())) {
                    int sessionid = Integer.parseInt(fileItem.getString());
                    SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
                    try {
                        authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid);
                    } catch (Exception e) {
                        throw new ServletException("Cannot authenticate request", e);
                    }
                }
                fileItem.delete();
            } else {
                // file item contains an actual uploaded file
                actualFiles.add(fileItem);
                log("file was uploaded: " + fileItem.getName());
            }
        }

        if (authenticatedSubject == null) {
            for (FileItem fileItem : actualFiles) {
                fileItem.delete();
            }
            throw new ServletException("Cannot process unauthenticated request");
        }

        if (retrieve && actualFiles.size() == 1) {
            // sending in "retrieve" form element with a single file means the client just wants the content echoed back
            FileItem fileItem = actualFiles.get(0);

            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.print("<html>");
            InputStream inputStream = fileItem.getInputStream();
            try {
                StreamUtil.copy(inputStream, outputStream, false);
            } finally {
                inputStream.close();
            }
            outputStream.print("</html>");
            outputStream.flush();

            fileItem.delete();
        } else {
            Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file
            Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name
            for (FileItem fileItem : actualFiles) {
                File theFile = forceToFile(fileItem);
                allUploadedFiles.put(fileItem.getFieldName(), theFile);
                allUploadedFileNames.put(fileItem.getFieldName(),
                        (fileItem.getName() != null) ? fileItem.getName() : theFile.getName());
            }
            processUploadedFiles(authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req,
                    resp);
        }
    }
}

From source file:Project.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  ww. ja  va2s  .  c om
 * @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);
    DB_Users db = new DB_Users();
    if (request.getParameter("username") != null && request.getParameter("password") != null) {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        int loginCheck = db.doLogin(userName, password);

        if (loginCheck == 1) {
            String loginUserName = db.updateLoginUserDetails(userName, password);
            HttpSession session = request.getSession();
            session.setAttribute("username", loginUserName);
            session.setMaxInactiveInterval(100);
            //response.sendRedirect("myprofile.jsp");            
            request.getRequestDispatcher("myprofile.jsp").forward(request, response);

        } else {
            String toEmail = db.getEmailIdOfLoginUser(userName);
            String fromEmail = "muthaiahpalaniappan92@gmail.com";
            String emailUserName = "muthaiahpalaniappan92";
            String emailPassword = "Muthaiah92";
            String subject = "Sign In Attempt Blocked";
            String message = "Someone have attempted to login your account with this password (" + password
                    + "). If this was you, then that\'s okay ., else please change your password ";
            mail.sendEmailForRegistration(toEmail, fromEmail, emailUserName, emailPassword, subject, message);
            request.setAttribute("loginFailedMessage", "UserName or Password you entered is incorrect");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
    //Update info
    if (request.getParameter("newAddress") != null && request.getParameter("newPassword") != null
            && request.getParameter("loginUser") != null && request.getParameter("newCity") != null) {
        String newAddress = request.getParameter("newAddress");
        String newPassword = request.getParameter("newPassword");
        String newCity = request.getParameter("newCity");
        String updatableUser = request.getParameter("loginUser");
        db.updateUserDetails(updatableUser, newPassword, newAddress, newCity);
        request.getRequestDispatcher("chatbox.jsp").forward(request, response);
    }

    if (request.getParameter("sender") != null && request.getParameter("receiver") != null
            && request.getParameter("message") != null) {
        String senderVar = request.getParameter("sender");
        String receiverVar = request.getParameter("receiver");
        String messageVar = request.getParameter("message");
        Chat c = new Chat(senderVar, receiverVar, messageVar);
        db.insertChat(c);
        request.getRequestDispatcher("chatbox.jsp").forward(request, response);
    } else {
        request.setAttribute("emptyReceiverOrMessage", "Receiver or Message should not be empty");
        request.getRequestDispatcher("chatbox.jsp").forward(request, response);
    }

    if (request.getParameter("user") != null && request.getParameter("opponent") != null) {
        db.deleteConversation(request.getParameter("user"), request.getParameter("opponent"));
    }

}

From source file:org.jasig.cas.web.flow.TerminateWebSessionListener.java

@Override
public void sessionEnded(final RequestContext context, final FlowSession session, final String outcome,
        final AttributeMap output) {

    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    // get session but don't create it if it doesn't already exist
    final HttpSession webSession = request.getSession(false);

    if (webSession != null) {
        logger.debug("Terminate web session {} in {} seconds", webSession.getId(), this.timeToDieInSeconds);
        // set the web session to die in timeToDieInSeconds
        webSession.setMaxInactiveInterval(this.timeToDieInSeconds);
    }//from w ww.j  a va  2  s. c  om
}

From source file:org.rhq.coregui.server.gwt.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession();
    session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL);

    if (ServletFileUpload.isMultipartContent(req)) {

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        if (tmpDir == null) {
            tmpDir = LookupUtil.getCoreServer().getJBossServerTempDir();
        }//from   w ww . j  a  va 2  s. co m
        fileItemFactory.setRepository(tmpDir);
        //fileItemFactory.setSizeThreshold(0);

        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        List<FileItem> fileItemsList;
        try {
            fileItemsList = servletFileUpload.parseRequest(req);
        } catch (FileUploadException e) {
            writeExceptionResponse(resp, "File upload failed", e);
            return;
        }

        List<FileItem> actualFiles = new ArrayList<FileItem>();
        Map<String, String> formFields = new HashMap<String, String>();
        boolean retrieve = false;
        boolean obfuscate = false;
        Subject authenticatedSubject = null;

        for (FileItem fileItem : fileItemsList) {
            if (fileItem.isFormField()) {
                if (fileItem.getFieldName() != null) {
                    formFields.put(fileItem.getFieldName(), fileItem.getString());
                }
                if ("retrieve".equals(fileItem.getFieldName())) {
                    retrieve = true;
                } else if ("obfuscate".equals(fileItem.getFieldName())) {
                    obfuscate = Boolean.parseBoolean(fileItem.getString());
                } else if ("sessionid".equals(fileItem.getFieldName())) {
                    int sessionid = Integer.parseInt(fileItem.getString());
                    SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
                    try {
                        authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid);
                    } catch (Exception e) {
                        throw new ServletException("Cannot authenticate request", e);
                    }
                }
                fileItem.delete();
            } else {
                // file item contains an actual uploaded file
                actualFiles.add(fileItem);
                log("file was uploaded: " + fileItem.getName());
            }
        }

        if (authenticatedSubject == null) {
            for (FileItem fileItem : actualFiles) {
                fileItem.delete();
            }
            throw new ServletException("Cannot process unauthenticated request");
        }

        if (retrieve && actualFiles.size() == 1) {
            // sending in "retrieve" form element with a single file means the client just wants the content echoed back
            resp.setContentType("text/html");
            FileItem fileItem = actualFiles.get(0);

            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.print("<html>");
            InputStream inputStream = fileItem.getInputStream();
            try {
                // we have to HTML escape inputStream before writing it to outputStream
                StreamUtil.copy(inputStream, outputStream, false, true);
            } finally {
                inputStream.close();
            }
            outputStream.print("</html>");
            outputStream.flush();

            fileItem.delete();
        } else {
            Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file
            Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name
            for (FileItem fileItem : actualFiles) {
                File theFile = forceToFile(fileItem);
                if (obfuscate) {
                    // The commons fileupload API has a file tracker that deletes the file when the File object is garbage collected (huh?).
                    // Because we will be using these files later, and because they are going to be obfuscated, we don't want this to happen,
                    // so just rename the file to move it away from the file tracker and thus won't get
                    // prematurely deleted before we get a chance to use it.
                    File movedFile = new File(theFile.getAbsolutePath() + ".temp");
                    if (theFile.renameTo(movedFile)) {
                        theFile = movedFile;
                    }
                    try {
                        FileUtil.compressFile(theFile); // we really just compress it with our special compressor since its faster than obsfucation
                    } catch (Exception e) {
                        throw new ServletException("Cannot obfuscate uploaded files", e);
                    }
                }
                allUploadedFiles.put(fileItem.getFieldName(), theFile);
                allUploadedFileNames.put(fileItem.getFieldName(),
                        (fileItem.getName() != null) ? fileItem.getName() : theFile.getName());
            }
            processUploadedFiles(authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req,
                    resp);
        }
    }
}

From source file:net.cit.tetrad.resource.LoginResource.java

@RequestMapping("/login.do")
public ModelAndView login(HttpServletRequest request, CommonDto dto) throws Exception {
    log.debug("login start");

    ModelAndView mav = new ModelAndView();
    Query query = new Query();
    try {/*  w ww.  j ava  2 s  . co  m*/
        int count = (int) monadService.getCount(query, User.class);
        if (count == 0) {
            insertSuperUser();
            mav.setViewName("login");
            mav.addObject("releaseVersion", PropertiesNames.RELEASEVERSIONINFO);
            mav.addObject("licensekey", Config.LICENSEKEY);
            mav.addObject("licensetype", Config.LICENSETYPE);
        } else {
            User user = doLogin(dto, mav);
            HttpSession session = request.getSession();
            session.setAttribute("loginUserCode", user.getIdx());
            session.setAttribute("loginAuth", user.getAuthority());
            session.setMaxInactiveInterval(1800);
        }
    } catch (Exception e) {
        dto.setMessage(" ?.");
    }
    mav.addObject("comm", dto);
    log.debug("login end");
    return mav;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
    out.println("<BODY><H1>Session Timer</H1>");

    // Display the previous timeout
    out.println("The previous timeout was " + session.getMaxInactiveInterval());
    out.println("<BR>");

    // Set the new timeout
    session.setMaxInactiveInterval(2 * 60 * 60); // two hours

    // Display the new timeout
    out.println("The newly assigned timeout is " + session.getMaxInactiveInterval());

    out.println("</BODY></HTML>");
}

From source file:leon.ssi.util.session.AppSessionListener.java

/**
 * set time out//  w  w  w.j a v a 2 s  .  c  o  m
 */
public void sessionCreated(HttpSessionEvent se) {
    HttpSession session = null;
    try {
        session = se.getSession();
        // get value
        ServletContext context = session.getServletContext();
        String timeoutValue = context.getInitParameter("sessionTimeout");
        int timeout = Integer.valueOf(timeoutValue);
        // set value
        session.setMaxInactiveInterval(timeout);
        logger.info("session max inactive interval has been set to " + timeout + " seconds.");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:fina.usuario.servlet.usuarioServlet.java

private void validarUsuario(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jsonResult = new JSONObject();
    Mensaje mensaje = new Mensaje(false, Mensaje.INFORMACION);
    String usuario = request.getParameter("txtUsuario").trim();
    String pass = request.getParameter("txtContrasenia").trim();
    boolean recordar = request.getParameter("txtRecordarP") == null;
    try {// w w w.j a v  a  2 s .c  o m
        UsuarioDao usuarioDao = new UsuarioDao();
        Usuario usu = usuarioDao.validarIngreso(usuario, pass);
        if (usu != null) {

            HttpSession session = request.getSession(true);
            session.setMaxInactiveInterval(60 * 60 * 2);
            session.setAttribute("usuarioLogeado", usu);
            mensaje.setHayMensaje(false);
            //response.sendRedirect("paginas/inicio.jsp");
        } else {
            mensaje.setHayMensaje(true);
            mensaje.setTipo(Mensaje.INFORMACION);
            mensaje.setMensaje("Usuario o contrsea no reconocidos.");
        }

    } catch (Exception e) {
        mensaje.setHayMensaje(true);
        mensaje.setTipo(Mensaje.ERROR);
        mensaje.setMensaje("Error al procesar la solicitud en el servidor.");
        mensaje.setDetalle(e.toString());
    }

    JSONObject jsonMensaje = new JSONObject(mensaje);
    try {
        jsonResult.put("msj", jsonMensaje);
        jsonResult.put("url", "paginas/inicio.jsp");
        enviarDatos(response, jsonResult.toString());

    } catch (Exception e) {
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.BasicAuthenticator.java

/**
 * Editors and other privileged users get a longer timeout interval.
 *//* w  ww  .j a  v a 2  s .c  o  m*/
private void setSessionTimeoutLimit(UserAccount userAccount, HttpSession session) {
    RoleLevel role = RoleLevel.getRoleFromLoginStatus(request);
    if (role == RoleLevel.EDITOR || role == RoleLevel.CURATOR || role == RoleLevel.DB_ADMIN) {
        session.setMaxInactiveInterval(PRIVILEGED_TIMEOUT_INTERVAL);
    } else if (userAccount.isRootUser()) {
        session.setMaxInactiveInterval(PRIVILEGED_TIMEOUT_INTERVAL);
    } else {
        session.setMaxInactiveInterval(LOGGED_IN_TIMEOUT_INTERVAL);
    }
}