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:fr.paris.lutece.plugins.directory.web.DirectoryJspBean.java

/**
 * Return management of directory record ( list of directory record )
 * @param request The Http request/*from ww  w .  j a  va 2s.c  o  m*/
 * @throws AccessDeniedException the {@link AccessDeniedException}
 * @return Html directory
 */
public String getCreateDirectoryRecord(HttpServletRequest request) throws AccessDeniedException {
    String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY);
    int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory);
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin());

    if ((directory == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE, strIdDirectory,
            DirectoryResourceIdService.PERMISSION_CREATE_RECORD, getUser())) {
        throw new AccessDeniedException(MESSAGE_ACCESS_DENIED);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    /**
     * Map of <idEntry, RecordFields>
     * 1) The user has uploaded/deleted a file
     * - The updated map is stored in the session
     * 2) The user has not uploaded/delete a file
     * - The map is filled with the data from the database
     * - The asynchronous uploaded files map is reinitialized
     */
    Map<String, List<RecordField>> map = null;

    // Get the map of <idEntry, RecordFields from session if it exists : 
    /**
     * 1) Case when the user has uploaded a file, the the map is stored in
     * the session
     */
    HttpSession session = request.getSession(false);

    if (session != null) {
        map = (Map<String, List<RecordField>>) session
                .getAttribute(DirectoryUtils.SESSION_DIRECTORY_LIST_SUBMITTED_RECORD_FIELDS);

        if (map != null) {
            model.put(MARK_MAP_ID_ENTRY_LIST_RECORD_FIELD, map);
            // IMPORTANT : Remove the map from the session
            session.removeAttribute(DirectoryUtils.SESSION_DIRECTORY_LIST_SUBMITTED_RECORD_FIELDS);
        }
    }

    // Get the map <idEntry, RecordFields> classically from the database
    /** 2) The user has not uploaded/delete a file */
    if (map == null) {
        // Remove asynchronous uploaded file from session
        DirectoryAsynchronousUploadHandler.getHandler().removeSessionFiles(request.getSession().getId());
    }

    List<IEntry> listEntry = DirectoryUtils.getFormEntries(nIdDirectory, getPlugin(), getUser());
    model.put(MARK_ENTRY_LIST, listEntry);

    if (SecurityService.isAuthenticationEnable()) {
        model.put(MARK_ROLE_REF_LIST, RoleHome.getRolesList());
    }

    model.put(MARK_DIRECTORY, directory);
    model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));
    model.put(MARK_LOCALE, getLocale());
    setPageTitleProperty(PROPERTY_CREATE_DIRECTORY_RECORD_PAGE_TITLE);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_CREATE_DIRECTORY_RECORD, getLocale(),
            model);

    return getAdminPage(template.getHtml());
}

From source file:com.adito.security.DefaultLogonController.java

public void initialiseSession(HttpSession session, User user) throws UserDatabaseException {
    if (log.isInfoEnabled())
        log.info("Initialising session " + session.getId() + " with user "
                + (user == null ? "[none]" : user.getPrincipalName()));
    PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
    session.setAttribute(Constants.USER, user);
    String logonInfo = MessageResources.getMessageResources("com.adito.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {//from   w w  w.  j  a v a  2 s. c  o m
        List profiles = ResourceUtil.filterResources(user, ProfilesFactory.getInstance()
                .getPropertyProfiles(user.getPrincipalName(), true, user.getRealm().getResourceId()), true);
        session.setAttribute(Constants.PROFILES, profiles);
        if (profiles.size() == 0) {
            throw new UserDatabaseException("You do not have permission to use any profiles.");
        }
        String startupProfile = Property.getProperty(new UserAttributeKey(user, User.USER_STARTUP_PROFILE));
        if (profiles.size() < 2) {
            profile = (PropertyProfile) profiles.get(0);
        } else if (!startupProfile.equals(ProfilesListDataSource.SELECT_ON_LOGIN)) {
            int profileId = Integer.parseInt(startupProfile);
            profile = null;
            for (Iterator i = profiles.iterator(); i.hasNext();) {
                PropertyProfile p = (PropertyProfile) i.next();
                if (profileId == p.getResourceId()) {
                    profile = p;
                    break;
                }
            }
            if (profile == null) {
                profile = ProfilesFactory.getInstance().getPropertyProfile(null, "Default",
                        UserDatabaseManager.getInstance().getDefaultUserDatabase().getRealm().getResourceId());
            }
        }
        if (profile != null) {
            if (log.isInfoEnabled())
                log.info("Switching user " + user.getPrincipalName() + " to profile "
                        + profile.getResourceName());
            session.setAttribute(Constants.SELECTED_PROFILE, profile);
        }
    } catch (Exception e) {
        throw new UserDatabaseException("Failed to initialise profiles.", e);
    }
    final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
    session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent evt) {
        }

        public void valueUnbound(HttpSessionBindingEvent evt) {
            if (log.isDebugEnabled())
                log.debug("Session unbound");
            // We should should only log off completely if no other
            // session has
            // the logon ticket
            SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
            if (currentTicketSessionInfo == null
                    || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                if (log.isDebugEnabled())
                    log.debug("Session (" + evt.getSession().getId()
                            + ") unbound is the current session for ticket " + logonTicket
                            + " so a logoff will be performed.");
                logoff(logonTicket);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Session unbound is NOT the current session, ignoring.");
            }
        }
    });
    if (log.isDebugEnabled())
        log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
    session.removeAttribute(Constants.SESSION_LOCKED);

    resetSessionTimeout(user, profile, session);
}

