com.rr.generic.ui.reports.reportController.java Source code

Java tutorial

Introduction

Here is the source code for com.rr.generic.ui.reports.reportController.java

Source

/*
 * 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.generic.ui.reports;

import com.registryKit.client.clientManager;
import com.registryKit.client.crosswalkData;
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.savedExports;
import com.registryKit.hierarchy.hierarchyManager;
import com.registryKit.hierarchy.programHierarchyDetails;
import com.registryKit.hierarchy.programOrgHierarchy;
import com.registryKit.program.programExportFields;
import com.registryKit.program.programManager;
import com.registryKit.reference.fileSystem;
import com.registryKit.report.reportManager;
import com.registryKit.report.reportRequest;
import com.registryKit.report.reportRequestEntity;
import com.registryKit.user.User;
import com.registryKit.user.userManager;
import com.registryKit.user.userProgramModules;
import com.rr.generic.ui.security.decryptObject;
import com.rr.generic.ui.security.encryptObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
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.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.servlet.ModelAndView;

/**
 *
 * @author chadmccue
 */
@Controller
@RequestMapping("/reports")
public class reportController {

    private static Integer moduleId = 3;

    @Autowired
    private userManager usermanager;

    @Autowired
    private hierarchyManager hierarchymanager;

    @Autowired
    private programManager programmanager;

    @Autowired
    private reportManager reportmanager;

    @Autowired
    private engagementManager engagementmanager;

    @Autowired
    private clientManager clientmanager;

    @Value("${programId}")
    private Integer programId;

    @Value("${topSecret}")
    private String topSecret;

    private static boolean allowDelete = false;

    @RequestMapping(value = "", method = { RequestMethod.POST, RequestMethod.GET })
    public ModelAndView listReports(HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/list");

        /* 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) {
            allowDelete = true;
        } else {
            allowDelete = modulePermissions.isAllowDelete();
        }
        mav.addObject("allowDelete", allowDelete);

        programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
        programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId);
        programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId);

        List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                userDetails.getId());
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", level1.getName());
        mav.addObject("level2Name", level2.getName());
        mav.addObject("level3Name", level3.getName());

        List<reportRequest> savedReports = reportmanager.getCreatedReports(programId, userDetails);

        if (savedReports != null && savedReports.size() > 0) {
            String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
                    .toLowerCase();

            fileSystem dir = new fileSystem();
            dir.setDir(registryName, "reports");

            Iterator<reportRequest> itr = savedReports.iterator();

            while (itr.hasNext()) {
                reportRequest report = itr.next();

                File newFile = new File(dir.getDir() + report.getReportFileName());

                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(report.getId()));
                map.put("topSecret", topSecret);

                String[] encrypted = encrypt.encryptObject(map);

                report.setEncryptedId(encrypted[0]);
                report.setEncryptedSecret(encrypted[1]);

                if (!newFile.exists()) {
                    itr.remove();
                }
            }
        }

        mav.addObject("savedReports", savedReports);

        return mav;
    }

    /**
     * 
     * @param surveyId
     * @param session
     * @param request
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/getReportModal.do", method = RequestMethod.GET)
    public ModelAndView getReportModal(HttpSession session, HttpServletRequest request) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/reports/reportModal");

        reportRequest reportDetails = new reportRequest();
        reportDetails.setFileTypeId(1);

        Random rand = new Random();
        reportDetails.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);

        List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                userDetails.getId());
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", level1.getName());
        mav.addObject("level2Name", level2.getName());
        mav.addObject("level3Name", level3.getName());

        mav.addObject("reportDetails", reportDetails);
        mav.addObject("showDateRange", true);

        return mav;
    }

    /**
     * 
     * @param surveyId
     * @param session
     * @param request
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/saveParticipantReport.do", method = RequestMethod.POST)
    public ModelAndView saveReport(@ModelAttribute(value = "reportDetails") reportRequest reportDetails,
            @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(reportDetails.getStartDate());
        Date endDate = datesearchFormat.parse(reportDetails.getEndDate());

        datesearchFormat.applyPattern("yyyy-MM-dd");

        String realStartDate = datesearchFormat.format(startDate);
        String realEndDate = datesearchFormat.format(endDate);

        String reportFileName = "";

        String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
                .toLowerCase();

        /* Get the client engagements */
        List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites,
                realStartDate, realEndDate);

