Example usage for javax.servlet.http HttpSession removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the object bound with the specified name from this session.

Usage

From source file:com.redsqirl.CanvasBean.java

public void removeMsgErrorInit() {

    logger.info("removeMsgErrorInit");

    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession httpSession = (HttpSession) facesContext.getExternalContext().getSession(false);
    httpSession.removeAttribute("msnErrorInit");
    //logger.info("remove msnErrorInit");
}

From source file:edu.isi.pfindr.servlets.QueryServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w w  w  .j a  v  a  2 s  .  c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    HttpSession session = request.getSession(false);
    Connection conn = (Connection) session.getAttribute("conn");
    response.setContentType("application/json");
    String action = request.getParameter("predicate");
    String text = "";

    if (action.equals("apply_filter_study_metadata")) {
        JSONObject res = applyFilterStudyMetadata(request, conn);
        text = res.toString();
    } else if (action.equals("study_metadata")) {
        JSONObject res = studyMetadata(request, conn);
        text = res.toString();
    } else if (action.equals("bookmark")) {
        JSONObject res = bookmarkQuery(request, conn);
        text = res.toString();
    } else if (action.equals("save")) {
        // save the query results to a file
        text = save(request, conn);
        //response.setContentType ("application/xml");
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"Results.xls\"");
        response.setContentLength(text.length());
    } else if (action.equals("export")) {
        // export the query to a file
        text = export(request, conn);
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"Query.txt\"");
        response.setContentLength(text.length());
    } else if (action.equals("import")) {
        // export the query to a file
        importQuery(request, conn);
        response.sendRedirect("/pfindr/query");
        return;
    } else if (action.equals("saveSelectedResults") || action.equals("markAsCorrect")
            || action.equals("markAsIncorrect")) {
        // save the query results to a file
        text = saveSelectedResults(request, conn);
        if (request.getParameter("timestamp") != null || action.equals("saveSelectedResults")) {
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment; filename=\"SelectedResults.xls\"");
            response.setContentLength(text.length());
        }
    } else if (action.equals("keyword")) {
        // get hints for a keyword
        JSONArray rows = keywords(request, conn);
        text = rows.toString();
    } else if (action.equals("select")) {
        // get query results
        try {
            JSONObject obj = new JSONObject();
            JSONObject queryDescription = (JSONObject) session.getAttribute("query");
            if (queryDescription == null) {
                String sql = request.getParameter("sql");
                JSONObject json = new JSONObject(sql);
                request.setAttribute("sql", json);
                obj = select(request, conn);
            } else {
                session.removeAttribute("query");
                obj.put("queryDescription", queryDescription);
            }
            text = obj.toString();
            //logger.info(text);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (action.equals("selectFilters")) {
        // get query results
        try {
            JSONObject obj = new JSONObject();
            String sql = request.getParameter("sql");
            JSONObject json = new JSONObject(sql);
            request.setAttribute("sql", json);
            obj = selectFilters(request, conn);
            text = obj.toString();
            //logger.info(text);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (action.equals("flat")) {
        // get query results
        JSONObject res = dataTables(request, conn);
        text = res.toString();
    } else {
        logger.error("Invalid action: \"" + action + "\".");
    }
    PrintWriter out = response.getWriter();
    out.print(text);
}

From source file:com.redsqirl.CanvasBean.java

/**
 * cleanErrorList//from w w  w.jav  a  2  s  .  c  om
 * 
 * Method to clean the list table
 * 
 * @return
 * @author Igor.Souza
 */
public void cleanErrorList() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

    if (session.getAttribute("listError") != null) {
        session.removeAttribute("listError");
        List<SelectItem> listError = new LinkedList<SelectItem>();
        session.setAttribute("listError", listError);
    }

}

From source file:com.cws.esolutions.security.filters.SessionAuthenticationFilter.java

