Jump to content
We've recently updated our Privacy Statement, available here ×

Trying to create a xlsx Report with data around 115620 records throwing GC overhead limit exceeded Error.


amolmanke89

Recommended Posts

Below is the code for report generation. Please let me know how excel file with large number of records can be generated . Ealry reply is really appreciated.

 

 

package com.fss.recon.outputfile.report.jasper;
import java.nio.file.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.export.JRTextExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.fill.JRGzipVirtualizer;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.util.JRSwapFile;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import com.fss.common.ums.form.KeyStoreForm;
import com.fss.recon.common.search.form.EJErrorKnockoffProcessForm;
import com.fss.recon.common.search.service.EJErrorKnockoffService;
import com.fss.recon.core.dao.KeystoreDao;
import com.fss.recon.core.dao.OutfileDao;
import com.fss.recon.core.daoimpl.KeystoreDaoImpl;
import com.fss.recon.core.exception.ReconUserDefinedException;
import com.fss.recon.core.form.ForceMatchReportGenForm;
import com.fss.recon.core.form.OutfileForm;
import com.fss.recon.core.form.SubreportForm;
import com.fss.recon.core.form.TallyProcessForm;
import com.fss.recon.core.service.ManrecProcessService;
import com.fss.recon.core.service.ReconciliationProcessService;
import com.fss.recon.core.util.DataBasePropertyUtil;
import com.fss.recon.core.util.DateUtil;
import com.fss.recon.core.util.LoopBack;
import com.fss.recon.core.util.QueryPropertyUtil;
import com.fss.recon.core.util.ReconConfigPropertyUtil;
import com.fss.recon.core.util.ReconConstants;
import com.fss.recon.core.util.ReportParallelProcess;
import com.fss.recon.core.util.ReportReWriteParallel;
import com.fss.recon.crypto.SecurityUtils;
import com.fss.recon.disputeaction.dao.InterchangeOutfileGeneratorDao;
import com.fss.recon.disputeaction.util.DisputeUtils;
import com.fss.recon.jdbcConn.utils.DatabaseService;
import com.fss.recon.jdbcConn.utils.LocalObject;
import com.fss.recon.jdbcConn.utils.LocalString;
import com.fss.recon.mof.form.mofdiscountForm;
import com.fss.recon.outputfile.report.model.OutputFileConfiguration;
import com.fss.recon.outputfile.report.model.OutputFileReportDetails;
import com.fss.recon.outputfile.report.service.TemplateMapperService;

/**
 * @author muralikrishnat
 *
 */
@Component
public class JasperReportGeneration implements Callable<Boolean> {
    @Autowired
    private TemplateMapperService templateMapperService;
    @Autowired
    private ReconciliationProcessService reconciliationProcessService;

    @Autowired
    private OutfileDao outfileDao;

    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("location");
    
    @Autowired
    protected  InterchangeOutfileGeneratorDao interchangeOutfileGeneratorDao;
    protected final static ResourceBundle RECONMESSAGES=ResourceBundle.getBundle("ReconMessages");
    private static final Logger logger = Logger.getLogger(JasperReportGeneration.class);

    private static final ResourceBundle LOCATION_BUNDLE = ResourceBundle.getBundle("location"); //Added by vinoth

    private String institutionName = "";
    public String processName = "";
    public String fileDate = "";
    private SubreportForm form = null;

    public static String OUTFILE_PATH;

    // Added By Kaviraj for Scheduler on 09/05/16
    public TemplateMapperService getTemplateMapperService() {
        return templateMapperService;
    }

    public void setTemplateMapperService(
            TemplateMapperService templateMapperService) {
        this.templateMapperService = templateMapperService;
    }

    @Autowired
    ManrecProcessService manrecProcessService;

    
    //Added by Kaviraj on 13-09-2017
    @Autowired
    EJErrorKnockoffService ejErrorKnockoffService;
        
    // Map<Object, Object> map = null;
    public void generateReportPreview() throws Exception {
        String userPath = System.getProperty("user.home");
        String outputFileReportPreviewPath = userPath + File.separator
                + "reportPreview.pdf";
        File pdfFile = new File(outputFileReportPreviewPath);
        if (!pdfFile.exists()) {
            pdfFile.createNewFile();
        }        
        // System.out.println(pdfFile.getAbsolutePath());
        FileOutputStream outputStream = new FileOutputStream(pdfFile, true);
        long pdf = System.currentTimeMillis();
        System.out.println("PDF Start Time " + pdf);
        callPDFReportPreview(outputStream);

        System.out.println("PDF creation time : "
                + (System.currentTimeMillis() - pdf));
        outputStream.flush();
        outputStream.close();
    }

