List of usage examples for javax.servlet.http HttpSession removeAttribute
public void removeAttribute(String name);
From source file:com.ssbusy.controller.catalog.CategoryController.java
@Override @SuppressWarnings("unchecked") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); MyCustomer customer = (MyCustomer) CustomerState.getCustomer(); HttpSession session = request.getSession(); MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode"); Boolean w_flag = Boolean.FALSE; // cookies/*from ww w.j a va 2 s .com*/ String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()); int count = 0;// ?? Cookie cookies[] = request.getCookies(); Boolean uiv2 = null; if (cookies != null) { for (Cookie c : cookies) { if (dateTime.equals(c.getName())) { count = Integer.valueOf(c.getValue()); break; // } else if ("uiv2".equals(c.getName())) { // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie } } } if (cookies != null) { for (Cookie c : cookies) { if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) { model.addObject("rember", c.getValue()); break; } } } // String uiParam = request.getParameter("uiv2"); // if (StringUtils.isNotEmpty(uiParam)) { // 1 param // uiv2 = Boolean.valueOf(uiParam); // Cookie c = new Cookie("uiv2", uiv2.toString()); // c.setPath("/"); // c.setMaxAge(60 * 60 * 24 * 360); // response.addCookie(c); // } else if (uiv2 == null) { uiv2 = Boolean.TRUE; // 3 default. // } session.setAttribute("uiv2", uiv2); // LOG.warn("uiv2=" + uiv2); if (myOfferCode != null) { if (customer.isRegistered()) giftService.updateOwnerCustomer(customer, myOfferCode); else myOfferCode = null; } else if (count < maxoffercodeCount) { myOfferCode = giftService.getgift(customer); if (myOfferCode != null) { if (customer.isAnonymous()) { session.setAttribute("bonusOfferCode", myOfferCode); model.addObject("bonusOfferCode", myOfferCode); myOfferCode = null; } } } if (myOfferCode != null) { session.removeAttribute("bonusOfferCode"); model.addObject("bonusOfferCode", myOfferCode); Cookie c = new Cookie(dateTime, String.valueOf(count + 1)); c.setPath("/"); c.setMaxAge(60 * 60 * 24); response.addCookie(c); LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr()); } if (request.getParameterMap().containsKey("facetField")) { // If we receive a facetField parameter, we need to convert the // field to the // product search criteria expected format. This is used in // multi-facet selection. We // will send a redirect to the appropriate URL to maintain canonical // URLs String fieldName = request.getParameter("facetField"); List<String> activeFieldFilters = new ArrayList<String>(); Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap()); for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, String[]> entry = iter.next(); String key = entry.getKey(); if (key.startsWith(fieldName + "-")) { activeFieldFilters.add(key.substring(key.indexOf('-') + 1)); iter.remove(); } } parameters.remove(ProductSearchCriteria.PAGE_NUMBER); parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()])); parameters.remove("facetField"); String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters); model.setViewName("redirect:" + newUrl); } else { // Else, if we received a GET to the category URL (either the user // clicked this link or we redirected // from the POST method, we can actually process the results Category category = (Category) request .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME); assert (category != null); List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category); ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets); String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING); ProductSearchResult result; List<FulfillmentLocation> locations = null; try { // if (customer != null && customer.getRegion() != null) { InventorySolrSearchServiceExtensionHandler.customerLocation .set(locations = customer.getRegion().getFulfillmentLocations()); } if (StringUtils.isNotBlank(searchTerm)) { result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria); } else { result = searchService.findProductsByCategory(category, searchCriteria); } } finally { InventorySolrSearchServiceExtensionHandler.customerLocation.remove(); } facetService.setActiveFacetResults(result.getFacets(), request); List<Product> products = result.getProducts(); if (products != null && products.size() > 0) { List<String> prodIds = new ArrayList<String>(products.size()); for (Product product : products) { prodIds.add(String.valueOf(product.getId())); } model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT)); // ?productinventories if (locations != null) { Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations); model.addObject("inventories", invs); } } model.addObject(PRODUCTS_ATTRIBUTE_NAME, products); model.addObject(CATEGORY_ATTRIBUTE_NAME, category); // facets List<SearchFacetDTO> facets = result.getFacets(); if (facets != null) { _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) { SearchFacetDTO dto = itr.next(); if (dto != null && dto.getFacetValues() != null) { for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) { if (searchFacetDTO != null) if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0) continue _nextFact; } } itr.remove(); } model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets()); } model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result); // TODO temp String view = category.getDisplayTemplate(); if (StringUtils.isEmpty(view)) view = getDefaultCategoryView(); if (request.getRequestURI().startsWith("/weixin/")) { view = "weixin/catalog/w_category_item"; w_flag = Boolean.TRUE; } if (uiv2) { if ("layout/home".equals(view)) view = "v2/home"; else { if (!view.startsWith("activity") && !view.startsWith("weixin/")) { view = "v2/" + view; } } } session.setAttribute("w_flag", w_flag); model.setViewName(view); } // if (isAjaxRequest(request)) { // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM); // model.addObject("ajax", Boolean.TRUE); // } return model; }
From source file:controllers.controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www .ja va 2 s.c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception { request.setCharacterEncoding(PageParameters.getParameter("charset").toString()); response.setCharacterEncoding(PageParameters.getParameter("charset").toString()); response.setContentType(PageParameters.getParameter("servletSetContentType").toString()); response.setHeader("Cache-Control", "no-cache"); HttpSession session; PrintWriter out; QUID quid; LinkedList<String> userAccess; quid = new QUID(); quid.setRequest(request); session = request.getSession(true); SessionUtil.addIfNotExistSession(session); out = response.getWriter(); try { try { if (PageParameters.getParameter("SiteOnMaintenance").equals("true")) { response.sendRedirect(PageParameters.getParameter("SiteOnMaintenanceURL").toString()); } else // <editor-fold defaultstate="collapsed" desc="Realizando LogIn de usuario"> //si proviene de la pgina de login aqui se detectara y se validara al usuario { if (request.getParameter("LogInPage") != null) { //aqui consulta el usuario en Base de Datos. // if (request.getParameter("captcha").equals(session.getAttribute("captcha")) && request.getParameter("captcha").equalsIgnoreCase("") == false) { if (true) { if (request.getParameter("user").equalsIgnoreCase("") == false && request.getParameter("pass").equalsIgnoreCase("") == false) { LinkedList infoUser = null; LinkedList<String> accessos = null; infoUser = quid.selectIdUsuario(request.getParameter("user"), request.getParameter("pass"), "ACTIVO"); if (infoUser != null) { session.removeAttribute("captcha"); SessionUtil.clearNCloseSession(session); session = request.getSession(true); session.setAttribute("tipoRol", infoUser.get(3)); session.setAttribute("userID", infoUser.get(0)); session.setAttribute("userName", infoUser.get(1)); session.setAttribute("FK_ID_Plantel", infoUser.get(2)); //asignacion de permisos //LinkedList<String> accessos = new LinkedList(); accessos = quid.selectPermisosUsuarios(infoUser.get(0).toString()); session.setMaxInactiveInterval(3 * 60 * 60); // 2hrs * 60 min * 60 seg //accesos del usaurio y parametros del mismo session.setAttribute("userAccess", accessos); SessionUtil.addIfNotExistSession(session); request.getRequestDispatcher(PageParameters.getParameter("mainMenuServLet")) .forward(request, response); } else { this.getServletConfig().getServletContext().getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Usuario o password incorrectos.&url=/" + PageParameters.getParameter("appName") + PageParameters.getParameter("LogInPage")).forward(request, response); } } else { this.getServletConfig().getServletContext().getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirectFull.jsp?title=Error&type=error&msg=El usuario y password no pueden estar vacos.&url=/" + PageParameters.getParameter("appName") + PageParameters.getParameter("LogInPage")).forward(request, response); } } else { this.getServletConfig().getServletContext().getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Cdigo de verificacin incorrecto.&url=/" + PageParameters.getParameter("appName") + PageParameters.getParameter("LogInPage")).forward(request, response); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Validando que sea un usuario logeado"> } else if (session.getAttribute("userAccess") == null) { response.sendRedirect("/" + PageParameters.getParameter("appName") + PageParameters.getParameter("LogInPage")); // </editor-fold> } else // <editor-fold defaultstate="collapsed" desc="Cerrando sesion"> { if (request.getParameter("exit") != null) { //session.invalidate(); this.clearNCloseSession(session, request, response, quid, out); //quid.insertLog("SysLogOut", "exit", "", "", "", ""); response.sendRedirect(PageParameters.getParameter("mainContext") + PageParameters.getParameter("LogInPage").toString()); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Revisando de que form viene"> } else if (request.getParameter("FormForm") != null) { switch (request.getParameter("FormForm")) { case "agregaFichaTecnica": this.agregaFichaTecnica(session, request, response, quid, out); break; case "modificaFichaTecnica": this.modificaFichaTecnica(session, request, response, quid, out); break; case "agregaEtapaDesarrollo": this.agregaEtapaDesarrollo(session, request, response, quid, out); break; case "modificaEtapaDesarrollo": this.modificaEtapaDesarrollo(session, request, response, quid, out); break; case "eliminaStage": this.eliminaEtapa(session, request, response, quid, out); break; case "agregaActivity": this.agregaActividad(session, request, response, quid, out); break; case "modificaActivity": this.modificaActividad(session, request, response, quid, out); break; case "eliminaActivity": this.eliminaActividad(session, request, response, quid, out); break; case "deleteObjetoArchivo": this.deleteObjetoArchivo(session, request, response, quid, out); break; } // </editor-fold> } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { this.subirArchivo(session, request, response, quid, out); } else { out.println("UPS.... Algo malo ha pasado"); } } } } catch (Exception ex) { Logger.getLogger(controller.class.getName()).log(Level.SEVERE, null, ex); } } finally { quid = null; out.close(); } }
From source file:com.rr.wabshs.ui.surveys.surveyController.java
/** * The '/startSessionSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted client id//from w w w. j a va 2s.c o m * @param v The encrypted decryption key * @param s The id of the selected survey * * @param session * @return * @throws Exception */ @RequestMapping(value = "/startSessionSurvey", method = RequestMethod.GET) public ModelAndView startSessionSurvey(@RequestParam(value = "i", required = true) String i, @RequestParam(value = "v", required = true) String v, @RequestParam(value = "j", required = true) String j, @RequestParam(value = "x", required = true) String x, @RequestParam(value = "z", required = true) Integer z, HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedProgramProfiles") != null) { session.removeAttribute("selectedProgramProfiles"); } session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>()); if (session.getAttribute("secondTierEntities") != null) { session.removeAttribute("secondTierEntities"); } session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); int clientId = 0; int surveyId = 0; /* Get the submitted surveys for the selected survey type */ if (!"".equals(i) && i != null && !"".equals(v) && v != null) { /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); surveyId = Integer.parseInt(result[0].substring(4)); } if (!"".equals(j) && j != null && !"".equals(x) && x != null) { /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(j, x); String[] result = obj.toString().split((",")); clientId = Integer.parseInt(result[0].substring(4)); } if (surveyId > 0) { surveys surveyDetails = surveyManager.getSurveyDetails(surveyId); /* Make sure the survey is part of this program and active */ if (surveyDetails.getProgramId() != programId || surveyDetails.getStatus() == false) { /* Redirect back to the survey list page */ } /* Set up the survey */ else { survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(surveyId); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(0); survey.setSessionId(z); encryptObject encrypt = new encryptObject(); Map<String, String> map; map = new HashMap<String, String>(); map.put("id", Integer.toString(surveyId)); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(surveyId, false, 0, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(surveyId, true, 1, clientId, 0, 0, 0, 0, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setPageId(currentPage.getId()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); if (surveyDetails.isAssociateToProgram()) { mav.addObject("showPrograms", true); } else { mav.addObject("showPrograms", false); } } } else { /* Redirect back to the survey list page */ } User userDetails = (User) session.getAttribute("userDetails"); mav.addObject("selSurvey", surveyId); mav.addObject("currentPage", 1); mav.addObject("currPageNum", 1); mav.addObject("qNum", 0); mav.addObject("disabled", false); return mav; }
From source file:com.aurel.track.prop.LoginBL.java
/** * Create a JSON string as a response to a login attempt or calling the login page. * @param username/*from ww w .j a va2s . c o m*/ * @param password * @param nonce * @param usingContainerBasedAuthentication * @param springAuthenticated * @param request * @param errors * @param httpSession * @param forwardUrl * @param motd * @param isMobileApplication * @param locale * @param mobileApplicationVersionNo * @param redirectMapEntry * @return the JSON response */ public static StringBuilder createLoginResponseJSON(String _username, String password, String nonce, boolean usingContainerBasedAuthentication, boolean springAuthenticated, HttpServletRequest request, List<LabelValueBean> errors, HttpSession httpSession, String forwardUrl, TMotdBean motd, boolean isMobileApplication, Locale locale, Integer mobileApplicationVersionNo, String redirectMapEntry) { StringBuilder sb = new StringBuilder(); sb.append("{"); Integer mappingEnum = 0; Map envResult = LoginBL.setEnvironment(_username, password, nonce, request, ActionContext.getContext().getSession(), false, usingContainerBasedAuthentication, springAuthenticated); mappingEnum = (Integer) envResult.get("mappingEnum"); errors = (List<LabelValueBean>) envResult.get("errors"); if (errors != null && errors.size() > 0) { JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, false); sb.append(DATABRACE); JSONUtility.appendLabelValueBeanList(sb, "errors", errors); } else { JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true); sb.append(DATABRACE); } JSONUtility.appendStringValue(sb, "nonce", nonce); JSONUtility.appendStringValue(sb, "j_username", _username); BanProcessor bp = BanProcessor.getBanProcessor(); String ipNumber = request.getRemoteAddr(); redirectMapEntry = "itemNavigator"; TPersonBean personBean = (TPersonBean) httpSession.getAttribute(Constants.USER_KEY); if (personBean != null && personBean.getHomePage() != null && personBean.getHomePage().trim().length() > 0) { redirectMapEntry = personBean.getHomePage(); } String redirectURL = redirectMapEntry + DOTACTION; Boolean firstTimeEver = false; switch (mappingEnum) { case 1: redirectURL = ""; break; case 2: // could not authenticate user bp.markBadAttempt(ipNumber); if (bp.isBanned(ipNumber)) { ACCESSLOGGER .warn("LOGON: Access attempt from banned IP " + ipNumber + " at " + new Date().toString()); JSONUtility.appendBooleanValue(sb, "banned", true); redirectMapEntry = "banned"; redirectURL = redirectMapEntry + DOTACTION; } break; case 3: case 4: // can't login, maintenance mode break; case 5: case 6: // license expired, too many login attempts // and not admin user. Admin can always log in // even with expired license. JSONUtility.appendBooleanValue(sb, "continyou", false); break; case 7: forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD); if (forwardUrl != null) { LOGGER.debug("Forward URL found :" + forwardUrl); httpSession.removeAttribute(Constants.POSTLOGINFORWARD); } redirectURL = forwardUrl; break; case 8: // First time and system administrator bp.removeBanEntry(ipNumber); redirectMapEntry = "admin"; redirectURL = redirectMapEntry + DOTACTION; JSONUtility.appendBooleanValue(sb, "continyou", true); break; case 9: // Everything is fine, we go to the itemNavigator bp.removeBanEntry(ipNumber); redirectURL = redirectMapEntry + DOTACTION; JSONUtility.appendBooleanValue(sb, "continyou", true); break; case 10: // Event handler binding continue ?? redirectURL = ""; break; case 18: // First login ever bp.removeBanEntry(ipNumber); firstTimeEver = true; if (ApplicationBean.getInstance().getLicenseManager() != null) { firstTimeEver = false; } redirectMapEntry = "admin"; redirectURL = redirectMapEntry + DOTACTION; JSONUtility.appendBooleanValue(sb, "continyou", true); break; case 19: // out of memory (<50 MB) break; default: break; } return assembleJSONPart2(sb, locale, firstTimeEver, personBean, httpSession, redirectURL, mobileApplicationVersionNo, motd); }
From source file:com.rr.wabshs.ui.surveys.surveyController.java
/** * The '/startSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted client id//from w w w. ja v a 2 s . c o m * @param v The encrypted decryption key * @param s The id of the selected survey * * @param session * @return * @throws Exception */ @RequestMapping(value = "/startSurvey", method = RequestMethod.POST) public ModelAndView startSurvey(@RequestParam(value = "s", required = false) String s, @RequestParam(value = "i", required = false) String i, @RequestParam(value = "v", required = false) String v, @RequestParam(value = "selectedEntities", required = false) List<Integer> selectedEntities, HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedProgramProfiles") != null) { session.removeAttribute("selectedProgramProfiles"); } session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>()); if (session.getAttribute("secondTierEntities") != null) { session.removeAttribute("secondTierEntities"); } session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); if (session.getAttribute("selectedExtras") != null) { session.removeAttribute("selectedExtras"); } session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>()); int clientId = 0; int surveyId = 0; /* Get the submitted surveys for the selected survey type */ if (!"".equals(i) && i != null && !"".equals(v) && v != null) { /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); surveyId = Integer.parseInt(result[0].substring(4)); } else { surveyId = Integer.parseInt(s); } if (surveyId > 0) { surveys surveyDetails = surveyManager.getSurveyDetails(surveyId); mav.addObject("surveyTag", surveyDetails.getSurveyTag()); /* Make sure the survey is part of this program and active */ if (surveyDetails.getProgramId() != programId || surveyDetails.getStatus() == false) { /* Redirect back to the survey list page */ } /* Set up the survey */ else { survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(surveyId); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(0); encryptObject encrypt = new encryptObject(); Map<String, String> map; map = new HashMap<String, String>(); map.put("id", Integer.toString(surveyId)); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(surveyId, false, 0, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(surveyId, true, 1, clientId, 0, 0, 0, 0, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setPageId(currentPage.getId()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); if (surveyDetails.isAssociateToProgram()) { mav.addObject("showPrograms", true); } else { mav.addObject("showPrograms", false); } } } else { /* Redirect back to the survey list page */ } User userDetails = (User) session.getAttribute("userDetails"); /* Get a list of available tier 3 for the selected tier 2's */ if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) { encryptObject encrypt = new encryptObject(); Map<String, String> map; List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session .getAttribute("secondTierEntities"); for (Integer entity : selectedEntities) { List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>(); secondTierEntities secondTierEntity = new secondTierEntities(); secondTierEntity.setId(entity); programHierarchyDetails secondTierEntityDetails = hierarchymanager .getProgramHierarchyItemDetails(entity); secondTierEntity.setName(secondTierEntityDetails.getName()); Integer userId = 0; if (userDetails.getRoleId() == 3) { userId = userDetails.getId(); } List tier3Entities = hierarchymanager.getActiveProgramOrgHierarchyItems(programId, 3, entity, userId); if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) { for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); thirdTierEntities thirdTierEntity = new thirdTierEntities(); thirdTierEntity.setId(Integer.parseInt(row[0].toString())); thirdTierEntity.setName(row[1].toString()); //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(Integer.parseInt(row[0].toString()))); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); thirdTierEntity.setEncryptedId(encrypted[0]); thirdTierEntity.setEncryptedSecret(encrypted[1]); tier3EntityList.add(thirdTierEntity); } secondTierEntity.setTier3EntityList(tier3EntityList); } tier2EntityList.add(secondTierEntity); } mav.addObject("seltier2EntityList", tier2EntityList); } mav.addObject("selSurvey", surveyId); mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", "")); mav.addObject("currentPage", 1); mav.addObject("currPageNum", 1); mav.addObject("qNum", 0); mav.addObject("disabled", false); return mav; }
From source file:fr.paris.lutece.plugins.calendar.web.CalendarJspBean.java
/** * Process Event creation/*w w w. ja v a 2s .c o m*/ * * @param request The Http request * @return URL */ public String doCreateEvent(HttpServletRequest request) { String strJspReturn = StringUtils.EMPTY; String strCalendarId = request.getParameter(Constants.PARAMETER_CALENDAR_ID); String strPeriodicity = request.getParameter(Constants.PARAMETER_PERIODICITY); if (StringUtils.isNotBlank(strCalendarId) && StringUtils.isNumeric(strCalendarId) && StringUtils.isNotBlank(strPeriodicity) && StringUtils.isNumeric(strPeriodicity)) { //Retrieving parameters from form int nCalendarId = Integer.parseInt(strCalendarId); int nPeriodicity = Integer.parseInt(strPeriodicity); String strEventDateEnd = request.getParameter(Constants.PARAMETER_EVENT_DATE_END); String strTimeStart = request.getParameter(Constants.PARAMETER_EVENT_TIME_START); String strTimeEnd = request.getParameter(Constants.PARAMETER_EVENT_TIME_END); String strOccurrence = request.getParameter(Constants.PARAMETER_OCCURRENCE); String strEventTitle = request.getParameter(Constants.PARAMETER_EVENT_TITLE); String strDate = request.getParameter(Constants.PARAMETER_EVENT_DATE); String strNotify = request.getParameter(Constants.PARAMETER_NOTIFY); //Retrieve the features of an event from form String strDescription = request.getParameter(Constants.PARAMETER_DESCRIPTION); String strEventTags = request.getParameter(Constants.PARAMETER_EVENT_TAGS).trim(); String strLocationAddress = request.getParameter(Constants.PARAMETER_EVENT_LOCATION_ADDRESS).trim(); String strLocationTown = request.getParameter(Constants.PARAMETER_LOCATION_TOWN).trim(); String strLocation = request.getParameter(Constants.PARAMETER_LOCATION).trim(); String strLocationZip = request.getParameter(Constants.PARAMETER_LOCATION_ZIP).trim(); String strLinkUrl = request.getParameter(Constants.PARAMETER_EVENT_LINK_URL).trim(); String strDocumentId = request.getParameter(Constants.PARAMETER_EVENT_DOCUMENT_ID).trim(); String strPageUrl = request.getParameter(Constants.PARAMETER_EVENT_PAGE_URL).trim(); String strTopEvent = request.getParameter(Constants.PARAMETER_EVENT_TOP_EVENT).trim(); String strMapUrl = request.getParameter(Constants.PARAMETER_EVENT_MAP_URL).trim(); //Retrieving the excluded days String[] arrayExcludedDays = request.getParameterValues(Constants.PARAMETER_EXCLUDED_DAYS); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(Constants.PARAMETER_EVENT_IMAGE); String[] arrayCategory = request.getParameterValues(Constants.PARAMETER_CATEGORY); //Categories List<Category> listCategories = new ArrayList<Category>(); if (arrayCategory != null) { for (String strIdCategory : arrayCategory) { Category category = CategoryHome.find(Integer.parseInt(strIdCategory), getPlugin()); if (category != null) { listCategories.add(category); } } } String[] strTabEventTags = null; // Mandatory field if (StringUtils.isBlank(strDate) || StringUtils.isBlank(strEventTitle) || StringUtils.isBlank(strDescription)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } if (StringUtils.isNotBlank(strEventTags) && strEventTags.length() > 0) { //Test if there aren't special characters in tag list boolean isAllowedExp = Pattern.matches(PROPERTY_TAGS_REGEXP, strEventTags); if (!isAllowedExp) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_TAG, AdminMessage.TYPE_STOP); } strTabEventTags = strEventTags.split("\\s"); } //Convert the date in form to a java.util.Date object Date dateEvent = DateUtil.formatDate(strDate, getLocale()); if ((dateEvent == null) || !Utils.isValidDate(dateEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } Date dateEndEvent = null; if (StringUtils.isNotBlank(strEventDateEnd)) { dateEndEvent = DateUtil.formatDate(strEventDateEnd, getLocale()); if ((dateEndEvent == null) || !Utils.isValidDate(dateEndEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } } //the number of occurrence is 1 by default int nOccurrence = 1; if ((strOccurrence.length() > 0) && !strOccurrence.equals("")) { try { nOccurrence = Integer.parseInt(strOccurrence); } catch (NumberFormatException e) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_OCCURRENCE_NUMBER, AdminMessage.TYPE_STOP); } } int nDocumentId = -1; if ((strDocumentId.length() > 0) && !strDocumentId.equals("")) { try { nDocumentId = Integer.parseInt(strDocumentId); } catch (NumberFormatException e) { return AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_OCCURRENCE_NUMBER, AdminMessage.TYPE_STOP); } } if (!Utils.checkTime(strTimeStart) || !Utils.checkTime(strTimeEnd)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_TIMEFORMAT, AdminMessage.TYPE_STOP); } //If a date end is chosen if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1) && StringUtils.isNotBlank(strEventDateEnd)) { if (dateEndEvent.before(dateEvent)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATE_END_BEFORE, AdminMessage.TYPE_STOP); } nPeriodicity = 0; nOccurrence = Utils.getOccurrenceWithinTwoDates(dateEvent, dateEndEvent, arrayExcludedDays); } else if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 1) && StringUtils.isBlank(strEventDateEnd)) { return AdminMessageService.getMessageUrl(request, Constants.PROPERTY_MESSAGE_DATEFORMAT, AdminMessage.TYPE_STOP); } //If a date end is not chosen if ((Integer.parseInt(request.getParameter(Constants.PARAMETER_RADIO_PERIODICITY)) == 0) && StringUtils.isBlank(strEventDateEnd)) { dateEndEvent = Utils.getDateForward(dateEvent, nPeriodicity, nOccurrence, arrayExcludedDays); if (dateEndEvent.before(dateEvent)) { nOccurrence = 0; dateEndEvent = dateEvent; } } SimpleEvent event = new SimpleEvent(); event.setDate(dateEvent); event.setDateEnd(dateEndEvent); event.setDateTimeStart(strTimeStart); event.setDateTimeEnd(strTimeEnd); event.setTitle(strEventTitle); event.setOccurrence(nOccurrence); event.setPeriodicity(nPeriodicity); event.setDescription(strDescription); if (item.getSize() == 0) { HttpSession session = request.getSession(true); if (session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE) != null && session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE) != null) { ImageResource imageResource = new ImageResource(); imageResource.setImage( (byte[]) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE)); imageResource.setMimeType( (String) session.getAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE)); event.setImageResource(imageResource); session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE); session.removeAttribute(ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE); } } if (item.getSize() >= 1) { ImageResource imageResource = new ImageResource(); imageResource.setImage(item.get()); imageResource.setMimeType(item.getContentType()); event.setImageResource(imageResource); } event.setTags(strTabEventTags); event.setLocationAddress(strLocationAddress); event.setLocation(strLocation); event.setLocationTown(strLocationTown); event.setLocationZip(strLocationZip); event.setLinkUrl(strLinkUrl); event.setPageUrl(strPageUrl); event.setTopEvent(Integer.parseInt(strTopEvent)); event.setMapUrl(strMapUrl); event.setDocumentId(nDocumentId); event.setListCategories(listCategories); event.setExcludedDays(arrayExcludedDays); event.setIdCalendar(nCalendarId); _eventListService.doAddEvent(event, null, getPlugin()); List<OccurrenceEvent> listOccurencesEvent = _eventListService.getOccurrenceEvents(nCalendarId, event.getId(), Constants.SORT_ASC, getPlugin()); for (OccurrenceEvent occ : listOccurencesEvent) { IndexationService.addIndexerAction(Integer.toString(occ.getId()), AppPropertiesService.getProperty(CalendarIndexer.PROPERTY_INDEXER_NAME), IndexerAction.TASK_CREATE); CalendarIndexerUtils.addIndexerAction(occ.getId(), IndexerAction.TASK_CREATE); } /* * IndexationService.addIndexerAction( Constants.EMPTY_STRING + * nCalendarId * ,AppPropertiesService.getProperty( * CalendarIndexer.PROPERTY_INDEXER_NAME ), * IndexerAction.TASK_CREATE ); */ boolean isNotify = Boolean.parseBoolean(strNotify); if (isNotify) { int nSubscriber = _agendaSubscriberService.getSubscriberNumber(nCalendarId, getPlugin()); if (nSubscriber > 0) { Collection<CalendarSubscriber> calendarSubscribers = _agendaSubscriberService .getSubscribers(nCalendarId, getPlugin()); _agendaSubscriberService.sendSubscriberMail(request, calendarSubscribers, event, nCalendarId); } } strJspReturn = AppPathService.getBaseUrl(request) + JSP_EVENT_LIST2 + nCalendarId; } else { strJspReturn = AdminMessageService.getMessageUrl(request, MESSAGE_INVALID_NUMBER_FORMAT, AdminMessage.TYPE_STOP); } return strJspReturn; }
From source file:com.mimp.controllers.familia.java
@RequestMapping(value = "/Fcambiarcontra", method = RequestMethod.GET) public ModelAndView Fcambiarcontra_GET(ModelMap map, HttpSession session) { Familia usuario = (Familia) session.getAttribute("usuario"); String mensaje = ""; if (usuario == null) { mensaje = "La sesin ha finalizado. Favor identificarse nuevamente"; map.addAttribute("mensaje", mensaje); return new ModelAndView("login", map); }//w w w. j a v a2 s. c o m if (session.getAttribute("oldpass") != null && session.getAttribute("newpass") != null && session.getAttribute("newpassconf") != null) { String oldpass = (String) session.getAttribute("oldpass"); String newpass = (String) session.getAttribute("newpass"); String newpassconf = (String) session.getAttribute("newpassconf"); oldpass = DigestUtils.sha512Hex(oldpass); if (usuario.getPass().equals(oldpass)) { if (newpass.equals(newpassconf)) { newpass = DigestUtils.sha512Hex(newpass); usuario.setPass(newpass); ServicioFamilia.CambiaPass(usuario); mensaje = "La contrasea se ha cambiado con exito."; } else { mensaje = "Las contraseas no coinciden. Favor de reescribir la nueva contrasea."; } } else { mensaje = "Contrasea de usuario incorrecta. Ingrese nuevamente."; } String pagina = "/Familia/contra_familia"; map.addAttribute("mensaje", mensaje); session.removeAttribute("oldpass"); session.removeAttribute("newpass"); session.removeAttribute("newpassconf"); return new ModelAndView(pagina, map); } else { String pagina = "/Familia/inicio_familia"; return new ModelAndView(pagina, map); } }
From source file:com.lrodriguez.SVNBrowser.java
private void doChangeUrl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); logDebug("dispatching changeUrl"); SVNHttpSession svnsession = (SVNHttpSession) session.getAttribute(SVNSESSION); if (svnsession == null) { request.setAttribute(ERROR,//from w w w . j a va 2 s. co m "svnsession is null, try deleting your cookies and accessing SVNBrowser with no parameters"); request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; } String webappRoot = this.getServletContext().getRealPath("/") == null ? getInitParameter(WEBAPP_ROOT) : this.getServletContext().getRealPath("/"); SVNHttpSession newSvnsession = new SVNHttpSession(request.getParameter(CHANGE_URL), getInitParameter(USER_NAME), getInitParameter("password"), webappRoot, getInitParameter(REPOSITORY_DIR)); logDebug("initializing SVNRepository.\nrepositoryURL=" + newSvnsession.getRepositoryURL() + "\nuser=" + newSvnsession.getUserName()); try { newSvnsession.init(); } catch (SVNException e) { e.printStackTrace(); request.setAttribute(ERROR, e.getErrorMessage()); request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; } session.setAttribute(SVNSESSION, newSvnsession); List branches = getAllBranches(request); if (request.getAttribute(ERROR) != null) { session.setAttribute(SVNSESSION, newSvnsession);//revert to original session request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; } session.setAttribute(BRANCHES, branches); logDebug("closing existing svnsession "); svnsession.getRepository().closeSession(); session.setAttribute(REPOSITORY_URL, request.getParameter(CHANGE_URL));//set the new URL in the session (used by JSP) session.removeAttribute(CURRENT_BRANCH); //currentBranch = persistCurrentBranch(request);//set the current branch //List uniqueEntries = getUniqueEntries(request, startDate, endDate); //if(request.getAttribute(ERROR)!= null){ // request.getRequestDispatcher("index.jsp").forward(request, response); // return; //} //uniqueEntries = filterListByCurrentBranch(uniqueEntries, currentBranch); //Collections.sort(uniqueEntries, comparator); session.setAttribute(UNIQUE_ENTRIES, null); request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; }
From source file:controller.controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a v a 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String action = request.getParameter("action"); String type = request.getParameter("type"); System.out.println(action); if (action.equals("getproduct")) { System.out.println(type); DAO dao = new DAO(); ArrayList<pro> product = dao.getProduct(type); session.setAttribute("product", product); dispatcher(request, response, "tablet.jsp"); } if (action.equals("productDetail")) { int id = Integer.parseInt(request.getParameter("id")); DAO detail = new DAO(); pro productDetail = detail.productDetail(id); session.setAttribute("productdetail", productDetail); dispatcher(request, response, "view.jsp"); } if (action.equals("AddtoCart")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { System.out.println("cart: " + null); cart = new shoppingCart(); } System.out.println("product " + session.getAttribute("productdetail")); pro temp = (pro) session.getAttribute("productdetail"); int qu = temp.getQuantity(); System.out.println("qu " + qu); if (qu > 0) { --qu; System.out.println("qu " + qu); temp.setQuantity(qu); //int quantity = Integer.parseInt(request.getParameter("quantity")); cart.addProduct(temp); System.out.println("cart " + cart.getProducts().size()); } session.setAttribute("cart", cart); } if (action.equals("checkout")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { cart = new shoppingCart(); } session.setAttribute("cart", cart); dispatcher(request, response, "checkout.jsp"); } if (action.equals("order")) { shoppingCart cart = (shoppingCart) session.getAttribute("cart"); String accid = (String) session.getAttribute("login"); DAO dao = new DAO(); dao.order(cart, accid); session.removeAttribute("cart"); response.sendRedirect("index.jsp"); } if (action.equals("upload")) { String dirNames = "D:\\Task\\IU\\Web Application Development\\New\\Final project\\ECommerceProject"; String user = (String) session.getAttribute("login"); String fileName = null; boolean isMultiPArt = ServletFileUpload.isMultipartContent(request); if (isMultiPArt) { System.out.println(1); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); File theDir = new File(dirNames + File.separator + user); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + user); boolean result = false; try { theDir.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String[] url = new String[5]; int cnt = 0; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path: " + fileName); String realPath = dirNames + File.separator + user + File.separator + fileName; System.out.println("realPath: " + realPath); File savedFile = new File(realPath); item.write(savedFile); url[cnt] = "./database" + File.separator + user + File.separator + fileName; ++cnt; } catch (Exception e) { e.printStackTrace(); } } } String name = (String) params.get("name"); String price = (String) params.get("price"); String quantity = (String) params.get("quantity"); String typepr = (String) params.get("type"); System.out.println(name + " " + price + " " + quantity + " " + typepr); DAO uploadReal = new DAO(); uploadReal.inserPro(name, price, quantity, typepr, url[0]); // newUser = new User(); // newUser.setEmail(Email); out.print(url[0]); String temp = ".\\User" + File.separator + user + File.separator + fileName; System.out.println("Temp " + temp); //Connector.editUser(myProfile.getEmail(), newUser); //response.sendRedirect("index.jsp"); dispatcher(request, response, "index.jsp"); } } } }
From source file:com.rr.wabshs.ui.surveys.surveyController.java
/** * The '/editSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted survey id/* ww w .j av a2 s. c o m*/ * @param v The encrypted decryption key * * @param session * @return * @throws Exception */ @RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET) public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletRequest request, @RequestParam(value = "sessionId", required = false) Integer sessionId) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedProgramProfiles") != null) { session.removeAttribute("selectedProgramProfiles"); } session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>()); if (session.getAttribute("secondTierEntities") != null) { session.removeAttribute("secondTierEntities"); } session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); if (session.getAttribute("selectedExtras") != null) { session.removeAttribute("selectedExtras"); } session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>()); int clientId = 0; /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); int submittedSurveyId = Integer.parseInt(result[0].substring(4)); /* Get the survey details */ submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId); surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId()); mav.addObject("surveyTag", surveyDetails.getSurveyTag()); if (surveyDetails.isAssociateToProgram()) { mav.addObject("showPrograms", true); } else { mav.addObject("showPrograms", false); } User userDetails = (User) session.getAttribute("userDetails"); survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(submittedSurveyDetails.getSurveyId()); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(submittedSurveyId); survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails)); encryptObject encrypt = new encryptObject(); Map<String, String> map; //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(submittedSurveyDetails.getSurveyId())); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1, clientId, 0, 0, submittedSurveyId, 0, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); survey.setPageId(currentPage.getId()); /* Need to update any date functions */ if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) { for (SurveyQuestions question : survey.getSurveyPageQuestions()) { if (question.getAnswerTypeId() == 6) { if (question.getQuestionValue().length() > 0 && !question.getQuestionValue().contains("^^^^^")) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy"); SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy"); SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy"); SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy"); SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy"); SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy"); SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy"); Date formattedDate; try { formattedDate = df.parse(question.getQuestionValue()); } catch (Exception ex) { try { formattedDate = df2.parse(question.getQuestionValue()); } catch (Exception ex2) { try { formattedDate = df3.parse(question.getQuestionValue()); } catch (Exception ex3) { try { formattedDate = df4.parse(question.getQuestionValue()); } catch (Exception ex4) { try { formattedDate = df5.parse(question.getQuestionValue()); } catch (Exception ex5) { try { formattedDate = df6.parse(question.getQuestionValue()); } catch (Exception ex6) { try { formattedDate = df7.parse(question.getQuestionValue()); } catch (Exception ex7) { try { formattedDate = df8.parse(question.getQuestionValue()); } catch (Exception ex8) { formattedDate = df9.parse(question.getQuestionValue()); } } } } } } } } if (question.getDateFormatType() == 2) { //dd/mm/yyyy df.applyPattern("dd/MM/yyyy"); } else { //mm/dd/yyyy df.applyPattern("MM/dd/yyyy"); } String formattedDateasString = df.format(formattedDate); question.setQuestionValue(formattedDateasString); } } } } if (sessionId != null && sessionId > 0) { survey.setSessionId(sessionId); } mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId); /* Get a list of available schools for the selected districts */ if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) { List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session .getAttribute("secondTierEntities"); for (Integer entityId : selectedEntities) { List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>(); secondTierEntities secondTierEntity = new secondTierEntities(); secondTierEntity.setId(entityId); programHierarchyDetails secondTierEntityDetails = hierarchymanager .getProgramHierarchyItemDetails(entityId); secondTierEntity.setName(secondTierEntityDetails.getName()); Integer userId = 0; if (userDetails.getRoleId() == 3) { userId = userDetails.getId(); } List tier3Entities = hierarchymanager.getProgramOrgHierarchyItems(programId, 3, entityId, userId); if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) { for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); thirdTierEntities thirdTierEntity = new thirdTierEntities(); thirdTierEntity.setId(Integer.parseInt(row[0].toString())); thirdTierEntity.setName(row[1].toString()); //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(Integer.parseInt(row[0].toString()))); map.put("topSecret", topSecret); String[] encrypted2 = encrypt.encryptObject(map); thirdTierEntity.setEncryptedId(encrypted2[0]); thirdTierEntity.setEncryptedSecret(encrypted2[1]); tier3EntityList.add(thirdTierEntity); } secondTierEntity.setTier3EntityList(tier3EntityList); } tier2EntityList.add(secondTierEntity); } mav.addObject("seltier2EntityList", tier2EntityList); } mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId()); mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", "")); mav.addObject("qNum", 0); mav.addObject("currPageNum", 1); boolean disabled = false; if ("/surveys/viewSurvey".equals(request.getServletPath())) { disabled = true; } mav.addObject("disabled", disabled); return mav; }