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.wabshs.ui.importexport; import com.registryKit.client.clientManager; import com.registryKit.client.customProgramFields; import com.registryKit.client.dataElements; import com.registryKit.client.engagementManager; import com.registryKit.client.engagements; import com.registryKit.client.programClientFields; import com.registryKit.client.programEngagementFields; import com.registryKit.exportTool.exportManager; import com.registryKit.exportTool.progressBar; import com.registryKit.exportTool.savedExportSites; import com.registryKit.exportTool.savedExports; import com.registryKit.program.programExportFields; import com.registryKit.hierarchy.hierarchyManager; import com.registryKit.hierarchy.programHierarchyDetails; import com.registryKit.hierarchy.programOrgHierarchy; import com.registryKit.program.programManager; import com.registryKit.reference.fileSystem; import com.registryKit.survey.surveyManager; import com.registryKit.user.User; import com.registryKit.user.userManager; import com.registryKit.user.userProgramModules; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; 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.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ModelAttribute; 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; /** * * @author chadmccue */ @Controller @RequestMapping("/import-export") public class importExportController { private static Integer moduleId = 4; @Autowired private userManager usermanager; @Autowired private surveyManager surveyManager; @Autowired private hierarchyManager hierarchymanager; @Autowired private exportManager exportManager; @Autowired private programManager programmanager; @Autowired private engagementManager engagementmanager; @Autowired private clientManager clientmanager; @Value("${programId}") private Integer programId; @Value("${topSecret}") private String topSecret; private static boolean allowImport = false; private static boolean allowExport = false; private static boolean allowDelete = false; @RequestMapping(value = "", method = RequestMethod.GET) public ModelAndView importExport(HttpSession session, RedirectAttributes redirectAttr) throws Exception { /* 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) { allowImport = true; //Import is not a feature for this registry allowExport = true; allowDelete = true; } else { allowImport = modulePermissions.isAllowImport(); //Import is not a feature for this registry allowExport = modulePermissions.isAllowExport(); allowDelete = modulePermissions.isAllowDelete(); } if (allowImport == true) { ModelAndView mav = new ModelAndView(new RedirectView("/import-export/import")); return mav; } else if (allowExport == true) { ModelAndView mav = new ModelAndView(new RedirectView("/import-export/export")); return mav; } else { ModelAndView mav = new ModelAndView(new RedirectView("/import-export/export")); return mav; } } /** * The '/import' GET request will display the import page. * * @param session * @return * @throws Exception */ @RequestMapping(value = "/import", method = RequestMethod.GET) public ModelAndView importFiles(HttpSession session) throws Exception { /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); ModelAndView mav = new ModelAndView(); mav.setViewName("/import"); mav.addObject("allowImport", allowImport); mav.addObject("allowExport", allowExport); mav.addObject("allowDelete", allowDelete); return mav; } /** * The '/export' GET request will display the export page. * * @param session * @return * @throws Exception */ @RequestMapping(value = "/export", method = RequestMethod.GET) public ModelAndView export(HttpSession session) throws Exception { /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); ModelAndView mav = new ModelAndView(); mav.setViewName("/export"); mav.addObject("allowImport", allowImport); mav.addObject("allowExport", allowExport); mav.addObject("allowDelete", allowDelete); programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId); programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId); programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId); Integer userId; if (userDetails.getRoleId() == 2) { userId = 0; } else { userId = userDetails.getId(); } List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(), userId); mav.addObject("level1Items", level1Items); mav.addObject("level1Name", level1.getName()); mav.addObject("level2Name", level2.getName()); mav.addObject("level3Name", level3.getName()); List<savedExports> savedExports = exportManager.getSavedExports(userId, programId); if (savedExports != null && savedExports.size() > 0) { String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-") .toLowerCase(); fileSystem dir = new fileSystem(); dir.setDir(registryName, "exportFiles"); Iterator<savedExports> itr = savedExports.iterator(); while (itr.hasNext()) { savedExports export = itr.next(); File newFile = new File(dir.getDir() + export.getExportFile()); if (!newFile.exists()) { itr.remove(); } } } mav.addObject("savedExports", savedExports); return mav; } /** * The 'getOrganizationSites' GET request will return the view containing the table for the list of client based on the search parameters. * * @param request * @param response * @param session * @param searchString The string containing the list of search parameters. * @return * @throws Exception */ @RequestMapping(value = "getOrganizationSites", method = RequestMethod.GET) @ResponseBody public ModelAndView getOrganizationSites(HttpSession session, @RequestParam(value = "entityValue", required = false) Integer entityValue, @RequestParam(value = "level", required = true) Integer level) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/importExport/siteList"); User userDetails = (User) session.getAttribute("userDetails"); List<programHierarchyDetails> sites = hierarchymanager.getProgramOrgHierarchyItemsWithClientTotal(programId, level, entityValue, userDetails.getId()); mav.addObject("sites", sites); return mav; } /** * * @param surveyId * @param session * @param request * @return * @throws Exception */ @RequestMapping(value = "/getExportModal.do", method = RequestMethod.GET) public ModelAndView getExportModal(HttpSession session, HttpServletRequest request) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/importExport/exportModal"); savedExports exportDetails = new savedExports(); exportDetails.setExportType(1); Random rand = new Random(); exportDetails.setUniqueId(rand.nextInt(50000000)); User userDetails = (User) session.getAttribute("userDetails"); programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId); programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId); programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId); Integer userId; if (userDetails.getRoleId() == 2) { userId = 0; } else { userId = userDetails.getId(); } List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(), userId); mav.addObject("level1Items", level1Items); mav.addObject("level1Name", level1.getName()); mav.addObject("level2Name", level2.getName()); mav.addObject("level3Name", level3.getName()); mav.addObject("exportDetails", exportDetails); mav.addObject("showDateRange", true); return mav; } /** * * @param surveyId * @param session * @param request * @return * @throws Exception */ @RequestMapping(value = "/saveParticipantExport.do", method = RequestMethod.POST) public ModelAndView saveExport(@ModelAttribute(value = "exportDetails") savedExports exportDetails, @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session, HttpServletRequest request) throws Exception { if (errors.hasErrors()) { for (ObjectError error : errors.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } User userDetails = (User) session.getAttribute("userDetails"); SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = datesearchFormat.parse(exportDetails.getStartDate()); Date endDate = datesearchFormat.parse(exportDetails.getEndDate()); datesearchFormat.applyPattern("yyyy-MM-dd"); String realStartDate = datesearchFormat.format(startDate); String realEndDate = datesearchFormat.format(endDate); String exportFileName = ""; String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-") .toLowerCase(); /* Get the client engagements */ List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites, realStartDate, realEndDate); Integer exportId = 0; /* Loop through sessions here */ if (engagements != null && engagements.size() > 0) { exportDetails.setProgramId(programId); exportDetails.setSystemUserId(userDetails.getId()); exportDetails.setSelectedDateRange(exportDetails.getStartDate() + " - " + exportDetails.getEndDate()); exportDetails.setDownloadType(1); exportDetails.setTotalRecords(engagements.size()); exportId = exportManager.saveExport(exportDetails); if (selectedSites != null && !"".equals(selectedSites)) { StringBuilder selectedSiteNames = new StringBuilder(); for (Integer site : selectedSites) { programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site); savedExportSites exportSite = new savedExportSites(); exportSite.setExportId(exportId); exportSite.setSiteName(siteDetails.getName()); exportSite.setSiteId(site); exportManager.saveExportSite(exportSite); } } progressBar newProgressBar = new progressBar(); newProgressBar.setExportId(exportDetails.getUniqueId()); newProgressBar.setPercentComplete(0); exportManager.saveProgessBar(newProgressBar); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS"); Date date = new Date(); String fileName = ""; String delimiter = ","; if (exportDetails.getExportType() == 1) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".csv") .toString(); delimiter = ","; } else if (exportDetails.getExportType() == 2) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = ","; } else if (exportDetails.getExportType() == 3) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = "|"; } else if (exportDetails.getExportType() == 4) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = "\t"; } /* Create new export file */ InputStream inputStream = null; OutputStream outputStream = null; fileSystem dir = new fileSystem(); dir.setDir(registryName, "exportFiles"); File newFile = new File(dir.getDir() + fileName); /* Create the empty file in the correct location */ try { if (newFile.exists()) { int i = 1; while (newFile.exists()) { int iDot = fileName.lastIndexOf("."); newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")" + fileName.substring(iDot)); } fileName = newFile.getName(); newFile.createNewFile(); } else { newFile.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } /* Read in the file */ FileInputStream fileInput = null; File file = new File(dir.getDir() + fileName); fileInput = new FileInputStream(file); exportFileName = fileName; FileWriter fw = null; try { fw = new FileWriter(file, true); } catch (IOException ex) { Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex); } exportDetails.setExportFile(exportFileName); exportManager.saveExport(exportDetails); StringBuilder exportRow = new StringBuilder(); exportRow.append("PATIENT NUMBER").append(delimiter); exportRow.append("FIRST NAME").append(delimiter); exportRow.append("LAST NAME").append(delimiter); exportRow.append("DOB").append(delimiter); exportRow.append("GENDER").append(delimiter); /* P */ exportRow.append("VISIT DATE").append(delimiter); /* P */ exportRow.append("WEIGHT").append(delimiter); /* P */ exportRow.append("HEIGHT").append(delimiter); /* P */ exportRow.append("BP SYSTOLIC").append(delimiter); /* P */ exportRow.append("BP DIASTOLIC").append(delimiter); /* P */ exportRow.append(System.getProperty("line.separator")); fw.write(exportRow.toString()); Integer participantId = 0; List<programExportFields> exportFields = programmanager.getProgramExportFields(programId); List<String> tableinfo = new ArrayList<String>(); Integer fieldId = 0; Integer customFieldId = 0; Integer validationValue = 0; String fieldTypeValue = ""; Integer crosswalkId = 0; for (programExportFields field : exportFields) { if (field.getFieldType() == 1) { fieldTypeValue = "1"; programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } else { fieldTypeValue = "2"; programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } if (fieldId > 0) { dataElements fieldDetails = clientmanager.getFieldDetails(fieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } else if (customFieldId > 0) { customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } } Integer totalDone = 0; float percentComplete; progressBar exportProgressBar = exportManager.getProgressBar(exportDetails.getUniqueId()); for (engagements engagement : engagements) { exportRow = new StringBuilder(); programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails( clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id()); String siteDisplayId = ""; if (hierarchyDetails.getDisplayId() != null) { siteDisplayId = hierarchyDetails.getDisplayId(); } //exportRow.append(siteDisplayId).append(delimiter); if (tableinfo != null & tableinfo.size() > 0) { for (String table : tableinfo) { String[] tableInfoArray = table.split("-"); String fieldValue = ""; String fieldType = tableInfoArray[0]; String tablename = tableInfoArray[1]; String tableCol = tableInfoArray[2]; String validation = tableInfoArray[3]; String crosswalk = tableInfoArray[4]; if ("1".equals(fieldType)) { fieldValue = clientmanager.getTableData(tablename, tableCol, engagement.getProgramPatientId()); } else { fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(), engagement.getProgramPatientId()); } if ("55".equals(crosswalk) && "0".equals(fieldValue)) { fieldValue = "2"; } /* If date format to correct display format */ if ("4".equals(validation)) { if ("dob".equals(tableCol)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date dob = format.parse(fieldValue); Date today = new Date(); format.applyPattern("yyyy"); String dobAsString = format.format(dob); String todayAsString = format.format(today); Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString); exportRow.append(age).append(delimiter); } else { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date formatedDate = format.parse(fieldValue); format.applyPattern("MM/dd/yy"); exportRow.append(format.format(formatedDate)).append(delimiter); } } else { exportRow.append(fieldValue).append(delimiter); } } } exportRow.append(System.getProperty("line.separator")); fw.write(exportRow.toString()); //Update progress bar totalDone = totalDone + 1; percentComplete = ((float) totalDone) / engagements.size(); exportProgressBar.setPercentComplete(Math.round(percentComplete * 100)); exportManager.saveProgessBar(exportProgressBar); } fw.close(); } ModelAndView mav = new ModelAndView(); /* If no results are found */ if (exportFileName.isEmpty()) { mav.setViewName("/importExport/exportModal"); savedExports newexportDetails = new savedExports(); exportDetails.setExportType(1); programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId); programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId); programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId); Integer userId; if (userDetails.getRoleId() == 2) { userId = 0; } else { userId = userDetails.getId(); } List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(), userId); mav.addObject("level1Items", level1Items); mav.addObject("level1Name", level1.getName()); mav.addObject("level2Name", level2.getName()); mav.addObject("level3Name", level3.getName()); mav.addObject("exportDetails", newexportDetails); mav.addObject("showDateRange", true); mav.addObject("noresults", true); } else { if (exportDetails.getUniqueId() > 0) { /* Delete progress bar entry */ exportManager.deleteProgressBar(exportDetails.getUniqueId()); } mav.setViewName("/importExport/exportDownloadModal"); mav.addObject("exportFileName", exportFileName); } return mav; } /** * The '/updateProgressBar.do' request will return the current value of export progress bar. * * @param uniqueId The unique export id * @return * @throws Exception */ @RequestMapping(value = "/updateProgressBar.do", method = RequestMethod.GET) @ResponseBody public Integer updateProgressBar(HttpSession session, @RequestParam Integer uniqueId) throws Exception { if (uniqueId != null && !"".equals(uniqueId) && uniqueId > 0) { progressBar exportProgressBar = exportManager.getProgressBar(uniqueId); if (exportProgressBar != null) { return exportProgressBar.getPercentComplete(); } else { return 0; } } else { return 0; } } /** * The '/deleteExport' GET request will change the status of the selected client . * * @param exportId The encrypted url value containing the selected user id * @return * @throws Exception */ @RequestMapping(value = "/deleteExport", method = RequestMethod.GET) @ResponseBody public boolean deleteExport(HttpSession session, @RequestParam(value = "exportId", required = false) Integer exportId) throws Exception { if (exportId != null) { exportManager.deleteExport(exportId); } return true; } }