From source file:com.sslexplorer.security.DefaultLogonController.java

public void initialiseSession(HttpSession session, User user) throws UserDatabaseException {
    if (log.isInfoEnabled())
        log.info("Initialising session " + session.getId() + " with user "
                + (user == null ? "[none]" : user.getPrincipalName()));
    PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
    session.setAttribute(Constants.USER, user);
    String logonInfo = MessageResources.getMessageResources("com.sslexplorer.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {//from  ww w .  ja v  a 2s.  c  o  m
        List profiles = ResourceUtil.filterResources(user, ProfilesFactory.getInstance()
                .getPropertyProfiles(user.getPrincipalName(), true, user.getRealm().getResourceId()), true);
        session.setAttribute(Constants.PROFILES, profiles);
        if (profiles.size() == 0) {
            throw new UserDatabaseException("You do not have permission to use any profiles.");
        }
        String startupProfile = Property.getProperty(new UserAttributeKey(user, User.USER_STARTUP_PROFILE));
        if (profiles.size() < 2) {
            profile = (PropertyProfile) profiles.get(0);
        } else if (!startupProfile.equals(ProfilesListDataSource.SELECT_ON_LOGIN)) {
            int profileId = Integer.parseInt(startupProfile);
            profile = null;
            for (Iterator i = profiles.iterator(); i.hasNext();) {
                PropertyProfile p = (PropertyProfile) i.next();
                if (profileId == p.getResourceId()) {
                    profile = p;
                    break;
                }
            }
            if (profile == null) {
                profile = ProfilesFactory.getInstance().getPropertyProfile(null, "Default",
                        UserDatabaseManager.getInstance().getDefaultUserDatabase().getRealm().getResourceId());
            }
        }
        if (profile != null) {
            if (log.isInfoEnabled())
                log.info("Switching user " + user.getPrincipalName() + " to profile "
                        + profile.getResourceName());
            session.setAttribute(Constants.SELECTED_PROFILE, profile);
        }
    } catch (Exception e) {
        throw new UserDatabaseException("Failed to initialise profiles.", e);
    }
    final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
    session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent evt) {
        }

        public void valueUnbound(HttpSessionBindingEvent evt) {
            if (log.isDebugEnabled())
                log.debug("Session unbound");
            // We should should only log off completely if no other
            // session has
            // the logon ticket
            SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
            if (currentTicketSessionInfo == null
                    || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                if (log.isDebugEnabled())
                    log.debug("Session (" + evt.getSession().getId()
                            + ") unbound is the current session for ticket " + logonTicket
                            + " so a logoff will be performed.");
                logoff(logonTicket);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Session unbound is NOT the current session, ignoring.");
            }
        }
    });
    if (log.isDebugEnabled())
        log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
    session.removeAttribute(Constants.SESSION_LOCKED);

    resetSessionTimeout(user, profile, session);
}

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

