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:org.kmnet.com.fw.web.token.transaction.HttpSessionTransactionTokenStore.java

/**
 * Creates a new Token key and reserve it in the HttpSession<br>
 * removes oldeset token if token size is greater than or equals {@link #transactionTokensPerTokenName} in the same
 * namespace./*  ww  w  . ja  v  a  2 s.c o  m*/
 * @see org.kmnet.com.fw.web.token.transaction.TransactionTokenStore#createAndReserveTokenKey(java.lang.String)
 */
@Override
public String createAndReserveTokenKey(String tokenName) {
    String tokenNamePrefix = TOKEN_HOLDER_SESSION_ATTRIBUTE_PREFIX + tokenName;
    Set<String> sessionAttributeNames = new HashSet<String>();
    HttpSession session = getSession();
    Object mutex = getMutex(session);
    String tokenKey = null;
    synchronized (mutex) {
        Enumeration<String> tokenNameEnumeration = session.getAttributeNames();
        while (tokenNameEnumeration.hasMoreElements()) {
            String name = tokenNameEnumeration.nextElement();
            // fetch the sessionKeyPrefix (session key with only Token prefix and namespace name) and compare
            if (tokenNamePrefix.equals(name.split(TransactionToken.TOKEN_STRING_SEPARATOR)[0])) {
                sessionAttributeNames.add(name);
            }
        }

        for (int i = 0, max = sessionAttributeNames.size(); i < max; i++) {
            // do not use while loop to avoid infinite loop
            if (sessionAttributeNames.size() >= transactionTokensPerTokenName) {
                String oldestTokenName = null;
                TokenHolder oldestTokenHolder = new TokenHolder(null, Long.MAX_VALUE);
                for (String name : sessionAttributeNames) {
                    TokenHolder tokenHolder = (TokenHolder) session.getAttribute(name);
                    if (tokenHolder.getTimestamp() < oldestTokenHolder.getTimestamp()) {
                        oldestTokenName = name;
                        oldestTokenHolder = tokenHolder;
                    }
                }
                session.removeAttribute(oldestTokenName);
                sessionAttributeNames.remove(oldestTokenName);
            } else {
                break;
            }
        }

        for (int i = 0; i < retryCreateTokenName; i++) {
            String str = generator.generate(session.getId());
            String name = tokenNamePrefix + TransactionToken.TOKEN_STRING_SEPARATOR + str;
            if (!sessionAttributeNames.contains(name)) {
                tokenKey = str;
                break;
            }
        }
    }
    if (tokenKey == null) {
        throw new IllegalStateException(
                "token key generation failed within retry count " + retryCreateTokenName);
    }

    return tokenKey;
}

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

@RequestMapping(value = "/Orgcambiarcontra", method = RequestMethod.GET)
public ModelAndView Orgcambiarcontra_GET(ModelMap map, HttpSession session) {
    Entidad usuario = (Entidad) session.getAttribute("usuario");
    String mensaje = "";
    if (usuario == null) {
        mensaje = "La sesin ha finalizado. Favor identificarse nuevamente";
        map.addAttribute("mensaje", mensaje);
        return new ModelAndView("login", map);
    }/* w ww. jav a2 s .  c  om*/
    if (session.getAttribute("oldpass") != null && session.getAttribute("newpass") != null
            && session.getAttribute("newpassconf") != null) {
        String oldpass = (String) session.getAttribute("oldpass");
        String newpass = (String) session.getAttribute("newpass");
        String newpassconf = (String) session.getAttribute("newpassconf");

        oldpass = DigestUtils.sha512Hex(oldpass);
        if (usuario.getPass().equals(oldpass)) {
            if (newpass.equals(newpassconf)) {
                newpass = DigestUtils.sha512Hex(newpass);
                usuario.setPass(newpass);
                ServicioOrganismo.CambiaPass(usuario);
                mensaje = "La contrasea se ha cambiado con exito.";
            } else {
                mensaje = "Las contraseas no coinciden. Favor de reescribir la nueva contrasea.";
            }
        } else {
            mensaje = "Contrasea de usuario incorrecta. Ingrese nuevamente.";
        }

        String pagina = "/Entidad/contra_ent";
        map.addAttribute("mensaje", mensaje);

        session.removeAttribute("oldpass");
        session.removeAttribute("newpass");
        session.removeAttribute("newpassconf");

        return new ModelAndView(pagina, map);
    } else {
        return new ModelAndView("/Entidad/inicio_ent", map);

    }

}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.TaskDetailHandler.java