        Integer reportRequestId = 0;

        /* Loop through sessions here */
        if (engagements != null && engagements.size() > 0) {

            reportDetails.setProgramId(programId);
            reportDetails.setSystemUserId(userDetails.getId());
            reportDetails.setSelectedDateRange(reportDetails.getStartDate() + " - " + reportDetails.getEndDate());
            reportDetails.setStartDateTime(startDate);
            reportDetails.setEndDateTime(endDate);

            reportRequestId = reportmanager.saveReportRequest(reportDetails);

            if (selectedSites != null && !"".equals(selectedSites)) {
                StringBuilder selectedSiteNames = new StringBuilder();
                for (Integer site : selectedSites) {
                    programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site);

                    reportRequestEntity reportSite = new reportRequestEntity();
                    reportSite.setSiteName(siteDetails.getName());
                    reportSite.setReportRequestId(reportRequestId);
                    reportSite.setEntity3Id(site);

                    reportmanager.saveReportRequestEntity(reportSite);
                }
            }

            progressBar newProgressBar = new progressBar();
            newProgressBar.setExportId(reportDetails.getUniqueId());
            newProgressBar.setPercentComplete(0);

            reportmanager.saveProgessBar(newProgressBar);

            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
            Date date = new Date();
            String fileName = "";
            String delimiter = ",";