@RequestMapping("/FfichaGuardar/opc1")
public ModelAndView FfichaGuardarElla(ModelMap map, @RequestParam("nombre_ella") String nombre,
        @RequestParam("apellido_p_ella") String apellido_p, @RequestParam("apellido_m_ella") String apellido_m,
        @RequestParam("edad_ella") String edad, @RequestParam("lugar_nac_ella") String lugar_nac,
        @RequestParam("depa_nac_ella") String depa_nac, @RequestParam("pais_nac_ella") String pais_nac,
        @RequestParam("TipoDoc") String tipo_doc, @RequestParam("n_doc_ella") String n_doc,
        @RequestParam("domicilio") String domicilio, @RequestParam("telefono") String telefono,
        @RequestParam("celular_ella") String celular, @RequestParam("correo_ella") String correo,
        @RequestParam("estCivil") String est_civil, @RequestParam("fechaMatri") String fecha_matri,
        @RequestParam("nivel_inst_ella") String nivel_inst, @RequestParam("culm_nivel_ella") String culm_nivel,
        @RequestParam("prof_ella") String prof, @RequestParam("Trabajador_Depend_ella") String trab_depend,
        @RequestParam(value = "ocup_act_dep_ella", required = false) String ocup_actual,
        @RequestParam(value = "centro_trabajo_ella", required = false) String centro_trabajo,
        @RequestParam(value = "dir_centro_ella", required = false) String dir_centro,
        @RequestParam(value = "tel_centro_ella", required = false) String tel_centro,
        @RequestParam(value = "ingreso_dep_ella", required = false) String ingreso_dep,
        @RequestParam("Trabajador_Indep_ella") String trab_indep,
        @RequestParam(value = "ocup_act_indep_ella", required = false) String ocup_act_indep,
        @RequestParam(value = "ingreso_ind_ella", required = false) String ingreso_ind,
        @RequestParam("seguro_salud_ella") String seguro_salud, @RequestParam("tipo_seguro") String tipo_seguro,
        @RequestParam("seguro_vida_ella") String seguro_vida, @RequestParam("sist_pen_ella") String sist_pen,
        @RequestParam("est_salud_ella") String est_salud, HttpSession session) {
    Familia usuario = (Familia) session.getAttribute("usuario");
    if (usuario == null) {
        String mensaje = "La sesin ha finalizado. Favor identificarse nuevamente";
        map.addAttribute("mensaje", mensaje);
        return new ModelAndView("login", map);
    }/*from   w w w.  j ava  2  s  .  co  m*/
    dateFormat format = new dateFormat();
    Date factual = new Date();
    String fechaactual = format.dateToString(factual);
    map.addAttribute("factual", fechaactual);

    FichaSolicitudAdopcion ficha = (FichaSolicitudAdopcion) session.getAttribute("ficha");
    Solicitante sol = new Solicitante();
    for (Iterator iter2 = ficha.getSolicitantes().iterator(); iter2.hasNext();) {
        sol = (Solicitante) iter2.next();
        if (sol.getSexo() == 'F') {
            ficha.getSolicitantes().remove(sol);
            break;
        }
    }
    sol.setNombre(nombre);
    sol.setApellidoP(apellido_p);
    sol.setApellidoM(apellido_m);
    try {
        sol.setEdad(Short.parseShort(edad));
    } catch (Exception ex) {
        String mensaje_edad = "ERROR: El campo Edad contiene parmetros invlidos";
        map.addAttribute("mensaje_edad", mensaje_edad);
    }
    sol.setLugarNac(lugar_nac);
    sol.setDepaNac(depa_nac);
    sol.setPaisNac(pais_nac);
    try {
        sol.setTipoDoc(tipo_doc.charAt(0));
    } catch (Exception ex) {

    }
    sol.setNDoc(n_doc);
    ficha.setDomicilio(domicilio);
    ficha.setFijo(telefono);
    sol.setCelular(celular);
    sol.setCorreo(correo);
    try {
        ficha.setEstadoCivil(est_civil);
    } catch (Exception ex) {

    }
    Date tempfecha = ficha.getFechaMatrimonio();
    if (fecha_matri.contains("ene") || fecha_matri.contains("feb") || fecha_matri.contains("mar")
            || fecha_matri.contains("abr") || fecha_matri.contains("may") || fecha_matri.contains("jun")
            || fecha_matri.contains("jul") || fecha_matri.contains("ago") || fecha_matri.contains("set")
            || fecha_matri.contains("oct") || fecha_matri.contains("nov") || fecha_matri.contains("dic")) {
        ficha.setFechaMatrimonio(tempfecha);
    } else {
        ficha.setFechaMatrimonio(format.stringToDate(fecha_matri));
    }
    sol.setNivelInstruccion(nivel_inst);
    sol.setCulminoNivel(Short.valueOf(culm_nivel));
    sol.setProfesion(prof);
    sol.setTrabajadorDepend(Short.valueOf(trab_depend));
    sol.setOcupActualDep(ocup_actual);
    sol.setCentroTrabajo(centro_trabajo);
    sol.setDireccionCentro(dir_centro);
    sol.setTelefonoCentro(tel_centro);
    try {
        sol.setIngresoDep(Long.valueOf(ingreso_dep));
    } catch (Exception ex) {
        if (ingreso_dep != null) {
            String mensaje_ingreso_dep = "ERROR: La informacin contenida en este campo contiene parmetros invlidos";
            map.addAttribute("mensaje_ing_dep", mensaje_ingreso_dep);
        }
    }
    sol.setTrabajadorIndepend(Short.valueOf(trab_indep));
    sol.setOcupActualInd(ocup_act_indep);
    try {
        sol.setIngresoIndep(Long.valueOf(ingreso_ind));
    } catch (Exception ex) {
        if (ingreso_ind != null) {
            String mensaje_ingreso_indep = "ERROR: La informacin contenida en este campo contiene parmetros invlidos";
            map.addAttribute("mensaje_ing_indep", mensaje_ingreso_indep);
        }
    }
    sol.setSeguroSalud(Short.valueOf(seguro_salud));
    sol.setTipoSeguro(tipo_seguro);
    sol.setSeguroVida(Short.valueOf(seguro_vida));
    sol.setSistPensiones(Short.valueOf(sist_pen));
    sol.setSaludActual(est_salud);
    ficha.getSolicitantes().add(sol);
    session.removeAttribute("ficha");
    session.setAttribute("ficha", ficha);

    map.put("sol", sol);
    String fechanac = format.dateToString(sol.getFechaNac());
    map.addAttribute("fechanac", fechanac);
    map.addAttribute("estCivil", est_civil.charAt(0));
    map.addAttribute("fechaMatri", format.dateToString(ficha.getFechaMatrimonio()));
    map.addAttribute("estCivil", ficha.getEstadoCivil().charAt(0));
    map.addAttribute("domicilio", ficha.getDomicilio());
    map.addAttribute("fijo", ficha.getFijo());

    String pagina = "/Familia/Ficha/ficha_inscripcion_ella";
    return new ModelAndView(pagina, map);
}