public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final String methodName = SessionAuthenticationFilter.CNAME
            + "#doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws IOException, ServletException";

    if (DEBUG) {//from ww w . j a va 2s . co  m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletRequest: {}", sRequest);
        DEBUGGER.debug("ServletResponse: {}", sResponse);
    }

    final HttpServletRequest hRequest = (HttpServletRequest) sRequest;
    final HttpServletResponse hResponse = (HttpServletResponse) sResponse;
    final HttpSession hSession = hRequest.getSession(false);
    final String requestURI = hRequest.getRequestURI();
    final String passwdPage = hRequest.getContextPath() + this.passwordURI;
    final StringBuilder redirectPath = new StringBuilder().append(hRequest.getContextPath() + this.loginURI)
            .append("?vpath=" + requestURI);

    if (DEBUG) {
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpServletResponse: {}", hResponse);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("RequestURI: {}", requestURI);
        DEBUGGER.debug("passwdPage: {}", passwdPage);
        DEBUGGER.debug("redirectPath: {}", redirectPath);

        DEBUGGER.debug("Dumping session content:");
        Enumeration<?> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String element = (String) sessionEnumeration.nextElement();
            Object value = hSession.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request content:");
        Enumeration<?> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String element = (String) requestEnumeration.nextElement();
            Object value = hRequest.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request parameters:");
        Enumeration<?> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String element = (String) paramsEnumeration.nextElement();
            Object value = hRequest.getParameter(element);

            DEBUGGER.debug("Parameter: {}; Value: {}", element, value);
        }
    }

    if (StringUtils.equals(this.loginURI, requestURI)) {
        if (DEBUG) {
            DEBUGGER.debug("Request authenticated. No action taken !");
        }

        filterChain.doFilter(sRequest, sResponse);

        return;
    }

    if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) {
        if (Arrays.asList(this.ignoreURIs).contains("ALL")) {
            if (DEBUG) {
                DEBUGGER.debug("ALL URIs are ignored. Breaking ...");
            }

            filterChain.doFilter(sRequest, sResponse);

            return;
        }

        // hostname isnt in ignore list
        for (String uri : this.ignoreURIs) {
            uri = hRequest.getContextPath().trim() + uri.trim();

            if (DEBUG) {
                DEBUGGER.debug(uri);
                DEBUGGER.debug(requestURI);
            }

            if (StringUtils.contains(requestURI, uri)) {
                // ignore
                if (DEBUG) {
                    DEBUGGER.debug("URI matched to ignore list - breaking out");
                }

                filterChain.doFilter(sRequest, sResponse);

                return;
            }
        }
    }

    if (hRequest.isRequestedSessionIdFromURL()) {
        ERROR_RECORDER.error("Session found is from URL. Redirecting request to " + hRequest.getContextPath()
                + this.loginURI);

        // invalidate the session
        hRequest.getSession(false).invalidate();
        hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
        hSession.invalidate();

        hResponse.sendRedirect(hRequest.getContextPath() + this.loginURI);

        return;
    }

    Enumeration<?> sessionAttributes = hSession.getAttributeNames();

    if (DEBUG) {
        DEBUGGER.debug("Enumeration<String>: {}", sessionAttributes);
    }

    while (sessionAttributes.hasMoreElements()) {
        String element = (String) sessionAttributes.nextElement();

        if (DEBUG) {
            DEBUGGER.debug("element: {}", element);
        }

        Object value = hSession.getAttribute(element);

        if (DEBUG) {
            DEBUGGER.debug("sessionValue: {}", value);
        }

        if (value instanceof UserAccount) {
            UserAccount userAccount = (UserAccount) value;

            if (DEBUG) {
                DEBUGGER.debug("UserAccount: {}", userAccount);
            }

            if (userAccount.getStatus() != null) {
                switch (userAccount.getStatus()) {
                case EXPIRED:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account is expired and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case RESET:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account has status RESET and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case SUCCESS:
                    filterChain.doFilter(sRequest, sResponse);

                    return;
                default:
                    break;
                }
            }
        }
    }

    // no user account in the session
    ERROR_RECORDER.error("Session contains no existing user account. Redirecting request to "
            + hRequest.getContextPath() + this.loginURI);

    // invalidate the session
    hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
    hSession.invalidate();

    if (StringUtils.isNotEmpty(hRequest.getQueryString())) {
        redirectPath.append("?" + hRequest.getQueryString());
    }

    if (DEBUG) {
        DEBUGGER.debug("redirectPath: {}", redirectPath.toString());
    }

    hResponse.sendRedirect(URLEncoder.encode(redirectPath.toString(), systemConfig.getEncoding()));

    return;
}

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

