Example usage for javax.servlet.http HttpSession isNew

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

Introduction

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

Prototype

public boolean isNew();

Source Link

Document

Returns true if the client does not yet know about the session or if the client chooses not to join the session.

Usage

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Check session.// w ww . java2  s .c  om
 * 
 * @param session the session
 * @param requestContext the request context
 * 
 * @throws SessionExpiredException the session expired exception
 */
private void checkSession(HttpSession session, RequestContextIFace requestContext)
        throws SessionExpiredException {

    // start modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
    boolean isRequestedSessionIdValid = true;
    boolean isRequiredNewSession = false; // Zerbetto on 25-02-2008
    RequestContainer requestContainer = requestContext.getRequestContainer();

    if (session.isNew()) {
        isRequestedSessionIdValid = (requestContainer.getAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID) == null);
        String newSessionRequestAttr = (String) requestContainer.getServiceRequest().getAttribute(NEW_SESSION); // Zerbetto on 25-02-2008
        isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE"); // Zerbetto on 25-02-2008
    } // if (session.isNew())
    synchronized (session) {
        RequestContainer parentRequestContainer = (RequestContainer) session
                .getAttribute(Constants.REQUEST_CONTAINER);
        if (!Navigator.isNavigatorEnabled()) {
            if (parentRequestContainer == null)
                requestContainer.setSessionContainer(new SessionContainer(true));
            else
                requestContainer.setSessionContainer(parentRequestContainer.getSessionContainer());
        } else {
            if (parentRequestContainer == null)
                requestContainer.setSessionContainer(new SessionContainer(true));
            else {
                requestContainer.setSessionContainer(new SessionContainer(false));
                requestContainer.setParent(parentRequestContainer);
            } // if (parentRequestContainer == null) else
        } // if (!Navigator.isNavigatorEnabled())
        session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
    } // synchronized (session)
    if (!isRequestedSessionIdValid) {
        if (!isRequiredNewSession) { // Zerbetto on 25-02-2008
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING,
                    "AdapterHTTP::service: sessione scaduta !");
            throw new SessionExpiredException(EMFErrorSeverity.ERROR, "Expired Session");
        } // Zerbetto on 25-02-2008
    } // if (!isRequestedSessionIdValid)
      // end modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
}

From source file:UsingContexts.java

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

    HttpSession session = request.getSession(true);

    Integer counter2 = (Integer) getServletContext().getAttribute("counter2");

    if (counter2 == null) {
        counter2 = new Integer(1);
    } else {//from  w  w w.ja  va2s .com
        counter2 = new Integer(counter2.intValue() + 1);
    }

    getServletContext().setAttribute("counter2", counter2);

    Integer counter = (Integer) session.getAttribute("counter");

    if (counter == null) {
        counter = new Integer(1);
    } else {
        counter = new Integer(counter.intValue() + 1);
    }

    session.setAttribute("counter", counter);

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("Using Contexts");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>Using Contexts</H1>");

    out.println("Welcome! You have been here " + counter + " times.<BR>");

    out.println("Total page accesses: " + counter2 + "<BR>");

    if (session.isNew()) {
        out.println("This is a new session.<BR>");
    } else {
        out.println("This is not a new session.<BR>");
    }

    out.println("The session ID: " + session.getId() + "<BR>");
    out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
    out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");

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

