Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rr.familyPlanning.ui.adhoc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import com.registryKit.adhoc.adhocFields; import com.registryKit.adhoc.adhocManager; import com.registryKit.adhoc.adhocRequestCriteria; import com.registryKit.adhoc.adhocRequestViews; import com.registryKit.adhoc.adhocRequests; import com.registryKit.adhoc.adhocView; import com.registryKit.hierarchy.hierarchyManager; import com.registryKit.hierarchy.programHierarchyDetails; import com.registryKit.hierarchy.programOrgHierarchy; import com.registryKit.user.User; import com.registryKit.user.userActivityLog; import com.registryKit.user.userManager; import com.registryKit.user.userProgramModules; import com.rr.familyPlanning.ui.security.decryptObject; import com.rr.familyPlanning.ui.security.encryptObject; /** * * @author gchan */ @Controller @RequestMapping("/adhoc") public class adhocController { private static Integer moduleId = 22; @Autowired private userManager usermanager; @Autowired private hierarchyManager hierarchymanager; @Autowired private adhocManager adhocmanager; @Value("${programId}") private Integer programId; @Value("${topSecret}") private String topSecret; private static boolean allowCreate = false; private static boolean allowEdit = false; private static boolean allowDelete = false; int hasPermission = 1; /** * The '' request will display the list of partners. * * @param request * @param response * @return the profile list view * @throws Exception */ @RequestMapping(value = { "", "/list" }, method = RequestMethod.GET) public ModelAndView listReports(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/adhocList"); /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); /* Get user permissions */ userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(), moduleId); int userId = userDetails.getId(); if (userDetails.getRoleId() == 2) { allowCreate = true; allowEdit = true; allowDelete = true; userId = 0; } else { if (modulePermissions == null) { hasPermission = 2; } else { allowCreate = modulePermissions.isAllowCreate(); allowDelete = modulePermissions.isAllowDelete(); allowEdit = modulePermissions.isAllowEdit(); } } mav.addObject("allowCreate", allowCreate); mav.addObject("allowDelete", allowDelete); mav.addObject("allowEdit", allowEdit); List<adhocRequests> requests = adhocmanager.getAdhocRequests(programId, userId); String requestIds = ""; if (requests != null) { for (adhocRequests adhocRequest : requests) { requestIds = requestIds + adhocRequest.getId() + " "; 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(adhocRequest.getId())); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); adhocRequest.setEncryptedId(encrypted[0]); adhocRequest.setEncryptedSecret(encrypted[1]); } } /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/list"); ual.setRequestMethod("GET"); ual.setMethodAccessed("listReports"); ual.setModuleId(moduleId); ual.setMiscNotes("hasPermission:" + hasPermission + "^^^^^requestIds:" + requestIds); ual.setProgramId(programId); usermanager.saveUserActivityLog(ual); mav.addObject("requests", requests); return mav; } @RequestMapping(value = { "/request" }, method = RequestMethod.GET) public ModelAndView reportRequestForm(HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/adhocRequest"); /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); /* Get user permissions */ userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(), moduleId); if (userDetails.getRoleId() == 2) { allowCreate = true; allowEdit = true; allowDelete = true; } else { if (modulePermissions == null) { hasPermission = 2; } else { allowCreate = modulePermissions.isAllowCreate(); allowDelete = modulePermissions.isAllowDelete(); allowEdit = modulePermissions.isAllowEdit(); } } mav.addObject("allowCreate", allowCreate); mav.addObject("allowDelete", allowDelete); mav.addObject("allowEdit", allowEdit); List<programOrgHierarchy> orgHierarchyList = hierarchymanager.getProgramOrgHierarchy(programId); //entity 1 items for (programOrgHierarchy hierarchy : orgHierarchyList) { if (userDetails.getRoleId() != 3) { List<programHierarchyDetails> hierarchyItems = hierarchymanager .getProgramHierarchyItemsForStatus(hierarchy.getId(), 0, true); hierarchy.setProgramHierarchyDetails(hierarchyItems); } else { List<programHierarchyDetails> hierarchyItems = hierarchymanager .getProgramHierarchyItemsForStatus(hierarchy.getId(), userDetails.getId(), true); hierarchy.setProgramHierarchyDetails(hierarchyItems); } } mav.addObject("entity1List", orgHierarchyList.get(0).getProgramHierarchyDetails()); mav.addObject("entity2List", orgHierarchyList.get(1).getProgramHierarchyDetails()); mav.addObject("entity3List", orgHierarchyList.get(2).getProgramHierarchyDetails()); if (orgHierarchyList.get(0).getProgramHierarchyDetails().size() == 1) { mav.addObject("entityList", orgHierarchyList.get(1).getProgramHierarchyDetails()); mav.addObject("tier", 2); } List<programOrgHierarchy> programEntities = orgHierarchyList; mav.addObject("tier1Name", programEntities.get(0).getName()); mav.addObject("tier1Id", programEntities.get(0).getId()); mav.addObject("tier2Name", programEntities.get(1).getName()); mav.addObject("tier2Id", programEntities.get(1).getId()); mav.addObject("tier3Name", programEntities.get(2).getName()); Integer loggeduserId = 0; if (userDetails.getRoleId() != 2) { loggeduserId = userDetails.getId(); } /* Get a list of entity items for the selected entity */ List<programHierarchyDetails> entity1tems = hierarchymanager .getProgramHierarchyItemsActiveOnly(programEntities.get(0).getId(), loggeduserId); mav.addObject("entity1tems", entity1tems); List<programHierarchyDetails> entity2tems = hierarchymanager .getProgramHierarchyItemsActiveOnly(programEntities.get(1).getId(), loggeduserId); mav.addObject("entity2tems", entity2tems); List<programHierarchyDetails> entity3tems = hierarchymanager .getProgramHierarchyItemsActiveOnly(programEntities.get(2).getId(), loggeduserId); mav.addObject("entity3tems", entity3tems); mav.addObject("orgHierarchyList", orgHierarchyList); mav.addObject("entity1ListSize", orgHierarchyList.get(0).getProgramHierarchyDetails().size()); //get the fields List<adhocFields> fieldList = adhocmanager.getAdhocFieldsWithCWValues(programId); mav.addObject("fieldList", fieldList); /** * Log Here * **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/request"); ual.setRequestMethod("GET"); ual.setMethodAccessed("reportRequestForm"); ual.setModuleId(moduleId); ual.setMiscNotes("hasPermission:" + hasPermission); ual.setProgramId(programId); usermanager.saveUserActivityLog(ual); return mav; } @RequestMapping(value = "/saveReportRequest.do", method = { RequestMethod.POST }) public ModelAndView saveReportRequest(HttpSession session, @RequestParam(value = "reportTypeId", required = true) Integer reportTypeId, @RequestParam(value = "reportId", required = true) Integer reportId, @RequestParam(value = "entity1Ids", required = true) String entity1Ids, @RequestParam(value = "entity2Ids", required = true) String entity2Ids, @RequestParam(value = "entity3Ids", required = true) String entity3Ids, @RequestParam(value = "startDate", required = true) String startDate, @RequestParam(value = "endDate", required = true) String endDate, @RequestParam(value = "criteriaIds", required = true) String criteriaIds, @RequestParam(value = "criteriaValues", required = true) String criteriaValues, @RequestParam(value = "criteriaValidations", required = false) String criteriaValidations, @RequestParam(value = "criteriaSqlActions", required = false) String criteriaSqlActions, @RequestParam(value = "criteriaFieldTags", required = false) String criteriaFieldTags) throws Exception { User userDetails = (User) session.getAttribute("userDetails"); String reportFileExt = "pdf"; /** set report type report Id * UU 27/V 28 /UU * details (1)/summary(2) * if 27 & 1 = 3 27 & 2 = 4 * **/ if (reportTypeId == 27) { switch (reportId) { case 1: reportId = 3; break; case 2: reportId = 4; break; default: break; } } adhocRequests ar = new adhocRequests(); SimpleDateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy"); Date sd = dateformat.parse(startDate); Date ed = dateformat.parse(endDate); ar.setStartDateTime(sd); ar.setEndDateTime(ed); ar.setAdhocReportId(reportId); ar.setProgramId(programId); ar.setSystemUserId(userDetails.getId()); ar.setReportFileExt(reportFileExt); Integer adhocRequestId = adhocmanager.saveRequest(ar); //we set up and insert entities adhocmanager.saveEntities(entity3Ids, adhocRequestId, 3); adhocmanager.saveEntities(entity2Ids, adhocRequestId, 2); adhocmanager.saveEntities(entity1Ids, adhocRequestId, 1); //save views adhocRequestViews arv = new adhocRequestViews(); arv.setAdhocRequestId(adhocRequestId); //only site view for detail if ((reportId == 2) || (reportId == 4)) { arv.setAdhocView(1); adhocmanager.saveAdhocViews(arv); arv.setAdhocView(2); adhocmanager.saveAdhocViews(arv); } arv.setAdhocView(3); adhocmanager.saveAdhocViews(arv); // save criteria //we need to split List<String> criteriaIdList = Arrays.asList(criteriaIds.split(",")); List<String> criteriaValueList = Arrays.asList(criteriaValues.split("\\^\\^\\^\\^\\^")); //List<String> criteriaValidationList = Arrays.asList(criteriaValidations.split(",")); List<String> criteriaSQLActionList = Arrays.asList(criteriaSqlActions.split(",")); List<String> criteriaFieldTagList = Arrays.asList(criteriaFieldTags.split(",")); for (int i = 0; i < criteriaIdList.size(); i++) { adhocRequestCriteria arc = new adhocRequestCriteria(); arc.setAdhocRequestId(adhocRequestId); arc.setAdhocFieldId(Integer.parseInt(criteriaIdList.get(i))); if (criteriaFieldTagList.get(i).equalsIgnoreCase("dob") || criteriaFieldTagList.get(i).equalsIgnoreCase("povertyLevel")) { //date field List<String> dateList = Arrays.asList(criteriaValueList.get(i).split("\\|\\|\\|")); arc.setStartValue(dateList.get(0)); if (dateList.size() > 1) { arc.setEndValue(dateList.get(1)); } } else if (criteriaSQLActionList.get(i).equalsIgnoreCase("1")) { arc.setStartValue(criteriaValueList.get(i)); } else { arc.setMatchList(criteriaValueList.get(i)); } adhocmanager.saveCriteria(arc); } /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/saveReportRequest.do"); ual.setRequestMethod("POST"); ual.setMethodAccessed("saveReportRequest"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(ar.getId()); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); ModelAndView mav = new ModelAndView(new RedirectView("/adhoc/list")); return mav; } //this returns available reports for selected type @RequestMapping(value = "/deleteReportRequest.do", method = RequestMethod.POST) public @ResponseBody Integer deleteReport(HttpSession session, RedirectAttributes redirectAttr, @RequestParam String reli, @RequestParam String relv) throws Exception { String i = URLDecoder.decode(reli, "UTF-8"); String v = URLDecoder.decode(relv, "UTF-8"); decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); Integer reportRequestId = Integer.parseInt(result[0].substring(4)); User userDetails = (User) session.getAttribute("userDetails"); adhocView view = new adhocView(); view.setSystemUserId(userDetails.getId()); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Deleted Report"); adhocmanager.saveAdhocView(view); adhocRequests ahr = adhocmanager.getAdhocRequestById(reportRequestId); if (ahr.getStatusId() == 3 || ahr.getStatusId() == 4) { adhocmanager.deleteReportFile(ahr); } redirectAttr.addFlashAttribute("msg", "Deleted"); ahr.setStatusId(6); adhocmanager.updateAdHocRequests(ahr); /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/deleteReportRequest.do"); ual.setRequestMethod("POST"); ual.setMethodAccessed("deleteReport"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(ahr.getId()); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); return 1; } @RequestMapping(value = "/DLReport", method = { RequestMethod.GET }) public void DLReport(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletResponse response) throws Exception { Integer reportRequestId = 0; adhocView view = new adhocView(); boolean canViewReport = false; User userDetails = new User(); if (session.getAttribute("userDetails") != null) { userDetails = (User) session.getAttribute("userDetails"); //1 decrpt and get the reportId decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); reportRequestId = Integer.parseInt(result[0].substring(4)); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Accessed Adhoc Report link"); view.setSystemUserId(userDetails.getId()); adhocmanager.saveAdhocView(view); //now we get the report details adhocRequests request = adhocmanager.getAdhocRequestById(reportRequestId); if (request != null) { //we check permission and program if (userDetails.getRoleId() == 3 && request.getSystemUserId() == userDetails.getId() && request.getProgramId() == programId) { canViewReport = true; } else if (userDetails.getRoleId() != 3 && request.getProgramId() == programId) { canViewReport = true; } } //we log them, grab report for them to download //if report doesn't exist we send them back to list with a message if (!canViewReport) { hasPermission = 2; view = new adhocView(); view.setAdhocRequestId(reportRequestId); view.setSystemUserId(userDetails.getId()); view.setAdhocAction("User does not have permission to view adhoc report"); adhocmanager.saveAdhocView(view); throw new Exception("user does not have permission to view adhoc report - " + reportRequestId); } else { //generate the report for user to download //need to get report path String filePath = adhocmanager.getReportPath(programId); String fileName = request.getReportFileName(); try { File f = new File(filePath + fileName); if (!f.exists()) { throw new Exception("Error with File " + filePath + fileName); } } catch (Exception e) { throw new Exception("File does not exists " + filePath + fileName); } try { // get your file as InputStream InputStream is = new FileInputStream(filePath + fileName); // copy it to response's OutputStream String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); view = new adhocView(); view.setSystemUserId(userDetails.getId()); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Viewed Report"); adhocmanager.saveAdhocView(view); //update status if (request.getStatusId() == 3) { request.setStatusId(4); adhocmanager.updateAdHocRequests(request); } /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/DLReport"); ual.setRequestMethod("GET"); ual.setMethodAccessed("DLReport"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(reportRequestId); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); } catch (IOException ex) { ex.printStackTrace(); System.out.println("Error writing file to output stream. Filename was '{}'" + fileName + ex); throw new Exception("Error with File " + filePath + fileName + ex); } } } else { //someone somehow got to this link, we just log //we log who is accessing //now we have report id, we check to see which program it belongs to and if the user has permission hasPermission = 2; /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/DLReport"); ual.setRequestMethod("GET"); ual.setMethodAccessed("DLReport"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(reportRequestId); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Accessed adhoc report link - no user session found"); adhocmanager.saveAdhocView(view); throw new Exception("invalid adhoc report download - " + reportRequestId); } } }