private void removeSessionCookie(javax.servlet.http.HttpServletResponse response, HttpSession session,
        WGDatabase database) {/*from w w w.  j av a  2  s . co  m*/
    if (!database.hasFeature(WGDatabase.FEATURE_SESSIONTOKEN)) {
        return;
    }

    String cookieName = (String) database.getAttribute(WGACore.DBATTRIB_SESSIONCOOKIE);
    if (cookieName == null) {
        return;
    }

    WGCookie sessionCookie = new WGCookie(cookieName, "");
    sessionCookie.setMaxAge(0);
    sessionCookie.setPath("/");
    String sessionCookieDomain = (String) database.getAttribute(WGACore.DBATTRIB_SESSIONCOOKIEDOMAIN);
    if (sessionCookieDomain != null) {
        sessionCookie.setDomain(sessionCookieDomain);
    }
    sessionCookie.addCookieHeader(response);
    session.removeAttribute(WGACore.SESSION_COOKIESET + cookieName);

}

From source file:com.virtusa.akura.common.controller.ChangePasswordController.java

/**
 * Request handler for submit user security question answers.
 * /*w  ww.  j ava2 s  .  c om*/
 * @param submitAnswers The wrapper security question to bind answers.
 * @param bindingResult The binding result object to bind all types of errors.
 * @param modelMap a map that keeps all the bonded values.
 * @param session get the logged i user information from session. The logged in user is always in the
 *        session.
 * @return view name of forgot password.
 * @throws AkuraAppException throws when fails.
 */