From source file:com.liferay.portlet.login.action.CreateAccountAction.java

protected void addUser(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpSession session = request.getSession();

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Company company = themeDisplay.getCompany();

    boolean autoPassword = true;
    String password1 = null;// w  w  w.j a  va  2s  .c o  m
    String password2 = null;
    boolean autoScreenName = false;
    String screenName = ParamUtil.getString(actionRequest, "emailAddress");
    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
    String openId = ParamUtil.getString(actionRequest, "openId");
    String firstName = ParamUtil.getString(actionRequest, "firstName");
    String middleName = ParamUtil.getString(actionRequest, "middleName");
    String lastName = ParamUtil.getString(actionRequest, "lastName");
    int prefixId = ParamUtil.getInteger(actionRequest, "prefixId");
    int suffixId = ParamUtil.getInteger(actionRequest, "suffixId");
    boolean male = ParamUtil.get(actionRequest, "male", true);
    int birthdayMonth = 1;
    int birthdayDay = 1;
    int birthdayYear = 1970;
    String jobTitle = ParamUtil.getString(actionRequest, "jobTitle");
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = true;

    // additional data [KRS]
    String phone = ParamUtil.getString(actionRequest, "phone");
    String position = ParamUtil.getString(actionRequest, "position");
    String companyName = ParamUtil.getString(actionRequest, "company_name");
    String companyAddress = ParamUtil.getString(actionRequest, "company_address");
    String companyPostalCode = ParamUtil.getString(actionRequest, "company_postal_code");
    String companyCity = ParamUtil.getString(actionRequest, "company_city");
    String companyPhone = ParamUtil.getString(actionRequest, "company_phone");
    String companyFax = ParamUtil.getString(actionRequest, "company_fax");
    String companyMail = ParamUtil.getString(actionRequest, "company_email");
    AccountType accountType = AccountType.valueOf(ParamUtil.getString(actionRequest, "account_type"));
    String acceptRules = ParamUtil.getString(actionRequest, "accept_rules");

    long[] roleIds = getUserRoles(accountType);

    additionalValidate(emailAddress, phone, position, companyName, companyAddress, companyPostalCode,
            companyCity, companyPhone, companyFax, companyMail, accountType, acceptRules);

    ServiceContext serviceContext = ServiceContextFactory.getInstance(User.class.getName(), actionRequest);

    if (PropsValues.LOGIN_CREATE_ACCOUNT_ALLOW_CUSTOM_PASSWORD) {
        autoPassword = false;

        password1 = ParamUtil.getString(actionRequest, "password1");
        password2 = ParamUtil.getString(actionRequest, "password2");
    }

    boolean openIdPending = false;

    Boolean openIdLoginPending = (Boolean) session.getAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);

    if ((openIdLoginPending != null) && (openIdLoginPending.booleanValue()) && (Validator.isNotNull(openId))) {

        sendEmail = false;
        openIdPending = true;
    }

    if (PropsValues.CAPTCHA_CHECK_PORTAL_CREATE_ACCOUNT) {
        CaptchaUtil.check(actionRequest);
    }

    User user = UserServiceUtil.addUser(company.getCompanyId(), autoPassword, password1, password2,
            autoScreenName, screenName, emailAddress, openId, themeDisplay.getLocale(), firstName, middleName,
            lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
            organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
    UserLocalServiceUtil.updateAgreedToTermsOfUse(user.getUserId(), true);

    // additional data
    if (accountType == AccountType.CONSULTANT_COMPANY || accountType == AccountType.EMITER) {
        long userOrganizationId = CounterLocalServiceUtil.increment();
        UserOrganization userOrganization = UserOrganizationLocalServiceUtil
                .createUserOrganization(userOrganizationId);
        userOrganization.setAddress(companyAddress);
        userOrganization.setCity(companyCity);
        userOrganization.setPostalCode(companyPostalCode);
        userOrganization.setEmail(companyMail);
        userOrganization.setFax(companyFax);
        userOrganization.setName(companyName);
        userOrganization.setPhone(companyPhone);
        UserOrganizationLocalServiceUtil.updateUserOrganization(userOrganization);

        UserAddon userAddon = UserAddonLocalServiceUtil.createUserAddon(user.getUserId());
        userAddon.setPhone(phone);
        userAddon.setPosition(position);
        userAddon.setOrganizationId(userOrganizationId);
        userAddon.setApiKey(getRandomApiKey());
        UserAddonLocalServiceUtil.updateUserAddon(userAddon);
    }

    if (openIdPending) {
        session.setAttribute(WebKeys.OPEN_ID_LOGIN, new Long(user.getUserId()));

        session.removeAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);
    } else {
        // Session messages
        SessionMessages.add(request, "user_added", user.getEmailAddress());
        SessionMessages.add(request, "user_added_password", user.getPasswordUnencrypted());
    }

    logger.info("Creating account: firstName" + firstName + ", lastName:" + lastName + ", email:" + emailAddress
            + ", accountType: " + accountType);

    // Send redirect

    String login = null;

    if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_ID)) {
        login = String.valueOf(user.getUserId());
    } else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_SN)) {
        login = user.getScreenName();
    } else {
        login = user.getEmailAddress();
    }

    PortletURL loginURL = LoginUtil.getLoginURL(request, themeDisplay.getPlid());

    loginURL.setParameter("login", login);

    String redirect = loginURL.toString();

    actionResponse.sendRedirect(redirect);
}

