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.mimp.controllers.familia.java

@RequestMapping(value = "/FamiliaInscribirTaller", method = RequestMethod.GET)
public ModelAndView FamiliaInscribirTaller_GET(ModelMap map, 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   www  .  j ava 2  s. c  om

    if (session.getAttribute("idTurno2") != null && session.getAttribute("nombreTaller") != null
            && session.getAttribute("nombreGrupo") != null && session.getAttribute("nombreTurno") != null) {

        long idTurno2 = (long) session.getAttribute("idTurno2");
        String nombreTaller = (String) session.getAttribute("nombreTaller");
        String nombreGrupo = (String) session.getAttribute("nombreGrupo");
        String nombreTurno = (String) session.getAttribute("nombreTurno");

        ArrayList<Reunion> allReuniones = new ArrayList();
        allReuniones = ServicioFamilia.listaReunionesTurno2(idTurno2);
        short numAsistentes = ServicioFamilia.numAsistentesFormulario(usuario.getIdfamilia());
        boolean inscripcion = false;
        for (Reunion reunion : allReuniones) {
            if ((reunion.getAsistenciaFRs().size() + numAsistentes) > reunion.getCapacidad()) {
                inscripcion = true;
            }
        }
        if (!inscripcion) {
            for (Reunion reunion : allReuniones) {
                AsistenciaFR tempAFR = new AsistenciaFR();
                tempAFR.setFamilia(usuario);
                tempAFR.setReunion(reunion);
                String asistencia = "F";
                char c = asistencia.charAt(0);
                tempAFR.setAsistencia(c);
                tempAFR.setInasJus(Short.parseShort("1"));
                ServicioFamilia.crearAFR(tempAFR);
                short x = 2;
                if (numAsistentes == x) {
                    AsistenciaFR tempAFR2 = new AsistenciaFR();
                    tempAFR2.setFamilia(usuario);
                    tempAFR2.setReunion(reunion);
                    String asistencia2 = "F";
                    char c2 = asistencia2.charAt(0);
                    tempAFR2.setAsistencia(c);
                    tempAFR2.setInasJus(Short.parseShort("1"));
                    ServicioFamilia.crearAFR(tempAFR2);
                }
            }
        }
        if (!inscripcion) {
            map.put("listaReuniones", allReuniones);
            map.put("nombreTaller", nombreTaller);
            map.put("nombreGrupo", nombreGrupo);
            map.put("nombreTurno", nombreTurno);
            map.put("df", format);
        } else {
            map.put("mensaje", "negativo");
            map.put("nombreGrupo", nombreGrupo);
            map.put("nombreTurno", nombreTurno);
        }
        String pagina = "/Familia/Inscripcion/inscripcion_Grupos_afirm";

        session.removeAttribute("idTurno2");
        session.removeAttribute("nombreTaller");
        session.removeAttribute("nombreGrupo");
        session.removeAttribute("nombreTurno");

        return new ModelAndView(pagina, map);
    } else {
        String pagina = "/Familia/inicio_familia";
        return new ModelAndView(pagina, map);
    }

}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public final void logoutFromWebservice(HttpSession session) {
    SpiritUserClientDto usr = null;//w  w w  .jav  a 2 s.  c  o  m
    SpiritEhrWsClientInterface webService = null;
    try {
        usr = (SpiritUserClientDto) session.getAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE);
        webService = (SpiritEhrWsClientInterface) session.getAttribute(EPSOS_WEBSERVICE_ATTRIBUTE);
        if (usr != null && webService != null) {
            webService.usrLogout();
            session.removeAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE);
            session.removeAttribute(EPSOS_WEBSERVICE_ATTRIBUTE);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.cabig.caaers.web.ae.EditAdverseEventController.java

/**
 * This method will do the following, make the command to be in a consistent state. 
 * //from  w  ww .  ja  v a2 s .  com
 * If from Review Report page?
 *  1.- If this is a new data collection:
 *    1.1. Create Expedited Report, associate it with Reporting period.
 *    1.2. Initialize the Treatment information
 *    1.3. Initialize the reporter.
 *  2. Add/Remove adverse events. 
 *  3. Find the mandatory sections.  
 *  4. Pre-initialize the mandatory section fields.    
 *   
 * If from Manage reports page?
 *  1. Find the mandatory sections
 *  2. Refresh/Initialize the Not applicable and mandatory fields. 
 *  
 */
@Override
protected void onBindOnNewForm(HttpServletRequest request, Object cmd) throws Exception {
    super.onBindOnNewForm(request, cmd);

    HttpSession session = request.getSession();

    String screenFlowSource = request.getParameter("from");

    EditExpeditedAdverseEventCommand command = (EditExpeditedAdverseEventCommand) cmd;
    command.setScreenFlowSource(screenFlowSource);

    command.getNewlySelectedReportDefinitions().clear();
    command.getSelectedReportDefinitions().clear();
    command.getApplicableReportDefinitions().clear();

    ReviewAndReportResult reviewResult = (ReviewAndReportResult) session.getAttribute("reviewResult");
    ExpeditedAdverseEventReport aeReport = command.getAeReport();
    if ((reviewResult != null) && StringUtils.equals("captureAE", screenFlowSource)) {

        //If a new data collection?
        if (reviewResult.getAeReportId() == 0) {
            //create expedited report.
            aeReport = new ExpeditedAdverseEventReport();
            aeReport.setCreatedAt(nowFactory.getNowTimestamp());
            command.setAeReport(aeReport);

            //populate the reporting period.
            AdverseEventReportingPeriod adverseEventReportingPeriod = adverseEventReportingPeriodDao
                    .getById(reviewResult.getReportingPeriodId());
            command.getAeReport().setReportingPeriod(adverseEventReportingPeriod);
            command.getAeReport().synchronizeMedicalHistoryFromAssignmentToReport();

            //initialize treatment information
            command.initializeTreatmentInformation();

            //set the default reporter as the logged-in person
            String loginId = SecurityUtils.getUserLoginName();
            if (loginId != null) {
                Person loggedInPerson = getPersonRepository().getByLoginId(loginId);
                command.getAeReport().getReporter().copy(loggedInPerson);
                if (loggedInPerson == null) {
                    User loggedInUser = getUserRepository().getUserByLoginName(loginId);
                    command.getAeReport().getReporter().copy(loggedInUser);
                }
            }

        }

        //Add all the aes to be added 
        for (Integer aeId : reviewResult.getAeList()) {
            AdverseEvent ae = command.getAdverseEventReportingPeriod().findAdverseEventById(aeId);
            if (aeReport.findAdverseEventById(aeId) == null) {
                aeReport.addAdverseEvent(ae);
            }
        }

        //remove all the aes to be removed
        for (Integer aeId : reviewResult.getUnwantedAEList()) {
            AdverseEvent ae = aeReport.findAdverseEventById(aeId);
            if (ae != null && aeReport.getAdverseEvents().remove(ae)) {
                ae.clearAttributions();
                ae.setReport(null);
            }
        }

        //modify the primary ae if necessary
        command.makeAdverseEventPrimary(reviewResult.getPrimaryAdverseEventId());

        //reload- the report definitions (from create & edit list)
        for (ReportDefinition rd : reviewResult.getCreateList()) {
            ReportDefinition loaded = reportDefinitionDao.getById(rd.getId());
            reportDefinitionDao.initialize(loaded);
            command.getSelectedReportDefinitions().add(loaded);
            command.getNewlySelectedReportDefinitions().add(loaded);
        }
        for (ReportDefinition rd : reviewResult.getEditList()) {
            ReportDefinition loaded = reportDefinitionDao.getById(rd.getId());
            command.getSelectedReportDefinitions().add(loaded);
        }

        //update the applicable report definitions.
        command.getApplicableReportDefinitions().addAll(command.getSelectedReportDefinitions());

    } else {
        //from manage reports / review and reports, so do cleanup of session attributes explicitly
        session.removeAttribute("reviewResult");

        String action = request.getParameter(ACTION_PARAMETER);
        String strReportId = request.getParameter("report");
        int reportId = -999;
        if (StringUtils.isNumeric(strReportId)) {
            reportId = Integer.parseInt(strReportId);
        }

        //find the report. 
        Report selectedReport = aeReport.findReportById(reportId);

        if (selectedReport != null) {
            command.getSelectedReportDefinitions().add(selectedReport.getReportDefinition());
            if (!selectedReport.isActive()) {
                //if selected report is not active, add it into applicable reports
                command.getApplicableReportDefinitions().add(selectedReport.getReportDefinition());
            }

            for (Report report : aeReport.getActiveReports()) {
                if (!command.getApplicableReportDefinitions().contains(report.getReportDefinition()))
                    command.getApplicableReportDefinitions().add(report.getReportDefinition());
            }

            //pre initialize all the report mandatory fields.
            for (ReportDefinition reportDefinition : command.getApplicableReportDefinitions()) {
                reportDefinition.getMandatoryFields().size();
                ;
            }

            //if action is amend, keep a mock reviewResult in session. 
            if (StringUtils.equals(action, "amendReport") && selectedReport.isSubmitted()) {
                command.getNewlySelectedReportDefinitions().add(selectedReport.getReportDefinition());
                reviewResult = new ReviewAndReportResult();
                reviewResult.getAmendList().add(selectedReport.getReportDefinition());
                reviewResult.getReportsToAmmendList().add(selectedReport);
                reviewResult.getCreateList().add(selectedReport.getReportDefinition());
                session.setAttribute("reviewResult", reviewResult);
            }

        }

    }

    //synchronize the outcomes
    command.updateOutcomes();

    //find the mandatory sections.
    command.refreshMandatorySections();

    if (aeReport.getId() == null) {
        //present status. 
        for (AdverseEvent ae : aeReport.getAdverseEvents()) {
            if (ae.getGrade() == null)
                continue;
            if (ae.getGrade().equals(Grade.DEATH)) {
                aeReport.getResponseDescription().setPresentStatus(PostAdverseEventStatus.DEAD);
                break;
            }
        }
    }

    // pre-init the mandatory section fields & set present status
    if (!command.getNewlySelectedReportDefinitions().isEmpty() || command.getAeReport().isActive()) {
        command.initializeMandatorySectionFields();
    }

    //will pre determine the display/render-ability of fields 
    command.updateFieldMandatoryness();

    //CAAERS-5865, if study is not CTEP-ESYS study, set outOfSync flag as false,
    //so syncing process will not be triggered
    if (command.getAeReport().getStudy().getCtepEsysIdentifier() == null) {
        command.setStudyOutOfSync(false);
    }

}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessorServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doPost");
    HttpSession httpSession = request.getSession();
    byte[] previousSignedDocument = clearAllSessionAttribute(httpSession);

    String target = (String) httpSession.getAttribute(this.targetSessionAttribute);
    String base64encodedSignatureRequest = (String) httpSession
            .getAttribute(this.signatureRequestSessionAttribute);
    String signatureRequestId = (String) httpSession.getAttribute(this.signatureRequestIdSessionAttribute);
    String relayState = (String) httpSession.getAttribute(this.relayStateSessionAttribute);
    LOG.debug("RelayState: " + relayState);

    SignatureResponse signatureResponse;
    try {/* www .  j a  va2s.c  o  m*/
        signatureResponse = this.signatureResponseProcessor.process(request, target,
                base64encodedSignatureRequest, signatureRequestId, relayState);
    } catch (UserCancelledSignatureResponseProcessorException e) {
        if (null != this.cancelPage) {
            LOG.debug("redirecting to cancel page");
            /*
             * In case of explicit user cancellation we preserve the signed
             * document session attribute.
             */
            httpSession.setAttribute(this.signedDocumentSessionAttribute, previousSignedDocument);
            redirectTo(response, request.getContextPath() + this.cancelPage);
            return;
        }
        showErrorPage(e.getMessage(), request, response);
        return;
    } catch (SignatureResponseProcessorException e) {
        showErrorPage(e.getMessage(), request, response);
        return;
    }

    byte[] decodedSignatureResponse = signatureResponse.getDecodedSignatureResponse();
    String signatureResponseId = signatureResponse.getSignatureResponseId();

    /*
     * Check signed document passed along, if not signatureResponseId should
     * be present.
     * 
     * If configuration is available for DSS WS Client fetch the signed
     * document here, else SP has to do it himself via signatureResponseId
     * pushed on session.
     */
    if (null == decodedSignatureResponse) {

        if (null == signatureResponseId) {
            showErrorPage("No signed document nor response ID found!", request, response);
            return;
        }

        // check WS client config available
        String dssWSUrl;
        if (this.signatureResponseServiceLocator.isConfigured()) {
            SignatureResponseService signatureResponseService = this.signatureResponseServiceLocator
                    .locateService();
            dssWSUrl = signatureResponseService.getDssWSUrl();
            LOG.debug("DSS WS URL: " + dssWSUrl);
        } else {
            dssWSUrl = this.dssWSUrl;
        }
        if (null != dssWSUrl) {
            DigitalSignatureServiceClient dssClient = new DigitalSignatureServiceClient(dssWSUrl);
            if (null != this.dssWSProxyHost) {
                dssClient.setProxy(this.dssWSProxyHost, this.dssWSProxyPort);
            } else {
                // disable previously set proxy
                dssClient.setProxy(null, 0);
            }
            try {
                decodedSignatureResponse = dssClient.retrieve(signatureResponseId);
            } catch (DocumentNotFoundException e) {
                showErrorPage("Document not found at the eID DSS WS.", request, response);
                return;
            }

        } else {

            if (null == this.signatureResponseIdSessionAttribute) {
                showErrorPage("No SignatureResponseId session attribute " + "specified, aborting...", request,
                        response);
                return;
            }
            // push response ID on session
            httpSession.setAttribute(this.signatureResponseIdSessionAttribute, signatureResponseId);

        }

        if (null != this.signatureRequestSessionAttribute) {
            httpSession.removeAttribute(this.signatureRequestSessionAttribute);
        }
        if (null != this.signatureRequestIdSessionAttribute) {
            httpSession.removeAttribute(this.signatureRequestIdSessionAttribute);
        }
    }

    /*
     * Push data into the HTTP session.
     */
    httpSession.setAttribute(this.signedDocumentSessionAttribute, decodedSignatureResponse);
    if (null != this.signatureCertificateSessionAttribute) {
        httpSession.setAttribute(this.signatureCertificateSessionAttribute,
                signatureResponse.getSignatureCertificate());
    }

    /*
     * Continue work-flow.
     */
    redirectTo(response, request.getContextPath() + this.nextPage);
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateIndexController.java

@RequestMapping(value = "/createindex", method = RequestMethod.POST)
public String createIndexAction(@ModelAttribute("indexAttribute") NewIndex indexAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*  w  w w  .  j  a v  a2  s .  c o  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create index");

    String tabName = indexAttribute.getTableName();
    String schema = indexAttribute.getSchemaName();
    String unique = indexAttribute.getUnique();
    String idxName = indexAttribute.getIndexName();
    String submit = request.getParameter("pSubmit");

    String[] selectedColumns = request.getParameterValues("selected_column[]");
    String[] indexOrder = request.getParameterValues("idxOrder[]");
    String[] position = request.getParameterValues("position[]");

    logger.debug("selectedColumns = " + Arrays.toString(selectedColumns));
    logger.debug("indexOrder = " + Arrays.toString(indexOrder));
    logger.debug("position = " + Arrays.toString(position));

    IndexDAO indexDAO = GemFireXDWebDAOFactory.getIndexDAO();

    List<IndexColumn> columns = indexDAO.retrieveIndexColumns(schema, tabName,
            (String) session.getAttribute("user_key"));

    StringBuffer createIndex = new StringBuffer();

    if (unique.equalsIgnoreCase("Y")) {
        createIndex.append("create unique index " + idxName + " on " + schema + "." + tabName + " ");
    } else {
        createIndex.append("create index " + idxName + " on " + schema + "." + tabName + " ");
    }

    createIndex.append("(");

    if (selectedColumns != null) {
        int i = 0;
        Map<String, IndexDefinition> cols = new HashMap<String, IndexDefinition>();

        for (String column : selectedColumns) {
            String columnName = column.substring(0, column.indexOf("_"));
            String index = column.substring(column.indexOf("_") + 1);
            String pos = position[Integer.parseInt(index) - 1];
            if (pos.trim().length() == 0) {
                pos = "" + i;
            }

            logger.debug("Column = " + columnName + ", indexOrder = " + indexOrder[Integer.parseInt(index) - 1]
                    + ", position = " + pos);

            IndexDefinition idxDef = new IndexDefinition(columnName, indexOrder[Integer.parseInt(index) - 1]);

            cols.put("" + pos, idxDef);
            i++;
        }

        // sort map and create index now
        SortedSet<String> keys = new TreeSet<String>(cols.keySet());
        int length = keys.size();
        i = 0;
        for (String key : keys) {
            IndexDefinition idxDefTemp = cols.get(key);
            if (i == (length - 1)) {
                createIndex.append(idxDefTemp.getColumnName() + " " + idxDefTemp.getOrderType() + ")");
            } else {
                createIndex.append(idxDefTemp.getColumnName() + " " + idxDefTemp.getOrderType() + ", ");
            }

            i++;

        }
    }

    if (!checkIfParameterEmpty(request, "caseSensitive")) {
        createIndex.append(" " + request.getParameter("caseSensitive") + "\n");
    }

    if (submit.equalsIgnoreCase("create")) {
        Result result = new Result();

        logger.debug("Creating index as -> " + createIndex.toString());

        result = GemFireXDWebDAOUtil.runCommand(createIndex.toString(),
                (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
        model.addAttribute("tabName", tabName);
        model.addAttribute("tableSchemaName", schema);
        model.addAttribute("columns", columns);
        model.addAttribute("schema", schema);

        session.removeAttribute("numColumns");
    } else if (submit.equalsIgnoreCase("Show SQL")) {
        logger.debug("Index SQL as follows as -> " + createIndex.toString());
        model.addAttribute("sql", createIndex.toString());
        model.addAttribute("tabName", tabName);
        model.addAttribute("tableSchemaName", schema);
        model.addAttribute("columns", columns);
        model.addAttribute("schema", schema);
    } else if (submit.equalsIgnoreCase("Save to File")) {
        response.setContentType(SAVE_CONTENT_TYPE);
        response.setHeader("Content-Disposition", "attachment; filename=" + String.format(FILENAME, idxName));

        ServletOutputStream out = response.getOutputStream();
        out.println(createIndex.toString());
        out.close();
        return null;
    }
    // This will resolve to /WEB-INF/jsp/create-index.jsp
    return "create-index";
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = { "", "/listusersforaccount" }, method = RequestMethod.GET)
public String listUsersForAccount(@ModelAttribute("currentTenant") Tenant tenant,
        @RequestParam(value = "showAll", required = false, defaultValue = "false") boolean showAll,
        @RequestParam(value = "tenant", required = false) String tenantParam, ModelMap map, HttpSession session,
        @RequestParam(value = "user", required = false) String userParam,
        @RequestParam(value = "page", required = false, defaultValue = "1") int page,
        @RequestParam(value = "perPage", required = false, defaultValue = "14") int perPage,
        @RequestParam(value = "showAddNewUserWizard", required = false) String showAddNewUserWizard,
        HttpServletRequest request) {/* ww  w  . ja v  a 2 s. c  o m*/

    logger.debug("###Entering in list(tenant,showAll,tenantId,map) method @GET");

    map.addAttribute("defaultPageSize", getDefaultPageSize());
    if (showAddNewUserWizard != null) {
        map.addAttribute("showAddNewUserWizard", showAddNewUserWizard);
    }
    session.setAttribute("currentPerPagesize", perPage);
    int totalUsers = 0;

    map.addAttribute("isShowingAll", showAll);
    List<User> results;
    String view = "users.list_with_admin_menu";
    if (isAdmin() && showAll) {
        results = userService.list(page, perPage, null, null, false, null, null, null);
        totalUsers = userService.count(null, null, null, null);
        map.addAttribute("userHasCloudServiceAccount",
                userService.isUserHasAnyActiveCloudService(getCurrentUser()));
    } else if (isAdmin() && (Boolean) request.getAttribute("isSurrogatedTenant")) {
        tenant = tenantService.get(tenantParam);
        results = userService.list(page, perPage, null, null, false, null, tenant.getId().toString(), null);
        totalUsers = userService.count(null, null, tenant.getId().toString(), null);
        map.addAttribute("showUserProfile", true);
        map.addAttribute("userHasCloudServiceAccount",
                userService.isUserHasAnyActiveCloudService(tenant.getOwner()));
        setPage(map, Page.CRM_ALL_USERS);
        view = "users.list_with_user_menu";
    } else {
        User currentUser = this.getCurrentUser();
        if (!userService.hasAuthority(currentUser, "ROLE_ACCOUNT_CRUD")) {
            view = "users.nonroot.list_with_user_menu";
            setPage(map, Page.USERS_ALL_USERS);
        }
        if (userParam != null) {
            results = new ArrayList<User>();
            results.add(userService.get(userParam));
            totalUsers = 1;
        } else {
            results = userService.list(page, perPage, null, null, false, null, tenant.getId().toString(), null);
            totalUsers = userService.count(null, null, tenant.getId().toString(), null);
        }
        map.addAttribute("userHasCloudServiceAccount", userService.isUserHasAnyActiveCloudService(currentUser));
        setPage(map, Page.ADMIN_ALL_USERS);
    }
    if (results != null && results.size() > 0) {
        customFieldService.populateCustomFields(results.get(0));
        customFieldService.populateCustomFields(results.get(0).getTenant());
    }

    map.addAttribute("tenant", tenant);
    map.addAttribute("users", results);
    map.addAttribute("size", results != null ? results.size() : 0);

    map.addAttribute("selectedUser", userParam);
    // get session data having any error messages
    String errormsg = (String) session.getAttribute("errormsg");
    session.removeAttribute("errormsg");
    if (errormsg != null && errormsg.equals("true")) {
        List<String> globalErrors = (List<String>) session.getAttribute("globalErrors");
        if (globalErrors != null) {
            map.addAttribute("globalErrors", globalErrors);
        }
        List<String> errorMsgList = (List<String>) session.getAttribute("errorMsgList");
        if (errorMsgList != null) {
            map.addAttribute("errorMsgList", errorMsgList);
        }
        map.addAttribute("errormsg", errormsg);

        session.removeAttribute("errorMsgList");
        session.removeAttribute("globalErrors");
    }
    // check user limit
    if (!isAllowedToAddUser(tenant)) {
        map.addAttribute("isUsersMaxReached", "Y");
    }

    map.addAttribute("enable_next", "False");

    if (totalUsers - page * perPage > 0) {
        map.addAttribute("enable_next", "True");
    } else {
        map.addAttribute("enable_next", "False");
    }
    map.addAttribute("current_page", page);

    logger.debug("###Exiting list(req,map,session) method");
    return view;
}

From source file:com.pkrete.locationservice.admin.controller.mvc.UserInfoController.java

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    if (user == null) {
        user = usersService.getUser(request.getRemoteUser());
        session.setAttribute("user", user);
    }/*from   w w  w. j a v a2 s. c om*/

    /* Model that is returned together with the view */
    java.util.Map<String, Object> model = new HashMap<String, Object>();

    if (request.getParameter("save") != null) {
        boolean ok = true;
        String passOld = request.getParameter("password_old");
        String passNew = request.getParameter("password_new");
        String passNewControl = request.getParameter("password_new_control");

        if (passOld.isEmpty()) {
            ok = false;
            model.put("errorMsgPwOld",
                    this.messageSource.getMessage("error.userinfo.password.old.missing", null, null));
        }
        if (passNew.isEmpty()) {
            ok = false;
            model.put("errorMsgPwNew",
                    this.messageSource.getMessage("error.userinfo.password.new.missing", null, null));
        } else if (passNew.length() < 5) {
            ok = false;
            model.put("errorMsgPwNew",
                    this.messageSource.getMessage("error.userinfo.password.new.length", null, null));
        } else if (!passNew.matches("\\w+")) {
            ok = false;
            model.put("errorMsgPwNew",
                    this.messageSource.getMessage("error.userinfo.password.new.form", null, null));
        }
        if (passNewControl.isEmpty()) {
            ok = false;
            model.put("errorMsgPwCtrl",
                    this.messageSource.getMessage("error.userinfo.password.control.missing", null, null));
        }
        if (!passNewControl.equals(passNew)) {
            ok = false;
            model.put("errorMsgPwNew",
                    this.messageSource.getMessage("error.userinfo.password.new.match", null, null));
        }

        if (passNew.length() > 100) {
            ok = false;
            model.put("errorMsgPwNew", this.messageSource.getMessage("error.user.password.length", null, null));
        }

        if (passNewControl.length() > 100) {
            ok = false;
            model.put("errorMsgPwCtrl",
                    this.messageSource.getMessage("error.user.password.length", null, null));
        }

        if (ok) {
            UserFull userFull = usersService.getFullUser(user.getUsername());
            String pass = this.encryptionService.encrypt(passOld);
            if (pass.equals(userFull.getPassword())) {
                String passNewCrypted = this.encryptionService.encrypt(passNew);
                if (!passNewCrypted.equals(userFull.getPassword())) {
                    userFull.setUpdater(user.getUsername());
                    userFull.setPasswordUi(passNew);
                    usersService.update(userFull);
                    model.put("responseMsg",
                            this.messageSource.getMessage("response.userinfo.password.changed", null, null));
                    user.setUpdated(new Date());
                    user.setUpdater(user.getUsername());
                } else {
                    model.put("errorMsgPwNew",
                            this.messageSource.getMessage("error.userinfo.password.old.new.same", null, null));
                }
            } else {
                model.put("errorMsgPwOld",
                        this.messageSource.getMessage("error.userinfo.password.old.match", null, null));
            }
        }
    } else if (request.getParameter("save_email") != null) {
        boolean ok = true;
        String email = request.getParameter("email");
        if (email.isEmpty()) {
            ok = false;
            model.put("errorMsgEmail", this.messageSource.getMessage("error.userinfo.email.empty", null, null));
        } else if (!WebUtil.validateEmail(email)) {
            ok = false;
            model.put("errorMsgEmail",
                    this.messageSource.getMessage("error.userinfo.email.invalid", null, null));
        } else if (email.length() > 100) {
            ok = false;
            model.put("errorMsgEmail", this.messageSource.getMessage("error.user.email.length", null, null));
        }

        if (ok) {
            UserFull userFull = usersService.getFullUser(user.getUsername());
            userFull.setUpdater(user.getUsername());
            userFull.setEmail(email);
            usersService.update(userFull);
            user.setEmail(email);
            session.removeAttribute("user");
            session.setAttribute("user", user);
            model.put("responseMsg",
                    this.messageSource.getMessage("response.userinfo.email.changed", null, null));
            user.setUpdated(new Date());
            user.setUpdater(user.getUsername());
        }
    }

    model.put("user", user);
    return new ModelAndView("user_info", "model", model);
}

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   w  ww  .  java 2  s.c o  m
 * @throws AccessDeniedException the {@link AccessDeniedException}
 * @return Html directory
 */
public String getModifyDirectoryRecord(HttpServletRequest request) throws AccessDeniedException {
    String strIdDirectoryRecord = request.getParameter(PARAMETER_ID_DIRECTORY_RECORD);
    int nIdDirectoryRecord = DirectoryUtils.convertStringToInt(strIdDirectoryRecord);
    Record record = _recordService.findByPrimaryKey(nIdDirectoryRecord, getPlugin());

    if ((record == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE,
            record.getDirectory().getIdDirectory() + DirectoryUtils.EMPTY_STRING,
            DirectoryResourceIdService.PERMISSION_MODIFY_RECORD, getUser())) {
        throw new AccessDeniedException(MESSAGE_ACCESS_DENIED);
    }

    // List of entries to display
    List<IEntry> listEntry = DirectoryUtils.getFormEntries(record.getDirectory().getIdDirectory(), getPlugin(),
            getUser());

    /**
     * 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);
        // 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) {
        map = DirectoryUtils.getMapIdEntryListRecordField(listEntry, nIdDirectoryRecord, getPlugin());
        // Reinit the asynchronous uploaded file map
        DirectoryAsynchronousUploadHandler.getHandler().reinitMap(request, map, getPlugin());
    }

    Directory directory = DirectoryHome.findByPrimaryKey(record.getDirectory().getIdDirectory(), getPlugin());

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

    model.put(MARK_ENTRY_LIST, listEntry);
    model.put(MARK_MAP_ID_ENTRY_LIST_RECORD_FIELD, map);
    model.put(MARK_DIRECTORY, directory);

    if (PortalService.isExtendActivated()) {
        ExtendableResourcePluginActionManager.fillModel(request, AdminUserService.getAdminUser(request), model,
                record.getIdExtendableResource(), record.getExtendableResourceType());
    }

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

    model.put(MARK_DIRECTORY_RECORD, record);
    model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));
    model.put(MARK_LOCALE, getLocale());
    setPageTitleProperty(PROPERTY_MODIFY_DIRECTORY_RECORD_PAGE_TITLE);

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

    return getAdminPage(template.getHtml());
}

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

@RequestMapping("/FfichaGuardar/opc2")
public ModelAndView FfichaGuardarEl(ModelMap map, @RequestParam("nombre_el") String nombre,
        @RequestParam("apellido_p_el") String apellido_p, @RequestParam("apellido_m_el") String apellido_m,
        @RequestParam("edad_el") String edad, @RequestParam("lugar_nac_el") String lugar_nac,
        @RequestParam("depa_nac_el") String depa_nac, @RequestParam("pais_nac_el") String pais_nac,
        @RequestParam("TipoDoc") String tipo_doc, @RequestParam("n_doc_el") String n_doc,
        @RequestParam("domicilio") String domicilio, @RequestParam("telefono") String telefono,
        @RequestParam("celular_el") String celular, @RequestParam("correo_el") String correo,
        @RequestParam("estCivil") String est_civil, @RequestParam("fechaMatri") String fecha_matri,
        @RequestParam("nivel_inst_el") String nivel_inst, @RequestParam("culm_nivel_el") String culm_nivel,
        @RequestParam("prof_el") String prof, @RequestParam("Trabajador_Depend_el") String trab_depend,
        @RequestParam(value = "ocup_act_dep_el", required = false) String ocup_actual,
        @RequestParam(value = "centro_trabajo_el", required = false) String centro_trabajo,
        @RequestParam(value = "dir_centro_el", required = false) String dir_centro,
        @RequestParam(value = "tel_centro_el", required = false) String tel_centro,
        @RequestParam(value = "ingreso_dep_el", required = false) String ingreso_dep,
        @RequestParam("Trabajador_Indep_el") String trab_indep,
        @RequestParam(value = "ocup_act_indep_el", required = false) String ocup_act_indep,
        @RequestParam(value = "ingreso_ind_el", required = false) String ingreso_ind,
        @RequestParam("seguro_salud_el") String seguro_salud, @RequestParam("tipo_seguro") String tipo_seguro,
        @RequestParam("seguro_vida_el") String seguro_vida, @RequestParam("sist_pen_el") String sist_pen,
        @RequestParam("est_salud_el") 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);
    }// ww  w.  j a v a2  s .com
    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() == 'M') {
            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) {
        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) {
        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_el";
    return new ModelAndView(pagina, map);
}