@RequestMapping(value = SUBMITANSWERS, method = RequestMethod.POST)
public String submitAnswers(@ModelAttribute(SUBMIT_ANSWERS) WrapperSecurityQuestions submitAnswers,
        BindingResult bindingResult, ModelMap modelMap, HttpSession session) throws AkuraAppException {

    UserLogin userLogin = (UserLogin) session.getAttribute(USERLOGIN);
    UserLogin userLoginByName = (UserLogin) session.getAttribute(USERLOGINBYNAME);
    boolean success = false;
    String mailError = null;

    if (userLogin == null) {
        userLogin = userLoginByName;
    }

    // set the user of security question one.
    UserSecurityQuestions userSecurityQuestionsOne = submitAnswers.getUserQuestionOne();

    // set the user of security question two.
    UserSecurityQuestions userSecurityQuestionsTwo = submitAnswers.getUserQuestionTwo();

    if (userSecurityQuestionsOne != null && userSecurityQuestionsTwo != null) {

        userSecurityQuestionsOne.setUserLogin(userLogin);

        userSecurityQuestionsTwo.setUserLogin(userLogin);

        userSecurityQuestionsValidator.validate(submitAnswers, bindingResult);

        List<UserSecurityQuestions> userSecurityQuestionsFromDB = userService
                .getUserSecurityQuestionsById(userLogin.getUserLoginId());
        List<UserSecurityQuestions> userSecurityQuestionsSubmitted = new ArrayList<UserSecurityQuestions>();
        userSecurityQuestionsSubmitted.add(0, userSecurityQuestionsOne);
        userSecurityQuestionsSubmitted.add(1, userSecurityQuestionsTwo);

        if (!bindingResult.hasErrors() && validateUserSecurityQuestions(userSecurityQuestionsSubmitted,
                userSecurityQuestionsFromDB, bindingResult)) {

            success = true;

            if (session.getAttribute(FORGOTPASSWORD) != null) {

                modelMap.addAttribute(USER_LOGIN, userLogin);

                String userOldPassword = userLogin.getPassword();

                // Change user password.
                String newPassword = userService.resetPassword(userLogin);

                try {
                    setMailProprties(userLogin, newPassword,
                            PropertyReader.getPropertyValue(EMAIL_PROPERTIES, FORGOT_PASSWORD_SUBJECT),
                            PropertyReader.getPropertyValue(EMAIL_PROPERTIES, NEW_PASSWORD_TO_USER));

                    // Add the message to Model to pass a value.
                    modelMap.addAttribute(MESSAGE, AkuraWebConstant.PASSWORD_CHANGE_SUCCESSFUL_MESSAGE);

                } catch (MailException e) {
                    resetUserPassword(userLogin, userOldPassword);
                    modelMap.addAttribute(MESSAGE, null);

                    if (e instanceof MailAuthenticationException) {

                        mailError = new ErrorMsgLoader()
                                .getErrorMessage(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR);
                        LOG.error(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR, e);

                    } else if (e instanceof MailSendException) {

                        mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
                        LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);

                    }

                } catch (AkuraAppException e) {
                    resetUserPassword(userLogin, userOldPassword);
                    mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
                    LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
                } finally {
                    session.removeAttribute(FORGOTPASSWORD);
                    modelMap.addAttribute(MAIL_ERRORS, mailError);

                }
                userLogin.setUsername(null);
                return FORGOT_PASSWORD_SUCCESS_OR_ERROR;

            }
        }

        if (bindingResult.hasErrors()) {
            return GET_USER_ANSWERS;
        }

    }

    if (success) {

        submitPasswordData(modelMap);

        return GET_USER_PASSWORD;
    }
    return GET_USER_ANSWERS;

}

From source file:com.exedio.cope.live.Bar.java