/**
 * Invokes this PageHandler/*from w  w  w  .  j a  v  a 2 s .com*/
 * 
 * @param p_thePageDescriptor
 *            the page desciptor
 * @param p_theRequest
 *            the original request sent from the browser
 * @param p_theResponse
 *            the original response object
 * @param p_context
 *            context the Servlet context
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, EnvoyServletException {
    HttpSession httpSession = p_request.getSession();
    // Get user id of the person who has logged in.
    User user = TaskHelper.getUser(httpSession);

    PermissionSet perms = new PermissionSet();
    try {
        perms = Permission.getPermissionManager()
                .getPermissionSetForUser(httpSession.getAttribute(WebAppConstants.USER_NAME).toString());
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }

    httpSession.removeAttribute(WebAppConstants.PERMISSIONS);
    httpSession.setAttribute(WebAppConstants.PERMISSIONS, perms);

    SessionManager sessionMgr = (SessionManager) httpSession.getAttribute(SESSION_MANAGER);

    // Set the task complete delay time for this company
    sessionMgr.setAttribute(SystemConfigParamNames.TASK_COMPLETE_DELAY_TIME, SystemConfiguration.getInstance()
            .getStringParameter(SystemConfigParamNames.TASK_COMPLETE_DELAY_TIME));
    sessionMgr.setAttribute(SystemConfigParamNames.DOWNLOAD_JOB_DELAY_TIME, SystemConfiguration.getInstance()
            .getStringParameter(SystemConfigParamNames.DOWNLOAD_JOB_DELAY_TIME));

    String action = p_request.getParameter(TASK_ACTION);

    if (TASK_ACTION_SAVEDETAILS.equals(action)) {
        saveTaskDetails(p_request, httpSession, user.getUserId());
    } else if (TASK_ACTION_ACCEPT.equals(action)) {
        acceptTask(p_request, httpSession, user.getUserId());

        // set detail page id in session
        TaskHelper.storeObject(httpSession, TASK_DETAILPAGE_ID, TaskHelper.DETAIL_PAGE_2);
    } else if (DTP_DOWNLOAD.equals(action)) {
        dtpDownload(p_request, p_response);
        return;
    } else if (DTP_UPLOAD.equals(action)) {
        dtpUpload(p_request);
    } else if (TASK_ACTION_CREATE_STF.equals(action)) {
        startStfCreationForWorkflow(p_request, httpSession, user.getUserId());
    } else if (TASK_ACTION_RETRIEVE.equals(action)) {
        sessionMgr.removeElement("sourcePageIdList");
        if (!getTask(p_request, httpSession, p_response, p_context, perms, user.getUserId()))
            return;
    }
    // default case action==null but must also handle pagesearch action
    else if (action == null) {
        Task task = null;
        String taskIdParam = p_request.getParameter(TASK_ID);
        String taskStateParam = p_request.getParameter(TASK_STATE);
        if (taskIdParam != null && taskStateParam != null) {
            long taskId = TaskHelper.getLong(taskIdParam);
            int taskState = TaskHelper.getInt(taskStateParam, -10);
            //get task
            task = TaskHelper.getTask(user.getUserId(), taskId, taskState);
            TaskHelper.storeObject(httpSession, TASK, task);
        }

        Locale uiLocale = (Locale) httpSession.getAttribute(UILOCALE);
        // Save the target pages to session - sorted
        List targetPages = task.getTargetPages();

        // store the search text that the pages are filtered by
        p_request.setAttribute(JobManagementHandler.PAGE_SEARCH_PARAM,
                p_request.getParameter(JobManagementHandler.PAGE_SEARCH_PARAM));
        // sorts the pages in the correct order and store the column and
        // sort order
        // also filters them according to the search params
        setPages(p_request, httpSession, targetPages, uiLocale);
    } else if (TASK_ACTION_TRANSLATED_TEXT_RETRIEVE.equals(action)) {
        // for counting translated text issue
        String pageIds = p_request.getParameter(TASK_PAGE_IDS);

        if (pageIds == null || pageIds.length() == 0 || "undefined".equalsIgnoreCase(pageIds)) {
            return;
        }
        String[] pageIdsArray = pageIds.split(",");
        getPercent(p_response, pageIdsArray);

        return;
    } else if (TASK_ACTION_APPROVE_TUV.equals(action)) {
        String pageIds = p_request.getParameter(TASK_PAGE_IDS);
        if (StringUtils.isBlank(pageIds))
            return;

        // for counting translated text issue
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        // Approve TUVs
        String[] trgPageIds = pageIds.split(",");
        for (String trgPageId : trgPageIds) {
            SegmentTuvUtil.approveTuvByTargetPageId(Long.parseLong(trgPageId));
        }
        out.write("1");
        out.close();
        return;
    } else if (TASK_ACTION_DOWNLOAD_SOURCEPAGES.equals(action)) {
        // Get taskId parameter
        String taskIdParam = p_request.getParameter(TASK_ID);
        long taskId = TaskHelper.getLong(taskIdParam);
        Task task = null;
        // get task state (determines from which tab, the task details is
        // requested)
        String taskStateParam = p_request.getParameter(TASK_STATE);
        int taskState = TaskHelper.getInt(taskStateParam, -10);// -10 as
                                                               // default
        try {
            // Get task
            task = TaskHelper.getTask(user.getUserId(), taskId, taskState);
        } catch (Exception e) {
        }
        downloadSourcePages(p_request, p_response, task);
        return;
    } else if (TASK_ACTION_SAVECOMMENT.equals(action)) {
        // Get taskId parameter
        String taskIdParam = p_request.getParameter(TASK_ID);
        long taskId = TaskHelper.getLong(taskIdParam);
        String taskStateParam = p_request.getParameter(TASK_STATE);
        int taskState = TaskHelper.getInt(taskStateParam, -10);

        Task task = TaskHelper.getTask(user.getUserId(), taskId, taskState);
        TaskHelper.storeObject(httpSession, WORK_OBJECT, task);
    } else if (TASK_ACTION_SCORECARD.equals(action)) {
        // Get taskId parameter
        String taskIdParam = p_request.getParameter(TASK_ID);
        long taskId = TaskHelper.getLong(taskIdParam);
        String taskStateParam = p_request.getParameter(TASK_STATE);
        int taskState = TaskHelper.getInt(taskStateParam, -10);
        Task task = TaskHelper.getTask(user.getUserId(), taskId, taskState);

        HashMap<String, Integer> scorecardMap = new HashMap<String, Integer>();
        long companyId = task.getCompanyId();
        ResourceBundle bundle = PageHandler.getBundle(httpSession);
        boolean isScored = isScored(scorecardMap, companyId, task.getWorkflow().getId(), bundle);
        List<Select> scorecardCategories = ScorecardScoreHelper.initSelectList(companyId, bundle);
        String scorecardComment = ((WorkflowImpl) task.getWorkflow()).getScorecardComment();
        sessionMgr.setAttribute("scorecardCategories", scorecardCategories);
        sessionMgr.setAttribute("scorecard", scorecardMap);
        sessionMgr.setAttribute("isScored", isScored);
        if (StringUtil.isEmpty(scorecardComment))
            scorecardComment = "";
        sessionMgr.setAttribute("scorecardComment", scorecardComment);
        TaskHelper.storeObject(httpSession, WORK_OBJECT, task);
        Locale uiLocale = (Locale) httpSession.getAttribute(UILOCALE);
        List targetPages = task.getTargetPages();
        setPages(p_request, httpSession, targetPages, uiLocale);
        getTask(p_request, httpSession, p_response, p_context, perms, user.getUserId());
    } else if (TASK_ACTION_SAVE_SCORECARD.equals(action)) {
        // Get taskId parameter
        String taskIdParam = p_request.getParameter(TASK_ID);
        long taskId = TaskHelper.getLong(taskIdParam);
        String taskStateParam = p_request.getParameter(TASK_STATE);
        int taskState = TaskHelper.getInt(taskStateParam, -10);
        Task task = TaskHelper.getTask(user.getUserId(), taskId, taskState);

        HashMap<String, Integer> scorecardMap = new HashMap<String, Integer>();
        long companyId = task.getCompanyId();
        ResourceBundle bundle = PageHandler.getBundle(httpSession);

        //save
        List<Select> scorecardCategories = ScorecardScoreHelper.initSelectList(companyId, bundle);
        long workflowId = task.getWorkflow().getId();
        long jobId = task.getJobId();
        String userId = (String) httpSession.getAttribute(WebAppConstants.USER_NAME);
        String scorecardComment = p_request.getParameter("scoreComment");

        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        try {
            for (Select select : scorecardCategories) {
                ScorecardScore score = new ScorecardScore();
                score.setScorecardCategory(select.getValue());
                score.setScore(new Integer(p_request.getParameter(select.getValue())));
                score.setWorkflowId(workflowId);
                score.setJobId(jobId);
                score.setCompanyId(companyId);
                score.setModifyUserId(userId);
                score.setIsActive(true);
                HibernateUtil.save(score);
            }

            WorkflowImpl workflowImpl = (WorkflowImpl) task.getWorkflow();
            workflowImpl.setScorecardComment(scorecardComment);
            HibernateUtil.save(workflowImpl);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        }

        boolean isScored = isScored(scorecardMap, companyId, task.getWorkflow().getId(), bundle);
        sessionMgr.setAttribute("scorecardCategories", scorecardCategories);
        sessionMgr.setAttribute("scorecard", scorecardMap);
        sessionMgr.setAttribute("isScored", isScored);
        sessionMgr.setAttribute("scorecardComment", scorecardComment);
    }

    //saveComment

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    Task task = (Task) TaskHelper.retrieveObject(httpSession, WORK_OBJECT);
    if (task != null) {
        sessionMgr.setAttribute(JobManagementHandler.JOB_ID, (new Long(task.getJobId())).toString());
        sessionMgr.setAttribute(WebAppConstants.TASK_ID, (new Long(task.getId())).toString());
    }

    p_request.setAttribute(WebAppConstants.PARAGRAPH_EDITOR, s_isParagraphEditorEnabled ? "true" : "false");

    // Keeps page cache for JavaScript Function.
    isCache = true;
    CommentMainHandler commentMainHandler = new CommentMainHandler();
    commentMainHandler.handleRequest(p_pageDescriptor, p_request, p_response, p_context);

    // Call parent invokePageHandler() to set link beans and invoke JSP
    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:dk.itst.oiosaml.sp.service.SPFilter.java

/**
 * Check whether the user is authenticated i.e. having session with a valid
 * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is sent to
 * the Login Site./*w w  w.  j a  va 2 s.  com*/
 * 
 * @param request
 *            The servletRequest
 * @param response
 *            The servletResponse
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("OIOSAML-J SP Filter invoked");

    if (!(request instanceof HttpServletRequest)) {
        throw new RuntimeException("Not supported operation...");
    }
    HttpServletRequest servletRequest = ((HttpServletRequest) request);
    Audit.init(servletRequest);

    if (!isFilterInitialized()) {
        try {
            Configuration conf = SAMLConfiguration.getSystemConfiguration();
            setRuntimeConfiguration(conf);
        } catch (IllegalStateException e) {
            request.getRequestDispatcher("/saml/configure").forward(request, response);
            return;
        }
    }
    if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) {
        log.warn("Running in debug mode, skipping regular filter");
        develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf);
        return;
    }

    if (cleanerRunning.compareAndSet(false, true)) {
        SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(),
                ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30);
    }

    SessionHandler sessionHandler = sessionHandlerFactory.getHandler();

    if (servletRequest.getServletPath().equals(conf.getProperty(Constants.PROP_SAML_SERVLET))) {
        log.debug("Request to SAML servlet, access granted");
        chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response);
        return;
    }

    final HttpSession session = servletRequest.getSession();
    if (log.isDebugEnabled())
        log.debug("sessionId....:" + session.getId());

    // Is the user logged in?
    if (sessionHandler.isLoggedIn(session.getId())
            && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null) {
        int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel();
        int assuranceLevel = conf.getInt(Constants.PROP_ASSURANCE_LEVEL);
        if (actualAssuranceLevel < assuranceLevel) {
            sessionHandler.logOut(session);
            log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
            throw new RuntimeException(
                    "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
        }
        UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION);
        if (log.isDebugEnabled())
            log.debug("Everything is ok... Assertion: " + ua);

        Audit.log(Operation.ACCESS, servletRequest.getRequestURI());

        try {
            UserAssertionHolder.set(ua);
            HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname);
            chain.doFilter(requestWrap, response);
            return;
        } finally {
            UserAssertionHolder.set(null);
        }
    } else {
        session.removeAttribute(Constants.SESSION_USER_ASSERTION);
        UserAssertionHolder.set(null);

        String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(servletRequest));

        String protocol = conf.getString(Constants.PROP_PROTOCOL, "saml20");
        String loginUrl = conf.getString(Constants.PROP_SAML_SERVLET, "/saml");

        String protocolUrl = conf.getString(Constants.PROP_PROTOCOL + "." + protocol);
        if (protocolUrl == null) {
            throw new RuntimeException(
                    "No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol);
        }
        loginUrl += protocolUrl;
        if (log.isDebugEnabled())
            log.debug("Redirecting to " + protocol + " login handler at " + loginUrl);

        RequestDispatcher dispatch = servletRequest.getRequestDispatcher(loginUrl);
        dispatch.forward(new SAMLHttpServletRequest(servletRequest, hostname, relayState), response);
    }
}

