public String execute() throws Exception {
    if (name == null || name.equals(ALL)) {
      Collection<PeriodType> periodTypes = periodService.getAllPeriodTypes();

      for (PeriodType type : periodTypes) {
        periods.addAll(periodService.getPeriodsByPeriodType(type));
      }
    } else {
      PeriodType periodType = periodService.getPeriodTypeByName(name);

      ArrayList<Period> allPeriodsOfSelectedPeriodType =
          new ArrayList<Period>(periodService.getPeriodsByPeriodType(periodType));

      for (Period p : allPeriodsOfSelectedPeriodType) {
        if (!(p.getStartDate().compareTo(new Date()) > 0)) {
          periods.add(p);
        }
      }
    }

    for (Period period : periods) {
      period.setName(format.formatPeriod(period));
    }

    Collections.sort(periods, new PeriodComparator());

    return SUCCESS;
  }
  /**
   * Gets the current and most recent periods to search, based on the period types from the rules to
   * run.
   *
   * <p>For each period type, return the period containing the current date (if any), and the most
   * recent previous period. Add whichever of these periods actually exist in the database.
   *
   * <p>TODO If the last successful daily run was more than one day ago, we might add some
   * additional periods of type DailyPeriodType not to miss any alerts.
   *
   * @param rules the ValidationRules to be evaluated on this run
   * @return periods to search for new alerts
   */
  private Set<Period> getAlertPeriodsFromRules(Set<ValidationRule> rules) {
    Set<Period> periods = new HashSet<>();

    Set<PeriodType> rulePeriodTypes = getPeriodTypesFromRules(rules);

    for (PeriodType periodType : rulePeriodTypes) {
      CalendarPeriodType calendarPeriodType = (CalendarPeriodType) periodType;
      Period currentPeriod = calendarPeriodType.createPeriod();
      Period previousPeriod = calendarPeriodType.getPreviousPeriod(currentPeriod);
      periods.addAll(
          periodService.getIntersectingPeriodsByPeriodType(
              periodType, previousPeriod.getStartDate(), currentPeriod.getEndDate()));
    }

    return periods;
  }
Exemplo n.º 3
0
  @Override
  public Map<DataElementOperand, Double> getAggregatedValues(
      final Collection<DataElementOperand> operands,
      final Period period,
      int unitLevel,
      final Collection<Integer> organisationUnits,
      String key) {
    if (CollectionUtils.isEmpty(operands)) {
      return EMPTY_MAP;
    }

    final Collection<CrossTabDataValue> crossTabValues =
        crossTabService.getCrossTabDataValues(
            operands,
            aggregationCache.getPeriodsBetweenDates(period.getStartDate(), period.getEndDate()),
            organisationUnits,
            key);

    final Map<DataElementOperand, Double> values = new HashMap<>(); // <Operand, total value>

    for (final CrossTabDataValue crossTabValue : crossTabValues) {
      final int dataValueLevel =
          aggregationCache.getLevelOfOrganisationUnit(crossTabValue.getSourceId());

      for (final Entry<DataElementOperand, String> entry :
          crossTabValue.getValueMap().entrySet()) // <Operand, value>
      {
        if (entry.getValue() != null
            && entry.getKey().aggregationLevelIsValid(unitLevel, dataValueLevel)) {
          double value = 0.0;

          try {
            value = Double.parseDouble(entry.getValue());
          } catch (NumberFormatException ex) {
            log.warn("Value skipped, not numeric: '" + entry.getValue());
            continue;
          }

          final Double current = values.get(entry.getKey());
          value += current != null ? current : 0.0;
          values.put(entry.getKey(), value);
        }
      }
    }

    return values;
  }
  /**
   * Validates a collection of validation rules.
   *
   * @param period the period to validate for.
   * @param source the source to validate for.
   * @param validationRules the rules to validate.
   * @param dataElementsInRules the data elements which are part of the rules expressions.
   * @param constantMap the constants which are part of the rule expressions.
   * @param currentSize the current number of validation violations.
   * @returns a collection of rules that did not pass validation.
   */
  private Collection<ValidationResult> validateInternal(
      Period period,
      OrganisationUnit unit,
      Collection<ValidationRule> validationRules,
      Set<DataElement> dataElementsInRules,
      Map<String, Double> constantMap,
      int currentSize) {
    Map<DataElementOperand, Double> valueMap =
        dataValueService.getDataValueMap(dataElementsInRules, period, unit);

    final Collection<ValidationResult> validationViolations = new HashSet<ValidationResult>();

    if (currentSize < MAX_VIOLATIONS) {
      Double leftSide = null;
      Double rightSide = null;

      boolean violation = false;

      for (final ValidationRule validationRule : validationRules) {
        if (validationRule.getPeriodType() != null
            && validationRule.getPeriodType().equals(period.getPeriodType())) {
          Operator operator = validationRule.getOperator();

          leftSide =
              expressionService.getExpressionValue(
                  validationRule.getLeftSide(), valueMap, constantMap, null);

          if (leftSide != null || Operator.compulsory_pair.equals(operator)) {
            rightSide =
                expressionService.getExpressionValue(
                    validationRule.getRightSide(), valueMap, constantMap, null);

            if (rightSide != null || Operator.compulsory_pair.equals(operator)) {
              if (Operator.compulsory_pair.equals(operator)) {
                violation =
                    (leftSide != null && rightSide == null)
                        || (leftSide == null && rightSide != null);
              } else if (leftSide != null && rightSide != null) {
                violation = !expressionIsTrue(leftSide, operator, rightSide);
              }

              if (violation) {
                validationViolations.add(
                    new ValidationResult(
                        period,
                        unit,
                        validationRule,
                        getRounded(zeroIfNull(leftSide), DECIMALS),
                        getRounded(zeroIfNull(rightSide), DECIMALS)));
              }
            }
          }
        }
      }
    }

    return validationViolations;
  }
  @Override
  public Collection<ValidationResult> validate(
      DataSet dataSet,
      Period period,
      OrganisationUnit source,
      DataElementCategoryOptionCombo attributeCombo) {
    log.info(
        "Validate data set: "
            + dataSet.getName()
            + " period: "
            + period.getPeriodType().getName()
            + " "
            + period.getStartDate()
            + " "
            + period.getEndDate()
            + " source: "
            + source.getName()
            + " attribute combo: "
            + (attributeCombo == null ? "[none]" : attributeCombo.getName()));

    Collection<Period> periods = new ArrayList<>();
    periods.add(period);

    Collection<ValidationRule> rules =
        getValidationTypeRulesForDataElements(dataSet.getDataElements());

    log.debug("Using validation rules: " + rules.size());

    Collection<OrganisationUnit> sources = new HashSet<>();
    sources.add(source);

    return Validator.validate(
        sources,
        periods,
        rules,
        attributeCombo,
        null,
        constantService,
        expressionService,
        periodService,
        dataValueService,
        dataElementCategoryService,
        userService,
        currentUserService);
  }