void doRequest(final HttpServletRequest request, final HttpSession httpSession,
        final HttpServletResponse response, final Anchor anchor) throws IOException {
    if (!Cop.isPost(request)) {
        try {//from w w  w .jav a2 s  .  co  m
            startTransaction("redirectHome");
            anchor.redirectHome(request, response);
            model.commit();
        } finally {
            model.rollbackIfNotCommitted();
        }
        return;
    }

    final String referer;

    if (isMultipartContent(request)) {
        final HashMap<String, String> fields = new HashMap<String, String>();
        final HashMap<String, FileItem> files = new HashMap<String, FileItem>();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(UTF_8.name());
        try {
            for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString(UTF_8.name()));
                else
                    files.put(item.getFieldName(), item);
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException(e);
        }

        final String featureID = fields.get(FEATURE);
        if (featureID == null)
            throw new NullPointerException();

        final Media feature = (Media) model.getFeature(featureID);
        if (feature == null)
            throw new NullPointerException(featureID);

        final String itemID = fields.get(ITEM);
        if (itemID == null)
            throw new NullPointerException();

        final FileItem file = files.get(FILE);

        try {
            startTransaction("publishFile(" + featureID + ',' + itemID + ')');

            final Item item = model.getItem(itemID);

            if (fields.get(PUBLISH_NOW) != null) {
                for (final History history : History.getHistories(item.getCopeType())) {
                    final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false);
                    event.createFeature(feature, feature.getName(),
                            feature.isNull(item) ? null
                                    : ("file type=" + feature.getContentType(item) + " size="
                                            + feature.getLength(item)),
                            "file name=" + file.getName() + " type=" + file.getContentType() + " size="
                                    + file.getSize());
                }

                // TODO use more efficient setter with File or byte[]
                feature.set(item, file.getInputStream(), file.getContentType());
            } else {
                anchor.modify(file, feature, item);
            }

            model.commit();
        } catch (final NoSuchIDException e) {
            throw new RuntimeException(e);
        } finally {
            model.rollbackIfNotCommitted();
        }

        referer = fields.get(REFERER);
    } else // isMultipartContent
    {
        if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) {
            anchor.borders = true;
        } else if (request.getParameter(BORDERS_OFF) != null
                || request.getParameter(BORDERS_OFF_IMAGE) != null) {
            anchor.borders = false;
        } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) {
            httpSession.removeAttribute(LoginServlet.ANCHOR);
        } else if (request.getParameter(SWITCH_TARGET) != null) {
            anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET)));
        } else if (request.getParameter(SAVE_TARGET) != null) {
            try {
                startTransaction("saveTarget");
                anchor.getTarget().save(anchor);
                model.commit();
            } finally {
                model.rollbackIfNotCommitted();
            }
            anchor.notifyPublishedAll();
        } else {
            final String featureID = request.getParameter(FEATURE);
            if (featureID == null)
                throw new NullPointerException();

            final Feature featureO = model.getFeature(featureID);
            if (featureO == null)
                throw new NullPointerException(featureID);

            final String itemID = request.getParameter(ITEM);
            if (itemID == null)
                throw new NullPointerException();

            if (featureO instanceof StringField) {
                final StringField feature = (StringField) featureO;
                final String value = request.getParameter(TEXT);

                try {
                    startTransaction("barText(" + featureID + ',' + itemID + ')');

                    final Item item = model.getItem(itemID);

                    if (request.getParameter(PUBLISH_NOW) != null) {
                        String v = value;
                        if ("".equals(v))
                            v = null;
                        for (final History history : History.getHistories(item.getCopeType())) {
                            final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(),
                                    false);
                            event.createFeature(feature, feature.getName(), feature.get(item), v);
                        }
                        feature.set(item, v);
                        anchor.notifyPublished(feature, item);
                    } else {
                        anchor.modify(value, feature, item);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            } else {
                final IntegerField feature = (IntegerField) featureO;
                final String itemIDFrom = request.getParameter(ITEM_FROM);
                if (itemIDFrom == null)
                    throw new NullPointerException();

                try {
                    startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')');

                    final Item itemFrom = model.getItem(itemIDFrom);
                    final Item itemTo = model.getItem(itemID);

                    final Integer positionFrom = feature.get(itemFrom);
                    final Integer positionTo = feature.get(itemTo);
                    feature.set(itemFrom, feature.getMinimum());
                    feature.set(itemTo, positionFrom);
                    feature.set(itemFrom, positionTo);

                    for (final History history : History.getHistories(itemFrom.getCopeType())) {
                        final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionFrom, positionTo);
                    }
                    for (final History history : History.getHistories(itemTo.getCopeType())) {
                        final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionTo, positionFrom);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            }
        }

        referer = request.getParameter(REFERER);
    }

    if (referer != null)
        response.sendRedirect(response.encodeRedirectURL(referer));
}

From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java