From source file:com.mss.mirage.recruitment.ConsultantAction.java

public String doResumeSearch() {
    String searchString;//from ww w .j  ava 2  s . c o m
    int gridSize;
    int strStartGrid = 0;
    int strEndGrid = 0;

    searchString = httpServletRequest.getParameter("resumeText");

    // System.out.println("seacrh:::::::"+searchString);

    /*
    File indexDir = new File(args[0]);
    String q = args[1];
    if (!indexDir.exists() || !indexDir.isDirectory()) {
    throw new Exception(indexDir +
    " does not exist or is not a directory.");
    }
    search(indexDir, q);
     */

    File indexDir = new File(Properties.getProperty("Lucene.Index.Path"));
    String q = searchString;

    try {
        /*if (!indexDir.exists() || !indexDir.isDirectory()) {
        throw new Exception(indexDir +
        " does not exist or is not a directory.");
        }*/

        HibernateDataProvider hibernateDataProvider = HibernateDataProvider.getInstance();
        datasourceDataProvider = DataSourceDataProvider.getInstance();
        setPracticeList(hibernateDataProvider.getPractice(ApplicationConstants.PRACTICE_OPTION));
        setStatesList(hibernateDataProvider.getStatesList(ApplicationConstants.STATES_OPTIONS));
        //  setAssignedMembers(datasourceDataProvider.getEmployeeNamesByUserId("Recruiting"));
        setAssignedMembers(datasourceDataProvider.getEmployeeNamesByRecruitingRole());
        HttpSession session = httpServletRequest.getSession(true);

        session.removeAttribute("searchResult");
        session.removeAttribute("searchString");
        session.removeAttribute("gridSize");

        //search(indexDir, q);
        List searchResult = null;
        searchResult = search(indexDir, q);
        //System.out.println("search result is::::::"+searchResult);

        session.setAttribute("searchResult", searchResult);
        session.setAttribute("searchString", searchString);

        if (searchResult.size() > 0) {
            gridSize = searchResult.size();
            //System.out.println("searchResult list size:::"+gridSize);
            session.setAttribute("gridSize", gridSize);
            //System.out.println("grid size::::::::"+session.getAttribute("gridSize"));

            if (searchResult.size() < 30) {
                strStartGrid = 0;
                httpServletRequest.setAttribute("strStartGrid", strStartGrid);
                strEndGrid = searchResult.size();
                httpServletRequest.setAttribute("strEndGrid", strEndGrid);
            } else {
                strStartGrid = 0;
                httpServletRequest.setAttribute("strStartGrid", strStartGrid);
                strEndGrid = 30;
                httpServletRequest.setAttribute("strEndGrid", strEndGrid);
            }
            resultType = SUCCESS;
        } else {
            strStartGrid = 0;
            httpServletRequest.setAttribute("strStartGrid", strStartGrid);
            strEndGrid = 0;
            httpServletRequest.setAttribute("strEndGrid", strEndGrid);
            resultType = INPUT;
            setResultMessage("<font color=\"red\" size=\"1.5\">Sorry! Please Try Search Again !</font>");
        }
        /*
        int gettxtStartGrid = Integer.parseInt(httpServletRequest.getParameter("txtStartGrid"));
        int gettxtEndGrid = Integer.parseInt(httpServletRequest.getParameter("txtEndGrid"));
                
        if( gettxtStartGrid != 0){
        strEndGrid = Integer.parseInt(httpServletRequest.getParameter("txtEndGrid"));
        strStartGrid = strEndGrid + 1;
        httpServletRequest.setAttribute("strStartGrid",strStartGrid);
        }else{
        strStartGrid = 1;
        httpServletRequest.setAttribute("strStartGrid",strStartGrid);
        }
                
        if( gettxtEndGrid != 0){
        strEndGrid = Integer.parseInt(httpServletRequest.getParameter("txtEndGrid"));
        strEndGrid = strEndGrid + 30;
        }else{
        strEndGrid = 30;
        httpServletRequest.setAttribute("strEndGrid",strEndGrid);
        }*/
        httpServletRequest.setAttribute(ApplicationConstants.RESULT_MSG, getResultMessage());
    } catch (Exception ex) {
        //ex.printStackTrace();
        httpServletRequest.getSession(false).setAttribute("errorMessage", ex.toString());
        resultType = ERROR;
    }
    return resultType;
}