Exemplo n.º 6
0
  public void testUpdateObject() {
    int id = periodService.addPeriod(periodA);

    periodA.setStartDate(dateA);

    batchHandler.updateObject(periodA);

    assertEquals(periodService.getPeriod(id).getStartDate(), dateA);
  }
  @Override
  public String execute() throws Exception {
    if (id != null) {
      lockException = dataSetService.getLockException(id);

      if (lockException == null) {
        return INPUT;
      }

      selectionTreeManager.setSelectedOrganisationUnit(lockException.getOrganisationUnit());
      dataSets = getDataSetsForCurrentUser(lockException.getOrganisationUnit().getId());
      periods = getPeriodsForDataSet(lockException.getDataSet().getId());

      for (Period period : periods) {
        period.setName(format.formatPeriod(period));
      }
    }

    return SUCCESS;
  }
  public String execute() throws Exception {
    // reportTypeName = ReportType.RT_LINELIST;

    reportTypeName = ReportType.RT_LINELIST_WEB_PORTAL;
    /* Monthly Periods */
    monthlyPeriodType = new MonthlyPeriodType();

    monthlyPeriods = new ArrayList<Period>(periodService.getPeriodsByPeriodType(monthlyPeriodType));
    Iterator<Period> periodIterator = monthlyPeriods.iterator();
    while (periodIterator.hasNext()) {
      Period p1 = periodIterator.next();

      if (p1.getStartDate().compareTo(new Date()) > 0) {
        periodIterator.remove();
      }
    }

    Collections.sort(monthlyPeriods, new PeriodComparator());
    simpleDateFormat = new SimpleDateFormat("MMM-yyyy");

    return SUCCESS;
  }
  public String execute() throws Exception {

    String periodType = "Quarterly";

    // periodType = periodType != null && !periodType.isEmpty() ? periodType :
    // MonthlyPeriodType.NAME;

    CalendarPeriodType _periodType =
        (CalendarPeriodType) CalendarPeriodType.getPeriodTypeByName(periodType);

    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    int currentYear = (Integer) SessionUtils.getSessionVar(SessionUtils.KEY_CURRENT_YEAR, thisYear);

    Calendar cal = PeriodType.createCalendarInstance();

    // Cannot go to next year if current year equals this year

    if (!(currentYear == thisYear && year > 0)) {
      cal.set(Calendar.YEAR, currentYear);
      cal.add(Calendar.YEAR, year);

      SessionUtils.setSessionVar(SessionUtils.KEY_CURRENT_YEAR, cal.get(Calendar.YEAR));
    }

    periods = _periodType.generatePeriods(cal.getTime());

    FilterUtils.filter(periods, new PastAndCurrentPeriodFilter());

    Collections.reverse(periods);

    for (Period period : periods) {
      period.setName(format.formatPeriod(period));
    }

    return SUCCESS;
  }
 @Override
 public boolean retain(Period period) {
   return period != null
       && period.getStartDate() != null
       && period.getStartDate().compareTo(new Date()) <= 0;
 }
  // -------------------------------------------------------------------------
  // Action Implementation
  // -------------------------------------------------------------------------
  public String execute() throws Exception {
    statementManager.initialise();

    // Initialization
    raFolderName = reportService.getRAFolderName();
    String deCodesXMLFileName = "";
    simpleDateFormat = new SimpleDateFormat("MMM-yyyy");
    monthFormat = new SimpleDateFormat("MMMM");
    yearFormat = new SimpleDateFormat("yyyy");
    simpleMonthFormat = new SimpleDateFormat("MMM");
    String parentUnit = "";

    Report_in selReportObj = reportService.getReport(Integer.parseInt(reportList));

    deCodesXMLFileName = selReportObj.getXmlTemplateName();

    reportModelTB = selReportObj.getModel();
    reportFileNameTB = selReportObj.getExcelTemplateName();

    String inputTemplatePath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + raFolderName
            + File.separator
            + "template"
            + File.separator
            + reportFileNameTB;
    // String outputReportFolderPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName
    // + File.separator + "output" + File.separator + UUID.randomUUID().toString();
    String outputReportFolderPath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + Configuration_IN.DEFAULT_TEMPFOLDER
            + File.separator
            + UUID.randomUUID().toString();
    File newdir = new File(outputReportFolderPath);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }

    if (reportModelTB.equalsIgnoreCase("STATIC")
        || reportModelTB.equalsIgnoreCase("STATIC-DATAELEMENTS")
        || reportModelTB.equalsIgnoreCase("STATIC-FINANCIAL")) {
      orgUnitList =
          new ArrayList<OrganisationUnit>(
              organisationUnitService.getOrganisationUnitWithChildren(ouIDTB));
      OrganisationUnitGroup orgUnitGroup = selReportObj.getOrgunitGroup();

      orgUnitList.retainAll(orgUnitGroup.getMembers());
    } else {
      return INPUT;
    }

    // System.out.println(  "---Size of Org Unit List ----: " + orgUnitList.size() + ",Report Group
    // name is :---" + selReportObj.getOrgunitGroup().getName() + ", Size of Group member is ----:"
    // + selReportObj.getOrgunitGroup().getMembers().size()  );

    System.out.println(" ---- Size of OrgUnit List is ---- " + orgUnitList.size());

    OrganisationUnit selOrgUnit = organisationUnitService.getOrganisationUnit(ouIDTB);

    System.out.println(
        selOrgUnit.getName()
            + " : "
            + selReportObj.getName()
            + " : Report Generation Start Time is : "
            + new Date());

    selectedPeriod = periodService.getPeriod(availablePeriods);

    sDate = format.parseDate(String.valueOf(selectedPeriod.getStartDate()));

    eDate = format.parseDate(String.valueOf(selectedPeriod.getEndDate()));

    Workbook templateWorkbook = Workbook.getWorkbook(new File(inputTemplatePath));

    // collect periodId by commaSepareted
    List<Period> tempPeriodList =
        new ArrayList<Period>(periodService.getIntersectingPeriods(sDate, eDate));

    Collection<Integer> tempPeriodIds =
        new ArrayList<Integer>(getIdentifiers(Period.class, tempPeriodList));

    String periodIdsByComma = getCommaDelimitedString(tempPeriodIds);

    // Getting DataValues
    List<Report_inDesign> reportDesignList = reportService.getReportDesign(deCodesXMLFileName);

    // collect dataElementIDs by commaSepareted
    String dataElmentIdsByComma = reportService.getDataelementIds(reportDesignList);

    int orgUnitCount = 0;

    Iterator<OrganisationUnit> it = orgUnitList.iterator();
    while (it.hasNext()) {
      OrganisationUnit currentOrgUnit = (OrganisationUnit) it.next();

      String outPutFileName = reportFileNameTB.replace(".xls", "");
      outPutFileName += "_" + currentOrgUnit.getShortName();
      outPutFileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".xls";

      String outputReportPath = outputReportFolderPath + File.separator + outPutFileName;
      WritableWorkbook outputReportWorkbook =
          Workbook.createWorkbook(new File(outputReportPath), templateWorkbook);

      Map<String, String> aggDeMap = new HashMap<String, String>();
      if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
        aggDeMap.putAll(
            reportService.getResultDataValueFromAggregateTable(
                currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma));
      } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
        List<OrganisationUnit> childOrgUnitTree =
            new ArrayList<OrganisationUnit>(
                organisationUnitService.getOrganisationUnitWithChildren(currentOrgUnit.getId()));
        List<Integer> childOrgUnitTreeIds =
            new ArrayList<Integer>(getIdentifiers(OrganisationUnit.class, childOrgUnitTree));
        String childOrgUnitsByComma = getCommaDelimitedString(childOrgUnitTreeIds);

        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                childOrgUnitsByComma, dataElmentIdsByComma, periodIdsByComma));
      } else if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                "" + currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma));
      }

      int count1 = 0;
      Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
      while (reportDesignIterator.hasNext()) {
        Report_inDesign report_inDesign = (Report_inDesign) reportDesignIterator.next();

        String deType = report_inDesign.getPtype();
        String sType = report_inDesign.getStype();
        String deCodeString = report_inDesign.getExpression();
        String tempStr = "";

        Calendar tempStartDate = Calendar.getInstance();
        Calendar tempEndDate = Calendar.getInstance();
        List<Calendar> calendarList =
            new ArrayList<Calendar>(reportService.getStartingEndingPeriods(deType, selectedPeriod));
        if (calendarList == null || calendarList.isEmpty()) {
          tempStartDate.setTime(selectedPeriod.getStartDate());
          tempEndDate.setTime(selectedPeriod.getEndDate());
          return SUCCESS;
        } else {
          tempStartDate = calendarList.get(0);
          tempEndDate = calendarList.get(1);
        }

        if (deCodeString.equalsIgnoreCase("FACILITY")) {
          tempStr = currentOrgUnit.getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITY-NOREPEAT")) {
          tempStr = parentUnit;
        } else if (deCodeString.equalsIgnoreCase("FACILITYP")) {
          tempStr = currentOrgUnit.getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("PERIOD")
            || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")) {
          tempStr = simpleDateFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("PERIOD-MONTH")) {
          tempStr = monthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("PERIOD-YEAR")) {
          tempStr = yearFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-START-SHORT")) {
          tempStr = simpleMonthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-END-SHORT")) {
          tempStr = simpleMonthFormat.format(eDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-START")) {
          tempStr = monthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-END")) {
          tempStr = monthFormat.format(eDate);
        } else if (deCodeString.equalsIgnoreCase("SLNO")) {
          tempStr = "" + (orgUnitCount + 1);
        } else if (deCodeString.equalsIgnoreCase("NA")) {
          tempStr = " ";
        } else {
          if (sType.equalsIgnoreCase("dataelement")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
              // tempStr = reportService.getIndividualResultDataValue(deCodeString,
              // tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit, reportModelTB );
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
              // tempStr = reportService.getResultDataValue( deCodeString, tempStartDate.getTime(),
              // tempEndDate.getTime(), currentOrgUnit, reportModelTB );
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {

              tempStr = getAggVal(deCodeString, aggDeMap);
              /*
              List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( tempStartDate.getTime(), tempEndDate.getTime() ) );
              Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) );
              tempStr = reportService.getResultDataValueFromAggregateTable( deCodeString, periodIds, currentOrgUnit, reportModelTB );
              */
            }
          } else if (sType.equalsIgnoreCase("dataelement-boolean")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            }
          } else {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr =
                  reportService.getIndividualResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr =
                  reportService.getResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              // List<Period> periodList = new ArrayList<Period>(
              // periodService.getPeriodsBetweenDates( tempStartDate.getTime(),
              // tempEndDate.getTime() ) );
              // Collection<Integer> periodIds = new ArrayList<Integer>(
              // getIdentifiers(Period.class, periodList ) );
              tempStr =
                  reportService.getResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            }
          }
        }

        int tempRowNo = report_inDesign.getRowno();
        int tempColNo = report_inDesign.getColno();
        int sheetNo = report_inDesign.getSheetno();
        WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

        if (tempStr == null || tempStr.equals(" ")) {
          tempColNo += orgUnitCount;

          WritableCellFormat wCellformat = new WritableCellFormat();
          wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
          wCellformat.setWrap(true);
          wCellformat.setAlignment(Alignment.CENTRE);

          sheet0.addCell(new Blank(tempColNo, tempRowNo, wCellformat));
        } else {
          if (reportModelTB.equalsIgnoreCase("DYNAMIC-ORGUNIT")) {
            if (deCodeString.equalsIgnoreCase("FACILITYP")
                || deCodeString.equalsIgnoreCase("FACILITYPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
            } else if (deCodeString.equalsIgnoreCase("PERIOD")
                || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")
                || deCodeString.equalsIgnoreCase("PERIOD-WEEK")
                || deCodeString.equalsIgnoreCase("PERIOD-MONTH")
                || deCodeString.equalsIgnoreCase("PERIOD-QUARTER")
                || deCodeString.equalsIgnoreCase("PERIOD-YEAR")
                || deCodeString.equalsIgnoreCase("MONTH-START")
                || deCodeString.equalsIgnoreCase("MONTH-END")
                || deCodeString.equalsIgnoreCase("MONTH-START-SHORT")
                || deCodeString.equalsIgnoreCase("MONTH-END-SHORT")
                || deCodeString.equalsIgnoreCase("SIMPLE-QUARTER")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS")
                || deCodeString.equalsIgnoreCase("QUARTER-START-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-END-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-START")
                || deCodeString.equalsIgnoreCase("QUARTER-END")
                || deCodeString.equalsIgnoreCase("SIMPLE-YEAR")
                || deCodeString.equalsIgnoreCase("YEAR-END")
                || deCodeString.equalsIgnoreCase("YEAR-FROMTO")) {
            } else {
              tempColNo += orgUnitCount;
            }
          } else if (reportModelTB.equalsIgnoreCase("dynamicwithrootfacility")) {
            if (deCodeString.equalsIgnoreCase("FACILITYP")
                || deCodeString.equalsIgnoreCase("FACILITY-NOREPEAT")
                || deCodeString.equalsIgnoreCase("FACILITYPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
            } else if (deCodeString.equalsIgnoreCase("PERIOD")
                || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")
                || deCodeString.equalsIgnoreCase("PERIOD-WEEK")
                || deCodeString.equalsIgnoreCase("PERIOD-MONTH")
                || deCodeString.equalsIgnoreCase("PERIOD-QUARTER")
                || deCodeString.equalsIgnoreCase("PERIOD-YEAR")
                || deCodeString.equalsIgnoreCase("MONTH-START")
                || deCodeString.equalsIgnoreCase("MONTH-END")
                || deCodeString.equalsIgnoreCase("MONTH-START-SHORT")
                || deCodeString.equalsIgnoreCase("MONTH-END-SHORT")
                || deCodeString.equalsIgnoreCase("SIMPLE-QUARTER")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS")
                || deCodeString.equalsIgnoreCase("QUARTER-START-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-END-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-START")
                || deCodeString.equalsIgnoreCase("QUARTER-END")
                || deCodeString.equalsIgnoreCase("SIMPLE-YEAR")
                || deCodeString.equalsIgnoreCase("YEAR-END")
                || deCodeString.equalsIgnoreCase("YEAR-FROMTO")) {
            } else {
              tempRowNo += orgUnitCount;
            }
          }

          WritableCell cell = sheet0.getWritableCell(tempColNo, tempRowNo);

          CellFormat cellFormat = cell.getCellFormat();
          WritableCellFormat wCellformat = new WritableCellFormat();
          wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
          wCellformat.setWrap(true);
          wCellformat.setAlignment(Alignment.CENTRE);

          if (cell.getType() == CellType.LABEL) {
            Label l = (Label) cell;
            l.setString(tempStr);
            l.setCellFormat(cellFormat);
          } else {
            try {
              sheet0.addCell(
                  new Number(tempColNo, tempRowNo, Double.parseDouble(tempStr), wCellformat));
            } catch (Exception e) {
              sheet0.addCell(new Label(tempColNo, tempRowNo, tempStr, wCellformat));
            }
          }
        }

        count1++;
      } // inner while loop end

      outputReportWorkbook.write();
      outputReportWorkbook.close();

      orgUnitCount++;
    } // outer while loop end

    statementManager.destroy();

    if (zipDirectory(outputReportFolderPath, outputReportFolderPath + ".zip")) {
      System.out.println(
          selOrgUnit.getName()
              + " : "
              + selReportObj.getName()
              + " Report Generation End Time is : "
              + new Date());

      fileName = reportFileNameTB.replace(".xls", "");
      fileName += "_" + selOrgUnit.getShortName();
      fileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".zip";

      File outputReportFile = new File(outputReportFolderPath + ".zip");
      inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));

      return SUCCESS;
    } else {
      return INPUT;
    }
  }