From source file:com.esd.ps.AdministratorController.java

/**
 * ?useremployer?,sessionuser?//from   w  w  w .j a v  a2s .c  o m
 * 
 * @param employerName
 * @param session
 * @return
 */
@RequestMapping(value = "/addinspector", method = RequestMethod.POST)
public ModelAndView addinspector(String inspectorName, HttpSession session, HttpServletRequest request,
        int userRegisted) {
    inspector inspector = new inspector();
    inspector.setInspectorName(inspectorName);
    inspector.setCreateTime(new Date());
    inspector.setUpdateTime(new Date());
    String address = null;
    if (userRegisted == 0) {
        inspector.setUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + "inspector";
    } else if (userRegisted == 1) {
        inspector.setUserId(Integer.parseInt(session.getAttribute(Constants.ADD_USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + "administrator";
    }
    inspector.setCreateId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    inspector.setCreateMethod(items[1].toString());
    inspector.setVersion(1);
    inspectorService.insertSelective(inspector);
    session.removeAttribute(Constants.ADD_USER_ID);
    return new ModelAndView(address);
}

From source file:com.emc.plants.web.servlets.AccountServlet.java

private void performTask(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String action = null;//from  w w  w .ja  v a2s  .  c  om

    action = req.getParameter(Util.ATTR_ACTION);
    Util.debug("action=" + action);

    if (action.equals(ACTION_LOGIN)) {
        try {
            HttpSession session = req.getSession(true);
            String userid = req.getParameter("userid");
            String passwd = req.getParameter("passwd");
            String updating = req.getParameter(Util.ATTR_UPDATING);

            String results = null;
            if (Util.validateString(userid)) {
                results = login.verifyUserAndPassword(userid, passwd);
            } else {
                //user id was invalid, and may contain XSS attack
                results = "\nEmail address was invalid.";
                Util.debug("User id or email address was invalid. id=" + userid);
            }

            // If results have an error msg, return it, otherwise continue.
            if (results != null) {
                // Proliferate UPDATING flag if user is trying to update his account.
                if (updating.equals("true"))
                    req.setAttribute(Util.ATTR_UPDATING, "true");

                req.setAttribute(Util.ATTR_RESULTS, results);
                requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_LOGIN);
            } else {
                // If not logging in for the first time, then clear out the
                // session data for the old user.
                if (session.getAttribute(Util.ATTR_CUSTOMER) != null) {
                    session.removeAttribute(Util.ATTR_CART);
                    session.removeAttribute(Util.ATTR_CART_CONTENTS);
                    session.removeAttribute(Util.ATTR_CHECKOUT);
                    session.removeAttribute(Util.ATTR_ORDERKEY);
                }

                // Store customer userid in HttpSession.
                CustomerInfo customerInfo = login.getCustomerInfo(userid);
                session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);
                Util.debug("updating=" + updating + "=");

                // Was customer trying to edit account information.
                if (updating.equals("true")) {
                    req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customerInfo);

                    requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ACCOUNT);
                } else {
                    // See if user was in the middle of checking out.
                    Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
                    Util.debug("checkingOut=" + checkingOut + "=");
                    if ((checkingOut != null) && (checkingOut.booleanValue())) {
                        Util.debug("must be checking out");
                        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERINFO);
                    } else {
                        Util.debug("must NOT be checking out");
                        String url;
                        String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

                        // Default to plants
                        Util.debug("category : " + category);
                        if ((category == null) || (category.equals("null"))) {
                            url = Util.PAGE_PROMO;
                        } else {
                            url = Util.PAGE_SHOPPING;
                            req.setAttribute(Util.ATTR_INVITEMS,
                                    catalog.getItemsByCategory(Integer.parseInt(category)));
                        }

                        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
                    }
                }
            }
        } catch (ServletException e) {
            e.printStackTrace();
            req.setAttribute(Util.ATTR_RESULTS, "/nException occurred");
            throw e;
        } catch (Exception e) {
            req.setAttribute(Util.ATTR_RESULTS, "/nException occurred");
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    } else if (action.equals(ACTION_REGISTER)) {
        // Register a new user.
        //         try
        //         {
        String url;
        HttpSession session = req.getSession(true);

        String userid = req.getParameter("userid");
        String password = req.getParameter("passwd");
        String cpassword = req.getParameter("vpasswd");
        String firstName = req.getParameter("fname");
        String lastName = req.getParameter("lname");
        String addr1 = req.getParameter("addr1");
        String addr2 = req.getParameter("addr2");
        String addrCity = req.getParameter("city");
        String addrState = req.getParameter("state");
        String addrZip = req.getParameter("zip");
        String phone = req.getParameter("phone");

        //validate all user input
        //This could be done more eloquently using a framework such as Struts...
        if (!Util.validateString(userid)) {
            req.setAttribute(Util.ATTR_RESULTS, "Email address contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(firstName)) {
            req.setAttribute(Util.ATTR_RESULTS, "First Name contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(lastName)) {
            req.setAttribute(Util.ATTR_RESULTS, "Last Name contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addr1)) {
            req.setAttribute(Util.ATTR_RESULTS, "Address Line 1 contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addr2)) {
            req.setAttribute(Util.ATTR_RESULTS, "Address Line 2 contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrCity)) {
            req.setAttribute(Util.ATTR_RESULTS, "City contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrState)) {
            req.setAttribute(Util.ATTR_RESULTS, "State contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrZip)) {
            req.setAttribute(Util.ATTR_RESULTS, "Zip contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(phone)) {
            req.setAttribute(Util.ATTR_RESULTS, "Phone Number contains invalid characters.");
            url = Util.PAGE_REGISTER;
        }
        // Make sure passwords match.
        else if (!password.equals(cpassword)) {
            req.setAttribute(Util.ATTR_RESULTS, "Passwords do not match.");
            url = Util.PAGE_REGISTER;
        } else {
            // Create the new user.
            CustomerInfo customerInfo = login.createNewUser(userid, password, firstName, lastName, addr1, addr2,
                    addrCity, addrState, addrZip, phone);

            if (customerInfo != null) {
                // Store customer info in HttpSession.
                session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);

                // See if user was in the middle of checking out.
                Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
                if ((checkingOut != null) && (checkingOut.booleanValue())) {
                    url = Util.PAGE_ORDERINFO;
                } else {
                    String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

                    // Default to plants
                    if (category == null) {
                        url = Util.PAGE_PROMO;
                    } else {
                        url = Util.PAGE_SHOPPING;
                        req.setAttribute(Util.ATTR_INVITEMS,
                                catalog.getItemsByCategory(Integer.parseInt(category)));
                    }
                }
            } else {
                url = Util.PAGE_REGISTER;
                req.setAttribute(Util.ATTR_RESULTS, "New user NOT created!");
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
        //         }
        //         catch (CreateException e) { }
    } else if (action.equals(ACTION_ACCOUNT)) {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        if (customerInfo == null) {
            url = Util.PAGE_LOGIN;
            req.setAttribute(Util.ATTR_UPDATING, "true");
            req.setAttribute(Util.ATTR_RESULTS, "\nYou must login first.");
        } else {
            url = Util.PAGE_ACCOUNT;
            req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customerInfo);
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
    } else if (action.equals(ACTION_ACCOUNTUPDATE)) {
        //         try
        //         {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);

        String userid = customerInfo.getCustomerID();
        String firstName = req.getParameter("fname");
        String lastName = req.getParameter("lname");
        String addr1 = req.getParameter("addr1");
        String addr2 = req.getParameter("addr2");
        String addrCity = req.getParameter("city");
        String addrState = req.getParameter("state");
        String addrZip = req.getParameter("zip");
        String phone = req.getParameter("phone");

        // Create the new user.
        customerInfo = login.updateUser(userid, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip,
                phone);
        // Store updated customer info in HttpSession.
        session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);

        // See if user was in the middle of checking out.
        Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
        if ((checkingOut != null) && (checkingOut.booleanValue())) {
            url = Util.PAGE_ORDERINFO;
        } else {
            String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

            // Default to plants
            if (category == null) {
                url = Util.PAGE_PROMO;
            } else {
                url = Util.PAGE_SHOPPING;
                req.setAttribute(Util.ATTR_INVITEMS, catalog.getItemsByCategory(Integer.parseInt(category)));
            }
        }

        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
        //         }
        //         catch (CreateException e) { }
    } else if (action.equals(ACTION_SETLOGGING)) {
        String debugSetting = req.getParameter("logging");
        if ((debugSetting == null) || (!debugSetting.equals("debug")))
            Util.setDebug(false);
        else
            Util.setDebug(true);

        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_HELP);
    }
}

From source file:com.esd.ps.AdministratorController.java

/**
 * ?usermangager?,sessionuser?/*from  w  ww  . j  a va2s  .c o  m*/
 * 
 * @param managerName
 * @param session
 * @return
 */
@RequestMapping(value = "/addmanager", method = RequestMethod.POST)
public ModelAndView addmanager(String managerName, HttpSession session, HttpServletRequest request,
        int userRegisted) {
    manager manager = new manager();
    manager.setManagerName(managerName);
    manager.setCreateTime(new Date());
    // int login =
    // Integer.parseInt(request.getAttribute("login").toString());
    String address = null;
    if (userRegisted == 0) {
        manager.setUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + Constants.MANAGER;
    } else if (userRegisted == 1) {
        manager.setUserId(Integer.parseInt(session.getAttribute(Constants.ADD_USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + "administrator";
    }
    manager.setCreateId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    manager.setCreateMethod(items[1].toString());
    manager.setVersion(1);
    managerService.insertSelective(manager);
    session.removeAttribute(Constants.ADD_USER_ID);
    return new ModelAndView(address);
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //unlock all forms locked by this session
    HttpSession session = request.getSession();
    String logTjsp = getServletConfig().getInitParameter("LogthroughJSP");
    if (logTjsp != null && !logTjsp.equals(""))
        LOGTHROUGH_JSP = logTjsp;//from   w w  w.ja  va 2s .  c  o  m

    String lojsp = getServletConfig().getInitParameter("LogoutJSP");
    if (lojsp != null && !lojsp.equals(""))
        LOGOUT_JSP = lojsp;
    String authjsp = getServletConfig().getInitParameter("ErrorJSP");
    if (authjsp != null && !authjsp.equals(""))
        AUTHORIZATION_ERROR_JSP = authjsp;

    if (!request.getContextPath().contains("CDEBrowser")) {
        getApplicationServiceLocator(session.getServletContext()).findLockingService()
                .unlockFormByUser(request.getRemoteUser());
    }
    synchronized (SessionUtils.sessionObjectCache) {
        log.error("LogoutServlet.doPost at start:" + TimeUtils.getEasternTime());
        String error = request.getParameter("authorizationError");
        String forwardUrl;
        //// GF29128 Begin. D.An, 20130729. 
        String un = (String) session.getAttribute("myUsername");
        ;
        ////   if (un == null)
        ////      un = "viewer";
        System.out.println("logoutServlet: " + session.getAttribute("myUsername"));
        if (error == null) {
            if (un.equals("viewer"))
                forwardUrl = LOGTHROUGH_JSP;
            //// GF29128  end.      
            else
                forwardUrl = LOGOUT_JSP;
        } else {
            forwardUrl = AUTHORIZATION_ERROR_JSP;
        }

        if ((session != null) && isLoggedIn(request)) {
            for (int i = 0; i < logoutKeys.length; i++) {
                session.removeAttribute(logoutKeys[i]);
            }

            //remove formbuilder specific objects
            //TODO has to be moved to an action
            Collection keys = (Collection) session.getAttribute(FormBuilderConstants.CLEAR_SESSION_KEYS);
            if (keys != null) {
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    session.removeAttribute((String) it.next());
                }
            }
            HashMap allMap = new HashMap();
            allMap.put(CaDSRConstants.GLOBAL_SESSION_KEYS, copyAllsessionKeys(session));
            allMap.put(CaDSRConstants.GLOBAL_SESSION_MAP, copyAllsessionObjects(session));
            SessionUtils.addToSessionCache(session.getId(), allMap);
            forwardUrl = forwardUrl + "?" + CaDSRConstants.PREVIOUS_SESSION_ID + "=" + session.getId();
            session.invalidate();
        }

        RequestDispatcher dispacher = request.getRequestDispatcher(forwardUrl);
        dispacher.forward(request, response);
        log.error("LogoutServlet.doPost at end:" + TimeUtils.getEasternTime());
    }
}

From source file:com.esd.ps.AdministratorController.java

/**
 * ?useremployer?,sessionuser?/*  ww w. j a v  a2s. c o  m*/
 * 
 * @param employerName
 * @param session
 * @return
 */
@RequestMapping(value = "/addemployer", method = RequestMethod.POST)
public ModelAndView addemployer(String employerName, HttpSession session, HttpServletRequest request,
        int userRegisted) {
    employer employer = new employer();
    employer.setEmployerName(employerName);
    employer.setCreateTime(new Date());
    // int login =
    // Integer.parseInt(request.getAttribute("login").toString());
    String address = null;
    if (userRegisted == 0) {
        employer.setUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + Constants.EMPLOYER;
    } else if (userRegisted == 1) {
        employer.setUserId(Integer.parseInt(session.getAttribute(Constants.ADD_USER_ID).toString()));
        address = Constants.REDIRECT + Constants.COLON + "administrator";
    }
    employer.setCreateId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    employer.setCreateMethod(items[1].toString());
    employer.setVersion(1);
    employerService.insertSelective(employer);
    session.removeAttribute(Constants.ADD_USER_ID);
    return new ModelAndView(address);
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void finalizeAuthBean(Object bean, HttpSession session) {
    executePreDestroy(bean);/*from ww  w .j a va 2s.  c o  m*/
    AuthBean authBean = bean.getClass().getAnnotation(AuthBean.class);
    session.removeAttribute(HELPER.getClassName(authBean, bean.getClass()));
}