From source file:com.mss.mirage.recruitment.ConsultantAction.java

public String doConsultantSearch() {

    //        String strStartGrid =null;
    //        String strEndGrid=null;

    int strStartGrid = 0;
    int strEndGrid = 0;
    int isUserManager = 0;
    int isUserTeamLead = 0;
    String loginId = "";
    Map employeeMap = new TreeMap();
    // int empId=0;
    resultType = LOGIN;/*from  ww w.j av a2  s.c  om*/
    StringBuffer queryStringBuffer = null;
    if (httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_USER_ID) != null) {
        userRoleId = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_ID).toString());
        //  empId = Integer.parseInt(httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_EMP_ID).toString());

        resultType = "accessFailed";
        loginId = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_USER_ID)
                .toString();
        isUserManager = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_IS_USER_MANAGER).toString());
        isUserTeamLead = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_IS_TEAM_LEAD).toString());
        if (AuthorizationManager.getInstance().isAuthorizedUser("PREPARE_CONSULTANT_SEARCH", userRoleId)) {
            try {
                HibernateDataProvider hibernateDataProvider = HibernateDataProvider.getInstance();
                datasourceDataProvider = DataSourceDataProvider.getInstance();
                //setPracticeList(hibernateDataProvider.getPractice(ApplicationConstants.PRACTICE_OPTION));
                setStatesList(hibernateDataProvider.getStatesList(ApplicationConstants.STATES_OPTIONS));
                // setAssignedMembers(datasourceDataProvider.getEmployeeNamesByUserId("Recruiting"));
                if (isUserManager == 1 || isUserTeamLead == 1) {
                    setAssignedMembers(datasourceDataProvider.getEmployeeNamesByRecruitingRole());
                } else {
                    String empName = datasourceDataProvider.getFname_Lname(loginId);
                    employeeMap.put(loginId, empName);
                    setAssignedMembers(employeeMap);
                }

                defaultDataProvider = DefaultDataProvider.getInstance();
                //  NEW 
                setOrgMap(defaultDataProvider.getOrgMap(ApplicationConstants.ORG_MAP));

                setExpMap(defaultDataProvider.getExpMap(ApplicationConstants.EXP_MAP));
                queryStringBuffer = new StringBuffer();

                //  String valueSession = (String) httpServletRequest.getSession(false).getAttribute("isSearch");
                if (getAll() != null) {

                    // queryStringBuffer.append("SELECT createdBy,Id,FName,CONCAT(trim(FName),' ', trim(MName),' ',trim(LName)) as Name, Email2," +
                    //    "CellPhoneNo,SkillSet,ModifiedDate,LastContactDate FROM tblRecConsultant");
                    queryStringBuffer.append(
                            "SELECT createdBy,Id,FName,CONCAT(TRIM(FName),' ', TRIM(MName),' ',TRIM(LName)) AS NAME,TitleTypeId,Email2,"
                                    + "Country,SkillSet ,CellPhoneNo,CreatedBy,ModifiedBy,LastContactDate,CreatedDate,ModifiedDate FROM tblRecConsultant ");
                    queryStringBuffer.append(" ORDER BY modifiedDate DESC LIMIT 200");

                    httpServletRequest.getSession(false).setAttribute(ApplicationConstants.IS_SEARCH, null);

                } else {

                    if (httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.IS_SEARCH) != null) {

                        //   if(!(httpServletRequest.getSession(false).getAttribute("search_Query_BackToList") == null))

                        if (httpServletRequest.getSession(false)
                                .getAttribute("search_Query_BackToList") != null) {
                            queryStringBuffer = (StringBuffer) httpServletRequest.getSession(false)
                                    .getAttribute("search_Query_BackToList");
                        }
                    } else {

                        // queryStringBuffer.append("SELECT createdBy,Id,FName,CONCAT(trim(FName),' ', trim(MName),' ',trim(LName)) as Name, Email2," +
                        //   "CellPhoneNo,SkillSet,ModifiedDate,LastContactDate FROM tblRecConsultant");
                        queryStringBuffer.append(
                                "SELECT createdBy,Id,FName,CONCAT(TRIM(FName),' ', TRIM(MName),' ',TRIM(LName)) AS NAME,TitleTypeId,Email2,"
                                        + "Country,SkillSet ,CellPhoneNo,CreatedBy,ModifiedBy,LastContactDate,CreatedDate,ModifiedDate FROM tblRecConsultant ");
                        queryStringBuffer.append(" ORDER BY modifiedDate DESC LIMIT 200");

                        httpServletRequest.getSession(false).setAttribute(ApplicationConstants.IS_SEARCH, null);
                    }
                }

                if (httpServletRequest.getSession(false)
                        .getAttribute(ApplicationConstants.QUERY_STRING) != null) {
                    httpServletRequest.getSession(false).removeAttribute(ApplicationConstants.QUERY_STRING);
                }
                httpServletRequest.getSession(false).setAttribute(ApplicationConstants.QUERY_STRING,
                        queryStringBuffer.toString());

                httpServletRequest.removeAttribute("strStartGrid");
                httpServletRequest.removeAttribute("strEndGrid");

                httpServletRequest.setAttribute("strStartGrid", strStartGrid);
                httpServletRequest.setAttribute("strEndGrid", strEndGrid);

                HttpSession session = httpServletRequest.getSession(true);
                session.removeAttribute("searchString");
                session.removeAttribute("gridSize");
                session.removeAttribute("searchResult");

                resultType = SUCCESS;

            } catch (Exception ex) {
                //List errorMsgList = ExceptionToListUtility.errorMessages(ex);
                httpServletRequest.getSession(false).setAttribute("errorMessage", ex.toString());
                resultType = ERROR;
            }
        }
    }
    return resultType;
}