protected void doRequestUserQuestions(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, Exception {

    logger.info("doRequestUserQuestions");

    try {/*from w  w  w  . jav  a 2 s. c  o m*/
        HttpSession session = req.getSession(false);
        if (session == null) {
            logger.debug("null session");
            // this shouldn't happen, make the user start over
            resp.sendRedirect("./jsp/loggedOut.jsp");
            return;
        }

        String username = req.getParameter("userid");
        if (username != null) {
            username = username.toUpperCase();
        }
        logger.debug("username " + username);
        //begin - CADSRPASSW-73
        String status = "";
        try {
            logger.info("doRequestUserQuestions: checking account status ...");
            status = doValidateAccountStatus(username, session, req, resp, Constants.ASK_USERID_URL);
            logger.debug("doRequestUserQuestions: account status check done");
        } catch (Exception e1) {
            logger.debug("doRequestUserQuestions: account status was: [" + status + "]");
            if (status != null && status.equals("")) {
                session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE,
                        Messages.getString("PasswordChangeHelper.101"));
                resp.sendRedirect(Constants.ASK_USERID_URL);
                return;
            } else {
                logger.debug("doRequestUserQuestions: account status check error was: " + e1.getMessage());
                e1.printStackTrace();
            }
        }
        //end - CADSRPASSW-73
        if (status.indexOf(Constants.LOCKED_STATUS) > -1) {
            logger.debug("doRequestUserQuestions:status [" + status + "] returning without doing anything ...");
            return;
        }

        connect();
        PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource);
        try {
            if (!userDAO.checkValidUser(username)) {
                session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE,
                        Messages.getString("PasswordChangeHelper.101"));
                resp.sendRedirect(Constants.ASK_USERID_URL);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            disconnect();
        }

        // Security enhancement
        Map<String, String> userQuestions = new HashMap<String, String>();
        Map<String, String> userAnswers = new HashMap<String, String>();

        //pull all questions related to this user
        loadUserStoredQna(username, userQuestions, userAnswers);

        //TBD - retrieve all questions related to the users from dao and set them into sessions
        session.setAttribute(Constants.USERNAME, username);
        session.removeAttribute(Constants.Q1);
        session.setAttribute(Constants.Q1, userQuestions.get(Constants.Q1));
        session.removeAttribute(Constants.Q2);
        session.setAttribute(Constants.Q2, userQuestions.get(Constants.Q2));
        session.removeAttribute(Constants.Q3);
        session.setAttribute(Constants.Q3, userQuestions.get(Constants.Q3));

        session.removeAttribute(Constants.ALL_QUESTIONS);
        logger.debug("questions removed from session.");
        session.setAttribute(Constants.ALL_QUESTIONS, userQuestions);
        logger.debug("questions saved in session.");
        session.removeAttribute(Constants.ALL_ANSWERS);
        logger.debug("answers removed from session.");
        session.setAttribute(Constants.ALL_ANSWERS, userAnswers);
        logger.debug("answers saved in session.");

        if (userQuestions == null || userQuestions.size() == 0) {
            logger.info("no security question found");
            session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE,
                    Messages.getString("PasswordChangeHelper.140"));
            resp.sendRedirect(Constants.ASK_USERID_URL);
            return;
        }

        if (doValidateAttemptedCount(session, resp, Constants.ASK_USERID_URL) == false) {
            return;
        }

        //resp.sendRedirect(Constants.Q1_URL);
        req.getRequestDispatcher("./jsp/askQuestion1.jsp").forward(req, resp);
    } catch (Throwable theException) {
        logger.error(theException);
    }
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * request has grouping alg params like disable move types and # of groups.
 * session is used mainly to put status messages and legacy param
 * unifiedGroupsAlg./*from w w  w.ja va2s  . c  o  m*/
 */