Exemplo n.º 12
0
 private final Period reloadPeriod(Period period) {
   return periodService.getPeriod(
       period.getStartDate(), period.getEndDate(), period.getPeriodType());
 }
  @Override
  public void setUpTest() {
    // ---------------------------------------------------------------------
    // Services
    // ---------------------------------------------------------------------

    importObjectService = (ImportObjectService) getBean(ImportObjectService.ID);

    batchHandlerFactory = (BatchHandlerFactory) getBean("batchHandlerFactory");

    dataElementService = (DataElementService) getBean(DataElementService.ID);

    categoryService = (DataElementCategoryService) getBean(DataElementCategoryService.ID);

    periodService = (PeriodService) getBean(PeriodService.ID);

    organisationUnitService = (OrganisationUnitService) getBean(OrganisationUnitService.ID);

    dataValueService = (DataValueService) getBean(DataValueService.ID);

    // ---------------------------------------------------------------------
    // CategoryOption
    // ---------------------------------------------------------------------

    categoryOptionA = new DataElementCategoryOption("CategoryOptionA");
    categoryOptionB = new DataElementCategoryOption("CategoryOptionB");
    categoryOptionC = new DataElementCategoryOption("CategoryOptionC");
    categoryOptionD = new DataElementCategoryOption("CategoryOptionD");

    categoryService.addDataElementCategoryOption(categoryOptionA);
    categoryService.addDataElementCategoryOption(categoryOptionB);
    categoryService.addDataElementCategoryOption(categoryOptionC);
    categoryService.addDataElementCategoryOption(categoryOptionD);

    categoryOptionADuplicate = new DataElementCategoryOption("CategoryOptionA");
    categoryOptionBDuplicate = new DataElementCategoryOption("CategoryOptionB");
    categoryOptionCDuplicate = new DataElementCategoryOption("CategoryOptionC");
    categoryOptionDDuplicate = new DataElementCategoryOption("CategoryOptionD");

    categoryOptionADuplicate.setId('A');
    categoryOptionBDuplicate.setId('B');
    categoryOptionCDuplicate.setId('C');
    categoryOptionDDuplicate.setId('D');

    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryOptionADuplicate, null);
    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryOptionBDuplicate, null);
    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryOptionCDuplicate, null);
    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryOptionDDuplicate, null);

    // ---------------------------------------------------------------------
    // Category
    // ---------------------------------------------------------------------

    categoryA = new DataElementCategory("CategoryA");
    categoryB = new DataElementCategory("CategoryB");

    categoryA.getCategoryOptions().add(categoryOptionA);
    categoryA.getCategoryOptions().add(categoryOptionB);
    categoryB.getCategoryOptions().add(categoryOptionC);
    categoryB.getCategoryOptions().add(categoryOptionD);

    categoryService.addDataElementCategory(categoryA);
    categoryService.addDataElementCategory(categoryB);

    categoryADuplicate = new DataElementCategory("CategoryA");
    categoryBDuplicate = new DataElementCategory("CategoryB");

    categoryADuplicate.setId('A');
    categoryBDuplicate.setId('B');

    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryADuplicate, null);
    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryBDuplicate, null);

    // ---------------------------------------------------------------------
    // Category - CategoryOption Association
    // ---------------------------------------------------------------------

    categoryCategoryOptionAssociationA = new GroupMemberAssociation('A', 'A', 1);
    categoryCategoryOptionAssociationB = new GroupMemberAssociation('A', 'B', 2);
    categoryCategoryOptionAssociationC = new GroupMemberAssociation('B', 'C', 1);
    categoryCategoryOptionAssociationD = new GroupMemberAssociation('B', 'D', 2);

    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORY_CATEGORYOPTION,
        categoryCategoryOptionAssociationA);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORY_CATEGORYOPTION,
        categoryCategoryOptionAssociationB);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORY_CATEGORYOPTION,
        categoryCategoryOptionAssociationC);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORY_CATEGORYOPTION,
        categoryCategoryOptionAssociationD);

    // ---------------------------------------------------------------------
    // CategoryCombo
    // ---------------------------------------------------------------------

    categoryComboA = new DataElementCategoryCombo("CategoryComboA");
    categoryComboB = new DataElementCategoryCombo("CategoryComboB");

    categoryComboA.getCategories().add(categoryA);
    categoryComboA.getCategories().add(categoryB);
    categoryComboB.getCategories().add(categoryA);

    categoryService.addDataElementCategoryCombo(categoryComboA);
    categoryService.addDataElementCategoryCombo(categoryComboB);

    categoryComboADuplicate = new DataElementCategoryCombo("CategoryComboA");
    categoryComboBDuplicate = new DataElementCategoryCombo("CategoryComboB");

    categoryComboADuplicate.setId('A');
    categoryComboBDuplicate.setId('B');

    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryComboADuplicate, null);
    importObjectService.addImportObject(ImportObjectStatus.MATCH, categoryComboBDuplicate, null);

    // ---------------------------------------------------------------------
    // CategoryCombo - Category Association
    // ---------------------------------------------------------------------

    categoryComboCategoryAssociationA = new GroupMemberAssociation('A', 'A', 1);
    categoryComboCategoryAssociationB = new GroupMemberAssociation('A', 'B', 2);
    categoryComboCategoryAssociationC = new GroupMemberAssociation('B', 'A', 1);

    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORYCOMBO_CATEGORY,
        categoryComboCategoryAssociationA);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORYCOMBO_CATEGORY,
        categoryComboCategoryAssociationB);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.CATEGORYCOMBO_CATEGORY,
        categoryComboCategoryAssociationC);

    // ---------------------------------------------------------------------
    // CategoryOptionCombo
    // ---------------------------------------------------------------------

    categoryOptionComboA = new DataElementCategoryOptionCombo();
    categoryOptionComboB = new DataElementCategoryOptionCombo();
    categoryOptionComboC = new DataElementCategoryOptionCombo();
    categoryOptionComboD = new DataElementCategoryOptionCombo();

    categoryOptionComboA.setCategoryCombo(categoryComboA);
    categoryOptionComboB.setCategoryCombo(categoryComboA);
    categoryOptionComboC.setCategoryCombo(categoryComboB);
    categoryOptionComboD.setCategoryCombo(categoryComboB);

    categoryOptionComboA.getCategoryOptions().add(categoryOptionA);
    categoryOptionComboA.getCategoryOptions().add(categoryOptionC);
    categoryOptionComboB.getCategoryOptions().add(categoryOptionB);
    categoryOptionComboB.getCategoryOptions().add(categoryOptionD);
    categoryOptionComboC.getCategoryOptions().add(categoryOptionA);
    categoryOptionComboD.getCategoryOptions().add(categoryOptionB);

    categoryService.addDataElementCategoryOptionCombo(categoryOptionComboA);
    categoryService.addDataElementCategoryOptionCombo(categoryOptionComboB);
    categoryService.addDataElementCategoryOptionCombo(categoryOptionComboC);
    categoryService.addDataElementCategoryOptionCombo(categoryOptionComboD);

    categoryOptionComboADuplicate = new DataElementCategoryOptionCombo();
    categoryOptionComboBDuplicate = new DataElementCategoryOptionCombo();
    categoryOptionComboCDuplicate = new DataElementCategoryOptionCombo();
    categoryOptionComboDDuplicate = new DataElementCategoryOptionCombo();

    categoryOptionComboADuplicate.setId('A');
    categoryOptionComboBDuplicate.setId('B');
    categoryOptionComboCDuplicate.setId('C');
    categoryOptionComboDDuplicate.setId('D');

    categoryOptionComboADuplicate.setCategoryCombo(categoryComboADuplicate);
    categoryOptionComboBDuplicate.setCategoryCombo(categoryComboADuplicate);
    categoryOptionComboCDuplicate.setCategoryCombo(categoryComboBDuplicate);
    categoryOptionComboDDuplicate.setCategoryCombo(categoryComboBDuplicate);

    categoryOptionComboADuplicate.getCategoryOptions().add(categoryOptionADuplicate);
    categoryOptionComboADuplicate.getCategoryOptions().add(categoryOptionCDuplicate);
    categoryOptionComboBDuplicate.getCategoryOptions().add(categoryOptionBDuplicate);
    categoryOptionComboBDuplicate.getCategoryOptions().add(categoryOptionDDuplicate);
    categoryOptionComboCDuplicate.getCategoryOptions().add(categoryOptionADuplicate);
    categoryOptionComboDDuplicate.getCategoryOptions().add(categoryOptionBDuplicate);

    importObjectService.addImportObject(
        ImportObjectStatus.MATCH, categoryOptionComboADuplicate, null);
    importObjectService.addImportObject(
        ImportObjectStatus.MATCH, categoryOptionComboBDuplicate, null);
    importObjectService.addImportObject(
        ImportObjectStatus.MATCH, categoryOptionComboCDuplicate, null);
    importObjectService.addImportObject(
        ImportObjectStatus.MATCH, categoryOptionComboDDuplicate, null);

    // ---------------------------------------------------------------------
    // DataElement
    // ---------------------------------------------------------------------

    dataElementA = createDataElement('A', categoryComboA);
    dataElementB = createDataElement('B', categoryComboA);
    dataElementC = createDataElement('C', categoryComboA);
    dataElementD = createDataElement('D', categoryComboA);

    dataElementAModified = createDataElement('A', categoryComboADuplicate);
    dataElementBModified = createDataElement('B', categoryComboADuplicate);
    dataElementCModified = createDataElement('C', categoryComboADuplicate);
    dataElementDModified = createDataElement('D', categoryComboADuplicate);

    dataElementAModified.setId('A');
    dataElementBModified.setId('B');
    dataElementCModified.setId('C');
    dataElementDModified.setId('D');

    dataElementAModified.setShortName("ShortNameModifiedA");
    dataElementBModified.setShortName("ShortNameModifiedB");
    dataElementCModified.setShortName("ShortNameModifiedC");
    dataElementDModified.setShortName("ShortNameModifiedD");

    // ---------------------------------------------------------------------
    // DataElementGroup
    // ---------------------------------------------------------------------

    dataElementGroupA = createDataElementGroup('A');
    dataElementGroupB = createDataElementGroup('B');
    dataElementGroupC = createDataElementGroup('C');

    dataElementGroupADuplicate = createDataElementGroup('A');
    dataElementGroupBDuplicate = createDataElementGroup('B');
    dataElementGroupCDuplicate = createDataElementGroup('C');

    dataElementGroupADuplicate.setId('A');
    dataElementGroupBDuplicate.setId('B');
    dataElementGroupCDuplicate.setId('C');

    dataElementGroupAssociationA = new GroupMemberAssociation('A', 'A');
    dataElementGroupAssociationB = new GroupMemberAssociation('A', 'B');
    dataElementGroupAssociationC = new GroupMemberAssociation('A', 'C');
    dataElementGroupAssociationD = new GroupMemberAssociation('A', 'D');
    dataElementGroupAssociationE = new GroupMemberAssociation('B', 'A');
    dataElementGroupAssociationF = new GroupMemberAssociation('B', 'B');
    dataElementGroupAssociationG = new GroupMemberAssociation('B', 'C');
    dataElementGroupAssociationH = new GroupMemberAssociation('B', 'D');
    dataElementGroupAssociationI = new GroupMemberAssociation('C', 'A');
    dataElementGroupAssociationJ = new GroupMemberAssociation('C', 'B');
    dataElementGroupAssociationK = new GroupMemberAssociation('C', 'C');
    dataElementGroupAssociationL = new GroupMemberAssociation('C', 'D');

    // ---------------------------------------------------------------------
    // Period
    // ---------------------------------------------------------------------

    periodTypeA = periodService.getPeriodTypeByName(MonthlyPeriodType.NAME);

    periodA = createPeriod(periodTypeA, getDate(1, 0, 2000), getDate(31, 0, 2000));

    periodADuplicate = createPeriod(periodTypeA, getDate(1, 0, 2000), getDate(31, 0, 2000));

    periodADuplicate.setId('A');

    // ---------------------------------------------------------------------
    // OrganisationUnit
    // ---------------------------------------------------------------------

    organisationUnitA = createOrganisationUnit('A');
    organisationUnitB = createOrganisationUnit('B');
    organisationUnitC = createOrganisationUnit('C');

    organisationUnitAModified = createOrganisationUnit('A');
    organisationUnitBModified = createOrganisationUnit('B');
    organisationUnitCModified = createOrganisationUnit('C');

    organisationUnitAModified.setId('A');
    organisationUnitBModified.setId('B');
    organisationUnitCModified.setId('C');

    organisationUnitAModified.setShortName("ShortNameModifiedA");
    organisationUnitBModified.setShortName("ShortNameModifiedB");
    organisationUnitCModified.setShortName("ShortNameModifiedC");

    // ---------------------------------------------------------------------
    // RelationshipAssociation
    // ---------------------------------------------------------------------

    relationshipAssociationA = new GroupMemberAssociation('A', 'B');
    relationshipAssociationB = new GroupMemberAssociation('B', 'C');

    // ---------------------------------------------------------------------
    // DataValue
    // ---------------------------------------------------------------------

    dataValueA =
        createDataValue(dataElementA, periodA, organisationUnitA, "10", categoryOptionComboA);
    dataValueB =
        createDataValue(dataElementA, periodA, organisationUnitB, "10", categoryOptionComboA);
    dataValueC =
        createDataValue(dataElementA, periodA, organisationUnitC, "10", categoryOptionComboA);
    dataValueD =
        createDataValue(dataElementB, periodA, organisationUnitA, "10", categoryOptionComboA);
    dataValueE =
        createDataValue(dataElementB, periodA, organisationUnitB, "10", categoryOptionComboA);
    dataValueF =
        createDataValue(dataElementB, periodA, organisationUnitC, "10", categoryOptionComboA);
    dataValueG =
        createDataValue(dataElementC, periodA, organisationUnitA, "10", categoryOptionComboA);
    dataValueH =
        createDataValue(dataElementC, periodA, organisationUnitB, "10", categoryOptionComboA);
    dataValueI =
        createDataValue(dataElementC, periodA, organisationUnitC, "10", categoryOptionComboA);

    dataValueADuplicate =
        createDataValue(
            dataElementAModified,
            periodADuplicate,
            organisationUnitAModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueBDuplicate =
        createDataValue(
            dataElementAModified,
            periodADuplicate,
            organisationUnitBModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueCDuplicate =
        createDataValue(
            dataElementAModified,
            periodADuplicate,
            organisationUnitCModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueDDuplicate =
        createDataValue(
            dataElementBModified,
            periodADuplicate,
            organisationUnitAModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueEDuplicate =
        createDataValue(
            dataElementBModified,
            periodADuplicate,
            organisationUnitBModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueFDuplicate =
        createDataValue(
            dataElementBModified,
            periodADuplicate,
            organisationUnitCModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueGDuplicate =
        createDataValue(
            dataElementCModified,
            periodADuplicate,
            organisationUnitAModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueHDuplicate =
        createDataValue(
            dataElementCModified,
            periodADuplicate,
            organisationUnitBModified,
            "10",
            categoryOptionComboADuplicate);
    dataValueIDuplicate =
        createDataValue(
            dataElementCModified,
            periodADuplicate,
            organisationUnitCModified,
            "10",
            categoryOptionComboADuplicate);
  }
  // -------------------------------------------------------------------------
  // Action implementation
  // -------------------------------------------------------------------------
  public String execute() throws Exception {
    statementManager.initialise();

    // Initialization
    raFolderName = reportService.getRAFolderName();

    String colArray[] = {
      "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
      "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ",
      "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY",
      "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN",
      "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ"
    };

    Report_in selReportObj = reportService.getReport(Integer.parseInt(reportList));

    // OrgUnit Info
    OrganisationUnit currentOrgUnit = organisationUnitService.getOrganisationUnit(ouIDTB);

    System.out.println(
        currentOrgUnit.getName()
            + " : "
            + selReportObj.getName()
            + " : Report Generation Start Time is : "
            + new Date());

    List<OrganisationUnit> childOrgUnitTree =
        new ArrayList<OrganisationUnit>(
            organisationUnitService.getOrganisationUnitWithChildren(ouIDTB));
    List<Integer> childOrgUnitTreeIds =
        new ArrayList<Integer>(getIdentifiers(OrganisationUnit.class, childOrgUnitTree));
    String childOrgUnitsByComma = getCommaDelimitedString(childOrgUnitTreeIds);

    // Report Info
    String deCodesXMLFileName = selReportObj.getXmlTemplateName();
    String reportModelTB = selReportObj.getModel();
    String reportFileNameTB = selReportObj.getExcelTemplateName();

    String inputTemplatePath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + raFolderName
            + File.separator
            + "template"
            + File.separator
            + reportFileNameTB;
    // String outputReportPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName +
    // File.separator + "output" + File.separator + UUID.randomUUID().toString() + ".xls";

    String outputReportPath =
        System.getenv("DHIS2_HOME") + File.separator + Configuration_IN.DEFAULT_TEMPFOLDER;
    File newdir = new File(outputReportPath);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }
    outputReportPath += File.separator + UUID.randomUUID().toString() + ".xls";

    Workbook templateWorkbook = Workbook.getWorkbook(new File(inputTemplatePath));

    WritableWorkbook outputReportWorkbook =
        Workbook.createWorkbook(new File(outputReportPath), templateWorkbook);
    WritableCellFormat wCellformat = new WritableCellFormat();
    wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
    wCellformat.setAlignment(Alignment.CENTRE);
    wCellformat.setVerticalAlignment(VerticalAlignment.CENTRE);
    wCellformat.setWrap(true);

    // Period Info
    selectedPeriod = periodService.getPeriod(availablePeriods);
    selectedEndPeriod = periodService.getPeriod(availablePeriodsto);

    sDate = format.parseDate(String.valueOf(selectedPeriod.getStartDate()));
    eDate = format.parseDate(String.valueOf(selectedEndPeriod.getEndDate()));

    PeriodType periodType = periodService.getPeriodTypeByName(periodTypeId);
    List<Period> periodList =
        new ArrayList<Period>(periodService.getPeriodsBetweenDates(periodType, sDate, eDate));
    // List<Period> periodList = new ArrayList<Period>( periodService.getIntersectingPeriods( sDate,
    // eDate ) );
    Collections.sort(periodList, new PeriodStartDateComparator());

    if (periodTypeId.equalsIgnoreCase("monthly")) {
      simpleDateFormat = new SimpleDateFormat("MMM-yyyy");
    } else if (periodTypeId.equalsIgnoreCase("yearly")) {
      simpleDateFormat = new SimpleDateFormat("yyyy");
    } else {
      simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    // To get Aggregation Data

    List<Report_inDesign> reportDesignList = reportService.getReportDesign(deCodesXMLFileName);

    // String dataElmentIdsByComma = reportService.getDataelementIds( reportDesignList );
    String dataElmentIdsByComma =
        reportService.getDataelementIdsByStype(reportDesignList, Report_inDesign.ST_DATAELEMENT);
    String nonNumberDataElementIdsByComma =
        reportService.getDataelementIdsByStype(
            reportDesignList, Report_inDesign.ST_NON_NUMBER_DATAELEMENT);

    // Collection<Integer> periodIds1 = new ArrayList<Integer>( getIdentifiers(Period.class,
    // periodList ) );
    String periodsByComma = "";
    // getCommaDelimitedString( periodIds1 );

    int colCount = 0;
    for (Period period : periodList) {
      if (periodTypeId.equalsIgnoreCase("daily")) {
        periodsByComma = "" + period.getId();
      } else {
        Collection<Integer> periodIds =
            new ArrayList<Integer>(
                getIdentifiers(
                    Period.class,
                    periodService.getIntersectingPeriods(
                        period.getStartDate(), period.getEndDate())));
        periodsByComma = getCommaDelimitedString(periodIds);
      }

      Map<String, String> aggDeMap = new HashMap<String, String>();
      if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
        aggDeMap.putAll(
            reportService.getResultDataValueFromAggregateTable(
                currentOrgUnit.getId(), dataElmentIdsByComma, periodsByComma));
      } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                childOrgUnitsByComma, dataElmentIdsByComma, periodsByComma));
        aggDeMap.putAll(
            reportService.getAggNonNumberDataFromDataValueTable(
                childOrgUnitsByComma, nonNumberDataElementIdsByComma, periodsByComma));
        System.out.println(
            childOrgUnitsByComma + " \n " + dataElmentIdsByComma + " \n " + periodsByComma);
      } else if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                "" + currentOrgUnit.getId(), dataElmentIdsByComma, periodsByComma));
        aggDeMap.putAll(
            reportService.getAggNonNumberDataFromDataValueTable(
                "" + currentOrgUnit.getId(), nonNumberDataElementIdsByComma, periodsByComma));
      }
      System.out.println("aggDeMap size : " + aggDeMap.size());

      Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
      while (reportDesignIterator.hasNext()) {
        Report_inDesign reportDesign = reportDesignIterator.next();
        String deCodeString = reportDesign.getExpression();

        String sType = reportDesign.getStype();
        String tempStr = "";

        tempRowNo = reportDesign.getRowno();
        tempColNo = reportDesign.getColno();
        sheetNo = reportDesign.getSheetno();

        if (deCodeString.equalsIgnoreCase("FACILITY")) {
          tempStr = currentOrgUnit.getName();
        } else if (deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
          tempStr =
              simpleDateFormat.format(selectedPeriod.getStartDate())
                  + " To "
                  + simpleDateFormat.format(selectedEndPeriod.getEndDate());
        } else if (deCodeString.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
          tempStr = simpleDateFormat.format(period.getStartDate());
        } else if (deCodeString.equalsIgnoreCase("NA")) {
          tempStr = " ";
        } else {
          if (sType.equalsIgnoreCase("dataelement")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              // tempStr = reportService.getIndividualResultDataValue( deCodeString,
              // period.getStartDate(), period.getEndDate(), currentOrgUnit, reportModelTB );
              tempStr = getAggVal(deCodeString, aggDeMap);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              // tempStr = reportService.getResultDataValue( deCodeString, period.getStartDate(),
              // period.getEndDate(), currentOrgUnit, reportModelTB );
              tempStr = getAggVal(deCodeString, aggDeMap);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
            }
          } else if (sType.equalsIgnoreCase(Report_inDesign.ST_DATAELEMENT_NO_REPEAT)) {
            deCodeString = deCodeString.replaceAll(":", "\\.");
            deCodeString = deCodeString.replaceAll("[", "");
            deCodeString = deCodeString.replaceAll("]", "");
            System.out.println("deCodeString : " + deCodeString);
            tempStr = aggDeMap.get(deCodeString);
          }
        }

        if (tempStr == null || tempStr.equals(" ")) {
          tempColNo += colCount;

          WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

          sheet0.addCell(new Blank(tempColNo, tempRowNo, wCellformat));
        } else {
          if (reportModelTB.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
            if (deCodeString.equalsIgnoreCase("FACILITY")
                || deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
            } else {
              tempColNo += colCount;
            }

            WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

            try {
              try {
                sheet0.addCell(
                    new Number(tempColNo, tempRowNo, Double.parseDouble(tempStr), wCellformat));
              } catch (Exception e) {
                sheet0.addCell(new Label(tempColNo, tempRowNo, tempStr, wCellformat));
              }
            } catch (Exception e) {
              System.out.println("Cannot write to Excel");
            }
          }
        }
      } // inner while loop end

      colCount++;
    } // outer while loop end

    // ---------------------------------------------------------------------
    // Writing Total Values
    // ---------------------------------------------------------------------

    Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
    while (reportDesignIterator.hasNext()) {
      Report_inDesign reportDesign = reportDesignIterator.next();

      String deCodeString = reportDesign.getExpression();

      if (deCodeString.equalsIgnoreCase("FACILITY")
          || deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
        continue;
      }

      tempRowNo = reportDesign.getRowno();
      tempColNo = reportDesign.getColno();
      sheetNo = reportDesign.getSheetno();

      String colStart = "" + colArray[tempColNo];
      String colEnd = "" + colArray[tempColNo + colCount - 1];

      String tempFormula =
          "SUM(" + colStart + (tempRowNo + 1) + ":" + colEnd + (tempRowNo + 1) + ")";

      WritableSheet totalSheet = outputReportWorkbook.getSheet(sheetNo);
      WritableFont arialBold = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
      WritableCellFormat totalCellformat = new WritableCellFormat(arialBold);
      totalCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
      totalCellformat.setAlignment(Alignment.CENTRE);
      totalCellformat.setVerticalAlignment(VerticalAlignment.CENTRE);
      totalCellformat.setWrap(true);

      if (deCodeString.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
        totalSheet.addCell(new Label(tempColNo + colCount, tempRowNo, "Total", totalCellformat));
      } else if (deCodeString.equalsIgnoreCase("NA")) {
        totalSheet.addCell(new Label(tempColNo + colCount, tempRowNo, " ", totalCellformat));
      } else {
        totalSheet.addCell(
            new Formula(tempColNo + colCount, tempRowNo, tempFormula, totalCellformat));
      }
    }

    outputReportWorkbook.write();
    outputReportWorkbook.close();

    fileName = reportFileNameTB.replace(".xls", "");
    fileName += "_" + currentOrgUnit.getShortName();
    fileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".xls";
    File outputReportFile = new File(outputReportPath);
    inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));

    System.out.println(
        currentOrgUnit.getName()
            + " : "
            + selReportObj.getName()
            + " : Report Generation End Time is : "
            + new Date());

    outputReportFile.deleteOnExit();

    statementManager.destroy();

    return SUCCESS;
  }