            if (reportDetails.getFileTypeId() == 1) {
                fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                        .append(".csv").toString();
                delimiter = ",";
            } else if (reportDetails.getFileTypeId() == 2) {
                fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                        .append(".txt").toString();
                delimiter = ",";
            } else if (reportDetails.getFileTypeId() == 3) {
                fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date))
                        .append(".txt").toString();
                delimiter = "|";
            } else if (reportDetails.getFileTypeId() == 4) {
                fileName = new StringBuilder().append("participantReport").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, "reports");

            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);

            reportFileName = fileName;

            FileWriter fw = null;

            try {
                fw = new FileWriter(file, true);
            } catch (IOException ex) {
                Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex);
            }

            reportDetails.setReportFileName(reportFileName);
            reportmanager.updateReportRequest(reportDetails);

            StringBuilder reportRow = new StringBuilder();
            reportRow.append("ORGCODE").append(delimiter);
            reportRow.append("PARTICIP").append(delimiter);
            reportRow.append("STATE").append(delimiter);
            reportRow.append("GLUCTEST").append(delimiter);
            reportRow.append("GDM").append(delimiter); /* P */
            reportRow.append("RISKTEST").append(delimiter); /* P */
            reportRow.append("AGE").append(delimiter); /* P */
            reportRow.append("ETHNIC").append(delimiter); /* P */
            reportRow.append("AIAN").append(delimiter); /* P */
            reportRow.append("ASIAN").append(delimiter); /* P */
            reportRow.append("BLACK").append(delimiter); /* P */
            reportRow.append("NHOPI").append(delimiter); /* P */
            reportRow.append("WHITE").append(delimiter); /* P */
            reportRow.append("SEX").append(delimiter); /* P */
            reportRow.append("HEIGHT").append(delimiter);
            reportRow.append("DATE").append(delimiter);
            reportRow.append("WEIGHT").append(delimiter);
            reportRow.append("PA").append(delimiter);

            reportRow.append(System.getProperty("line.separator"));

            fw.write(reportRow.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 reportProgressBar = reportmanager.getProgressBar(reportDetails.getUniqueId());

            for (engagements engagement : engagements) {

                reportRow = new StringBuilder();

                programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails(
                        clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id());

                String siteDisplayId = "";

                if (hierarchyDetails.getDisplayId() != null) {
                    siteDisplayId = hierarchyDetails.getDisplayId();
                }

                reportRow.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 (!"".equals(crosswalk) && !"0".equals(crosswalk)) {
                            crosswalkData cwData = clientmanager
                                    .getCrosswalkDataByTarget(Integer.parseInt(crosswalk), fieldValue);
                            if (cwData != null) {
                                fieldValue = cwData.getDescValue();
                            } else {
                                fieldValue = "";
                            }
                        }

                        /* 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);
                                reportRow.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");
                                reportRow.append(format.format(formatedDate)).append(delimiter);
                            }
                        } else {
                            reportRow.append(fieldValue).append(delimiter);
                        }
                    }
                }

                reportRow.append(System.getProperty("line.separator"));
                fw.write(reportRow.toString());

                //Update progress bar
                totalDone = totalDone + 1;
                percentComplete = ((float) totalDone) / engagements.size();
                reportProgressBar.setPercentComplete(Math.round(percentComplete * 100));
                reportmanager.saveProgessBar(reportProgressBar);

            }

            fw.close();
        }

        ModelAndView mav = new ModelAndView();

        /* If no results are found */
        if (reportFileName.isEmpty()) {
            mav.setViewName("/reports/reportModal");

            savedExports newexportDetails = new savedExports();
            reportDetails.setFileTypeId(1);

            programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
            programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId);
            programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId);

            List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(),
                    userDetails.getId());
            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 (reportDetails.getUniqueId() > 0) {
                /* Delete progress bar entry */
                reportmanager.deleteProgressBar(reportDetails.getUniqueId());
            }

            mav.setViewName("/reports/reportDownloadModal");
            mav.addObject("reportFileName", reportFileName);
        }

        return mav;
    }

    /**
     * The '/viewReport' GET request will display the created csv report
     * 
     * @param i The encrypted url value containing the selected user id
     * @param v The encrypted url value containing the secret decode key
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/viewReport", method = RequestMethod.GET)
    public ModelAndView viewReport(HttpServletResponse response, HttpSession session,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v) throws Exception {

        ModelAndView mav = new ModelAndView();

        User userDetails = (User) session.getAttribute("userDetails");

        int reportId = 0;

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            reportId = Integer.parseInt(result[0].substring(4));

        }

        reportRequest reportDetails = reportmanager.getReportRequestById(reportId);

        String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-")
                .toLowerCase();

        fileSystem dir = new fileSystem();
        dir.setDir(registryName, "reports");

        File newFile = new File(dir.getDir() + reportDetails.getReportFileName());

        StringBuilder reportHTML = new StringBuilder();
        if (newFile.exists()) {
            String line = "";
            String cvsSplitBy = ",";
            int rowCount = 0;

            BufferedReader br = new BufferedReader(new FileReader(newFile));

            while ((line = br.readLine()) != null) {

                if (rowCount > 0) {
                    // use comma as separator
                    String[] reportRow = line.split(cvsSplitBy);

                    reportHTML.append("<tr>").append("<td>" + reportRow[0] + "</td>")
                            .append("<td>" + reportRow[1] + "</td>").append("<td>" + reportRow[2] + "</td>")
                            .append("<td>" + reportRow[3] + "</td>").append("<td>" + reportRow[4] + "</td>")
                            .append("<td>" + reportRow[5] + "</td>").append("<td>" + reportRow[6] + "</td>")
                            .append("<td>" + reportRow[7] + "</td>").append("<td>" + reportRow[8] + "</td>")
                            .append("<td>" + reportRow[9] + "</td>").append("<td>" + reportRow[10] + "</td>")
                            .append("<td>" + reportRow[11] + "</td>").append("<td>" + reportRow[12] + "</td>")
                            .append("<td>" + reportRow[13] + "</td>").append("<td>" + reportRow[14] + "</td>")
                            .append("<td>" + reportRow[15] + "</td>").append("<td>" + reportRow[16] + "</td>")
                            .append("<td>" + reportRow[17] + "</td>").append("</tr>");
                } else {
                    rowCount++;
                }
            }

            /*response.setContentType("text/html;charset=UTF-8");
                
            BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));
            String line = "";
            PrintWriter out = response.getWriter();
                
            while((line = fr.readLine()) != null) {
               out.println(line + "<br />");
               out.flush();
            }
                
                
            fr.close();*/
        }

        mav.setViewName("/viewReport");
        mav.addObject("reportHTML", reportHTML);

        return mav;

    }

}