public static GroupAssigner doGroups(HttpServletRequest request, HttpSession session,
        Collection<EmailDocument> allDocs, AddressBook addressBook) throws JSONException {
    try {
        GroupAssigner ga;

        GroupAlgorithmStats<String> groupAlgorithmStats = null;

        // session.setAttribute("statusProvider", new StaticStatusProvider("Finding groups...<br/>&nbsp;"));
        int minFreq = Util.getMinFreq(allDocs.size(), 0.5f);
        groupAlgorithmStats = new GroupAlgorithmStats<String>();

        // check which groups alg to run
        boolean unifiedGroupsAlg = true;
        if ("false".equals(getSessionAttribute(session, "unifiedGroupsAlg")))
            unifiedGroupsAlg = false;

        int DEFAULT_NUM_GROUPS = 20;
        int nGroups = HTMLUtils.getIntParam(request, "numGroups", DEFAULT_NUM_GROUPS);
        GroupHierarchy<String> hierarchy = null;
        ga = new GroupAssigner();
        if (unifiedGroupsAlg) {
            Grouper<String> grouper = new Grouper<String>();
            session.setAttribute("statusProvider", grouper);
            if (request.getParameter("disableMergeMove") != null)
                grouper.setDisableMergeMove(true);
            if (request.getParameter("disableIntersectMove") != null)
                grouper.setDisableIntersectMove(true);
            if (request.getParameter("disableDominateMove") != null)
                grouper.setDisableDominateMove(true);
            if (request.getParameter("disableDropMove") != null)
                grouper.setDisableDropMove(true);

            // we'll ignore the one-sies
            int threshold = 1;
            Set<Contact> contactsToIgnore = GroupUtils.contactsAtOrBelowThreshold(addressBook, allDocs,
                    threshold);
            log.info(contactsToIgnore.size() + " contacts will be ignored because they are below threshold of "
                    + threshold);
            Map<Group<String>, Float> weightedInputMap = GroupUtils.convertEmailsToGroupsWeighted(addressBook,
                    allDocs, contactsToIgnore);
            List<Pair<Group<String>, Float>> weightedInputList = Util.mapToListOfPairs(weightedInputMap);
            Util.sortPairsBySecondElement(weightedInputList);

            Map<String, Float> individualElementsValueMap = GroupUtils.getScoreForContacts(addressBook, allDocs,
                    contactsToIgnore);
            individualElementsValueMap = Util.reorderMapByValue(individualElementsValueMap);
            try {
                grouper.setAffinityMap(GroupUtils.computeAffinityMap(addressBook.allContacts()));
                grouper.setIndividualElementsValueMap(individualElementsValueMap);
            } catch (Throwable t) {
                log.warn("Exception trying to compute grouper affinity map " + t);
                Util.print_exception(t, log);
            }

            float errWeight = HTMLUtils.getFloatParam(request, "errWeight", 0.4f);
            hierarchy = grouper.findGroupsWeighted(weightedInputList, nGroups - 1, errWeight); // err weight of 0.4 seems to work well.
            if (hierarchy != null) {
                List<SimilarGroup<String>> selectedGroups = SimilarGroupMethods.topGroups(hierarchy,
                        nGroups - 1);
                ga.setupGroups(allDocs, selectedGroups, addressBook, 0);
                // DON'T put grouper in session, it points to things like GrouperStats that are not serializable
                //    session.setAttribute("grouper", grouper);
            } else {
                log.error("Grouping failed, not setting groups of groupsAssigner");
            }
            session.removeAttribute("statusProvider");
        } else {
            // old groups algorithm in IUI-2011 "Groups without tears" paper, not used or maintained any more...
            List<Group<String>> input = GroupUtils.convertEmailsToGroups(addressBook, allDocs);

            hierarchy = SimilarGroupMethods.findContactGroupsIUI(input, minFreq, 2, 1.0f, 0.35f, "linear", 1.4f,
                    groupAlgorithmStats);
            if (hierarchy != null) {
                List<SimilarGroup<String>> selectedGroups = SimilarGroupMethods.topGroups(hierarchy, 15);
                ga.setupGroups(allDocs, selectedGroups, addressBook, 5);
            } else {
                log.error("Grouping failed, not setting groups of groupsAssigner");
            }
        }

        if (hierarchy != null) {
            //Map<SimilarGroup<String>, List<SimilarGroup<String>>> parentToChildGroupMap = hierarchy.parentToChildrenMap;
            List<SimilarGroup<String>> rootGroups = new ArrayList<SimilarGroup<String>>();
            rootGroups.addAll(hierarchy.rootGroups);
            GroupUtils.sortByMass(allDocs, addressBook, rootGroups);
        }

        return ga;
    } catch (Exception e) {
        log.warn("Grouper failed!");
        Util.print_exception(e, log);
        // return with our tail between our legs.... but better than crashing.
    }
    return null;
}