    private void callPDFReportPreview(FileOutputStream outputStream)
            throws Exception {

        String userPath = System.getProperty("user.home");
        String jrxmlTemplatePath = userPath + File.separator + "report7.jrxml";
        try {
            InputStream inputStream = new FileInputStream(new File(
                    jrxmlTemplatePath));

            // ArrayList<Amount> dataBeanList = getDataBeanLists();
            ArrayList<Amount> dataBeanList = new ArrayList<Amount>();

            JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(
                    dataBeanList);
            Map parameters = new HashMap();
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            JasperReport jasperReport = JasperCompileManager
                    .compileReport(jasperDesign);
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, parameters, beanColDataSource);

            /*
             * long text = System.currentTimeMillis();
             * System.out.println("TEXT Start Time "+text); JRTextExporter
             * exporter = new JRTextExporter();
             * exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 180);
             * exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 40);
             * exporter.setParameter(JRTextExporterParameter.JASPER_PRINT,
             * jasperPrint);
             * exporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
             * outputStream); System.err.println("TEXT creation time : " +
             * (System.currentTimeMillis() - text)); exporter.exportReport();
             */

            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,
                    jasperPrint);
            // exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST,
            // jasperPrintList);
            exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
                    outputStream);
            exporter.exportReport();
        } catch (Exception e) {
            System.out.println("Exception " + e);
        }

    }

    public ArrayList<Amount> getDataBeanLists() throws Exception,
            InvocationTargetException {
        logger.info("Report generation retrieve information start");
        ArrayList<Amount> dataBeanList = new ArrayList<Amount>();
        String query = QueryPropertyUtil.getProperty("DB.TEST");

        LocalObject localObject = null;
        DatabaseService databaseService = null;
        List<LocalObject> objList = null;
        Iterator<LocalObject> itr = null;
        Map<Object, Object> map = new HashMap<Object, Object>();
        try {
            databaseService = new DatabaseService();
            localObject = new LocalObject();
            objList = databaseService.executeQuery(query, localObject);
            itr = objList.iterator();

            while (itr.hasNext()) {
                Amount a = new Amount();
                localObject = (LocalObject) itr.next();
                map = localObject.getMap();
                localObject = null;
                BeanUtils.populate(a, map);
                dataBeanList.add(a);
            }

        } catch (Exception e) {
            // e.printStackTrace();
            logger.error("Report generation retrieve information "
                    + e.getMessage());
        } finally {
            map = null;
            objList = null;
            localObject = null;
            databaseService = null;
        }

        /********************* End List Of Files **************************/

        logger.info("Report generation retrieve information End" + query);

        return dataBeanList;
    }

    public boolean callTextReportGeneration(FileOutputStream outputStream,JasperPrint jasperPrint) {
        logger.debug("Report Generation callTextReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        /*textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 300);// 200
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 38);*/
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH,500);// 200  //added by saurabh to remove less row count issue in report 24/11/17

        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT,50);

        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,
                jasperPrint);
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
                outputStream);
        // textExporter.setParameter(JRTextExporterParameter.IGNORE_PAGE_MARGINS,
        // textExporter);
        // textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
        // outputStream);
        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        } finally {
            textExporter = null;
        }
        logger.debug("Report Generation callTextReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;

    }

    //SN: Added by Maitri Shah on 24/4/18 for fixing spacing issue in Unrec Swt Recon Reports
    public boolean callTextReportGeneration(FileOutputStream outputStream,JasperPrint jasperPrint,boolean isUnrecSwtRecRep) {
        logger.debug("Report Generation callTextReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH,1000);
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT,50);

        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,jasperPrint);
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,outputStream);
        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        } finally {
            textExporter = null;
        }
        logger.debug("Report Generation callTextReportGeneration  End "    + reportGenerationStatus);
        return reportGenerationStatus;
    }
    //EN: Added by Maitri Shah

    public boolean callRLXTextReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        logger.debug("Report Generation callTextReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 300);// 200
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 20); // 38//42
        //textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 38);
        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,
                jasperPrint);
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
                outputStream);
        // textExporter.setParameter(JRTextExporterParameter.IGNORE_PAGE_MARGINS,
        // textExporter);
        // textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
        // outputStream);
        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        } finally {
            textExporter = null;
        }
        logger.debug("Report Generation callTextReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;

    }


    // For ttum
    public boolean callTTUMTextReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint,int size) {
        /*if((size-3) <= 0){
            size=1;
        }else{
            size = size-3;
        }*/
        logger.debug("Report Generation callTextReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, size);  //Modified by saurabh to take size dynamically for TTUM 22/12/17
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 90);   //MODIFIED BY SAURABH TO update height of the data
        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,jasperPrint);
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,outputStream);
        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        } finally {
            textExporter = null;
        }
        logger.debug("Report Generation callTextReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;

    }


    // For ttum
    public boolean callTTUMTextReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        /*if((size-3) <= 0){
                size=1;
            }else{
                size = size-3;
            }*/
        logger.debug("Report Generation callTextReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 2000);  //Modified by saurabh to take size dynamically for TTUM 22/12/17
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 100);
        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,jasperPrint);
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,outputStream);
        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        } finally {
            textExporter = null;
        }
        logger.debug("Report Generation callTextReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;

    }


    public boolean callPDFReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {

        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRPdfExporter pdfExporter = new JRPdfExporter();
        pdfExporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,
                jasperPrint);
        pdfExporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
                outputStream);
        try {
            pdfExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;
            logger.debug("PDF Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean callCSVReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRCsvExporter csvExporter = new JRCsvExporter();

        csvExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        csvExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                outputStream);

        try {
            csvExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.debug("CSV Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }
    
    //Added By Kaviraj on 25-Sep-2017
    public boolean callCSVMultipleReportGeneration(FileOutputStream outputStream,ArrayList<JasperPrint> jasperPrintlist)
    {
        logger.debug("Report Generation callCSVMultipleReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRCsvExporter csvExporter = new JRCsvExporter();

        csvExporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintlist);
        csvExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,outputStream);

        try {
            csvExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.error("CSV Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callCSVMultipleReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean callXlsxReportGeneration(FileOutputStream outputStream, JasperPrint jasperPrint) {
        logger.debug("Report Generation callXlsxReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRXlsxExporter xlsxExporter = new JRXlsxExporter();

        xlsxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xlsxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,outputStream);
        xlsxExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);
        //        xlsxExporter.setParameter(JExcelApiExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
        xlsxExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
        //        xlsxExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);

        try {
            xlsxExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.debug("XLSX Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callXlsxReportGeneration  End "+ reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean callHtmlReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRHtmlExporter htmlExporter = new JRHtmlExporter();

        htmlExporter
        .setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        htmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                outputStream);

        try {
            htmlExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.debug("HTML Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End   "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean callXmlReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRXmlExporter xmlExporter = new JRXmlExporter();

        xmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                outputStream);
        try {
            xmlExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;
            logger.debug("XML Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End  "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean callXlsReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint) {
        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRXlsExporter xlsExporter = new JRXlsExporter();

        xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                outputStream);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
                Boolean.FALSE);

        try {
            xlsExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.debug("XLS Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End  "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    public boolean reportGeneration(String reportGenerationPath,String inputFileId, int reportTypeId, LoopBack loopBack)throws Exception {

        boolean reportGenerationStatus = true;
        ExecutorService executorService = null;
        List<Future<Integer>> futureList = null;
        int reportThreadCount = 0 ;
        int successCount = 0 ;
        ArrayList<String> ReportNameList = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = new Date();

        // get current date time with Calendar()
        Calendar cal = Calendar.getInstance();
        String dateAndTime = dateFormat.format(cal.getTime()).substring(11);
        String dateString = dateFormat.format(date).substring(0, 10);
        String timeString = dateFormat.format(date).substring(11);
        String time = timeString.replace(":", "");
        //Added by Amol for Clear Card Num display in Report on 16-July-2018
        String maskReportGenerationPath ="";
        String unMaskReportGenerationPath ="";
        try {
            List<OutputFileConfiguration> outputFileConfigurationList = new ArrayList<OutputFileConfiguration>();
            outputFileConfigurationList = templateMapperService.retrieveOutputFileConfiguration(inputFileId, reportTypeId,
                    loopBack);
            logger.debug("Report List received:: "+(outputFileConfigurationList!=null?outputFileConfigurationList.size():"0"));
            // ONLY FOR RECON REPORTS GET PROCESS NAME TO DISPLAY IN JRXML REPORT
            if (reportTypeId == 4) {
                processName = getProcessName(inputFileId, loopBack);
                //Added by Amol for Clear Card Num display in Report on 16-July-2018
                maskReportGenerationPath = reportGenerationPath+File.separator+"MASK"+File.separator;
                unMaskReportGenerationPath = reportGenerationPath+File.separator+"UNMASK"+File.separator;
                File repDirPath_full = new File(maskReportGenerationPath);
                if(!repDirPath_full.exists()){
                    repDirPath_full.mkdirs();
                }
                File repDirPath_full_unmask = new File(unMaskReportGenerationPath);
                if(!repDirPath_full_unmask.exists()){
                    repDirPath_full_unmask.mkdirs();
                }
            }
            // GET FILE DATE FOR EXTRACTION REPORTS TO DISPLAY IN JRXML REPORT
            if (reportTypeId == 3) {
                fileDate = getProcessDate(inputFileId, loopBack);
            }

            if ((outputFileConfigurationList != null) && !(outputFileConfigurationList.isEmpty())) {

                // Started by Mohan Raj.V for parallel Processing for Report Generation on 13-02-2017
                logger.info(" Enter into reportGeneration parallel processing Block");

                Long startTime = System.currentTimeMillis();
                reportThreadCount = Integer.parseInt( DataBasePropertyUtil.getProperty("report.parallel.thread").trim() );
                //                reportThreadCount = outputFileConfigurationList.size();
                logger.info("Total Number of Report configured :"+outputFileConfigurationList.size());
                logger.info("Report Thread Count :"+reportThreadCount);

                executorService = Executors.newFixedThreadPool(reportThreadCount);
                futureList = new ArrayList<>();
                if (reportTypeId ==4){
                    for (OutputFileConfiguration outputFileConfiguration : outputFileConfigurationList) {
                        String reportName = outputFileConfiguration.getOutputFileName().toString();
                        String withoutSpaceRetportName = reportName.replaceAll("\s", "");
                        OUTFILE_PATH = maskReportGenerationPath+ withoutSpaceRetportName+ "-"+ dateString+ "-"+ time+ "."+ (outputFileConfiguration.getOutputFileFormat()).toLowerCase();// Added by Kaviraj.J
                        ReportNameList.add(OUTFILE_PATH);
                        File outputFile = new File(OUTFILE_PATH);
                        FileOutputStream outputStream = new FileOutputStream(outputFile, true);

                        ReportParallelProcess reportParallelProcess = new ReportParallelProcess(this,outputFileConfiguration, loopBack,outputStream, LOCATION_BUNDLE, outputFile,reportTypeId);
                        Future<Integer> result = executorService.submit(reportParallelProcess);
                        futureList.add(result);
                    }

                    for (Future<Integer> future : futureList) {
                        successCount = successCount + future.get(); // blocks until the runnable completes
                    }
                    logger.info("Generated Report Success Count :" + successCount );

                    executorService.shutdown();

//                    Long endTime = System.currentTimeMillis();

//                    logger.info("Total Time Taken for the Report Generation : = "+(endTime - startTime)/1000);

                    if( successCount > 0 ) {
                        if( outputFileConfigurationList.size() == successCount ) {
                            reportGenerationStatus = true ;
                            logger.info("All the Configured Reports got Generated successfully");
                        } else {
                            reportGenerationStatus = false ;
                            logger.error("Some of the Report Generation got failed");
                        }
                    } else {
                        reportGenerationStatus = false ;
                        logger.error("Exception Occured in Report Generation None of the Reports is Generated");
                    }
                    successCount = 0;
                    futureList.clear();
                    executorService = Executors.newFixedThreadPool(reportThreadCount);
                    for (OutputFileConfiguration outputFileConfiguration : outputFileConfigurationList) {
                        String reportName = outputFileConfiguration.getOutputFileName().toString();
                        String withoutSpaceRetportName = reportName.replaceAll("\s", "");
                        OUTFILE_PATH = unMaskReportGenerationPath+ withoutSpaceRetportName+ "-"+ dateString+ "-"+ time+ "."+ (outputFileConfiguration.getOutputFileFormat()).toLowerCase();// Added by Kaviraj.J
                        
                        ReportNameList.add(OUTFILE_PATH);
                        File outputFile = new File(OUTFILE_PATH);
                        FileOutputStream outputStream = new FileOutputStream(outputFile, true);

                        ReportParallelProcess reportParallelProcess = new ReportParallelProcess(this,outputFileConfiguration, loopBack,outputStream, LOCATION_BUNDLE, outputFile,reportTypeId);
                        Future<Integer> result = executorService.submit(reportParallelProcess);
                        futureList.add(result);
                    }

                    for (Future<Integer> future : futureList) {
                        successCount = successCount + future.get(); // blocks until the runnable completes
                    }
                    logger.info("Generated Report Success Count :" + successCount );

                    executorService.shutdown();

                    Long endTime = System.currentTimeMillis();

                    logger.info("Total Time Taken for the Report Generation : = "+(endTime - startTime)/1000);

                    if( successCount > 0 ) {
                        if( outputFileConfigurationList.size() == successCount ) {
                            reportGenerationStatus = true ;
                            logger.info("All the Configured Reports got Generated successfully");
                        } else {
                            reportGenerationStatus = false ;
                            logger.error("Some of the Report Generation got failed");
                        }
                    } else {
                        reportGenerationStatus = false ;
                        logger.error("Exception Occured in Report Generation None of the Reports is Generated");
                    }
                    
                }
                else{
                    for (OutputFileConfiguration outputFileConfiguration : outputFileConfigurationList) {
                        String reportName = outputFileConfiguration.getOutputFileName().toString();
                        String withoutSpaceRetportName = reportName.replaceAll("\s", "");
                        OUTFILE_PATH = reportGenerationPath+ withoutSpaceRetportName+ "-"+ dateString+ "-"+ time+ "."+ (outputFileConfiguration.getOutputFileFormat()).toLowerCase();// Added by Kaviraj.J
                        ReportNameList.add(OUTFILE_PATH);
                        File outputFile = new File(OUTFILE_PATH);
                        FileOutputStream outputStream = new FileOutputStream(outputFile, true);

                        ReportParallelProcess reportParallelProcess = new ReportParallelProcess(this,outputFileConfiguration, loopBack,outputStream, LOCATION_BUNDLE, outputFile,reportTypeId);
                        Future<Integer> result = executorService.submit(reportParallelProcess);
                        futureList.add(result);
                    }

                for (Future<Integer> future : futureList) {
                    successCount = successCount + future.get(); // blocks until the runnable completes
                }
                logger.info("Generated Report Success Count :" + successCount );

                executorService.shutdown();

                Long endTime = System.currentTimeMillis();

                logger.info("Total Time Taken for the Report Generation : = "+(endTime - startTime)/1000);

                if( successCount > 0 ) {
                    if( outputFileConfigurationList.size() == successCount ) {
                        reportGenerationStatus = true ;
                        logger.info("All the Configured Reports got Generated successfully");
                    } else {
                        reportGenerationStatus = false ;
                        logger.error("Some of the Report Generation got failed");
                    }
                } else {
                    reportGenerationStatus = false ;
                    logger.error("Exception Occured in Report Generation None of the Reports is Generated");
                }


                    successCount = 0;
                }
                    
                
                if(ReportNameList.size()>0  && reportGenerationStatus){  // BY BALAJI
                    logger.info(" Enter into reportGeneration parallel processing Block");

                    startTime = System.currentTimeMillis();
                    reportThreadCount = Integer.parseInt( DataBasePropertyUtil.getProperty("report.parallel.thread").trim() );
                    //                        reportThreadCount = outputFileConfigurationList.size();
                    logger.info("Total Number of Report  re write :"+outputFileConfigurationList.size());
                    logger.info("re-write Report Thread Count :"+reportThreadCount);

                    executorService = Executors.newFixedThreadPool(reportThreadCount);
                    futureList = new ArrayList<>();
                    successCount =0;
                    for (String msReportName : ReportNameList) {
                        logger.info(" Report list size is -->"+ReportNameList);

                        ReportReWriteParallel reportParallelProcess = new ReportReWriteParallel(this,msReportName,reportTypeId);
                        Future<Integer> result = executorService.submit(reportParallelProcess);
                        futureList.add(result);
                    }

                    for (Future<Integer> future : futureList) {
                        successCount = successCount + future.get(); // blocks until the runnable completes
                    }
                    logger.info("re-write Report Success Count :" + successCount +"ReportNameList.size() "+ReportNameList.size() +"ReportNameList ");

                    executorService.shutdown();

                    Long endTime = System.currentTimeMillis();

                    logger.info("Total Time Taken for the re-write Report Generation : = "+(endTime - startTime)/1000);

                    if( successCount > 0 ) {
                        if( ReportNameList.size() == successCount ) {
                            reportGenerationStatus = true ;
                            logger.info("All the Configured re-write Reports got Generated successfully");
                        } else {
                            reportGenerationStatus = false ;
                            logger.error("Some of the re-write Report Generation got failed");
                        }
                    } else {
                        reportGenerationStatus = false ;
                        logger.error("Exception Occured in re-write Report Generation None of the Reports is Generated");
                    }

                }


                if(reportGenerationStatus){
                    for (String msReportName : ReportNameList) {
                        if((msReportName.endsWith(".txt")||msReportName.endsWith(".text")))
                            deleteOLDReport(msReportName);
                    }
                }

                //Commented by Mohan Raj.V
                /*for (OutputFileConfiguration outputFileConfiguration : outputFileConfigurationList) {
                    if (reportGenerationStatus) {
                        String reportName = outputFileConfiguration.getOutputFileName().toString();
                        String withoutSpaceRetportName = reportName.replaceAll("\s", "");

                        OUTFILE_PATH = reportGenerationPath+ withoutSpaceRetportName+ "-"+ dateString+ "-"+ time+ "."+ (outputFileConfiguration.getOutputFileFormat()).toLowerCase();// Added By  Kaviraj

                        File outputFile = new File(OUTFILE_PATH);
                        FileOutputStream outputStream = new FileOutputStream(outputFile, true);

                        if (outputFileConfiguration.getOutputFileId() == null || "".equalsIgnoreCase(outputFileConfiguration.getOutputFileId())) {

                            reportGenerationStatus = false;

                        } else {

                            reportGenerationStatus = callReportGeneration(outputFileConfiguration, loopBack,outputStream, LOCATION_BUNDLE, outputFile);
                        }
                        outputStream.flush();
                        outputStream.close();
                    }
                }*/

            }

            /*else if (reportTypeId == 5 || reportTypeId == 7|| reportTypeId == 6) {// OUTPUT FILE CONFIGURATION IS NOT MANDATORY FOR DISPUTE MODULE(5 FOR DISPUTE PROCESS & 7 FOR PREPROCESS & 6 FOR MANREC)

                reportGenerationStatus = true; }*/      //Commeneted by saurabh to for getting report status as true in extraction for which report is not configured  
            else {
                //reportGenerationStatus = false;
                reportGenerationStatus = true;  // Added by saurabh to for getting report status as true in extraction for which report is not configured
            }
        } catch (Exception e) {
            reportGenerationStatus = false;
            logger.error("Report Generation " + e.getMessage());
        }

        return reportGenerationStatus;

    }

    public boolean callReportGeneration(
            OutputFileConfiguration outputFileConfiguration, LoopBack loopBack,
            FileOutputStream outputStream, ResourceBundle resourceBundle,
            File outputFile) throws Exception {

        String title = "";
        boolean reportGenerationStatus = true;
        // ResourceBundle resourceBundle = null;
        // List<ReportGeneration> reportList = new
        // ArrayList<ReportGeneration>();

        JasperReportGeneration jasperReportGeneration = new JasperReportGeneration();
        List<OutputFileReportDetails> outputFileReportDetailsList = new ArrayList<OutputFileReportDetails>();
        outputFileReportDetailsList.addAll(templateMapperService.retrieveOutputFileReportDetails(outputFileConfiguration.getOutputFileId().toString(), loopBack));
        outputFileConfiguration.setOutputFileReportDetails(outputFileReportDetailsList);

        Collection<Map<String, ?>> jasperReportsMapList = null;

        Collection<Map<String, ?>> jasperReportsMapList1 = new ArrayList<Map<String, ?>>();

        if ((outputFileReportDetailsList != null) && !(outputFileReportDetailsList.isEmpty())) {

            for (OutputFileReportDetails outputFileReportDetails : outputFileReportDetailsList) {

                try {
                    logger.info("Enter into callReport Generation ");
                    if (reportGenerationStatus) {

                        jasperReportsMapList = new ArrayList<Map<String, ?>>();

                        String ruleQuery = templateMapperService.retrieveRuleQuery(outputFileReportDetails.getRuleTemplateId().toString(),loopBack);
                        if(outputFile.getPath().contains("UNMASK")){
                            if(ruleQuery.contains("UNRECONCILED")){
                                ruleQuery=ruleQuery.replace("CARD_NUM AS CARD_NUM", "SYS_DECRYPT(ENCR_CARD_NUM)CARD_NUM");
                            }
                        }
                        logger.info("callReportGeneration rule Query :"+ruleQuery);
                        // String ruleQuery = "select CARD_NUM,TRAN_DATE,TRAN_TIME,SEQ_NUM,TRAN_AMOUNT, msg_type,ACTUAL_TRAN_AMOUNT,CARD_ACQ_TERM_ID,TRAN_CODE,RESP_CODE,FILE_SEQ_NUM from REC_NFSA_ACQ_STAGE_T";
                        if (ruleQuery != null&& !"".equalsIgnoreCase(ruleQuery)) {

                            String rowCountQuery = "select Count(*)  CNT from ("+ ruleQuery + ")";
                            logger.debug("rowCountQuery :"+rowCountQuery);
                            int rowCount = templateMapperService.retrieveReportRecordsCount(rowCountQuery,loopBack);
                            logger.debug("Number of rows returned :"+rowCount);

                            /****************************************************** START *****************************/
                            /*
                             * if(rowCount>10000){
                             *//******************************* START##### ***********************************/
                            /*
                             * String retrieveQuery1 = "SELECT * FROM (select row_.*, rownum rownum_ from ("+ruleQuery+")"+"row_  where rownum <="+ 10000+") where rownum_  >"+ 0;
                             *
                             * jasperReportsMapList = templateMapperService.retrieveJasperReportList(retrieveQuery1, loopBack);
                             *//******************************************************************************** TEST START *************************/
                            /*
                             * if((jasperReportsMapList!=null)&&!( jasperReportsMapList.isEmpty())){
                             *
                             * reportGenerationStatus =callReport(outputFileConfiguration,outputFileReportDetails,loopBack,outputStream,resourceBundle
                             * ,jasperReportsMapList,reportGenerationStatus ,jasperReportGeneration,outputFile);
                             *//**************************** END################# ***************************/
                            /*
                             *
                             * int realCount = 0; int tempCount = 0; int
                             * endCount =0;
                             *
                             *
                             * while(rowCount>10000){
                             * realCount = realCount+10000;
                             * endCount = realCount+10000;
                             * rowCount=rowCount-10000;
                             * String retrieveQuery ="SELECT * FROM (select row_.*, rownum rownum_ from ("+ruleQuery+")"+"row_  where rownum <="+ endCount+") where rownum_  >"+ realCount;
                             * jasperReportsMapList = templateMapperService.retrieveJasperReportList(retrieveQuery, loopBack);
                             *//******************************************************************************** TEST START *************************/
                            /*
                             * reportGenerationStatus =callReport(outputFileConfiguration ,outputFileReportDetails,loopBack,outputStream, resourceBundle ,jasperReportsMapList,reportGenerationStatus ,jasperReportGeneration,outputFile);
                             *//********************************************** TEST END ************************************************************/
                            /*
                             * System.out.println("RealCount  "+realCount+" TempCount "+tempCount+" EndCount "+endCount); }
                             * }else{
                             * outputStream.flush(); outputStream.close();
                             * outputStream = null; // System.gc();
                             * outputFile.delete(); reportGenerationStatus
                             * =false; }
                             *
                             * }else{
                             */

                            jasperReportsMapList = templateMapperService.retrieveJasperReportList(ruleQuery,loopBack);
                            jasperReportsMapList1.addAll(jasperReportsMapList);
                            jasperReportsMapList.clear();
                            // jasperReportsMapList=null;
                            /******************** TEST2 ************************************/
                            // modified by Nancy to generated report even map
                            // list is empty also 20.10.16
                            if ((jasperReportsMapList1 != null)
                                    && !(jasperReportsMapList1.isEmpty())) {
                                reportGenerationStatus = callReport(outputFileConfiguration,outputFileReportDetails, loopBack,outputStream, resourceBundle,jasperReportsMapList1,
                                        reportGenerationStatus,jasperReportGeneration, outputFile);
                            } else {
                                // added By Nancy (to get title from query when
                                // jasperReportsMapList is empty ) on 21-10-2016
                                boolean titlests = ruleQuery.contains("'");

                                if (titlests) {
                                    String temp1[] = ruleQuery.split("TITLE"); // TO handle more than one "'" (single quotes) in query
                                    ruleQuery = temp1[0];

                                    String temp[] = ruleQuery.split("'");// to split the query(select 'title' from table)

                                    int templen = temp.length;

                                    title = temp[templen - 2];// TO get report  title String
                                    Map<String, String> titlemap = new HashMap<String, String>();
                                    titlemap.put("TITLE", title);

                                    jasperReportsMapList1.add(titlemap);// appending the title into jasperReportsMapList
                                }

                                reportGenerationStatus = callReport(outputFileConfiguration,outputFileReportDetails, loopBack,outputStream, resourceBundle,
                                        jasperReportsMapList1,reportGenerationStatus,jasperReportGeneration, outputFile);
                                // nancy:ends

                                // outputStream.flush();
                                // outputStream.close();
                                // outputStream = null;
                                // System.gc();
                                // outputFile.delete();
                                // reportGenerationStatus =true;
                            }
                            // nancy:ends
                            /******************* TEST2 END *****************************/
                            // }

                            /****************************************************** END *******************************/

                        } else {
                            reportGenerationStatus = false;
                            outputStream.flush();
                            outputStream.close();
                            outputStream = null;
                            // System.gc();
                            outputFile.delete();
                            // reportGenerationStatus =false;
                        }
                    }

                } catch (Exception e) {

                    logger.error("Exception Occurred while generating Report : Report Name:"+outputFileReportDetails.getReportName());
                    reportGenerationStatus = false;
                    logger.error(" Exception Occured in Report Generation " + e.getMessage());
                    outputStream.flush();
                    outputStream.close();
                    outputStream = null;
                    // System.gc();
                    outputFile.delete();
                    // reportGenerationStatus =false;
                } finally {
                    jasperReportsMapList1.clear();
                    // jasperReportsMapList1 = null;
                    // jasperReportGeneration = null;
                }

            }

        } else {
            logger.error("Unable to to find Report Configuration for :"+outputFileConfiguration.getOutputFileName());
            reportGenerationStatus = false;
            outputStream.flush();
            outputStream.close();
            outputStream = null;
            // System.gc();
            outputFile.delete();
            // reportGenerationStatus =false;
        }

        return reportGenerationStatus;

    }

    public String getProcessName(String processId, LoopBack loopback) {

        String processname = " ";
        try {
            processname = templateMapperService.getFileProcessName(processId,
                    loopback);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return processname;
    }

    public String getProcessDate(String processId, LoopBack loopback) {

        String fileProcessDate = " ";
        try {
            fileProcessDate = templateMapperService.getFileProcessDate(processId, loopback);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return fileProcessDate;
    }

    @SuppressWarnings("unchecked")
    public boolean callReport(OutputFileConfiguration outputFileConfiguration,
            OutputFileReportDetails outputFileReportDetails, LoopBack loopBack,
            FileOutputStream outputStream, ResourceBundle resourceBundle,
            Collection<Map<String, ?>> jasperReportsMapList,
            boolean reportGenerationStatus,
            JasperReportGeneration jasperReportGeneration, File outputFile)
                    throws Exception {
        logger.debug("Report Generation callReport  Start...");
        String jrxmlTemplateName = templateMapperService.retrieveJRXMLTemplateName(outputFileReportDetails.getJrxmlTemplateId().toString(), loopBack);
        String jrxmlReportTemplatesPath = "";
        JasperDesign jasperDesign = null;
        JasperReport jasperReport = null;
        JasperPrint jasperPrint = null;
        JRSwapFileVirtualizer virtualizer = null;
        JRGzipVirtualizer gzipVirtualiser=null;//Added by saurabh for checking 09082018
        JRMapCollectionDataSource beanColDataSource = null;
        InputStream inputStream = null;
        Long startTime = null;
        Long endTime = null;
        int jasperListSize=38;
        logger.debug("JRXML TEMPLATE NAME..." + jrxmlTemplateName);
        if ("E".equalsIgnoreCase(outputFileConfiguration.getProcessType())) {
            // jrxmlReportTemplatesPath =userPath+File.separator+"ReportTemplates"+File.separator+"Extraction"+File.separator+jrxmlTemplateName;
            jrxmlReportTemplatesPath = resourceBundle.getString("RECON_TEMPLATES_EXTRACTION_PATH");
            jrxmlReportTemplatesPath = jrxmlReportTemplatesPath+ File.separator + jrxmlTemplateName;

        } else if ("R".equalsIgnoreCase(outputFileConfiguration.getProcessType())) {
            // jrxmlReportTemplatesPath = userPath+File.separator+"ReportTemplates"+File.separator+"Reconciliation"+File.separator+jrxmlTemplateName;
            jrxmlReportTemplatesPath = resourceBundle.getString("RECON_TEMPLATES_RECONCILIATION_PATH");
            jrxmlReportTemplatesPath = jrxmlReportTemplatesPath+ File.separator + jrxmlTemplateName;
        } else if ("D".equalsIgnoreCase(outputFileConfiguration.getProcessType())) {
            // jrxmlReportTemplatesPath = userPath+File.separator+"ReportTemplates"+File.separator+"Reconciliation"+File.separator+jrxmlTemplateName;
            jrxmlReportTemplatesPath = resourceBundle.getString("RECON_TEMPLATES_DISPUTEREPORTS_PATH");
            jrxmlReportTemplatesPath = jrxmlReportTemplatesPath+ File.separator + jrxmlTemplateName;
        } else if ("MR".equalsIgnoreCase(outputFileConfiguration.getProcessType())) {
            jrxmlReportTemplatesPath = resourceBundle.getString("RECON_TEMPLATES_MANRECREPORTS_PATH");
            jrxmlReportTemplatesPath = jrxmlReportTemplatesPath+ File.separator + jrxmlTemplateName;
        }
        try {

            File inputFile = new File(jrxmlReportTemplatesPath);

            inputStream = new FileInputStream(inputFile);
            beanColDataSource = new JRMapCollectionDataSource(jasperReportsMapList);

            //virtualizer = new JRSwapFileVirtualizer(100, new JRSwapFile(resourceBundle.getString("EXTRACTION_REPORTS_CACHE_PATH"),1024, 1024), true);

            // JRFileVirtualizer virtualizer = new JRFileVirtualizer(20,
            // "D:\FilesPath\Recon_Reports\Test\");
            //virtualizer.setReadOnly(false);
            //
            gzipVirtualiser=new JRGzipVirtualizer(5);//Added by saurabh for checking 09082018
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put(JRParameter.REPORT_VIRTUALIZER, gzipVirtualiser);
            // Added by Nancy for report Title parameter on oct.2016
            String title = null;

            for (Map<String, ?> id : jasperReportsMapList) {
                boolean status = id.containsKey("TITLE");
                boolean status1 = id.containsKey("PAGE_HEIGHT");
                if (status) {
                    title = id.get("TITLE").toString();
                    logger.debug(title+"is Running");
                    break;
                }
                /*if (status1) {
                    jasperListSize = Integer.parseInt(id.get("PAGE_HEIGHT").toString());
                    logger.debug("Page Height is:"+jasperListSize);
                    break;
                }*/
                
            }
            // String title = jasperReportsMapList.
            parameters.put("TITLE", title);
            if (processName != " ") {
                parameters.put("TITLE1", processName);
                parameters.put("FILEDATE", fileDate);
            }

            // nancy:ends

            //SN: Added by Maitri Shah on 24/4/18 for fixing spacing issue between column of UNREC SWT Recon Reports
            boolean isUnrecSwtRecRep = false;
            /*if(title.toUpperCase().contains("UNRECONCILED SW") || title.toUpperCase().contains("UNRECONCILED  SW") || title.toUpperCase().contains("(ATM)PRESENT IN SWITCH")) {
                isUnrecSwtRecRep = true;
            }*/

            //EN: Added by Maitri


            jasperDesign = JRXmlLoader.load(inputStream);
            jasperReport = JasperCompileManager.compileReport(jasperDesign);
            jasperPrint = null;

            startTime = System.currentTimeMillis();
            
            
//            DefaultJasperReportsContext context = DefaultJasperReportsContext.getInstance();
//            JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.xpath.executer.factory",
//                "net.sf.jasperreports.engine.util.xml.JaxenXPathExecuterFactory");
            // added by Mohan Raj.V to use Jaxen engine insted of default xpath engine
            JRProperties.setProperty("net.sf.jasperreports.xpath.executer.factory","net.sf.jasperreports.engine.util.xml.JaxenXPathExecuterFactory");//Added by saurabh for checking 09082018
            
            
            if (jasperReportsMapList != null && !jasperReportsMapList.isEmpty()) {

                jasperPrint = JasperFillManager.fillReport(jasperReport,parameters, beanColDataSource);
                // virtualizer.cleanup();
            } else {

                jasperPrint = JasperFillManager.fillReport(jasperReport,parameters, new JREmptyDataSource());
            }
            endTime = System.currentTimeMillis();
            
            logger.info("Report Fill Time ="+(endTime-startTime)/1000);
            
            startTime = System.currentTimeMillis();

            if ("PDF".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callPDFReportGeneration(outputStream, jasperPrint);

            } else if ("CSV".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callCSVReportGeneration(outputStream, jasperPrint);

            } else if ("TEXT".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {
                if(!isUnrecSwtRecRep) {                    
                    reportGenerationStatus = jasperReportGeneration.callTextReportGeneration(outputStream, jasperPrint);
                } else {
                    reportGenerationStatus = jasperReportGeneration.callTextReportGeneration(outputStream, jasperPrint,isUnrecSwtRecRep);
                }

            } else if ("XLSX".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callXlsxReportGeneration(outputStream, jasperPrint);

            } else if ("HTML".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callHtmlReportGeneration(outputStream, jasperPrint);

            } else if ("XML".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callXmlReportGeneration(outputStream, jasperPrint);

            } else if ("XLS".equalsIgnoreCase(outputFileConfiguration.getOutputFileFormat())) {

                reportGenerationStatus = jasperReportGeneration.callXlsReportGeneration(outputStream, jasperPrint);
            } else {
                reportGenerationStatus = jasperReportGeneration.callPDFReportGeneration(outputStream, jasperPrint);
            }
            endTime = System.currentTimeMillis();
            
            logger.info("Report write time ="+(endTime-startTime)/1000);

        } catch (Exception e) {
            logger.error("Exception Occurred while Report Generation : Format"+outputFileConfiguration.getOutputFileFormat() +
                    " Name Of The JRXML "+jrxmlTemplateName + " Path for JRXML "+jrxmlReportTemplatesPath  +e);
            outputStream.flush();
            outputStream.close();
            outputStream = null;
            // System.gc();
            outputFile.delete();
            reportGenerationStatus = false;
        } finally {
            virtualizer.cleanup();
            jasperDesign = null;
            jasperReport = null;
            jasperPrint = null;
            beanColDataSource = null;
            if (inputStream != null)
                inputStream.close();
            inputStream = null;

        }
        logger.debug("Report Generation callReport  End"+ reportGenerationStatus);
        return reportGenerationStatus;
    }

    /* Added by Mohan Raj.V on 12-04-16 for Cash Tally Report Generation */
/*
    public boolean callCashTallyReportGeneration(TallyProcessForm form,HttpServletRequest request,HttpServletResponse response)
            throws Exception {
        boolean status = false;
        String reportQuery = "";
        String tempDirName  = "";
        String tempFileName = "";
        String jrxmlTalliedTemplatePath = "";

        //Added By Kaviraj on 13-09-2017
        String outFilePath="";
        EJErrorKnockoffProcessForm ejErrform=null;

        //ResourceBundle rb = ResourceBundle.getBundle("location"); // genReport to Location
        try {

            Map<String, Object> parameters = new HashMap<String, Object>();
            if( "tally".equals( form.getReportType() ) ) {
                reportQuery = QueryPropertyUtil.getProperty("rcn.reconProcess.cashtallyReport.talliedReport");

                reportQuery = reportQuery + " where RTT_TRAN_DATE between TO_Date( '"+ form.getFromDate() + "','MM-DD-YYYY' )  and TO_Date( '"+ form.getToDate() + "' , 'MM-DD-YYYY')  and RTT_CASH_TALLY_FLG = 'Y' ";

                if( ! "".equals( form.getTerminalId() ) ) {
                    if( ! "all".equals( form.getTerminalId() ) )
                        reportQuery = reportQuery +" and RTT_TERM_Id = '"+form.getTerminalId()+"'";
                }

                jrxmlTalliedTemplatePath = LOCATION_BUNDLE.getString("jrxml_template_cashTally_filePath");
                tempDirName = LOCATION_BUNDLE.getString("OUTPUT_FILE_PATH_CASHTALLY");
                tempFileName = "CASH-TALLY-REP";
                parameters.put("TITLE", "CASH TALLY REPORT");

            } else if( "untally".equals( form.getReportType() ) ) {
                reportQuery = QueryPropertyUtil.getProperty("rcn.reconProcess.cashtallyReport.talliedReport");

                reportQuery = reportQuery + " where RTT_TRAN_DATE between TO_Date( '"+ form.getFromDate() + "','MM-DD-YYYY' )  and TO_Date( '"+ form.getToDate() + "' , 'MM-DD-YYYY')  and RTT_CASH_TALLY_FLG = 'N' ";

                if( ! "".equals( form.getTerminalId() ) ) {
                    if( ! "all".equals( form.getTerminalId() ) )
                        reportQuery = reportQuery +" and RTT_TERM_Id = '"+form.getTerminalId()+"'";
                }

                jrxmlTalliedTemplatePath = LOCATION_BUNDLE.getString("jrxml_template_cashTally_filePath");
                tempDirName = LOCATION_BUNDLE.getString("OUTPUT_FILE_PATH_CASHUNTALLY");
                tempFileName = "CASH-UNTALLY-REP";

                parameters.put("TITLE", "CASH UNTALLY REPORT");

            } else if( "adjustment".equals( form.getReportType() ) ) {

            } else if( "summary".equals( form.getReportType() ) ) {

                reportQuery = QueryPropertyUtil.getProperty("rcn.reconProcess.cashtallyReport.summaryReport");
                reportQuery = reportQuery + " where TRUNC(RCS_DATE) between TO_Date( '"+ form.getFromDate() + "','MM-DD-YYYY' )  and TO_Date( '"+ form.getToDate() + "' , 'MM-DD-YYYY')";

                jrxmlTalliedTemplatePath = LOCATION_BUNDLE.getString("TALLY_SUMMARY_JRXML_PATH").trim();
                //                tempFileName="TALLY_SUMMARY_REPORT"+"-"+new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(new Date()) + ".xlsx";
                tempFileName="TALLY_SUMMARY_REPORT";
                tempDirName=LOCATION_BUNDLE.getString("COMMON_REPORTS_TALLY_SUMMARY_PATH").trim();
            }

            //Added By NancyK for C3R Report Generation on 07-Sep-17:starts
            else if(("c3r").equals(form.getReportType())){

                reportQuery = QueryPropertyUtil.getProperty("rcn.reconProcess.cashtallyReport.C3RReport");
                reportQuery = reportQuery + " where TRUNC(PROCESS_DATE) between TO_Date( '"+ form.getFromDate() + "','MM-DD-YYYY' )  and TO_Date( '"+ form.getToDate() + "' , 'MM-DD-YYYY')";

                if( ! "".equals( form.getTerminalId() ) ) {
                    if( ! "all".equals( form.getTerminalId() ) )
                        reportQuery = reportQuery +" and TERM_ID = '"+form.getTerminalId()+"'";
                }

                if(("All").equals(form.getTimeMatchType())){
                    reportQuery = reportQuery + "AND LOAD_MATCH_FLG in ('Y','N','E','U')";//Y-Time Matched,N-Time Unmatched,E-No Load time,U-Un Processed (load time not present in swt also)
                }else{
                    reportQuery = reportQuery + "AND LOAD_MATCH_FLG='"+form.getTimeMatchType()+"' ";
                }
                parameters.put("TITLE", "C3R REPORT");
                //                tempFileName="TALLY_SUMMARY_REPORT"+"-"+new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(new Date()) + ".xlsx";
                jrxmlTalliedTemplatePath = LOCATION_BUNDLE.getString("CASH_TALLY_JRXML_PATH").trim()+ReconConfigPropertyUtil.getProperty("CASH_TALLY_C3R_JRXML");
                tempFileName="TALLY_C3R_REPORT";
                tempDirName=LOCATION_BUNDLE.getString("CASH_TALLY_C3R_REPORT_PATH").trim();

            }
            //ends
            //Added By Kaviraj on 13-09-2017
            else if("ejerr".equals(form.getReportType()))
            {
                ejErrform=new EJErrorKnockoffProcessForm();
                String[] splitArr=form.getChannel().split("-");
                ejErrform.setChannel(splitArr[0]);
                ejErrform.setChannelNames(splitArr[1].toUpperCase());
                ejErrform.setFromTranDate(form.getFromDate());
                ejErrform.setToTranDate(form.getToDate());

                outFilePath=ejErrorKnockoffService.callReportGeneration(ejErrform);
                if(outFilePath==null)
                    throw new Exception("Unable to Generate EJ Error Knockoff Report!!");

                status=true;

                if(("D").equals(form.getReportGenType()))
                {
                    splitArr=outFilePath.split("~~");
                    tempFileName=splitArr[0];
                    outFilePath=splitArr[1];
                }    
            }

            if(!"ejerr".equals(form.getReportType()))//If condition alone Added By Kaviraj on 13-09-2017
            {

                Collection<Map<String, ?>> talliedJasperReportsMapList = new ArrayList<Map<String, ?>>();

                logger.debug("Query to fetch Cash Tally Report :" + reportQuery);
                LoopBack loopBack = new LoopBack();


                talliedJasperReportsMapList = templateMapperService.retrieveJasperReportList(reportQuery, loopBack);


                File file = new File(jrxmlTalliedTemplatePath);
                InputStream inputStream = new FileInputStream(file);

                JRMapCollectionDataSource masterMapTalliedColDataSource = new JRMapCollectionDataSource(talliedJasperReportsMapList);

 

                JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
                JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
                JasperPrint jasperPrint = null;
                if (talliedJasperReportsMapList != null && !talliedJasperReportsMapList.isEmpty()) {

                    jasperPrint = JasperFillManager.fillReport(jasperReport,parameters, masterMapTalliedColDataSource);

                } else {

                    jasperPrint = JasperFillManager.fillReport(jasperReport,parameters, new JREmptyDataSource());
                }

                String outputFileFormat = LOCATION_BUNDLE.getString("OUTPUT_FILE_FORMAT");


                String fileNameDetail = getFileName(tempDirName, tempFileName);
                FileOutputStream outputStream = new FileOutputStream(new File(fileNameDetail) + "." + outputFileFormat.toLowerCase());
                JasperReportGeneration jasperReportGeneration = new JasperReportGeneration();

                if (outputFileFormat.equals("XLSX"))
                    status = jasperReportGeneration.callXlsxReportGeneration(outputStream, jasperPrint);
                else if (outputFileFormat.equals("PDF"))
                    status = jasperReportGeneration.callPDFReportGeneration(outputStream, jasperPrint);
                else if (outputFileFormat.equals("TXT"))
                    status = jasperReportGeneration.callTextReportGeneration(outputStream, jasperPrint);
                else if (outputFileFormat.equals("CSV"))
                    status = jasperReportGeneration.callCSVReportGeneration(outputStream, jasperPrint);
                else if (outputFileFormat.equals("XML"))
                    status = jasperReportGeneration.callXmlReportGeneration(outputStream, jasperPrint);

                inputStream.close();
                outputStream.flush();
                outputStream.close();
                ////Added by Nancy for C3R Reports on 07-Sep-17:starts
                outFilePath = fileNameDetail + "." + outputFileFormat.toLowerCase();
                tempFileName = tempFileName+new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(new Date())+ "." + outputFileFormat.toLowerCase();
            }

            if(("D").equals(form.getReportGenType()))
            {
                File downLoadOutFile=new File(outFilePath);
                InputStream inStream=new FileInputStream(downLoadOutFile);
                OutputStream outStream=null;

                //Download Logic here
                request.setAttribute("downloadFlag", new String("Download Request"));
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename="+tempFileName+";");
                outStream = response.getOutputStream();

                FileCopyUtils.copy(inStream, outStream);
                inStream.close();
                outStream.flush();
                outStream.close();

                //Deleting file from the path
                // if(downLoadOutFile.exists())
                //    downLoadOutFile.delete();

            }
            //Nancy:ends
        } catch (Exception e) {
            logger.error("Exception Occured in call cashtally report generation :",e);
        }
        return status;
    }
*/
    /*public boolean callCashTallyReportGeneration(TallyProcessForm form)
            throws Exception {
        boolean status = false;

        //ResourceBundle rb = ResourceBundle.getBundle("location"); // genReport to Location
        try {
            Collection<Map<String, ?>> talliedJasperReportsMapList = new ArrayList<Map<String, ?>>();
            String talliedReportQuery = QueryPropertyUtil
                    .getProperty("rcn.reconProcess.cashtallyReport.talliedReport");

            talliedReportQuery = talliedReportQuery + "  TO_Date( '"+ form.getFromDate() + "','MM-DD-YYYY' )  and TO_Date( '"+ form.getToDate() + "' , 'MM-DD-YYYY') order by rownum ";

            logger.debug("Query to fetch TalliedReport :" + talliedReportQuery);
            LoopBack loopBack = new LoopBack();

            // Commented by Mohan Raj.V for fixing Loopback Problem on 19-04-16
            /*
     * if (DataBasePropertyUtil.getProperty("recon.jndi") != null)
     * loopBack.setJndi((String)
     * DataBasePropertyUtil.getProperty("recon.jndi")); else {
     * loopBack.setJdbcUrl((String)
     * DataBasePropertyUtil.getProperty("recon.serviceName"));
     * loopBack.setJdbcUserId((String)
     * DataBasePropertyUtil.getProperty("recon.username"));
     * loopBack.setJdbcPassword((String)
     * DataBasePropertyUtil.getProperty("recon.password")); }

            // end by mohan raj.v

            talliedJasperReportsMapList = templateMapperService.retrieveJasperReportList(talliedReportQuery, loopBack);
            String jrxmlTalliedTemplatePath = LOCATION_BUNDLE.getString("jrxml_template_cashTallied_filePath");

            File file = new File(jrxmlTalliedTemplatePath);
            InputStream inputStream = new FileInputStream(file);

            JRMapCollectionDataSource masterMapTalliedColDataSource = new JRMapCollectionDataSource(
                    talliedJasperReportsMapList);

            Map<String, Object> parameters = new HashMap<String, Object>();
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            JasperReport jasperReport = JasperCompileManager
                    .compileReport(jasperDesign);
            JasperPrint jasperPrint = null;
            if (talliedJasperReportsMapList != null
                    && !talliedJasperReportsMapList.isEmpty()) {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, masterMapTalliedColDataSource);

            } else {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, new JREmptyDataSource());
            }

            String outputFileFormat = LOCATION_BUNDLE.getString("OUTPUT_FILE_FORMAT");
            String tempDirName = LOCATION_BUNDLE.getString("OUTPUT_FILE_PATH_CASHTALLY");
            String tempFileName = "CASH-TALLY-REP";

            String fileNameDetail = getFileName(tempDirName, tempFileName);
            FileOutputStream outputStream = new FileOutputStream(new File(
                    fileNameDetail) + "." + outputFileFormat.toLowerCase());
            JasperReportGeneration jasperReportGeneration = new JasperReportGeneration();

            if (outputFileFormat.equals("XLSX"))
                status = jasperReportGeneration.callXlsxReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("PDF"))
                status = jasperReportGeneration.callPDFReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("TXT"))
                status = jasperReportGeneration.callTextReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("CSV"))
                status = jasperReportGeneration.callCSVReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("XML"))
                status = jasperReportGeneration.callXmlReportGeneration(
                        outputStream, jasperPrint);

            inputStream.close();
            outputStream.flush();
            outputStream.close();

            // untallied Report Generation

            if (status) {

                Collection<Map<String, ?>> untalliedJasperReportsMapList = new ArrayList<Map<String, ?>>();

                String untalliedReportQuery = QueryPropertyUtil
                        .getProperty("rcn.reconProcess.cashtallyReport.untalliedReport");

                untalliedReportQuery = untalliedReportQuery + "  TO_Date( '"
                        + form.getFromDate()
                        + "','MM-DD-YYYY' )  and TO_Date( '" + form.getToDate()
                        + "' , 'MM-DD-YYYY') order by rownum ";

                logger.debug("Query to fetch UnTalliedReport :"
                        + untalliedReportQuery);

                untalliedJasperReportsMapList = templateMapperService
                        .retrieveJasperReportList(untalliedReportQuery,
                                loopBack);

                String jrxmlUntalliedTemplatePath = LOCATION_BUNDLE.getString("jrxml_template_cashUntallied_filePath");

                // System.exit(0);

                File file2 = new File(jrxmlUntalliedTemplatePath);
                InputStream inputStream2 = new FileInputStream(file2);

                JRMapCollectionDataSource masterMapUntalliedColDataSource = new JRMapCollectionDataSource(
                        untalliedJasperReportsMapList);

                Map<String, Object> parameters2 = new HashMap<String, Object>();
                JasperDesign jasperDesign2 = JRXmlLoader.load(inputStream2);
                JasperReport jasperReport2 = JasperCompileManager
                        .compileReport(jasperDesign2);
                JasperPrint jasperPrint2 = null;
                if (untalliedJasperReportsMapList != null
                        && !untalliedJasperReportsMapList.isEmpty()) {

                    jasperPrint2 = JasperFillManager.fillReport(jasperReport2,
                            parameters2, masterMapUntalliedColDataSource);

                } else {

                    jasperPrint2 = JasperFillManager.fillReport(jasperReport2,
                            parameters2, new JREmptyDataSource());
                }

                String outputFileFormat2 = LOCATION_BUNDLE.getString("OUTPUT_FILE_FORMAT");
                String tempDirName2 = LOCATION_BUNDLE.getString("OUTPUT_FILE_PATH_CASHUNTALLY");
                String tempFileName2 = "CASH-UNTALLY-REP";

                String fileNameDetail2 = getFileName(tempDirName2,
                        tempFileName2);
                FileOutputStream outputStream2 = new FileOutputStream(new File(
                        fileNameDetail2) + "." + outputFileFormat.toLowerCase());

                JasperReportGeneration jasperReportGeneration2 = new JasperReportGeneration();

                if (outputFileFormat2.equals("XLSX"))
                    status = jasperReportGeneration2.callXlsxReportGeneration(
                            outputStream2, jasperPrint2);
                else if (outputFileFormat2.equals("PDF"))
                    status = jasperReportGeneration2.callPDFReportGeneration(
                            outputStream2, jasperPrint2);
                else if (outputFileFormat2.equals("TXT"))
                    status = jasperReportGeneration2.callTextReportGeneration(
                            outputStream2, jasperPrint2);
                else if (outputFileFormat2.equals("CSV"))
                    status = jasperReportGeneration2.callCSVReportGeneration(
                            outputStream2, jasperPrint2);
                else if (outputFileFormat2.equals("XML"))
                    status = jasperReportGeneration2.callXmlReportGeneration(
                            outputStream2, jasperPrint2);

                inputStream2.close();
                outputStream2.flush();
                outputStream2.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return status;
    }
     */
    // Added by Mohan Raj.V
    public String getFileName(String tempDirName, String tempFileName)
            throws Exception {

        String dat = DisputeUtils.getddMMyyyy(DisputeUtils.getCurrentDate());
        String tempName = "";
        int tmpcnt = 0;
        int fileLength = 0;
        int dotIndex = 0;
        fileLength = tempFileName.length() + 8 + 1;
        tempFileName = tempFileName + dat + "." + "00";

        try {
            File dir = new File(tempDirName);
            if (!dir.exists() || !dir.isDirectory())
                throw new ReconUserDefinedException(tempDirName
                        + " Directory not Found.");
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files.exists() && files.isFile())
                    tempName = files.getName();
                dotIndex = tempName.toString().lastIndexOf(".");
                if (tempFileName.equals(tempName.toString().substring(0,
                        dotIndex))) {

                    tempFileName = tempFileName.substring(0, fileLength)
                            + DisputeUtils.padLeft(Integer.toString(Integer
                                    .parseInt(tempFileName
                                            .substring(fileLength)) + 1), 2,
                                    "0");
                }
            }
        }// try
        catch (Exception e) {
            throw new ReconUserDefinedException("Exception " + e);
        }
        return tempDirName + tempFileName;
    }

    public boolean callReportGeneration(mofdiscountForm form, String vendorname) {
        boolean status = false;

        //ResourceBundle rb = ResourceBundle.getBundle("location");
        try {
            Collection<Map<String, ?>> masterJasperReportsMapList = new ArrayList<Map<String, ?>>();
            String masterRuleQuery = QueryPropertyUtil
                    .getProperty("MASTER_REPORT_DATA_QUERY");
            LoopBack loopBack = new LoopBack();

            if (DataBasePropertyUtil.getProperty("recon.jndi") != null)
                loopBack.setJndi((String) DataBasePropertyUtil
                        .getProperty("recon.jndi"));
            else {
                loopBack.setJdbcUrl((String) DataBasePropertyUtil
                        .getProperty("recon.serviceName"));
                loopBack.setJdbcUserId((String) DataBasePropertyUtil
                        .getProperty("recon.username"));
                loopBack.setJdbcPassword((String) DataBasePropertyUtil
                        .getProperty("recon.password"));
            }
            masterJasperReportsMapList = templateMapperService
                    .retrieveJasperReportList(masterRuleQuery, loopBack);

            System.out.println(masterJasperReportsMapList);
            String jrxmlTemplatePath = LOCATION_BUNDLE.getString("JRXML_TEMPLATE_FILE_PATH");

            // System.exit(0);

            File file = new File(jrxmlTemplatePath);
            InputStream inputStream = new FileInputStream(file);

            JRMapCollectionDataSource masterMapColDataSource = new JRMapCollectionDataSource(
                    masterJasperReportsMapList);

            Map<String, Object> parameters = new HashMap<String, Object>();
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            JasperReport jasperReport = JasperCompileManager
                    .compileReport(jasperDesign);
            JasperPrint jasperPrint = null;
            if (masterJasperReportsMapList != null
                    && !masterJasperReportsMapList.isEmpty()) {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, masterMapColDataSource);

            } else {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, new JREmptyDataSource());
            }

            String outputFileFormat = LOCATION_BUNDLE.getString("OUTPUT_FILE_FORMAT");
            FileOutputStream outputStream = new FileOutputStream(
                    new File(LOCATION_BUNDLE.getString("OUTPUT_FILE_PATH_DISCNT") + "_"
                            + form.getMonth() + "-" + form.getYear() + "_"
                            + vendorname + "." + outputFileFormat.toLowerCase()));
            JasperReportGeneration jasperReportGeneration = new JasperReportGeneration();

            if (outputFileFormat.equals("XLSX"))
                status = jasperReportGeneration.callXlsxReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("PDF"))
                status = jasperReportGeneration.callPDFReportGeneration(
                        outputStream, jasperPrint);

            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return status;
    }

    public boolean callMOFBillingReportGeneration(mofdiscountForm form,
            String vendorname) {
        boolean status = false;

        //ResourceBundle rb = ResourceBundle.getBundle("location");
        try {
            Collection<Map<String, ?>> masterJasperReportsMapList = new ArrayList<Map<String, ?>>();
            String masterRuleQuery = QueryPropertyUtil
                    .getProperty("MOF_BILLINGREPORT_QUERY");
            LoopBack loopBack = new LoopBack();

            if (DataBasePropertyUtil.getProperty("recon.jndi") != null)
                loopBack.setJndi((String) DataBasePropertyUtil
                        .getProperty("recon.jndi"));
            else {
                loopBack.setJdbcUrl((String) DataBasePropertyUtil
                        .getProperty("recon.serviceName"));
                loopBack.setJdbcUserId((String) DataBasePropertyUtil
                        .getProperty("recon.username"));
                loopBack.setJdbcPassword((String) DataBasePropertyUtil
                        .getProperty("recon.password"));
            }
            masterJasperReportsMapList = templateMapperService
                    .retrieveJasperReportList(masterRuleQuery, loopBack);

            System.out.println(masterJasperReportsMapList);
            String jrxmlTemplatePath = LOCATION_BUNDLE.getString("JRXML_MOF_BILLING_TEMPLATE_FILE_PATH");

            // System.exit(0);

            File file = new File(jrxmlTemplatePath);
            InputStream inputStream = new FileInputStream(file);

            JRMapCollectionDataSource masterMapColDataSource = new JRMapCollectionDataSource(
                    masterJasperReportsMapList);

            Map<String, Object> parameters = new HashMap<String, Object>();
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            JasperReport jasperReport = JasperCompileManager
                    .compileReport(jasperDesign);
            JasperPrint jasperPrint = null;
            if (masterJasperReportsMapList != null
                    && !masterJasperReportsMapList.isEmpty()) {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, masterMapColDataSource);

            } else {

                jasperPrint = JasperFillManager.fillReport(jasperReport,
                        parameters, new JREmptyDataSource());
            }

            String outputFileFormat = LOCATION_BUNDLE.getString("OUTPUT_FILE_FORMAT");
            FileOutputStream outputStream = new FileOutputStream(
                    new File(LOCATION_BUNDLE.getString("OUTPUT_MOF_BILLING_FILE_PATH") + "_"
                            + form.getMonth() + "-" + form.getYear() + "_"
                            + vendorname + "." + outputFileFormat.toLowerCase()));
            JasperReportGeneration jasperReportGeneration = new JasperReportGeneration();

            if (outputFileFormat.equals("XLSX"))
                status = jasperReportGeneration.callXlsxReportGeneration(
                        outputStream, jasperPrint);
            else if (outputFileFormat.equals("PDF"))
                status = jasperReportGeneration.callPDFReportGeneration(
                        outputStream, jasperPrint);

            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return status;
    }

    public boolean callSubreportGeneration(SubreportForm form,
            String institutionName) {
        boolean status = true;
        try {
            this.institutionName = institutionName;
            this.form = form;
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Future<Boolean> future = executor.submit(this);
            executor.shutdown();
        } catch (Exception e) {
            status = false;
            logger.error("Error in subreport generation : " + e.getMessage());
        }
        return status;
    }

    @Override
    public Boolean call() throws Exception {
        boolean status = true;
        File file = null;
        FileOutputStream outputStream = null;
        LocalObject localObject = new LocalObject();
        List<LocalObject> list = null;
        Iterator<LocalObject> listIterator = null;
        DatabaseService dbService = new DatabaseService();
        Collection<Map<String, ?>> bodyReportsMapList = new ArrayList<Map<String, ?>>();
        LoopBack loopBack = null;
        String tableName = "";
        String columnName = "";
        String query1 = "";
        String query2 = "";        
        DateFormat sdf = new SimpleDateFormat("ddMMyyHHmmss");
        Date date = new Date();
        String dateTimeStr = sdf.format(date);
        try {

            tableName = form.getTableName();
            columnName = form.getColumnName();

            loopBack = new LoopBack();
            if (DataBasePropertyUtil.getProperty("recon.jndi") != null)
                loopBack.setJndi((String) DataBasePropertyUtil
                        .getProperty(institutionName + ".jndi"));
            else {
                loopBack.setJdbcUrl(DataBasePropertyUtil
                        .getProperty(institutionName + ".serviceName"));
                loopBack.setJdbcUserId(DataBasePropertyUtil
                        .getProperty(institutionName + ".username"));
                loopBack.setJdbcPassword(DataBasePropertyUtil
                        .getProperty(institutionName + ".password"));
                loopBack.setDriver(DataBasePropertyUtil
                        .getProperty(institutionName + ".driver"));
                loopBack.setInstitutionCode(institutionName);
            }

            //rb = ResourceBundle.getBundle("location");
            file = new File(LOCATION_BUNDLE.getString("RECON_SUBREPORTS_GENERATION_PATH")
                    + File.separator + "subreport" + dateTimeStr + ".txt");
            outputStream = new FileOutputStream(file, true);

            String jrxmlPath = LOCATION_BUNDLE.getString("RECON_TEMPLATES_SUBREPORTS_PATH")
                    + File.separator;
            String titleJrxmlPath = jrxmlPath + "titlereport.jrxml";
            File titleJrxml = new File(titleJrxmlPath);
            InputStream inputStream = new FileInputStream(titleJrxml);

            String bodyJrxmlPath = "";
            if (columnName.equalsIgnoreCase("BIN")) {
                bodyJrxmlPath = jrxmlPath + "binbasedreport.jrxml";
                query1 = QueryPropertyUtil
                        .getProperty("rcn.reconprocess.subreport.reportsfetchbin")
                        + tableName;
            } else if (columnName.equalsIgnoreCase("BRANCH")) {
                bodyJrxmlPath = jrxmlPath + "branchbasedreport.jrxml";
                query1 = QueryPropertyUtil
                        .getProperty("rcn.reconprocess.subreport.reportsfetchbranch")
                        + tableName + " where brch_id is not null";
            }
            File bodyJrxml = new File(bodyJrxmlPath);

            Map<String, Object> parameters = new HashMap<String, Object>();
            JasperDesign titleJasperDesign = JRXmlLoader.load(inputStream);
            JasperReport titleJasperReport = JasperCompileManager
                    .compileReport(titleJasperDesign);
            JasperPrint titleJasperPrint = null;

            titleJasperPrint = JasperFillManager.fillReport(titleJasperReport,
                    parameters, new JREmptyDataSource());

            JRTextExporter textExporter = new JRTextExporter();
            textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 150);
            textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 7); // 35
            textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT,
                    titleJasperPrint);
            textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
                    outputStream);

            textExporter.exportReport();
            inputStream.close();

            localObject.put("LOOPBACK", loopBack);
            list = dbService.executeQuery(query1, localObject);

            listIterator = list.iterator();

            while (listIterator.hasNext()) {
                // query2 =
                // QueryPropertyUtil.getProperty("rcn.reconprocess.subreport.reportsfetchtransaction")+tableName;
                String criteria = "";
                if (columnName.equalsIgnoreCase("BIN")) {
                    criteria = listIterator.next().get("BIN").toString();
                    query2 = QueryPropertyUtil
                            .getProperty("rcn.reconprocess.subreport.reportsfetchtransaction")
                            + tableName
                            + " where substr(CARD_NUM, 1, 6) = '"
                            + criteria + "'";
                } else if (columnName.equalsIgnoreCase("BRANCH")) {
                    criteria = listIterator.next().get("BRANCH").toString();
                    query2 = QueryPropertyUtil
                            .getProperty("rcn.reconprocess.subreport.reportsfetchtransaction")
                            + tableName + " where brch_id = '" + criteria + "'";
                }

                String rowCountQuery = "select Count(*)  CNT from (" + query2
                        + ")";
                int rowCount = templateMapperService
                        .retrieveReportRecordsCount(rowCountQuery, loopBack);

                if (rowCount <= 50000) {
                    bodyReportsMapList = templateMapperService
                            .retrieveJasperReportList(query2, loopBack);

                    JRMapCollectionDataSource bodyMapColDataSource = new JRMapCollectionDataSource(
                            bodyReportsMapList);

                    InputStream inputStream2 = new FileInputStream(bodyJrxml);
                    Map<String, Object> bodyParameters = new HashMap<String, Object>();
                    JasperDesign jasperDesign = JRXmlLoader.load(inputStream2);
                    JasperReport jasperReport = JasperCompileManager
                            .compileReport(jasperDesign);
                    JasperPrint jasperPrint = null;
                    if (bodyReportsMapList != null
                            && !bodyReportsMapList.isEmpty()) {

                        jasperPrint = JasperFillManager.fillReport(
                                jasperReport, bodyParameters,
                                bodyMapColDataSource);

                    } else {

                        jasperPrint = JasperFillManager.fillReport(
                                jasperReport, parameters,
                                new JREmptyDataSource());
                    }

                    textExporter = new JRTextExporter();
                    textExporter.setParameter(
                            JRTextExporterParameter.PAGE_WIDTH, 150);
                    textExporter.setParameter(
                            JRTextExporterParameter.PAGE_HEIGHT, 25); // 35
                    textExporter.setParameter(
                            JRTextExporterParameter.JASPER_PRINT, jasperPrint);
                    textExporter
                    .setParameter(
                            JRTextExporterParameter.OUTPUT_STREAM,
                            outputStream);
                    textExporter.exportReport();

                    inputStream2.close();
                } else {
                    String retrieveQuery1 = "SELECT * FROM (select row_.*, rownum rownum_ from ("
                            + query2
                            + ")"
                            + "row_  where rownum <="
                            + 50000
                            + ") where rownum_  >" + 0;

                    bodyReportsMapList = templateMapperService
                            .retrieveJasperReportList(retrieveQuery1, loopBack);

                    if (bodyReportsMapList != null
                            && !bodyReportsMapList.isEmpty()) {
                        JRMapCollectionDataSource bodyMapColDataSource = new JRMapCollectionDataSource(
                                bodyReportsMapList);

                        InputStream inputStream2 = new FileInputStream(
                                bodyJrxml);
                        Map<String, Object> bodyParameters = new HashMap<String, Object>();
                        JasperDesign jasperDesign = JRXmlLoader
                                .load(inputStream2);
                        JasperReport jasperReport = JasperCompileManager
                                .compileReport(jasperDesign);
                        JasperPrint jasperPrint = null;
                        if (bodyReportsMapList != null
                                && !bodyReportsMapList.isEmpty()) {

                            jasperPrint = JasperFillManager.fillReport(
                                    jasperReport, bodyParameters,
                                    bodyMapColDataSource);

                        } else {

                            jasperPrint = JasperFillManager.fillReport(
                                    jasperReport, parameters,
                                    new JREmptyDataSource());
                        }

                        textExporter = new JRTextExporter();
                        textExporter.setParameter(
                                JRTextExporterParameter.PAGE_WIDTH, 150);
                        textExporter.setParameter(
                                JRTextExporterParameter.PAGE_HEIGHT, 25); // 35
                        textExporter.setParameter(
                                JRTextExporterParameter.JASPER_PRINT,
                                jasperPrint);
                        textExporter.setParameter(
                                JRTextExporterParameter.OUTPUT_STREAM,
                                outputStream);
                        textExporter.exportReport();

                        inputStream2.close();
                    } else {
                        outputStream.flush();
                        outputStream.close();
                        file.delete();
                        status = false;
                    }

                    int realCount = 0;
                    int endCount = 0;

                    while (rowCount > 50000) {
                        realCount = realCount + 50000;
                        endCount = realCount + 50000;
                        rowCount = rowCount - 50000;

                        String retrieveQuery = "SELECT * FROM (select row_.*, rownum rownum_ from ("
                                + query2
                                + ")"
                                + "row_  where rownum <="
                                + endCount + ") where rownum_  >" + realCount;
                        bodyReportsMapList = templateMapperService
                                .retrieveJasperReportList(retrieveQuery,
                                        loopBack);

                        JRMapCollectionDataSource bodyMapColDataSource = new JRMapCollectionDataSource(
                                bodyReportsMapList);

                        InputStream inputStream2 = new FileInputStream(
                                bodyJrxml);
                        Map<String, Object> bodyParameters = new HashMap<String, Object>();
                        JasperDesign jasperDesign = JRXmlLoader
                                .load(inputStream2);
                        JasperReport jasperReport = JasperCompileManager
                                .compileReport(jasperDesign);
                        JasperPrint jasperPrint = null;
                        if (bodyReportsMapList != null
                                && !bodyReportsMapList.isEmpty()) {

                            jasperPrint = JasperFillManager.fillReport(
                                    jasperReport, bodyParameters,
                                    bodyMapColDataSource);

                        } else {

                            jasperPrint = JasperFillManager.fillReport(
                                    jasperReport, parameters,
                                    new JREmptyDataSource());
                        }

                        textExporter = new JRTextExporter();
                        textExporter.setParameter(
                                JRTextExporterParameter.PAGE_WIDTH, 150);
                        textExporter.setParameter(
                                JRTextExporterParameter.PAGE_HEIGHT, 25); // 35
                        textExporter.setParameter(
                                JRTextExporterParameter.JASPER_PRINT,
                                jasperPrint);
                        textExporter.setParameter(
                                JRTextExporterParameter.OUTPUT_STREAM,
                                outputStream);
                        textExporter.exportReport();

                        inputStream2.close();
                    }
                }

                textExporter = null;
            }
        } catch (Exception e) {
            outputStream.flush();
            outputStream.close();
            file.delete();
            status = false;
            logger.error("Exception occured in callSubreportGeneration : "
                    + e.getMessage());
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                logger.error("Error in closing output stream in callSubreportGeneration : "
                        + e.getMessage());
            }
            dbService = null;
            localObject = null;
            list = null;
            listIterator = null;
            bodyReportsMapList = null;
            loopBack = null;
        }
        return status;
    }

    // Added by Nancy for xls voucher (ttum) on 03-11-16
    public boolean callXlsxReportGeneration(FileOutputStream outputStream,
            JasperPrint jasperPrint, ArrayList<JasperPrint> list,
            String[] sheetNames) {
        logger.debug("Report Generation callXlsxReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRXlsxExporter xlsxExporter = new JRXlsxExporter();
        xlsxExporter
        .setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xlsxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                outputStream);
        xlsxExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
                Boolean.TRUE);
        xlsxExporter.setParameter(JRXlsExporterParameter.SHEET_NAMES,
                sheetNames);
        xlsxExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT_LIST,
                list);
        xlsxExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,
                Boolean.TRUE);
        xlsxExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,Boolean.TRUE);//Added by saurabh for Voucher Issue UAT 95 14/05/18
        try {
            xlsxExporter.exportReport();
        } catch (JRException e) {

            reportGenerationStatus = false;
            logger.debug("XLSX Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callXlsxReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    /**
     * @purpose:This method is to support Multiple JasperPrint for TEXT
     * @author :Kaviraj.J
     * @date :10-11-2016
     * @param :FileOutputStream,ArrayList<JasperPrint>
     * @return :boolean
     */
    public boolean callTextMultipleReportGeneration(
            FileOutputStream outputStream,
            ArrayList<JasperPrint> jasperPrintlist) {
        logger.debug("Report Generation callTextMultipleReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 250);
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 38); // 35//42
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
                outputStream);
        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT_LIST,
                jasperPrintlist);

        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callTextMultipleReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }
    /**
     * @purpose:This method is to support Multiple JasperPrint for Text
     * @author :Nancy.J
     * @date :08-09-2017
     * @param :FileOutputStream,ArrayList<JasperPrint>
     * @return :boolean
     */
    public boolean callTextMultipleReportCashTallyGeneration(
            FileOutputStream outputStream,
            ArrayList<JasperPrint> jasperPrintlist) {
        logger.debug("Report Generation callTextMultipleReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRTextExporter textExporter = new JRTextExporter();
        textExporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 250);
        textExporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 20); // 35//42
        textExporter.setParameter(JRTextExporterParameter.OUTPUT_STREAM,
                outputStream);
        textExporter.setParameter(JRTextExporterParameter.JASPER_PRINT_LIST,
                jasperPrintlist);

        try {
            textExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;

            logger.debug("TEXT Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callTextMultipleReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    /**
     * @purpose:This method is to support Multiple JasperPrint for PDF
     * @author :Kaviraj.J
     * @date :10-11-2016
     * @param :FileOutputStream,ArrayList<JasperPrint>
     * @return :boolean
     */
    public boolean callPDFMultipleReportGeneration(
            FileOutputStream outputStream,
            ArrayList<JasperPrint> jasperPrintlist) {
        logger.debug("Report Generation callPDFReportGeneration  Start");
        boolean reportGenerationStatus = true;
        JRPdfExporter pdfExporter = new JRPdfExporter();
        pdfExporter.setParameter(JRTextExporterParameter.JASPER_PRINT_LIST,
                jasperPrintlist);
        pdfExporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,
                outputStream);
        try {
            pdfExporter.exportReport();
        } catch (JRException e) {
            reportGenerationStatus = false;
            logger.debug("PDF Report Generation " + e.getMessage());
        }
        logger.debug("Report Generation callPDFReportGeneration  End "
                + reportGenerationStatus);
        return reportGenerationStatus;
    }

    /**
     * @purpose:This method is to generate Report for Force Match
     * @author :Kaviraj.J
     * @date :20-10-2016
     * @param :String processName,String outfilePath, String processId,LoopBack loopBack
     * @return :boolean
     */
    public boolean forceMatchReportGeneration(String processName,String outfilePath, String processId)
    {
        logger.debug("Force Match Report Generation Starts...");
        List<ForceMatchReportGenForm> list = new ArrayList<ForceMatchReportGenForm>();        
        String jrxmlPath = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        String outFileName = "";
        String startEndTime = "";
        boolean flag = true;
        try
        {
            jrxmlPath = LOCATION_BUNDLE.getString("FORCE_MATCH_REPORT_JRXML").trim();
            File jrxmlfile = null;

            try
            {
                jrxmlfile = new File(jrxmlPath);
                inputStream = new FileInputStream(jrxmlfile);
            } catch (Exception e) {
                logger.error("JRXML File Not Found in this path is "+ jrxmlPath);
                return false;
            }

            list = manrecProcessService.getReportDetails(processId);
            startEndTime=manrecProcessService.getMaxStartEndTime(processId);

            jasperPrintlist = frameJasperPrintList(processId, list, inputStream,processName,startEndTime);

            if (jasperPrintlist != null && jasperPrintlist.size() > 0)
            {
                outFileName = outfilePath+ processName.replaceAll(" ","")+ "-"+ new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss").format(new Date()) + ".xlsx";
                outputStream = new FileOutputStream(new File(outFileName));

                callXlsxReportGeneration(outputStream, new JasperPrint(),jasperPrintlist, new String[5]);

                inputStream.close();
                outputStream.flush();
                outputStream.close();
            } else
                flag = false;

        } catch (Exception e) {
            logger.error("Exception occured in Force Match Report Generation... "
                    + e);
            flag = false;
        }
        logger.debug("Force Match Report Generation Ends...");
        return flag;
    }

    /**
     * @purpose:This method is to frame JasperPrint List
     * @author :Kaviraj.J
     * @date :20-10-2016
     * @param :String processId,String outfilePath, String processId,LoopBack
     *        loopBack
     * @return :ArrayList<JasperPrint>
     */

    public ArrayList<JasperPrint> frameJasperPrintList(String processId,List<ForceMatchReportGenForm> list, InputStream inputStream,String processName,String startEndTime)throws Exception
    {
        logger.debug("Frame Jasper Print List for Force Match Report Starts...");

        Collection<Map<String, ?>> dataList = null;
        String query = null;

        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        JasperPrint jasperPrint = null;
        JasperDesign jasperDesign = null;
        JasperReport jasperReport = null;
        Map<String, Object> parameters = new HashMap<String, Object>();
        List<String> fileTypes = new ArrayList<String>();
        String actualQry = null;
        String preManRecFlg="1";
        String[] startTimeEndTime;
        try
        {
            jasperDesign = JRXmlLoader.load(inputStream);// loading jrxml
            jasperReport = JasperCompileManager.compileReport(jasperDesign);// Compiling jrxml

            if (list != null && list.size() > 0)
            {
                fileTypes = manrecProcessService.getFileTypesForCardIgnore();
                startTimeEndTime=startEndTime.split("\|");
                query = QueryPropertyUtil.getProperty("DB.FORCE_MATCH.REPORT_GEN.GET.COLUMNS");

                for (ForceMatchReportGenForm form : list)
                {
                    //For Plain and Adjustment knockoff PreManRecFlg is '1'
                    //For Keep It Unreconciled PreManRecFlg is '2'
                    if(form.getActionTypeId()!=null && form.getActionTypeId().equals("2"))
                        preManRecFlg="2";

                    // Removing CARD_NUM field from the query for some filetypes
                    actualQry = frameQueryForForceMatchReportGeneration(query,form.getTableName(), fileTypes)+ " "+ form.getTableName()+ " WHERE ACTION_ID='"+ form.getActionId()
                            + "' AND PREMANRECREL_FLG='"+preManRecFlg+"'";

                    if(form.getApprReqFlag().equalsIgnoreCase("N"))
                    {    
                        actualQry+=" AND MANRECREL_FLG='1' AND REC_FLG='1' AND USER_PROCESS_DATE BETWEEN TO_DATE('"+startTimeEndTime[0]+"','DD-MON-YYYY HH24:MI:SS')"
                                +" AND TO_DATE('"+startTimeEndTime[1]+"','DD-MON-YYYY HH24:MI:SS')";
                    }else
                        actualQry+=" AND MANRECREL_FLG='0' AND REC_FLG='0'";

                    logger.debug("Force Match Report Query for the Action Id "+form.getActionId()+" is :"+ actualQry);

                    parameters.put("TITLE", form.getDescription());
                    parameters.put("DESCRIPTION", form.getDescription());
                    parameters.put("PROCESS_NAME", processName);
                    parameters.put("ACTION_TYPE", form.getActionType());

                    dataList = templateMapperService.retrieveJasperReportList(actualQry, null);
                    if (dataList != null && !dataList.isEmpty())
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JRMapCollectionDataSource(dataList));
                    else
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JREmptyDataSource());

                    jasperPrintlist.add(jasperPrint);
                }
            }
        } catch (Exception e) {
            logger.error("Exception occured in Frame Jasper Print List for Force Match Report ... "
                    + e);
            jasperPrintlist = new ArrayList<JasperPrint>();
        }
        logger.debug("Frame Jasper Print List for Force Match Report Ends...");
        return jasperPrintlist;
    }

    /**
     * @purpose:This method is to frame Select Query for Report Generation
     * @author :Kaviraj.J
     * @date :20-10-2016
     * @param :String query,String tableName,List<String> fileTypes
     * @return :String
     */
    public String frameQueryForForceMatchReportGeneration(String query,
            String tableName, List<String> fileTypes) throws Exception {
        logger.debug("Frame Query For Force Match Report Generation Starts..");
        String actualQry = null;
        try {
            if (fileTypes.contains(tableName.split("_")[1]))
                actualQry = query.replace("CARD_NUM,", " ").replace("TERM_ID,","");// Removing CARD NUMBER and TERM ID
            else
                actualQry = query;
        } catch (Exception e) {
            logger.error("Exception occured in Frame Query For Force Match Report Generation");
        }
        logger.debug("Frame Query For Force Match Report Generation Ends..");
        return actualQry;
    }

    public boolean reconGenericReport(String processId, String processName,
            LoopBack loopBack) {

        //rb = ResourceBundle.getBundle("location");
        logger.debug("Voucher Config getInterchange Starts");
        List<LocalObject> objectList = null;
        DatabaseService databaseService = null;
        LocalObject localObj = null;
        Iterator<LocalObject> itr = null;
        Map<Object, Object> map = null;
        // LoopBack loopBack = null;
        ArrayList<String> templateTypeNames = new ArrayList<String>();
        String file_name_date = new SimpleDateFormat("HH-mm").format(new Date());
        //rb = ResourceBundle.getBundle("location");
        // BufferedWriter out = null;
        boolean status = false;
        logger.debug("Recon generic reports start");
        try {
            // get input count (2-way/3-way/4-way)
            // loopBack = new LoopBack();
            String query = QueryPropertyUtil.getProperty("DB.GET.INPUT.COUNT");
            logger.debug("Query TO GET INPUT COUNT: " + query);
            System.out.println("query " + query);
            map = new HashMap<Object, Object>();
            objectList = new ArrayList<LocalObject>();
            databaseService = new DatabaseService();
            localObj = new LocalObject();
            localObj.put(1, processId);
            localObj.put("LOOPBACK", loopBack);

            objectList = databaseService.executeQuery(query, localObj);

            itr = objectList.iterator();
            localObj = (LocalObject) itr.next();
            map = localObj.getMap();

            String inputCount = map.get("RPM_INPUT_COUNT").toString();
            // GET RECON COUNT - COMMON FOR 2,3,4 WAY RECON
            String query5 = QueryPropertyUtil
                    .getProperty("DB.GET.RECON.MASTERTABLE");
            logger.debug("Query Is: " + query5);
            localObj = new LocalObject();
            localObj.put(1, processId);
            localObj.put("LOOPBACK", loopBack);
            objectList = databaseService.executeQuery(query5, localObj);

            itr = objectList.iterator();
            localObj = (LocalObject) itr.next();
            map = localObj.getMap();
            String tableR = map.get("RPM_DATA_TAB_NAME1").toString();
            String queryR = "select count(1) AS RECON_COUNT, nvl(SUM(TRAN_AMOUNT), 0) AS REC_AMT from " + tableR
                    + " where rec_flg = 1 and rev_flag = 'N'"; //rev_flag added by Mohan Raj.V  to prevent summation of full reversal data on 21-03-17
            logger.debug("Query Is: " + queryR);
            localObj = new LocalObject();
            localObj.put("LOOPBACK", loopBack);
            objectList = databaseService.executeQuery(queryR, localObj);

            itr = objectList.iterator();
            localObj = (LocalObject) itr.next();
            map = localObj.getMap();
            String REC_COUNT = map.get("RECON_COUNT").toString();
            String SUM_REC_AMOUNT = map.get("REC_AMT").toString();
            if (inputCount == "2" || inputCount.equals("2")) {
                // ---------------------------------------************ TWO WAY
                // RECON ***********--------------------------------------
                // UNRECONCILED COUNT A
                String query1 = QueryPropertyUtil
                        .getProperty("DB.GET.RECON.TWOWAY.TABLESA");
                logger.debug("Query Is: " + query1);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query1, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableA = map.get("RPM_DATA_TAB_NAME1").toString();
                String flagTwo = map.get("RPM_REC_FLAG_NAME2").toString();

                String queryA = "SELECT (SELECT COUNT(1) FROM " + tableA
                        + " WHERE rec_flg=0 AND " + flagTwo + " = 0) INA,  "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE  rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0) SUMTWOA,"
                        + "(SELECT COUNT(1) FROM " + tableA
                        + " WHERE rec_flg=0 AND " + flagTwo
                        + " = 1 ) INAB,  "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE  rec_flg=0 AND rev_flg!='F' AND" + flagTwo + " = 1) SUMTWOAB FROM DUAL";
                logger.debug("Query Is: " + queryA);
                System.out.println("QUERY " + queryA);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryA, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INA = map.get("INA").toString();
                String UNREC_INAB = map.get("INAB").toString();
                String SUM_TWO_TRAN_A = map.get("SUMTWOA").toString();
                String SUM_TWO_TRAN_AB = map.get("SUMTWOAB").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT B
                String queryB = QueryPropertyUtil
                        .getProperty("DB.GET.RECON.TWOWAY.TABLESB");
                logger.debug("Query Is: " + queryB);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryB, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableB = map.get("RPM_DATA_TAB_NAME2").toString();
                String flagOne = map.get("RPM_REC_FLAG_NAME1").toString();

                String query2 = "SELECT (SELECT COUNT(1) FROM " + tableB
                        + " WHERE rec_flg=0 AND " + flagOne + " = 0) INB, "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE  rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0) SUMTWOB,"
                        + "(SELECT COUNT(1) FROM " + tableB
                        + " WHERE rec_flg=0 AND " + flagOne
                        + " = 1 ) INBA,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE  rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1) SUMTWOBA FROM DUAL";
                logger.debug("Query Is: " + query2);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query2, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INB = map.get("INB").toString();
                String UNREC_INBA = map.get("INBA").toString();
                String SUM_TWO_TRAN_B = map.get("SUMTWOB").toString();
                String SUM_TWO_TRAN_BA = map.get("SUMTWOBA").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // get process short names
                String queryT = QueryPropertyUtil
                        .getProperty("DB.GET.TEMPLATETYPE.NAME");
                logger.debug("Query Is: " + queryT);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put(2, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryT, localObj);
                itr = objectList.iterator();

                while (itr.hasNext()) {
                    localObj = (LocalObject) itr.next();
                    map = localObj.getMap();
                    templateTypeNames.add(map.get("RTM_TYPE_NAME").toString());
                    localObj = null;
                }
                System.out.println(templateTypeNames.toString());
                // -----------------------------------------------------------********************---------------------------------------------------------
                // write details to a report
                String date = new SimpleDateFormat("dd-MMM-yy")
                .format(new Date());
                System.out.println("DATE " + date);
                String outFilePath_full = LOCATION_BUNDLE
                        .getString("RECON_REPORTS_GENERATION_PATH")
                        + File.separator
                        + processName
                        + File.separator
                        + date
                        + File.separator;
                String outFilePath = LOCATION_BUNDLE
                        .getString("RECON_REPORTS_GENERATION_PATH")
                        + File.separator + processName + File.separator;
                File repDirPath_full = new File(outFilePath_full);
                //File repDirPath_date = new File(outFilePath);

                if (!repDirPath_full.exists())
                    repDirPath_full.mkdirs();

                OutputStream out = new FileOutputStream(new File(
                        repDirPath_full + File.separator + processName + "_"
                                + file_name_date + "SUMMARYREPORT" + ".txt"));

                String aa = "REPORT NAME    :  " + processName
                        + " SUMMARY REPORT " + "n";
                aa += "DATE           : "
                        + new SimpleDateFormat("dd-MM-yy").format(new Date())
                        + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "RECONCILED COUNT                                : " + REC_COUNT + "n";
                aa += "SUM OF RECONCILED TRAN AMOUNT            : " + SUM_REC_AMOUNT + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + ")                : " + UNREC_INA+"            "+SUM_TWO_TRAN_A
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(1) + ")        : " + UNREC_INAB+"            "+SUM_TWO_TRAN_AB
                        + "n";
                //                aa += "SUM OF TRAN AMOUNT(PRESENT IN "
                //                        + templateTypeNames.get(0) + ")                : " + SUM_TWO_TRAN_A + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + ")                    : " + UNREC_INB+"            "+SUM_TWO_TRAN_B
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(0) + ")        : " + UNREC_INBA+"            "+SUM_TWO_TRAN_BA
                        + "n";
                //                aa += "SUM OF TRAN AMOUNT(PRESENT IN "
                //                        + templateTypeNames.get(1) + ")                : " + SUM_TWO_TRAN_B + "n";
                out.write(aa.getBytes());
                out.close();
                status=true;

            } else if (inputCount == "3" || inputCount.equals("3")) {
                // ---------------------------------------************ THREE WAY
                // RECON ***********--------------------------------------
                // UNRECONCILED COUNT A
                String query1 = QueryPropertyUtil
                        .getProperty("DB.GET.RECON.TABLESA");
                logger.debug("Query Is: " + query1);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query1, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableA = map.get("RPM_DATA_TAB_NAME1").toString();
                String flagTwo = map.get("RPM_REC_FLAG_NAME2").toString();
                String flagThree = map.get("RPM_REC_FLAG_NAME3").toString();

                String queryA = "SELECT (SELECT COUNT(1) FROM "
                        + tableA
                        + " WHERE rec_flg=0 AND "
                        + flagTwo
                        + " = 0 AND "
                        + flagThree
                        + " =0) INA, "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg =0 AND "
                        + flagTwo + " = 0" + "AND " + flagThree + "  =0) SUMA,"
                        + "(SELECT COUNT(1) FROM " + tableA
                        + " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 1 AND "
                        + flagThree + " =0) INAB, "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg =0 AND "
                        + flagTwo + " = 1" + "AND " + flagThree + "  =0) SUMAB, (SELECT COUNT(1) FROM "
                        + tableA + " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo
                        + " = 0 AND " + flagThree + " =1)" + "INAC, "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg =0 AND rev_flg!='F' AND "
                        + flagTwo + " = 0" + "AND " + flagThree + "  =1) SUMAC FROM DUAL";
                logger.debug("Query Is: " + queryA);
                System.out.println("QUERY " + queryA);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryA, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INA = map.get("INA").toString();
                String UNREC_INAB = map.get("INAB").toString();
                String UNREC_INAC = map.get("INAC").toString();
                String SUM_A_TRAN = map.get("SUMA").toString();
                String SUM_AB_TRAN = map.get("SUMAB").toString();
                String SUM_AC_TRAN = map.get("SUMAC").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT B
                String queryB = QueryPropertyUtil
                        .getProperty("DB.GET.RECON.TABLESB");
                logger.debug("Query Is: " + queryB);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryB, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableB = map.get("RPM_DATA_TAB_NAME2").toString();
                String flagOne = map.get("RPM_REC_FLAG_NAME1").toString();
                String flagThre = map.get("RPM_REC_FLAG_NAME3").toString();

                String query2 = "SELECT (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND  rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =0) INB, "
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg =0 AND rev_flg!='F' AND "+ flagOne + " = 0" + "AND " + flagThre + "  =0) SUMB,"
                        + "(SELECT COUNT(1) FROM "+ tableB + " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne+ " = 1 AND " + flagThre+ " =0) INBA,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg =0 AND rev_flg!='F' AND "+ flagOne + " = 1" + "AND " + flagThre + "  =0) SUMBA,"
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =1)" + "INBC,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg =0 AND rev_flg!='F' AND "+ flagOne + " = 0" + "AND " + flagThre + "  =1) SUMBC"
                        + " FROM DUAL";
                logger.debug("Query Is: " + query2);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query2, localObj);
                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INB = map.get("INB").toString();
                String UNREC_INBA = map.get("INBA").toString();
                String UNREC_INBC = map.get("INBC").toString();
                String SUM_B_TRAN = map.get("SUMB").toString();
                String SUM_BA_TRAN = map.get("SUMBA").toString();
                String SUM_BC_TRAN = map.get("SUMBC").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT C
                String query3 = QueryPropertyUtil
                        .getProperty("DB.GET.RECON.TABLESC");
                logger.debug("Query Is: " + query3);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query3, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableC = map.get("RPM_DATA_TAB_NAME3").toString();
                String flagTW = map.get("RPM_REC_FLAG_NAME1").toString();
                String flagON = map.get("RPM_REC_FLAG_NAME2").toString();

                String queryC = "SELECT (SELECT COUNT(1) FROM " + tableC
                        + " WHERE rec_flg=0 AND " + flagTW + " = 0 AND "
                        + flagON + " =0) INC,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg =0 AND rev_flg!='F' AND "
                        + flagTW + " = 0" + "AND " + flagON + "  =0) SUMC," + "(SELECT COUNT(1) FROM "
                        + tableC + " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTW
                        + " = 1 AND " + flagON
                        + " =0) INCA,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg =0 AND "
                        + flagTW + " = 1" + "AND " + flagON + "  =0) SUMCA, (SELECT COUNT(1) FROM " + tableC
                        + " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTW + " = 0 AND "
                        + flagON + " =1)" + "INCB,"
                        + "(SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg =0 AND rev_flg!='F' AND "
                        + flagTW + " = 0" + "AND " + flagON + "  =1) SUMCB FROM DUAL";
                logger.debug("Query Is: " + queryC);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryC, localObj);
                // objectList = databaseService.E

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INC = map.get("INC").toString();
                String UNREC_INCA = map.get("INCA").toString();
                String UNREC_INCB = map.get("INCB").toString();
                String SUM_C_TRAN = map.get("SUMC").toString();
                String SUM_CA_TRAN = map.get("SUMCA").toString();
                String SUM_CB_TRAN = map.get("SUMCB").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // get process short names
                String queryT = QueryPropertyUtil
                        .getProperty("DB.GET.TEMPLATETYPE.NAME");
                logger.debug("Query Is: " + queryT);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put(2, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryT, localObj);
                itr = objectList.iterator();

                while (itr.hasNext()) {
                    localObj = (LocalObject) itr.next();
                    map = localObj.getMap();
                    templateTypeNames.add(map.get("RTM_TYPE_NAME").toString());
                    localObj = null;
                }
                System.out.println(templateTypeNames.toString());
                // -----------------------------------------------------------********************---------------------------------------------------------
                // write details to a report
                String date = new SimpleDateFormat("dd-MMM-yy")
                .format(new Date());
                String outFilePath_full = LOCATION_BUNDLE
                        .getString("RECON_REPORTS_GENERATION_PATH")
                        + File.separator
                        + processName
                        + File.separator
                        + date
                        + File.separator;
                String outFilePath = LOCATION_BUNDLE
                        .getString("RECON_REPORTS_GENERATION_PATH")
                        + File.separator + processName + File.separator;
                File repDirPath_full = new File(outFilePath_full);
                File repDirPath_date = new File(outFilePath);

                if (!repDirPath_full.exists())
                    repDirPath_full.mkdirs();

                OutputStream out = new FileOutputStream(new File(
                        repDirPath_full + File.separator + processName
                        + "SUMMARYREPORT" + "_" + file_name_date
                        + ".txt"));
                String emptySpace = "                                                          ";
                String aa = "REPORT NAME    : " + processName
                        + " SUMMARY REPORT " + "n";
                aa += "DATE           : "
                        + new SimpleDateFormat("dd-MM-yy").format(new Date())
                        + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "RECONCILED COUNT                        : " + REC_COUNT + "n";
                aa += "SUM OF RECONCILED TRAN AMOUNT            : " + SUM_REC_AMOUNT + "n";
                //                String.format("%20s %20s rn", aa);
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";

                int spaceLength =emptySpace.length();
                int alen = templateTypeNames.get(0).length() ;
                int blen = templateTypeNames.get(0).length() +3 + templateTypeNames.get(1).length() ;
                int clen = templateTypeNames.get(0).length() +3 + templateTypeNames.get(2).length() ;

                int aspace = spaceLength - alen;
                int bspace  =spaceLength - blen;
                int cspace  =spaceLength - clen;
                String aspaces = String.format("%"+aspace+"s", "");
                String bspaces = String.format("%"+bspace+"s", "");
                String cspaces = String.format("%"+cspace+"s", "");

                //---------------
                int dlen = templateTypeNames.get(1).length() ;
                int elen = templateTypeNames.get(1).length() +3 + templateTypeNames.get(0).length() ;
                int flen = templateTypeNames.get(1).length() +3 + templateTypeNames.get(2).length() ;

                int dspace = spaceLength - dlen;
                int espace  =spaceLength - elen;
                int fspace  =spaceLength - flen;
                String dspaces = String.format("%"+dspace+"s", "");
                String espaces = String.format("%"+espace+"s", "");
                String fspaces = String.format("%"+fspace+"s", "");
                //--------------
                int glen = templateTypeNames.get(2).length() ;
                int hlen = templateTypeNames.get(2).length() +3 + templateTypeNames.get(0).length() ;
                int ilen = templateTypeNames.get(2).length() +3 + templateTypeNames.get(1).length() ;

                int gspace = spaceLength - glen;
                int hspace  =spaceLength - hlen;
                int ispace  =spaceLength - ilen;
                String gspaces = String.format("%"+gspace+"s", "");
                String hspaces = String.format("%"+hspace+"s", "");
                String ispaces = String.format("%"+ispace+"s", "");

                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + ")"+aspaces+": "+ UNREC_INA+"   "+SUM_A_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(1) + ")"+bspaces+": "+ UNREC_INAB+"   "+SUM_AB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(2) + ")"+cspaces+": "+ UNREC_INAC+"   "+SUM_AC_TRAN
                        + "n";

                //                aa += "SUM OF TRAN AMOUNT(PRESENT IN "
                //                        + templateTypeNames.get(0) + ")                                    : " + SUM_A_TRAN + "n";

                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + ")"+dspaces+": "+ UNREC_INB+"   "+SUM_B_TRAN + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(0) + ")"+espaces+": "+ UNREC_INBA+"   "+SUM_BA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(2) + ")"+fspaces+": "+ UNREC_INBC+"   "+SUM_BC_TRAN
                        + "n";
                //                aa += "SUM OF TRAN AMOUNT(PRESENT IN "
                //                        + templateTypeNames.get(1) + ")                                            : " + SUM_B_TRAN + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + ")"+gspaces+": "+UNREC_INC+"   "+SUM_C_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        + templateTypeNames.get(0) + ")"+hspaces+": "+ UNREC_INCA+"   "+SUM_CA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        + templateTypeNames.get(1) + ")"+ispaces+": "+ UNREC_INCB+"   "+SUM_CB_TRAN
                        + "n";
                //                aa += "SUM OF TRAN AMOUNT(PRESENT IN "
                //                        + templateTypeNames.get(2) + ")                                    : " + SUM_C_TRAN + "n";
                out.write(aa.getBytes());
                out.close();
                status=true;

            }else if (inputCount == "4" || inputCount.equals("4")) {
                // ---------------------------------------************ FOUR WAY
                // RECON ***********--------------------------------------
                // UNRECONCILED COUNT A
                String query1 = QueryPropertyUtil.getProperty("DB.GET.RECON.FOURWAY.TABLESA");
                logger.debug(" UNRECONCILED A Table Detail Query: " + query1);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query1, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableA = map.get("RPM_DATA_TAB_NAME1").toString();
                String flagTwo = map.get("RPM_REC_FLAG_NAME2").toString();
                String flagThree = map.get("RPM_REC_FLAG_NAME3").toString();
                String flagFour = map.get("RPM_REC_FLAG_NAME4").toString();

                String queryA = " SELECT (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =0 AND " + flagFour+ " = 0) INA,"
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =0 AND " + flagFour+ " = 0) SUMA, "
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 1 AND "+ flagThree + " =0 AND " + flagFour+ " = 0) INAB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =0 AND " + flagFour+ " = 0) SUMAB, "
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =1 AND " + flagFour+ " = 0) INAC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =1 AND " + flagFour+ " = 0) SUMAC, "
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =0 AND " + flagFour+ " = 1) INAD, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =0 AND " + flagFour+ " = 1) SUMAD, "
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 1 AND "+ flagThree + " =1 AND " + flagFour+ " = 0) INABC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 1 AND "+ flagThree + " =1 AND " + flagFour+ " = 0) SUMABC, "    
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =1 AND " + flagFour+ " = 1) INACD, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =1 AND " + flagFour+ " = 1) SUMACD, "    
                        + " (SELECT COUNT(1) FROM " + tableA+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 0 AND "+ flagThree + " =1 AND " + flagFour+ " = 0) INADB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableA+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagTwo + " = 1 AND "+ flagThree + " =0 AND " + flagFour+ " = 1) SUMADB "    
                        + " FROM DUAL";

                logger.debug(" UNRECONCILED A SUM AND COUNT QUERY: " + queryA);
                System.out.println("QUERY " + queryA);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryA, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INA = map.get("INA").toString();
                String UNREC_INAB = map.get("INAB").toString();
                String UNREC_INAC = map.get("INAC").toString();
                String UNREC_INAD = map.get("INAD").toString();
                String UNREC_INABC = map.get("INABC").toString();
                String UNREC_INACD = map.get("INACD").toString();
                String UNREC_INADB = map.get("INADB").toString();
                String SUM_A_TRAN = map.get("SUMA").toString();
                String SUM_AB_TRAN = map.get("SUMAB").toString();
                String SUM_AC_TRAN = map.get("SUMAC").toString();
                String SUM_AD_TRAN = map.get("SUMAD").toString();
                String SUM_ABC_TRAN = map.get("SUMABC").toString();
                String SUM_ACD_TRAN = map.get("SUMACD").toString();
                String SUM_ADB_TRAN = map.get("SUMADB").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT B
                String queryB = QueryPropertyUtil.getProperty("DB.GET.RECON.FOURWAY.TABLESB");
                logger.debug(" UNRECONCILED B Table Detail Query: " + queryB);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryB, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableB = map.get("RPM_DATA_TAB_NAME2").toString();
                String flagOne = map.get("RPM_REC_FLAG_NAME1").toString();
                String flagThre = map.get("RPM_REC_FLAG_NAME3").toString();
                String flagFou = map.get("RPM_REC_FLAG_NAME4").toString();

                String query2 = " SELECT (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =0 AND " + flagFou+ " = 0) INB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =0 AND " + flagFou+ " = 0) SUMB, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =0 AND " + flagFou+ " = 0) INBA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =0 AND " + flagFou+ " = 0) SUMBA, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =1 AND " + flagFou+ " = 0) INBC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =1 AND " + flagFou+ " = 0) SUMBC, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =0 AND " + flagFou+ " = 1) INBD, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =0 AND " + flagFou+ " = 1) SUMBD, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =1 AND " + flagFou+ " = 0) INBAC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =1 AND " + flagFou+ " = 0) SUMBAC, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =1 AND " + flagFou+ " = 1) INBCD, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 0 AND "+ flagThre + " =1 AND " + flagFou+ " = 1) SUMBCD, "
                        + " (SELECT COUNT(1) FROM " + tableB+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =0 AND " + flagFou+ " = 1) INBDA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableB+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagOne + " = 1 AND "+ flagThre + " =0 AND " + flagFou+ " = 1) SUMBDA "
                        + " FROM DUAL";

                logger.debug(" UNRECONCILED B SUM AND COUNT QUERY: " + query2);

                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query2, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INB = map.get("INB").toString();
                String UNREC_INBA = map.get("INBA").toString();
                String UNREC_INBC = map.get("INBC").toString();
                String UNREC_INBD = map.get("INBD").toString();
                String UNREC_INBAC = map.get("INBAC").toString();
                String UNREC_INBCD = map.get("INBCD").toString();
                String UNREC_INBDA = map.get("INBDA").toString();
                String SUM_B_TRAN = map.get("SUMB").toString();
                String SUM_BA_TRAN = map.get("SUMBA").toString();
                String SUM_BC_TRAN = map.get("SUMBC").toString();
                String SUM_BD_TRAN = map.get("SUMBD").toString();
                String SUM_BAC_TRAN = map.get("SUMBAC").toString();
                String SUM_BCD_TRAN = map.get("SUMBCD").toString();
                String SUM_BDA_TRAN = map.get("SUMBDA").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT C
                String query3 = QueryPropertyUtil.getProperty("DB.GET.RECON.FOURWAY.TABLESC");
                logger.debug(" UNRECONCILED C Table Detail Query: " + query3);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query3, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableC = map.get("RPM_DATA_TAB_NAME3").toString();
                String flagTW = map.get("RPM_REC_FLAG_NAME2").toString();
                String flagON = map.get("RPM_REC_FLAG_NAME1").toString();
                String flagFO = map.get("RPM_REC_FLAG_NAME4").toString();

                String queryC = " SELECT (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =0 AND " + flagFO+ " = 0) INC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =0 AND " + flagFO+ " = 0) SUMC, "
                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =0 AND " + flagFO+ " = 0) INCA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =0 AND " + flagFO+ " = 0) SUMCA, "
                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =1 AND " + flagFO+ " = 0) INCB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =1 AND " + flagFO+ " = 0) SUMCB, "
                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =0 AND " + flagFO + " = 1) INCD, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =1 AND " + flagFO+ " = 0) SUMCD, "

                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =0 AND " + flagFO + " = 1) INCDA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =0 AND " + flagFO+ " = 1) SUMCDA, "
                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =1 AND " + flagFO + " = 1) INCDB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 0 AND "+ flagTW + " =1 AND " + flagFO+ " = 0) SUMCDB, "
                        + " (SELECT COUNT(1) FROM " + tableC+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =1 AND " + flagFO + " = 0) INCAB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableC+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagON + " = 1 AND "+ flagTW + " =1 AND " + flagFO+ " = 0) SUMCAB "
                        + " FROM DUAL";

                logger.debug(" UNRECONCILED C SUM AND COUNT QUERY: " + queryC);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryC, localObj);
                // objectList = databaseService.E

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_INC = map.get("INC").toString();
                String UNREC_INCA = map.get("INCA").toString();
                String UNREC_INCB = map.get("INCB").toString();
                String UNREC_INCD = map.get("INCD").toString();

                String UNREC_INCDA = map.get("INCDA").toString();
                String UNREC_INCDB = map.get("INCDB").toString();
                String UNREC_INCAB = map.get("INCAB").toString();

                String SUM_C_TRAN = map.get("SUMC").toString();
                String SUM_CA_TRAN = map.get("SUMCA").toString();
                String SUM_CB_TRAN = map.get("SUMCB").toString();
                String SUM_CD_TRAN = map.get("SUMCD").toString();

                String SUM_CDA_TRAN = map.get("SUMCDA").toString();
                String SUM_CDB_TRAN = map.get("SUMCDB").toString();
                String SUM_CAB_TRAN = map.get("SUMCAB").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // UNRECONCILED COUNT D
                String query4 = QueryPropertyUtil.getProperty("DB.GET.RECON.FOURWAY.TABLESD");
                logger.debug(" UNRECONCILED D Table Detail Query: " + query4);

                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(query4, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String tableD = map.get("RPM_DATA_TAB_NAME4").toString();
                String flagTW0 = map.get("RPM_REC_FLAG_NAME2").toString();
                String flagONE = map.get("RPM_REC_FLAG_NAME1").toString();
                String flagTHR = map.get("RPM_REC_FLAG_NAME3").toString();

                String queryD = " SELECT (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 0) IND, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 0) SUMD, "
                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 0) INDA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 0) SUMDA, "
                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 0) INDB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 0) SUMDB, "
                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 1) INDC, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 1) SUMDC, "

                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 1) INDCA, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =0 AND " + flagTHR+ " = 1) SUMDCA, "
                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 1) INDCB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 0 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 1) SUMDCB, "
                        + " (SELECT COUNT(1) FROM " + tableD+ " WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 0) INDAB, "
                        + " (SELECT NVL(SUM(TRAN_AMOUNT), 0) FROM "+tableD+" WHERE rec_flg=0 AND rev_flg!='F' AND " + flagONE + " = 1 AND "+ flagTW0 + " =1 AND " + flagTHR+ " = 0) SUMDAB "
                        + " FROM DUAL";
                logger.debug(" UNRECONCILED D SUM AND COUNT QUERY: " + queryD);
                localObj = new LocalObject();
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryD, localObj);

                itr = objectList.iterator();
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                String UNREC_IND = map.get("IND").toString();
                String UNREC_INDA = map.get("INDA").toString();
                String UNREC_INDB = map.get("INDB").toString();
                String UNREC_INDC = map.get("INDC").toString();

                String UNREC_INDCA = map.get("INDCA").toString();
                String UNREC_INDCB = map.get("INDCB").toString();
                String UNREC_INDAB = map.get("INDAB").toString();

                String SUM_D_TRAN = map.get("SUMD").toString();
                String SUM_DA_TRAN = map.get("SUMDA").toString();
                String SUM_DB_TRAN = map.get("SUMDB").toString();
                String SUM_DC_TRAN = map.get("SUMDC").toString();

                String SUM_DCA_TRAN = map.get("SUMDCA").toString();
                String SUM_DCB_TRAN = map.get("SUMDCB").toString();
                String SUM_DAB_TRAN = map.get("SUMDAB").toString();
                // ------------------------------------------------------------******----------------------------------------------------------------

                // get process short names
                String queryT = QueryPropertyUtil.getProperty("DB.GET.TEMPLATETYPE.NAME");
                logger.debug("Query TO GET TEMPLATE TYPE NAME : " + queryT);
                localObj = new LocalObject();
                localObj.put(1, processId);
                localObj.put(2, processId);
                localObj.put("LOOPBACK", loopBack);
                objectList = databaseService.executeQuery(queryT, localObj);
                itr = objectList.iterator();

                while (itr.hasNext()) {
                    localObj = (LocalObject) itr.next();
                    map = localObj.getMap();
                    templateTypeNames.add(map.get("RTM_TYPE_NAME").toString());
                    localObj = null;
                }
                System.out.println(templateTypeNames.toString());
                // -----------------------------------------------------------********************---------------------------------------------------------
                // write details to a report
                String date = new SimpleDateFormat("dd-MMM-yy")
                .format(new Date());
                String outFilePath_full = LOCATION_BUNDLE.getString("RECON_REPORTS_GENERATION_PATH")+ File.separator+ processName+ File.separator+ date+ File.separator;
                String outFilePath = LOCATION_BUNDLE.getString("RECON_REPORTS_GENERATION_PATH")+ File.separator + processName + File.separator;
                File repDirPath_full = new File(outFilePath_full);
                File repDirPath_date = new File(outFilePath);

                if (!repDirPath_full.exists())
                    repDirPath_full.mkdirs();

                OutputStream out = new FileOutputStream(new File(repDirPath_full + File.separator + processName+ "SUMMARYREPORT" + "_" + file_name_date+ ".txt"));
                String emptySpace = "                                                          ";
                String aa = "REPORT NAME    : " + processName
                        + "SUMMARY REPORT" + "n";
                aa += "DATE           : "
                        + new SimpleDateFormat("dd-MM-yy").format(new Date())
                        + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "RECONCILED COUNT                        : " + REC_COUNT + "n";
                aa += "SUM OF RECONCILED TRAN AMOUNT            : " + SUM_REC_AMOUNT + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";

                int spaceLength =emptySpace.length();
                int alen = templateTypeNames.get(0).length() ;
                int blen = templateTypeNames.get(0).length() +3 + templateTypeNames.get(1).length() ;
                int clen = templateTypeNames.get(0).length() +3 + templateTypeNames.get(2).length() ;
                int dlen = templateTypeNames.get(0).length() +3 + templateTypeNames.get(3).length() ;
                int d1len = templateTypeNames.get(0).length() +3 + templateTypeNames.get(1).length() + 3 + templateTypeNames.get(2).length() ;
                int d2len = templateTypeNames.get(0).length() +3 + templateTypeNames.get(2).length() + 3 + templateTypeNames.get(3).length() ;
                int d3len = templateTypeNames.get(0).length() +3 + templateTypeNames.get(3).length() + 3 + templateTypeNames.get(1).length() ;

                int aspace = spaceLength - alen;
                int bspace  =spaceLength - blen;
                int cspace  =spaceLength - clen;
                int dspace = spaceLength - dlen;
                int d1space = spaceLength - d1len;
                int d2space = spaceLength - d2len;
                int d3space = spaceLength - d3len;
                String aspaces = String.format("%"+aspace+"s", "");
                String bspaces = String.format("%"+bspace+"s", "");
                String cspaces = String.format("%"+cspace+"s", "");
                String dspaces = String.format("%"+dspace+"s", "");

                String d1spaces = String.format("%"+d1space+"s", "");
                String d2spaces = String.format("%"+d2space+"s", "");
                String d3spaces = String.format("%"+d3space+"s", "");

                //--------------- a0 b1 c2 d3
                int elen = templateTypeNames.get(1).length() ;
                int flen = templateTypeNames.get(1).length() +3 + templateTypeNames.get(0).length() ;
                int glen = templateTypeNames.get(1).length() +3 + templateTypeNames.get(2).length() ;
                int hlen = templateTypeNames.get(1).length() +3 + templateTypeNames.get(3).length() ;
                int h1len = templateTypeNames.get(1).length() +3 + templateTypeNames.get(0).length() + 3 + templateTypeNames.get(2).length() ;
                int h2len = templateTypeNames.get(1).length() +3 + templateTypeNames.get(2).length() + 3 + templateTypeNames.get(3).length() ;
                int h3len = templateTypeNames.get(1).length() +3 + templateTypeNames.get(3).length() + 3 + templateTypeNames.get(0).length() ;

                int espace = spaceLength - elen;
                int fspace  =spaceLength - flen;
                int gspace  =spaceLength - glen;
                int hspace  =spaceLength - hlen;
                int h1space  =spaceLength - h1len;
                int h2space  =spaceLength - h2len;
                int h3space  =spaceLength - h3len;
                String espaces = String.format("%"+espace+"s", "");
                String fspaces = String.format("%"+fspace+"s", "");
                String gspaces = String.format("%"+gspace+"s", "");
                String hspaces = String.format("%"+hspace+"s", "");
                String h1spaces = String.format("%"+h1space+"s", "");
                String h2spaces = String.format("%"+h2space+"s", "");
                String h3spaces = String.format("%"+h3space+"s", "");
                //--------------
                int ilen = templateTypeNames.get(2).length() ;
                int jlen = templateTypeNames.get(2).length() +3 + templateTypeNames.get(0).length() ;
                int klen = templateTypeNames.get(2).length() +3 + templateTypeNames.get(1).length() ;
                int llen = templateTypeNames.get(2).length() +3 + templateTypeNames.get(3).length() ;
                int l1len = templateTypeNames.get(2).length() +3 + templateTypeNames.get(3).length() +3 + templateTypeNames.get(0).length() ;
                int l2len = templateTypeNames.get(2).length() +3 + templateTypeNames.get(3).length() +3 + templateTypeNames.get(1).length() ;
                int l3len = templateTypeNames.get(2).length() +3 + templateTypeNames.get(0).length() +3 + templateTypeNames.get(1).length() ;

                int ispace = spaceLength - ilen;
                int jspace  =spaceLength - jlen;
                int kspace  =spaceLength - klen;
                int lspace  =spaceLength - llen;
                int l1space  =spaceLength - l1len;
                int l2space  =spaceLength - l2len;
                int l3space  =spaceLength - l3len;

                String ispaces = String.format("%"+ispace+"s", "");
                String jspaces = String.format("%"+jspace+"s", "");
                String kspaces = String.format("%"+kspace+"s", "");
                String lspaces = String.format("%"+lspace+"s", "");
                String l1spaces = String.format("%"+l1space+"s", "");
                String l2spaces = String.format("%"+l2space+"s", "");
                String l3spaces = String.format("%"+l3space+"s", "");
                //--------------
                int mlen = templateTypeNames.get(3).length() ;
                int nlen = templateTypeNames.get(3).length() +3 + templateTypeNames.get(0).length() ;
                int olen = templateTypeNames.get(3).length() +3 + templateTypeNames.get(1).length() ;
                int plen = templateTypeNames.get(3).length() +3 + templateTypeNames.get(2).length() ;

                int p1len = templateTypeNames.get(3).length() +3 + templateTypeNames.get(2).length() +3 + templateTypeNames.get(0).length() ;
                int p2len = templateTypeNames.get(3).length() +3 + templateTypeNames.get(2).length() +3 + templateTypeNames.get(1).length() ;
                int p3len = templateTypeNames.get(3).length() +3 + templateTypeNames.get(0).length() +3 + templateTypeNames.get(1).length() ;

                int mspace = spaceLength - mlen;
                int nspace  =spaceLength - nlen;
                int ospace  =spaceLength - olen;
                int pspace  =spaceLength - plen;
                int p1space  =spaceLength - p1len;
                int p2space  =spaceLength - p2len;
                int p3space  =spaceLength - p3len;
                String mspaces = String.format("%"+mspace+"s", "");
                String nspaces = String.format("%"+nspace+"s", "");
                String ospaces = String.format("%"+ospace+"s", "");
                String pspaces = String.format("%"+pspace+"s", "");
                String p1spaces = String.format("%"+p1space+"s", "");
                String p2spaces = String.format("%"+p2space+"s", "");
                String p3spaces = String.format("%"+p3space+"s", "");

                //+ templateTypeNames.get(0) + ")"+aspaces+": "+ UNREC_INA+"   "+SUM_A_TRAN

                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + ")"+aspaces+":  " + UNREC_INA+"   "+SUM_A_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(1) + ")"+bspaces+":  " + UNREC_INAB+"   "+SUM_AB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(2) + ")"+cspaces+":  " + UNREC_INAC+"   "+SUM_AC_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        + templateTypeNames.get(3) + ")"+dspaces+":  " + UNREC_INAD+"   "+SUM_AD_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(1) + " & "
                        +  templateTypeNames.get(2) + ")"+d1spaces+":  " + UNREC_INABC+"   "+SUM_ABC_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(3) + ")"+d2spaces+":  " + UNREC_INACD+"   "+SUM_ACD_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(1) + ")"+d3spaces+":  " + UNREC_INADB+"   "+SUM_ADB_TRAN
                        + "n";

                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + ")"+espaces+":  " + UNREC_INB+"   "+SUM_B_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(0) + ")"+fspaces+":  " + UNREC_INBA+"   "+SUM_BA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(2) + ")"+gspaces+":  " + UNREC_INBC+"   "+SUM_BC_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        + templateTypeNames.get(3) + ")"+hspaces+":  " + UNREC_INBD+"   "+SUM_BD_TRAN
                        + "n";

                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        +  templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(2) + ")"+h1spaces+":  " + UNREC_INBAC+"   "+SUM_BAC_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        +  templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(3) + ")"+h2spaces+":  " + UNREC_INBCD+"   "+SUM_BCD_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(1) + " & "
                        +  templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(0) + ")"+h3spaces+":  " + UNREC_INBDA+"   "+SUM_BDA_TRAN
                        + "n";

                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + ")"+ispaces+":  " + UNREC_INC+"   "+SUM_C_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        + templateTypeNames.get(0) + ")"+jspaces+":  " + UNREC_INCA+"   "+SUM_CA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        + templateTypeNames.get(1) + ")"+kspaces+":  " + UNREC_INCB+"   "+SUM_CB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        + templateTypeNames.get(3) + ")"+lspaces+":  " + UNREC_INCD+"   "+SUM_CD_TRAN
                        + "n";

                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(0) + ")"+l1spaces+":  " + UNREC_INCDA+"   "+SUM_CDA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(1) + ")"+l2spaces+":  " + UNREC_INCDB+"   "+SUM_CDB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(1) + ")"+l3spaces+":  " + UNREC_INCAB+"   "+SUM_CAB_TRAN
                        + "n";
                aa += "---------------------------------------------------------------------------------------------------------------"
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + ")"+mspaces+":  " + UNREC_IND+"   "+SUM_D_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        + templateTypeNames.get(0) + ")"+nspaces+":  " + UNREC_INDA+"   "+SUM_DA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        + templateTypeNames.get(1) + ")"+ospaces+":  " + UNREC_INDB+"   "+SUM_DB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        + templateTypeNames.get(2) + ")"+pspaces+":  " + UNREC_INDC+"   "+SUM_DC_TRAN
                        + "n";

                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(0) + ")"+p1spaces+":  " + UNREC_INDCA+"   "+SUM_DCA_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(2) + " & "
                        +  templateTypeNames.get(1) + ")"+p2spaces+":  " + UNREC_INDCB+"   "+SUM_DCB_TRAN
                        + "n";
                aa += "UNRECONCILED COUNT & SUM (PRESENT IN "
                        + templateTypeNames.get(3) + " & "
                        +  templateTypeNames.get(0) + " & "
                        +  templateTypeNames.get(1) + ")"+p3spaces+":  " + UNREC_INDAB+"   "+SUM_DAB_TRAN
                        + "n";
                out.write(aa.getBytes());
                out.close();
                status=true;

            }else
                status=false;
        } catch (Exception e) {
            status=false;
            logger.error("Reconciliation updateProcessStatus " + e);
        }
        return status;

    }

    public boolean disputeProcessReportGeneration(String processId,String processName){

        logger.debug("Entered into disputeProcessReportGeneration...");

        ArrayList<Map<String, String>> arrayList = null;        
        String currentStatus = null;
        String proposedStatus = null;

        Collection<Map<String, ?>> dataList = null;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        JasperReport jasperReport = null;
        JasperPrint jasperPrint = null;
        ArrayList<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        StringBuffer stringBuffer = new StringBuffer();
        Integer count = -1;
        boolean flag=false;
        try {

            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            String reportPath = LOCATION_BUNDLE.getString("OUTFILE_DISPUTE_PROCESS_REPORT_PATH");

            String currentDate = DateUtil.getcurrentDate(ReconConstants.DDMMMYY);

            File destinationPath = new File(reportPath+"Process"+File.separator+processName+File.separator+currentDate);

            if(!destinationPath.exists())
                destinationPath.mkdirs();                    

            inputStream = new FileInputStream(jrxmlPath+"DisputeProcessReport.jrxml");

            outputStream = new FileOutputStream(new File(destinationPath+File.separator+processName+"_DisputeProcessReport-"+DateUtil.getcurrentDate(ReconConstants.TIME)+".xlsx"));

            arrayList  = templateMapperService.FetchActionList(processId);

            logger.debug("disputeProcessReportGeneration Action List : "+arrayList);

            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));

            for(Map<String, String> actionList : arrayList) {

                currentStatus  = actionList.get("CURRENT_STATUS").toString();    
                proposedStatus = actionList.get("PROPOSED_STATUS").toString();

                dataList = templateMapperService.retrieveProcessedDisputeData(processId,currentStatus,proposedStatus);


                if (dataList != null && !dataList.isEmpty())
                    jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JRMapCollectionDataSource(dataList));
                else
                    jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JREmptyDataSource());

                jasperPrintList.add(jasperPrint);

                for(Map<String, ?> map : dataList){  //Sheet names

                    if(stringBuffer.length() == 0)
                        stringBuffer.append(map.get("DES"));
                    else
                        stringBuffer.append("|"+map.get("DES"));

                    break;
                }

            }

            count = errorCheck(processId);
            if(count > 0)
            {
                flag = disputeProcessErrorReport(processId,processName);//call for Error Report
                if(arrayList.size() > 0 && flag == true)
                    return callXlsxReportGeneration(outputStream, new JasperPrint(), jasperPrintList, stringBuffer.toString().split("\|"));
                else
                    return true;
            }
            else
            {
                if(arrayList.size() > 0)//Modified for Issue
                    return callXlsxReportGeneration(outputStream, new JasperPrint(), jasperPrintList, stringBuffer.toString().split("\|"));
                else
                    return true;
            }

        } catch(Exception e) {
            logger.error("Exception in disputeProcessReportGeneration ", e);
        } finally{
            if( outputStream != null ) {
                try {
                    outputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }

            if( inputStream != null ) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
        }
        return false;

    }

    private boolean disputeProcessErrorReport(String processId,String processName) {

        ArrayList<Map<String, String>> arrayList = null;        
        String currentStatus = null;
        String proposedStatus = null;

        Collection<Map<String, ?>> dataList = null;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        JasperReport jasperReport = null;
        JasperPrint jasperPrint = null;
        ArrayList<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        StringBuffer stringBuffer = new StringBuffer();
        try {

            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            String reportPath = LOCATION_BUNDLE.getString("OUTFILE_DISPUTE_PROCESS_REPORT_PATH");

            String currentDate = DateUtil.getcurrentDate(ReconConstants.DDMMMYY);

            File destinationPath = new File(reportPath+"Process"+File.separator+processName+File.separator+currentDate);

            if(!destinationPath.exists())
                destinationPath.mkdirs();                    

            inputStream = new FileInputStream(jrxmlPath+"DisputeProcessErrorReport.jrxml");

            outputStream = new FileOutputStream(new File(destinationPath+File.separator+processName+"_DisputeProcessErrorReport-"+DateUtil.getcurrentDate(ReconConstants.TIME)+".xlsx"));

            arrayList  = templateMapperService.FetchActionListForErrorReport(processId);
            logger.debug("Dispute UnProcessed Error Report Generation Action List : "+arrayList);

            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));

            for(Map<String, String> actionList : arrayList) {

                currentStatus  = actionList.get("CURRENT_STATUS").toString();    
                proposedStatus = actionList.get("PROPOSED_STATUS").toString();

                dataList = templateMapperService.retrieveErrorUnProcessedDisputeData(processId,currentStatus,proposedStatus);


                if (dataList != null && !dataList.isEmpty())
                    jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JRMapCollectionDataSource(dataList));
                else
                    jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JREmptyDataSource());

                jasperPrintList.add(jasperPrint);

                for(Map<String, ?> map : dataList){  //Sheet names

                    if(stringBuffer.length() == 0)
                        stringBuffer.append(map.get("DES"));
                    else
                        stringBuffer.append("|"+map.get("DES"));

                    break;
                }

            }
            if(arrayList.size() > 0)
                return callXlsxReportGeneration(outputStream, new JasperPrint(), jasperPrintList, stringBuffer.toString().split("\|"));
            else
                return true;
        } catch(Exception e) {
            logger.error("Exception in disputeProcessReportGeneration ", e);
        } finally{
            if( outputStream != null ) {
                try {
                    outputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }

            if( inputStream != null ) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    private Integer errorCheck(String processId) {

        logger.debug("Error Count Check Starts in DaoImpl..");

        String query = QueryPropertyUtil.getProperty("DB.DISPUTE.PROCESS.ERROR.REPORT.COUNT");
        Integer count = -1;
        List<LocalObject> objectList = null;
        DatabaseService databaseService=null;
        LocalObject localObj=null;
        Iterator<LocalObject> itr = null;
        Map<Object, Object>  map = new HashMap<Object, Object>();

        try
        {   
            objectList=new ArrayList<LocalObject>();
            databaseService = new DatabaseService();
            localObj=new LocalObject();
            localObj.put(1, processId);
            objectList = databaseService.executeQuery(query,localObj);
            itr = objectList.iterator();

            while (itr.hasNext())
            {
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                count=Integer.parseInt(map.get("DCR_ERR_FLG").toString());
            }
        }catch(Exception e) {
            logger.error("Exception in Error Count Check ", e);
        }
        logger.debug("Error Count Check ends in DaoImpl..");
        return count;

    }
    //Modified by Archana.J
    public boolean generateDisputeReports(String interchange,List<Long> claimIdList,String outFileName,String issAcqFlag,String processName) throws ReconUserDefinedException {
        logger.info("Entering into generateDisputeReports...");
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        Collection<Map<String, ?>> dataList = null;
        JasperReport  jasperReport = null;
        JasperPrint   jasperPrint = null;
        String reportPath = null;
        
        Properties prop = null;
        String configFile =  null;
        File inFile = null;
        FileInputStream inStream = null;
        try{
            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            //added by shipra to read today's date
            DateFormat dateFormat = new SimpleDateFormat("dd-MMM-YY");
            Date date = new Date();
                //get current date time with Calendar()
            String Recdate = dateFormat.format(date);
        //    jrxmlPath = jrxmlPath+"DisputeReport.jrxml";
            
            configFile = LOCATION_BUNDLE.getString("RECON_CONFIGURATION");  //modified by dhanapriyanga
            prop = new Properties();
            inFile = new File(configFile);
            inStream = new FileInputStream(inFile);
            prop.load(inStream);
            
            jrxmlPath = jrxmlPath+prop.getProperty("dispute.outfile.reports.jrxml");
            
            logger.debug("jrxmlPath : "+jrxmlPath);
            
            if(("NFS").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("NFS_"+issAcqFlag+"_OUTFILE_GENERATION_PATH"+File.separator+processName+File.separator+Recdate);
            else if(("Rupay").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("RUPAY_OUTFILE_GENERATION_PATH"+File.separator+processName+File.separator+Recdate);
            else if(("Visa").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("VISA_"+issAcqFlag+"_OUTFILE_GENERATION_PATH"+File.separator+processName+File.separator+Recdate);
            else if(("MasterCard").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("MDU_OUTFILE_GENERATION_PATH")+File.separator+processName+File.separator+Recdate;
            else if(("IMPS").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("IMPS_OUTFILE_PATH"+File.separator+processName+File.separator+Recdate);            
            
//            reportPath = reportPath+File.separator+"Reports";
            logger.debug("report Path : "+reportPath);
            File destinationPath = new File(reportPath);
            if(!destinationPath.exists())
                destinationPath.mkdirs();                    
            inputStream = new FileInputStream(jrxmlPath);
            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
                    if(outFileName.contains("."))
            outFileName=outFileName.substring(0,outFileName.indexOf("."));
            outputStream = new FileOutputStream(new File(reportPath+File.separator+outFileName+"_REP"+".xlsx"));
            dataList = interchangeOutfileGeneratorDao.retrieveDisputeData(claimIdList, interchange,issAcqFlag);
            if (dataList != null && !dataList.isEmpty())
                jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JRMapCollectionDataSource(dataList));
            else
                jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JREmptyDataSource());
            return callXlsxReportGeneration(outputStream, jasperPrint);
        }catch(Exception e){
            logger.error("Exception in generateDisputeReports ", e);
            throw new ReconUserDefinedException(RECONMESSAGES.getString("rcn.exception.errorcode.20"));
        }finally{
            if(inputStream!=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
            if(outputStream!=null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //Added by Ishwarya -  for UPI Adjustment excel report generation - 31-07-17
    public boolean upiAdjReportGeneration(String processName,
            String outfilePath, String processId) {
        logger.debug("UPI ADJ Report Generation Starts...");
        List<ForceMatchReportGenForm> list = new ArrayList<ForceMatchReportGenForm>();        
        String jrxmlPath = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        String outFileName = "";
        boolean flag = true;
        try {
            //rb = ResourceBundle.getBundle("location");
            jrxmlPath = LOCATION_BUNDLE.getString("UPI_ADJ_PROCESSED_REPORT_JRXML").trim();
            File jrxmlfile = null;

            try {
                jrxmlfile = new File(jrxmlPath);
                inputStream = new FileInputStream(jrxmlfile);
            } catch (Exception e) {
                logger.error("JRXML File Not Found in this path is "
                        + jrxmlPath);
                return false;
            }
            ArrayList<String> adjTypeList =  new ArrayList<String>();
            adjTypeList.add("T");
            adjTypeList.add("R");
            adjTypeList.add("CR");
            adjTypeList.add("RC");
            adjTypeList.add("CA");
            adjTypeList.add("N");
            ArrayList<String> adjTypeListHeader =  new ArrayList<String>();
            adjTypeListHeader.add("TCC");
            adjTypeListHeader.add("RET");
            adjTypeListHeader.add("COMPLAINT RAISE");
            adjTypeListHeader.add("RESPONSE TO COMPLAINT");
            adjTypeListHeader.add("CREDIT ADJUSTMENT");
            adjTypeListHeader.add("NOT PROCESSED");
            String[] listHeaders = {"TCC","RET","COMPLAINT RAISE","RESPONSE TO COMPLAINT","CREDIT ADJUSTMENT","NOT PROCESSED"};
            jasperPrintlist = frameJasperPrintListForUpiAdj(inputStream,adjTypeList,adjTypeListHeader);

            if (jasperPrintlist != null && jasperPrintlist.size() > 0) {
                outFileName = outfilePath
                        + processName
                        + "-"
                        + new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss")
                .format(new Date()) + ".xlsx";
                outputStream = new FileOutputStream(new File(outFileName));

                callXlsxReportGeneration(outputStream, new JasperPrint(),
                        jasperPrintlist, listHeaders);

                inputStream.close();
                outputStream.flush();
                outputStream.close();
            } else
                flag = false;


        } catch (Exception e) {
            logger.error("Exception occured in Force Match Report Generation... "
                    + e);
            flag = false;
        }
        logger.debug("Force Match Report Generation Ends...");
        return flag;
    }
    public ArrayList<JasperPrint> frameJasperPrintListForUpiAdj(InputStream inputStream,ArrayList<String> adjTypeList,ArrayList<String> adjTypeListHeader)
            throws Exception {
        logger.debug("Frame Jasper Print List for UPI ADJ Report Starts...");

        Collection<Map<String, ?>> dataList = null;
        String query = null;

        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        JasperPrint jasperPrint = null;
        JasperDesign jasperDesign = null;
        JasperReport jasperReport = null;
        Map<String, Object> parameters = new HashMap<String, Object>();
        List<String> fileTypes = new ArrayList<String>();
        String actualQry = null;
        String preManRecFlg="1";
        try {
            jasperDesign = JRXmlLoader.load(inputStream);// loading jrxml
            jasperReport = JasperCompileManager.compileReport(jasperDesign);// Compiling
            // jrxml

            for(int i=0;i<adjTypeList.size();i++){
                {
                    if(adjTypeList.get(i).equals('N') || adjTypeList.get(i) == "N"){ //NOT PROCESSED
                        actualQry =QueryPropertyUtil.getProperty("DB.GET.UPI.ADJ.NOT.PROCESSED.RECORDS");
                    }else{
                        actualQry =QueryPropertyUtil.getProperty("DB.GET.UPI.ADJ.PROCESSED.RECORDS");
                        actualQry = actualQry+" TCC_RET_FLG = '"+adjTypeList.get(i)+"'";
                    }
                    logger.debug("Query for UPI ADJ Report is :"+ actualQry);

                    parameters.put("TITLE", adjTypeListHeader.get(i));
                    parameters.put("DESCRIPTION","PROCESSED RECORDS");

                    dataList = templateMapperService.retrieveJasperReportList(actualQry, null);
                    if (dataList != null && !dataList.isEmpty())
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JRMapCollectionDataSource(dataList));
                    else
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JREmptyDataSource());

                    jasperPrintlist.add(jasperPrint);
                }
            }
        } catch (Exception e) {
            logger.error("Exception occured in Frame Jasper Print List for UPI ADJ Report ... "
                    + e);
            jasperPrintlist = new ArrayList<JasperPrint>();
        }
        logger.debug("Frame Jasper Print List for UPI ADJ Report Ends...");
        return jasperPrintlist;
    }


    public boolean callReportReWrite( String filePath) throws Exception {
        boolean reportGenerationStatus= true;

        FileReader fr = null;
        BufferedReader br = null;
        FileWriter f2  = null;
        try {

            fr = new FileReader(filePath);
            br = new BufferedReader(fr);
            f2 = new FileWriter(filePath+"_3");
            String s;
            while((s = br.readLine()) != null) {
                //System.out.println(s);
                if(s.trim().equals("")){
                    continue;
                }
                f2.write(s+"n");
            }


        }catch(Exception e){

            logger.error("Exception occured in report re write Report callReportReWrite ... "+ e);
        }
        finally {
            fr.close();
            f2.close();
        }

        return reportGenerationStatus;

    }

    public void deleteOLDReport(String file) throws Exception{
        logger.error(" Entered deleteOLDReport method ");
        try
        {
            File f = new File(file);
            if (f.exists()) {
                f.delete();  
            }
            //Added by Amol to rename the files to original
            File f1 = new File(file+"_3");
            if(f1.exists()){
                f1.renameTo(f);
            }
        }

        catch(Exception e)
        {
            logger.error("Old Report file Deletion not happen , Invalid permissions."+ e);

        }
        logger.error(" Deletion successful , Exit deleteOLDReport  ");

    }

    //Added by Ishwarya - 06Oct17
    public boolean disputePreProcessReportGeneration(int InterchangeId,String subChannel,String processName){

        logger.debug("Entered into disputeProcessReportGeneration...");

        ArrayList<Map<String, String>> arrayList = null;        
        Collection<Map<String, ?>> dataList = null;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        JasperReport jasperReport = null;
        JasperPrint jasperPrint = null;
        ArrayList<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        StringBuffer stringBuffer = new StringBuffer();
        Integer count = -1;
        boolean flag=false;
        Map<String, Object> parameters = new HashMap<String, Object>();
        try {

            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            String reportPath = LOCATION_BUNDLE.getString("OUTFILE_DISPUTE_PROCESS_REPORT_PATH");

            String currentDate = DateUtil.getcurrentDate(ReconConstants.DDMMMYY);

            File destinationPath = new File(reportPath+"Process"+File.separator+processName+File.separator+currentDate);

            if(!destinationPath.exists())
                destinationPath.mkdirs();                    

            inputStream = new FileInputStream(jrxmlPath+"DisputePreProcessReport.jrxml");

            outputStream = new FileOutputStream(new File(destinationPath+File.separator+processName+"_DisputePreProcessReport-"+DateUtil.getcurrentDate(ReconConstants.TIME)+".xlsx"));

            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
            parameters.put("TITLE", processName);
            String[] dispFlgList = {"Y","N","E","D"};
            String[] sheetnames = {"Processed","Not processed","Expired","Disputed"};
            for(int i = 0; i < 4; i++) {
                dataList =  templateMapperService.fetchPreProcessedData(InterchangeId,subChannel,""+InterchangeId+""+subChannel,dispFlgList);

                if (dataList != null && !dataList.isEmpty()){
                    /*jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JRMapCollectionDataSource(dataList));*/
                    jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,new JRMapCollectionDataSource(dataList));
                }else{
                    /*jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JREmptyDataSource());*/
                    jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JREmptyDataSource());
                }
                jasperPrintList.add(jasperPrint);
            }
            if(dataList.size() > 0)//Modified for Issue
                return callXlsxReportGeneration(outputStream, new JasperPrint(), jasperPrintList, sheetnames);
            else
                return true;


        } catch(Exception e) {
            logger.error("Exception in disputeProcessReportGeneration ", e);
        } finally{
            if( outputStream != null ) {
                try {
                    outputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }

            if( inputStream != null ) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

 

    /*    //Modified by Archana.J
    public boolean generateDisputeReports(String interchange,List<Long> claimIdList,String outFileName,String issAcqFlag) throws ReconUserDefinedException {
        logger.info("Entering into generateDisputeReports...");
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        Collection<Map<String, ?>> dataList = null;
        JasperReport  jasperReport = null;
        JasperPrint   jasperPrint = null;
        String reportPath = null;
        try{
            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            jrxmlPath = jrxmlPath+"DisputeReport.jrxml";
            logger.debug("jrxmlPath : "+jrxmlPath);
            if(("NFS").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("NFS_"+issAcqFlag+"_OUTFILE_GENERATION_PATH");
            else if(("Rupay").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("RUPAY_OUTFILE_GENERATION_PATH");
            else if(("Visa").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("VISA_"+issAcqFlag+"_OUTFILE_GENERATION_PATH");
            else if(("MasterCard").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("MDU_OUTFILE_GENERATION_PATH");
            else if(("IMPS").equalsIgnoreCase(interchange))
                reportPath=LOCATION_BUNDLE.getString("IMPS_OUTFILE_PATH");            

            reportPath = reportPath+File.separator+"Reports";
            logger.debug("report Path : "+reportPath);
            File destinationPath = new File(reportPath);
            if(!destinationPath.exists())
                destinationPath.mkdirs();                    
            inputStream = new FileInputStream(jrxmlPath);
            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
            if(outFileName.contains("."))
                outFileName=outFileName.substring(0,outFileName.indexOf("."));
            outputStream = new FileOutputStream(new File(reportPath+File.separator+outFileName+"_REP"+".xlsx"));
            dataList = interchangeOutfileGeneratorDao.retrieveDisputeData(claimIdList, interchange);
            if (dataList != null && !dataList.isEmpty())
                jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JRMapCollectionDataSource(dataList));
            else
                jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String, Object>(),new JREmptyDataSource());
            return callXlsxReportGeneration(outputStream, jasperPrint);
        }catch(Exception e){
            logger.error("Exception in generateDisputeReports ", e);
            throw new ReconUserDefinedException(RECONMESSAGES.getString("rcn.exception.errorcode.20"));
        }finally{
            if(inputStream!=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
            if(outputStream!=null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
    /**
     * @purpose:This method used to getPlainCardNumList
     * @author :Nancy K
     * @date   :13-02-2018
     * @param  :encrCardNum, instId
     * @return :plainCardNum
     */
    public String getPlainCardNumList(String encrCardNum,int instId ) throws Exception {


        KeyStoreForm keyStoreForm = new KeyStoreForm();
        String plainCardNum="";
        KeystoreDao  keystoreDao = new KeystoreDaoImpl();

        try{
            keyStoreForm=keystoreDao.fetchKeystorepwd2(instId, null);
            plainCardNum = SecurityUtils.decryptText(encrCardNum, instId, keyStoreForm.getKeystorePassword2(),keyStoreForm.getHexData());

        }catch(Exception e){
            logger.error("Exception while converting encrypted card num into plain card number:",e);
        }
        return plainCardNum;


    }
    /**
     * @purpose:This method used to getPlainCardNumList
     * @author :Nancy K
     * @date   :13-02-2018
     * @param  :userID
     * @return :securitySts
     */
    public boolean getsecurityStatus(String userID) {

        List<LocalObject> objectList = null;
        DatabaseService databaseService=null;
        LocalObject localObj=null;
        Iterator<LocalObject> itr = null;
        Map<Object, Object> map = null;
        String query ="";
        String securityStatus= "";
        boolean securitySts = false;

        try{

            query = QueryPropertyUtil.getProperty("RCN.Get.User.Security.Check");

            logger.debug("Query to get security status for user id:"+userID+"-->"+query);
            databaseService = new DatabaseService();
            localObj=new LocalObject();    
            localObj.put(1, userID);
            objectList = databaseService.executeQuery(query,localObj);
            itr = objectList.iterator();

            while (itr.hasNext())
            {
                localObj = (LocalObject) itr.next();
                map = localObj.getMap();
                securityStatus= map.get("SECURITY_CHECK").toString();
            }

            if(("Y").equals(securityStatus)){
                securitySts = true;
            }else if(("Y").equals(securityStatus)){
                securitySts = false;
            }

        }catch(Exception e){
            logger.error("");
        }
        return securitySts;

    }    
    //SN:added by akankshac for Fraud preprocess Report
    public boolean SafePreProcessReportGeneration(int InterchangeId,String subChannel,String processName){

        logger.debug("Entered into SafePreProcessReportGeneration...");

        Collection<Map<String, ?>> dataList = null;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        JasperReport jasperReport = null;
        JasperPrint jasperPrint = null;
        ArrayList<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        Map<String, Object> parameters = new HashMap<String, Object>();
        try {

            String jrxmlPath = LOCATION_BUNDLE.getString("JRXML_DISPUTE_PROCESS_REPORT_PATH");
            String reportPath = LOCATION_BUNDLE.getString("OUTFILE_DISPUTE_PROCESS_REPORT_PATH");

            String currentDate = DateUtil.getcurrentDate(ReconConstants.DDMMMYY);

            File destinationPath = new File(reportPath+"Process"+File.separator+processName+File.separator+currentDate);

            if(!destinationPath.exists())
                destinationPath.mkdirs();                    

            inputStream = new FileInputStream(jrxmlPath+"SafePreProcessReport.jrxml");

            outputStream = new FileOutputStream(new File(destinationPath+File.separator+processName+"_SafePreProcessReport-"+DateUtil.getcurrentDate(ReconConstants.TIME)+".xlsx"));
            String[] sheetnames={"SafePreProcessReport"};        
            jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
            parameters.put("TITLE", processName);
            dataList =  templateMapperService.fetchSafePreProcessedData(InterchangeId,subChannel,""+InterchangeId+""+subChannel);

            if (dataList != null && !dataList.isEmpty()){
                jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,new JRMapCollectionDataSource(dataList));
            }else{
                jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JREmptyDataSource());
            }
            jasperPrintList.add(jasperPrint);
            if(dataList.size() > 0){//Modified for Issue
                return callXlsxReportGeneration(outputStream, new JasperPrint(), jasperPrintList, sheetnames);
            }else {
                return true;
            }

        } catch(Exception e) {
            logger.error("Exception in SafePreProcessReportGeneration ", e);
        } finally{
            if( outputStream != null ) {
                try {
                    outputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }

            if( inputStream != null ) {
                try {
                    inputStream.close();
                } catch (IOException e) {                    
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
    public boolean forceMatchReportGenerationForScreen(String processName,String outfilePath, String processId,String actionids,String datatable,Connection connection)
    {
        logger.debug("Force Match Report Generation Starts...");
        List<ForceMatchReportGenForm> list = new ArrayList<ForceMatchReportGenForm>();        
        String jrxmlPath = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        String outFileName = "";
        String startEndTime = "";
        boolean flag = true;
        try
        {
            jrxmlPath = LOCATION_BUNDLE.getString("MANUAL_KNOCKOFF_REPORT_JRXML").trim();
            File jrxmlfile = null;

            try
            {
                jrxmlfile = new File(jrxmlPath);
                inputStream = new FileInputStream(jrxmlfile);
            } catch (Exception e) {
                logger.error("JRXML File Not Found in this path is "+ jrxmlPath);
                return false;
            }


            
            jasperPrintlist = frameJasperPrintListForScreen(processId, inputStream,processName,startEndTime, actionids, datatable,connection);

            if (jasperPrintlist != null && jasperPrintlist.size() > 0)
            {
                outFileName = outfilePath+processName.replaceAll(" ","")+"-MANREC"+ "-"+ new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss").format(new Date()) + ".xlsx";
                outputStream = new FileOutputStream(new File(outFileName));

                callXlsxReportGeneration(outputStream, new JasperPrint(),jasperPrintlist, new String[5]);

                inputStream.close();
                outputStream.flush();
                outputStream.close();
            } else
                flag = false;

        } catch (Exception e) {
            logger.error("Exception occured in Force Match Report Generation... "
                    + e);
            flag = false;
        }
        logger.debug("Force Match Report Generation Ends...");
        return flag;
    }
    //ADDED BY SAURABH TO FRAME QUERY FOR MANREC FROM SCREEN
    public ArrayList<JasperPrint> frameJasperPrintListForScreen(String processId, InputStream inputStream,String processName,String startEndTime,String actionids,String datatable,Connection connection)throws Exception
    {
        logger.debug("Frame Jasper Print List for Force Match Report Starts...");

        Collection<Map<String, ?>> dataList = null;
        String query = null;

        ArrayList<JasperPrint> jasperPrintlist = new ArrayList<JasperPrint>();
        JasperPrint jasperPrint = null;
        JasperDesign jasperDesign = null;
        JasperReport jasperReport = null;
        Map<String, Object> parameters = new HashMap<String, Object>();
        List<String> fileTypes = new ArrayList<String>();
        String actualQry = null;
        String preManRecFlg="9";
        String[] startTimeEndTime;
        Collection<Map<String, ?>> jasperReportListMap = new ArrayList<Map<String,?>>();
        DatabaseService databaseService =null;
        LocalString localString = null;
        try
        {
            jasperDesign = JRXmlLoader.load(inputStream);// loading jrxml
            jasperReport = JasperCompileManager.compileReport(jasperDesign);// Compiling jrxml
            databaseService = new DatabaseService();
            localString = new LocalString();
                //fileTypes = manrecProcessService.getFileTypesForCardIgnore();
                //startTimeEndTime=startEndTime.split("\|");
                query = QueryPropertyUtil.getProperty("DB.MANUALKNOCKOFF.REPORT_GEN.GET.COLUMNS");
                
            
                    //For Plain and Adjustment knockoff PreManRecFlg is '1'
                    //For Keep It Unreconciled PreManRecFlg is '2'
                         actionids=actionids.substring(0,actionids.length()-1);
                    // Removing CARD_NUM field from the query for some filetypes
                    actualQry = query +" "+ datatable+ " WHERE ACTION_ID in ("+actionids+") "+ " AND PREMANRECREL_FLG='"+preManRecFlg+"'"+" AND MANRECREL_FLG='0' AND REC_FLG='0'";
                            
                            //frameQueryForForceMatchReportGeneration(query,datatable, fileTypes)+ " "+ datatable+ " WHERE ACTION_ID in ("+actionids+") "
                        //        + "' AND PREMANRECREL_FLG='"+preManRecFlg+"'";
                    
    /*                if(form.getApprReqFlag().equalsIgnoreCase("N"))
                    {    
                        actualQry+=" AND MANRECREL_FLG='1' AND REC_FLG='1' AND USER_PROCESS_DATE BETWEEN TO_DATE('"+startTimeEndTime[0]+"','DD-MON-YYYY HH24:MI:SS')"
                                  +" AND TO_DATE('"+startTimeEndTime[1]+"','DD-MON-YYYY HH24:MI:SS')";
                    }else*/
                        //actualQry+=" AND MANRECREL_FLG='0' AND REC_FLG='0'";
                    
                    //logger.debug("Force Match Report Query for the Action Id "+form.getActionId()+" is :"+ actualQry);
                    
                    //parameters.put("TITLE", form.getDescription());
                    //parameters.put("DESCRIPTION", form.getDescription());
                    parameters.put("TITLE", processName+" MANUAL KNOCKOFF REPORT ");
                    //parameters.put("ACTION_TYPE", form.getActionType());
                    jasperReportListMap.addAll(databaseService.executeQueryString(actualQry, localString, connection));
                    dataList=jasperReportListMap;
                    //dataList = templateMapperService.retrieveJasperReportList(actualQry, null);
                    if (dataList != null && !dataList.isEmpty())
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JRMapCollectionDataSource(dataList));
                    else
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,new JREmptyDataSource());
                    
                    jasperPrintlist.add(jasperPrint);
                
            
        } catch (Exception e) {
            logger.error("Exception occured in Frame Jasper Print List for Force Match Report ... "
                    + e);
            jasperPrintlist = new ArrayList<JasperPrint>();
        }
        logger.debug("Frame Jasper Print List for Force Match Report Ends...");
        return jasperPrintlist;
    }
    
    
}

Link to comment
Share on other sites

  • Replies 1
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...