From source file:edu.stanford.muse.email.MuseEmailFetcher.java

/** key method to fetch actual email messages. can take a long time.
 * @param session is used only to set the status provider object. callers who do not need to track status can leave it as null
 * @param selectedFolders is in the format <account name>^-^<folder name>
 * @param session is used only to put a status object in. can be null in which case status object is not set.
 * emailDocs, addressBook and blobstore//from  ww  w  . j a va 2s .c  o  m
 * @throws NoDefaultFolderException 
 * */
public void fetchAndIndexEmails(Archive archive, String[] selectedFolders, boolean useDefaultFolders,
        FetchConfig fetchConfig, HttpSession session) throws MessagingException, InterruptedException,
        IOException, JSONException, NoDefaultFolderException, CancelledException {
    setupFetchers(-1);

    long startTime = System.currentTimeMillis();
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Starting to process messages..."));

    boolean op_cancelled = false, out_of_mem = false;

    BlobStore attachmentsStore = archive.getBlobStore();
    fetchConfig.downloadAttachments = fetchConfig.downloadAttachments && attachmentsStore != null;

    if (Util.nullOrEmpty(fetchers)) {
        log.warn("Trying to fetch email with no fetchers, setup not called ?");
        return;
    }

    setupFoldersForFetchers(fetchers, selectedFolders, useDefaultFolders);

    List<FolderInfo> fetchedFolderInfos = new ArrayList<FolderInfo>();

    // one fetcher will aggregate everything
    FetchStats stats = new FetchStats();
    MTEmailFetcher aggregatingFetcher = null;

    // a fetcher is one source, like an account or a top-level mbox dir. A fetcher could include multiple folders.
    long startTimeMillis = System.currentTimeMillis();
    for (MTEmailFetcher fetcher : fetchers) {
        // in theory, different iterations of this loop could be run in parallel ("archive" access will be synchronized)

        if (session != null)
            session.setAttribute("statusProvider", fetcher);

        fetcher.setArchive(archive);
        fetcher.setFetchConfig(fetchConfig);
        log.info("Memory status before fetching emails: " + Util.getMemoryStats());

        List<FolderInfo> foldersFetchedByThisFetcher = fetcher.run(); // this is the big call, can run for a long time. Note: running in the same thread, its not fetcher.start();

        // if fetcher was cancelled or out of mem, bail out of all fetchers
        // but don't abort immediately, only at the end, after addressbook has been built for at least the processed messages
        if (fetcher.isCancelled()) {
            log.info("NOTE: fetcher operation was cancelled");
            op_cancelled = true;
            break;
        }

        if (fetcher.mayHaveRunOutOfMemory()) {
            log.warn("Fetcher operation ran out of memory " + fetcher);
            out_of_mem = true;
            break;
        }

        fetchedFolderInfos.addAll(foldersFetchedByThisFetcher);

        if (aggregatingFetcher == null && !Util.nullOrEmpty(foldersFetchedByThisFetcher))
            aggregatingFetcher = fetcher; // first non-empty fetcher

        if (aggregatingFetcher != null)
            aggregatingFetcher.merge(fetcher);

        // add the indexed folders to the stats
        EmailStore store = fetcher.getStore();
        String fetcherDescription = store.displayName + ":" + store.emailAddress;
        for (FolderInfo fi : fetchedFolderInfos)
            stats.selectedFolders.add(new Pair<>(fetcherDescription, fi));
    }

    if (op_cancelled)
        throw new CancelledException();
    if (out_of_mem)
        throw new OutOfMemoryError();

    if (aggregatingFetcher != null) {
        stats.importStats = aggregatingFetcher.stats;
        if (aggregatingFetcher.mayHaveRunOutOfMemory())
            throw new OutOfMemoryError();
    }
    aggregatingFetcher = null; // save memory

    long endTimeMillis = System.currentTimeMillis();
    long elapsedMillis = endTimeMillis - startTimeMillis;
    log.info(elapsedMillis + " ms for fetch+index, Memory status: " + Util.getMemoryStats());

    List<EmailDocument> allEmailDocs = (List) archive.getAllDocs(); // note: this is all archive docs, not just the ones that may have been just imported

    archive.addFetchedFolderInfos(fetchedFolderInfos);

    if (allEmailDocs.size() == 0)
        log.warn("0 messages from email fetcher");

    EmailUtils.cleanDates(allEmailDocs);

    // create a new address book   
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Building address book..."));
    AddressBook addressBook = EmailDocument.buildAddressBook(allEmailDocs, archive.ownerEmailAddrs,
            archive.ownerNames);
    log.info("Address book stats: " + addressBook.getStats());
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Finishing up..."));
    archive.setAddressBook(addressBook);

    // we shouldn't really have dups now because the archive ensures that only unique docs are added
    // move sorting to archive.postprocess? 
    EmailUtils.removeDupsAndSort(allEmailDocs);

    // report stats
    stats.lastUpdate = new Date().getTime();

    stats.userKey = "USER KEY UNUSED"; // (String) JSPHelper.getSessionAttribute(session, "userKey");
    stats.fetchAndIndexTimeMillis = elapsedMillis;

    updateStats(archive, addressBook, stats);
    if (session != null)
        session.removeAttribute("statusProvider");
    log.info("Fetch+index complete: " + Util.commatize(System.currentTimeMillis() - startTime) + " ms");

}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from w w  w  .  j  av  a2  s  .c  o  m*/
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

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

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

    int turno = 0;
    try {/*from  w ww.java 2  s  . c o m*/
        turno = Integer.parseInt(session.getAttribute("idTurno").toString());
    } catch (Exception ex) {
        session.removeAttribute("idTurno");

        return new ModelAndView("redirect:/", map);
    }
    session.removeAttribute("idTurno");

    Turno tempTurno = new Turno();
    tempTurno = ServicioMain.getTurno(turno);
    map.addAttribute("idTurno", turno);
    map.addAttribute("objTurno", tempTurno);
    return new ModelAndView("/Inscripcion/inscripcion_sesion2", map);

}