From source file:org.jahia.bin.filters.jcr.JcrSessionFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    if (bypass(servletRequest)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;//  w ww.j  a  v a2  s .  c  o m
    }
    boolean initialized = SpringContextSingleton.getInstance().isInitialized();
    try {
        AuthValveContext authValveContext = null;
        if (initialized) {
            try {
                sessionFactory.setCurrentUser(null);
                authValveContext = new AuthValveContext((HttpServletRequest) servletRequest,
                        (HttpServletResponse) servletResponse, sessionFactory);
                authPipeline.invoke(authValveContext);
            } catch (PipelineException pe) {
                logger.error("Error while authorizing user", pe);
            }
        }

        if (sessionFactory.getCurrentUser() == null) {
            sessionFactory.setCurrentUser(
                    userManagerService.lookupUserByPath(JahiaUserManagerService.GUEST_USERPATH).getJahiaUser());
        } else {
            JCRUserNode userNode = userManagerService
                    .lookupUserByPath(sessionFactory.getCurrentUser().getLocalPath());
            if (userNode == null || userNode.isAccountLocked()) {
                sessionFactory.setCurrentUser(null);
            }
            HttpSession httpSession = ((HttpServletRequest) servletRequest).getSession();
            // the following check is done to make sure that the user hasn't been logged out between the reading
            // from the session and the writing back to it. In the case of the logout, the isAuthRetrievedFromSession
            // will return true, but the session will not contain a user because the old session was invalidated
            // and a new one was created. In that case we will not insert the user back into the session.
            // In all other cases we set the user in the session, even if we read from it because this is an expected
            // behavior in the case where the user was updated in the backend (JCR) but not yet in the session.
            // For more information see : https://jira.jahia.org/browse/BACKLOG-5166 and https://jira.jahia.org/browse/BACKLOG-5207
            if (authValveContext == null || !httpSession.isNew()
                    || !authValveContext.isAuthRetrievedFromSession()) {
                httpSession.setAttribute(Constants.SESSION_USER, sessionFactory.getCurrentUser());
                // an IllegalStateException might be raised by the setAttribute call if the session was
                // invalidated, which is the expected behavior because we do want to interrupt the
                // processing in that case.
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (initialized) {
            endRequest();
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGAUsageStatistics.java

public void addRequestStatistic(HttpServletRequest req, HttpSession sess, WGDatabase db,
        TMLUserProfile profile) {/*w  ww .j  a v a 2 s.co m*/
    try {

        RequestStatistic requestStatistic = new RequestStatistic();
        requestStatistic.setDatabase(db.getDbReference());
        requestStatistic.setLastAccess(new Date());
        requestStatistic.setTask(db.getSessionContext().getTask());
        requestStatistic.setUser(db.getSessionContext().getUser());
        requestStatistic.setSessionId(sess.getId());
        requestStatistic.setSessionCreated(new Date(sess.getCreationTime()));
        requestStatistic.setNewSession(sess.isNew());
        requestStatistic.setRemoteHost(req.getRemoteAddr());
        String userAgent = req.getHeader("USER-AGENT");
        if (userAgent != null) {
            requestStatistic.setUserAgent(userAgent);
        } else {
            requestStatistic.setUserAgent("(unknown)");
        }

        if (profile != null) {
            requestStatistic.setProfile(profile.getprofile().getName());
        } else {
            requestStatistic.setProfile("(none)");
        }

        try {
            _requestStatisticQueue.add(requestStatistic);
        } catch (IllegalStateException e) {
            if (!_warnedAboutFullQueue) {
                _wgaCore.getLog().warn(
                        "Session statistics queue is temporarily full. Currently displayed statistics may not be accurate.");
                _warnedAboutFullQueue = true;
            }
        }

    } catch (Exception e) {
        _wgaCore.log.error("Unable to update usage statistics.", e);
    }
}

From source file:org.testdwr.plain.Test.java

public void reverseAjaxCreateSessionFromWorkerThread(final String replyFuncName) {
    final ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
    HttpServletRequest callRequest = WebContextFactory.get().getHttpServletRequest();
    if (callRequest.getSession(false) != null) {
        callReverseAjaxFunc(scriptSession, replyFuncName, "Error: session already exists");
        return;//from   w w w  .  j  a  va  2s. com
    }
    Runnable r = new Runnable() {
        public void run() {
            try {
                Thread.sleep(500);
                scriptSession.addRunnable(new Runnable() {
                    public void run() {
                        HttpServletRequest pollRequest1 = WebContextFactory.get().getHttpServletRequest();
                        HttpSession session = pollRequest1.getSession();
                        if (!session.isNew()) {
                            callReverseAjaxFunc(scriptSession, replyFuncName,
                                    "Error: session is already confirmed");
                            return;
                        }
                        scriptSession.addRunnable(new Runnable() {
                            public void run() {
                                HttpServletRequest pollRequest2 = WebContextFactory.get()
                                        .getHttpServletRequest();
                                HttpSession session = pollRequest2.getSession();
                                if (session.isNew()) {
                                    callReverseAjaxFunc(scriptSession, replyFuncName,
                                            "Error: session is not confirmed");
                                    return;
                                }
                                callReverseAjaxFunc(scriptSession, replyFuncName, "ok: " + session.getId());
                            }
                        });
                    }
                });
            } catch (InterruptedException e) {
                // Ignore
            }
        }
    };
    Thread t = new Thread(r);
    t.start();
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private WTSSession setUpSession(WTSSession pWtsSession, boolean pCacheScene, HttpServletRequest pRequest,
        VgEnvelope pBBox, String pDrape, String pWmsLayers) {
    HttpSession lSession;
    TempFileHandler lRequTmpMngr;//  w w  w .ja v  a2  s. c o  m
    TempFileHandler lSessionTmpMngr = null;

    if (pCacheScene) {
        lSession = pRequest.getSession(true);
        if (lSession == null)
            throw new T3dException("Could not get session object...", 102);

        lRequTmpMngr = new TempFileHandler();

        if (lSession.isNew()) {
            lSession.setMaxInactiveInterval(mSessionMaxInactiveInterval);
            lSessionTmpMngr = new TempFileHandler();
            lSession.setAttribute("shndlr_" + lSession.getId(), lSessionTmpMngr);
        } else {
            lSessionTmpMngr = (TempFileHandler) lSession.getAttribute("shndlr_" + lSession.getId());
            if (lSessionTmpMngr == null) {
                // Session nicht neu, aber lTmpMngr nicht in Session, Fall tritt z. B. in JSP-Client auf.
                lSessionTmpMngr = new TempFileHandler();
                lSession.setAttribute("shndlr_" + lSession.getId(), lSessionTmpMngr);
            } else {
                // Parameterwerte der letzten Anfrage holen...
                VgEnvelope oldBBox = (VgEnvelope) lSession.getAttribute("rqBBOX_" + lSession.getId()); // BBOX
                String oldDrape = (String) lSession.getAttribute("rqDRAPE_" + lSession.getId()); // DRAPE
                String oldWmsLayers = (String) lSession.getAttribute("rqWMSLAYERS_" + lSession.getId()); // WMSLAYERS
                boolean changesBBox = false, changesDrp = false;
                // BBOX seit letzter Anfrage gendert?
                if (oldBBox != null && !oldBBox.isSpatiallyEquivalent(pBBox))
                    changesBBox = true;
                // DRAPE seit letzter Anfrage gendert?
                if (oldDrape != null && oldDrape.compareTo(pDrape) != 0)
                    changesDrp = true;
                // WMSLAYERS seit letzter Anfrage gendert?
                if (oldWmsLayers != null && oldWmsLayers.compareTo(pWmsLayers) != 0)
                    changesDrp = true;

                // ... und im Falle relevanter nderungen Cache-Inhalte leeren:
                if (changesBBox) {
                    lSession.removeAttribute("terrain_" + lSession.getId());
                    lSessionTmpMngr
                            .removeTempFile((String) lSession.getAttribute("demgif_" + lSession.getId()));
                    lSession.removeAttribute("demgif_" + lSession.getId());
                }
                if (changesDrp || changesBBox) {
                    lSessionTmpMngr.removeTempFile((String) lSession.getAttribute("drape_" + lSession.getId()));
                    lSession.removeAttribute("drape_" + lSession.getId());
                }
            }
            lSession.setAttribute("rqBBOX_" + lSession.getId(), pBBox); // BBOX in Session legen
            lSession.setAttribute("rqDRAPE_" + lSession.getId(), pDrape); // DRAPE in Session legen
            lSession.setAttribute("rqWMSLAYERS_" + lSession.getId(), pWmsLayers); // WMSLAYERS in Session legen
        }
    } else {
        // Fr CACHESCENE=false ggf. Objekte aus vorherigen Aufrufen mit CACHESCENE=true aus Session entfernen:
        lSession = pRequest.getSession(false);
        if (lSession != null) {
            lSession.removeAttribute("shndlr_" + lSession.getId());
            lSession.removeAttribute("terrain_" + lSession.getId());
            lSession.removeAttribute("drape_" + lSession.getId());
            lSession.removeAttribute("demgif_" + lSession.getId());
            lSession.invalidate();
        }
        lRequTmpMngr = new TempFileHandler();
    }
    pWtsSession.setHttpSession(lSession);
    pWtsSession.setRequTempFileHandler(lRequTmpMngr);
    pWtsSession.setSessionTempFileHandler(lSessionTmpMngr);
    return pWtsSession;
}

From source file:org.apache.tapestry.request.RequestContext.java

/**
 * Writes the state of the context to the writer, typically for inclusion
 * in a HTML page returned to the user. This is useful
 * when debugging.  The Inspector uses this as well.
 *
 **///ww  w. j  av  a2s .c o  m

public void write(IMarkupWriter writer) {
    // Create a box around all of this stuff ...

    writer.begin("table");
    writer.attribute("class", "request-context-border");
    writer.begin("tr");
    writer.begin("td");

    // Get the session, if it exists, and display it.

    HttpSession session = getSession();

    if (session != null) {
        object(writer, "Session");
        writer.begin("table");
        writer.attribute("class", "request-context-object");

        section(writer, "Properties");
        header(writer, "Name", "Value");

        pair(writer, "id", session.getId());
        datePair(writer, "creationTime", session.getCreationTime());
        datePair(writer, "lastAccessedTime", session.getLastAccessedTime());
        pair(writer, "maxInactiveInterval", session.getMaxInactiveInterval());
        pair(writer, "new", session.isNew());

        List names = getSorted(session.getAttributeNames());
        int count = names.size();

        for (int i = 0; i < count; i++) {
            if (i == 0) {
                section(writer, "Attributes");
                header(writer, "Name", "Value");
            }

            String name = (String) names.get(i);
            pair(writer, name, session.getAttribute(name));
        }

        writer.end(); // Session

    }

    object(writer, "Request");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    // Parameters ...

    List parameters = getSorted(_request.getParameterNames());
    int count = parameters.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Parameters");
            header(writer, "Name", "Value(s)");
        }

        String name = (String) parameters.get(i);
        String[] values = _request.getParameterValues(name);

        writer.begin("tr");
        writer.attribute("class", getRowClass());
        writer.begin("th");
        writer.print(name);
        writer.end();
        writer.begin("td");

        if (values.length > 1)
            writer.begin("ul");

        for (int j = 0; j < values.length; j++) {
            if (values.length > 1)
                writer.beginEmpty("li");

            writer.print(values[j]);

        }

        writer.end("tr");
    }

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "authType", _request.getAuthType());
    pair(writer, "characterEncoding", _request.getCharacterEncoding());
    pair(writer, "contentLength", _request.getContentLength());
    pair(writer, "contentType", _request.getContentType());
    pair(writer, "method", _request.getMethod());
    pair(writer, "pathInfo", _request.getPathInfo());
    pair(writer, "pathTranslated", _request.getPathTranslated());
    pair(writer, "protocol", _request.getProtocol());
    pair(writer, "queryString", _request.getQueryString());
    pair(writer, "remoteAddr", _request.getRemoteAddr());
    pair(writer, "remoteHost", _request.getRemoteHost());
    pair(writer, "remoteUser", _request.getRemoteUser());
    pair(writer, "requestedSessionId", _request.getRequestedSessionId());
    pair(writer, "requestedSessionIdFromCookie", _request.isRequestedSessionIdFromCookie());
    pair(writer, "requestedSessionIdFromURL", _request.isRequestedSessionIdFromURL());
    pair(writer, "requestedSessionIdValid", _request.isRequestedSessionIdValid());
    pair(writer, "requestURI", _request.getRequestURI());
    pair(writer, "scheme", _request.getScheme());
    pair(writer, "serverName", _request.getServerName());
    pair(writer, "serverPort", _request.getServerPort());
    pair(writer, "contextPath", _request.getContextPath());
    pair(writer, "servletPath", _request.getServletPath());

    // Now deal with any headers

    List headers = getSorted(_request.getHeaderNames());
    count = headers.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Headers");
            header(writer, "Name", "Value");
        }

        String name = (String) headers.get(i);
        String value = _request.getHeader(name);

        pair(writer, name, value);
    }

    // Attributes

    List attributes = getSorted(_request.getAttributeNames());
    count = attributes.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) attributes.get(i);

        pair(writer, name, _request.getAttribute(name));
    }

    // Cookies ...

    Cookie[] cookies = _request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {

            if (i == 0) {
                section(writer, "Cookies");
                header(writer, "Name", "Value");
            }

            Cookie cookie = cookies[i];

            pair(writer, cookie.getName(), cookie.getValue());

        } // Cookies loop
    }

    writer.end(); // Request

    object(writer, "Servlet");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "servlet", _servlet);
    pair(writer, "name", _servlet.getServletName());
    pair(writer, "servletInfo", _servlet.getServletInfo());

    ServletConfig config = _servlet.getServletConfig();

    List names = getSorted(config.getInitParameterNames());
    count = names.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Init Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        ;
        pair(writer, name, config.getInitParameter(name));

    }

    writer.end(); // Servlet

    ServletContext context = config.getServletContext();

    object(writer, "Servlet Context");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "majorVersion", context.getMajorVersion());
    pair(writer, "minorVersion", context.getMinorVersion());
    pair(writer, "serverInfo", context.getServerInfo());

    names = getSorted(context.getInitParameterNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Initial Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getInitParameter(name));
    }

    names = getSorted(context.getAttributeNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getAttribute(name));
    }

    writer.end(); // Servlet Context

    writeSystemProperties(writer);

    writer.end("table"); // The enclosing border
}

From source file:com.mhe.mediabanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = Configuration.getSystemValue(Constants.IMAGE_THUMBNAIL_URL_PATH);
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;/*ww w .j av a 2s. c om*/
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");
        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:com.mhe.imagebanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = AmazonServiceUtilTag.getImageThumbnailURL();
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;/*from   w w  w .  j a  v  a 2s .com*/
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId, ASSETBANK_TYPE);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");

        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = { "**/login**" }, method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {
    ModelAndView model = new ModelAndView();
    ResultSet rs = null;//www. ja v  a 2  s  .co  m
    try {
        boolean flag = false;
        String correct_time = "";
        String userName = "";
        String system_time = "";
        int web_sec = 0;
        int sys_sec = 0;
        correct_time = TimeUtility.generateSysDateMethod();
        system_time = TimeUtility.generateSysDateMethod();
        web_sec = TimeUtility.generateSysSecondsMethod();
        sys_sec = TimeUtility.generateSysSecondsMethod();
        session = request.getSession();
        if (!session.isNew()) {
            LOG.error("New session created");
        } else {
            model = new ModelAndView();
            LoginHandler handler = new LoginHandler();
            model.setViewName("index");
            if (userName != null && !flag) {
                userName = (String) session.getAttribute("USERNAME");
                handler.updateLoggedInFlag(userName, 0);
                session.invalidate();

                return model;
            }
        }

        if (correct_time.equals(system_time) && Math.abs(web_sec - sys_sec) < 1800) {
            model = new ModelAndView();
            String password = "";
            String captchaData = "";
            String captchaString = "";
            if (request.getParameter("submit") != null) {
                userName = request.getParameter("username");
                password = request.getParameter("password");
                captchaData = request.getParameter("captcha");
                captchaString = (String) session.getAttribute("CAPTCHA");

                if (userName.equals("") || password.equals("") || captchaData.equals("")) {
                    flag = true;
                    session.setAttribute("FLAG", flag);
                    model.addObject("emptyFields", "All fields are mandatory");
                    model.setViewName("login");
                }

                else if (!captchaData.equals(captchaString)) {
                    flag = true;
                    session.setAttribute("FLAG", flag);
                    model.addObject("wrongCaptcha", "Please re-enter captcha");
                    model.setViewName("login");
                }

                else {
                    LoginHandler handler = new LoginHandler();
                    rs = handler.requestLoginHandler(userName);
                    if (rs.next()) {
                        String uName = rs.getString("username");
                        String fName = rs.getString("firstname");
                        String pass = rs.getString("usercurrentpassword");
                        String role = rs.getString("usertype");
                        int loggedIn = rs.getInt("isloggedin");
                        String ispwdchange = rs.getString("ispasswordchange");
                        int lock = rs.getInt("islocked");
                        session.setAttribute("USERNAME", userName);
                        if (lock == 0) {
                            boolean correctPass;
                            if (ispwdchange.equals("1")) {
                                correctPass = password.equals(pass);
                            } else {
                                SaltModule saltPass = new SaltModule();
                                correctPass = saltPass.isPasswordValid(password, pass);
                            }
                            if (uName.equals(userName) && correctPass) {
                                if (loggedIn == 0) {

                                    if (ispwdchange.equals("1")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        model.addObject("user", userName);
                                        model.setViewName("resetpassword");
                                        return model;
                                    }
                                    handler.updateLoggedInFlag(userName, 1);
                                    request.getSession().setAttribute("Role", role);
                                    if (role.equals("MANAGER")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Manager", fName);
                                        model.setViewName("managerhome");
                                    } else if (role.equals("EMPLOYEE")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Employee", fName);
                                        model.setViewName("employeehome");
                                    } else if (role.equals("ADMIN")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Admin", fName);
                                        model.setViewName("admin");
                                    } else if (role.equals("MERCHANT")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Merchant", fName);
                                        model.setViewName("merchanthome");
                                    } else if (role.equals("USER")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("User", fName);
                                        model.setViewName("customerhome");
                                    } else if (role.equals("GOVERNMENT")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Government", fName);
                                        model.setViewName("government");
                                    }
                                } else {
                                    flag = true;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("loggedIn",
                                            "User is already logged in to the other system");
                                    model.setViewName("login");
                                }
                            } else {
                                count++;
                                if (count > 2) {
                                    flag = false;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("user", userName);
                                    handler.updateLockedFlag(userName, 1);
                                    model.addObject("lock",
                                            "Your account has been locked. Please fill in the below details to make a request for unlock account.");
                                    model.setViewName("unlockaccount");
                                } else {
                                    flag = true;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("wrongCredentials", "Username and Password do not match");
                                    model.setViewName("login");
                                }
                            }
                        } else {
                            flag = false;
                            session.setAttribute("FLAG", flag);
                            model.addObject("user", userName);
                            model.addObject("lock",
                                    "Your account has been locked. Please fill in the below details to make a request for unlock account.");
                            model.setViewName("unlockaccount");
                        }
                    } else {
                        flag = true;
                        session.setAttribute("FLAG", flag);
                        model.addObject("wrongCredentials",
                                "Username does not exist. Please enter correct username");
                        model.setViewName("login");
                    }
                }
            } else if (request.getParameter("imgCaptcha") != null) {
                flag = true;
                session.setAttribute("FLAG", flag);
                CaptchaUtility captcha = new CaptchaUtility();
                captcha.generateCaptcha(request, response);
                model.setViewName("login");
            } else {
                flag = false;
                session.setAttribute("FLAG", flag);
                LoginHandler handler;
                handler = new LoginHandler();
                String userSessionName = (String) session.getAttribute("USERNAME");
                handler.updateLoggedInFlag(userSessionName, 0);
                model.setViewName("login");
            }
        } else {
            flag = false;
            session.setAttribute("FLAG", flag);
            model = new ModelAndView();
            model.addObject("Timetampering", "System time is not updated");
            model.setViewName("login");
        }
    } catch (Exception e) {
        LoginHandler handler;
        handler = new LoginHandler();
        String userSessionName = (String) session.getAttribute("USERNAME");
        handler.updateLoggedInFlag(userSessionName, 0);
        model.setViewName("login");
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            LoginHandler handler;
            handler = new LoginHandler();
            String userSessionName = (String) session.getAttribute("USERNAME");
            handler.updateLoggedInFlag(userSessionName, 0);
            model.setViewName("login");
        }
    }
    return model;
}