@Override
  public String execute() throws Exception {
    DataSet dataSet = dataSetService.getDataSet(dataSetId);

    DataEntryForm dataEntryForm = dataEntryFormService.getDataEntryForm(dataEntryFormId);

    dataSet.setDataEntryForm(null);
    dataSet.increaseVersion();

    dataSetService.updateDataSet(dataSet);

    dataEntryFormService.deleteDataEntryForm(dataEntryForm);

    return SUCCESS;
  }
  public String execute() {
    if (dataSetId != null) {
      dataSet = dataSetService.getDataSet(dataSetId);

      operands =
          new ArrayList<DataElementOperand>(
              dataElementCategoryService.getFullOperands(dataSet.getDataElements()));
    } else {
      operands = new ArrayList<DataElementOperand>();
    }

    if (key != null) {
      Iterator<DataElementOperand> iterator = operands.iterator();

      while (iterator.hasNext()) {
        DataElementOperand operand = iterator.next();

        if (operand.getOperandName().toLowerCase().indexOf(key.toLowerCase()) == -1) {
          iterator.remove();
        }
      }
    }

    Collections.sort(operands, new DataElementOperandNameComparator());

    if (usePaging) {
      this.paging = createPaging(operands.size());

      operands = operands.subList(paging.getStartPos(), paging.getEndPos());
    }

    return SUCCESS;
  }
  public String execute() throws Exception {
    // ---------------------------------------------------------------------
    // Prepare values
    // ---------------------------------------------------------------------

    code = nullIfEmpty(code);
    shortName = nullIfEmpty(shortName);
    description = nullIfEmpty(description);

    PeriodType periodType = PeriodType.getPeriodTypeByName(frequencySelect);

    DataSet dataSet = new DataSet(name, shortName, code, periodType);

    MapLegendSet legendSet = mappingService.getMapLegendSet(selectedLegendSetId);

    dataSet.setExpiryDays(expiryDays);
    dataSet.setTimelyDays(timelyDays);
    dataSet.setSkipAggregation(skipAggregation);

    for (String id : dataElementsSelectedList) {
      dataSet.addDataElement(dataElementService.getDataElement(Integer.parseInt(id)));
    }

    Set<Indicator> indicators = new HashSet<Indicator>();

    for (String id : indicatorsSelectedList) {
      indicators.add(indicatorService.getIndicator(Integer.parseInt(id)));
    }

    if (categoryComboId != null) {
      dataSet.setCategoryCombo(categoryService.getDataElementCategoryCombo(categoryComboId));
    }

    dataSet.setDescription(description);
    dataSet.setVersion(1);
    dataSet.setMobile(false);
    dataSet.setIndicators(indicators);
    dataSet.setNotificationRecipients(userGroupService.getUserGroup(notificationRecipients));
    dataSet.setAllowFuturePeriods(allowFuturePeriods);
    dataSet.setFieldCombinationRequired(fieldCombinationRequired);
    dataSet.setValidCompleteOnly(validCompleteOnly);
    dataSet.setNotifyCompletingUser(notifyCompletingUser);
    dataSet.setApproveData(approveData);
    dataSet.setSkipOffline(skipOffline);
    dataSet.setDataElementDecoration(dataElementDecoration);
    dataSet.setRenderAsTabs(renderAsTabs);
    dataSet.setRenderHorizontally(renderHorizontally);
    dataSet.setLegendSet(legendSet);

    dataSetService.addDataSet(dataSet);

    userService.assignDataSetToUserRole(dataSet);

    return SUCCESS;
  }
  @Test
  public void testAverageIntDataElement() {
    DataElement dataElement = createDataElement('A', categoryCombo);

    dataElement.setType(DataElement.VALUE_TYPE_INT);
    dataElement.setAggregationOperator(DataElement.AGGREGATION_OPERATOR_AVERAGE_SUM);

    dataElementIds.add(dataElementService.addDataElement(dataElement));

    DataSet dataSet = createDataSet('A', new YearlyPeriodType());
    dataSet.getDataElements().add(dataElement);
    dataSetService.addDataSet(dataSet);
    dataElement.getDataSets().add(dataSet);
    dataElementService.updateDataElement(dataElement);

    Period dataPeriod =
        createPeriod(new YearlyPeriodType(), getDate(2000, 1, 1), getDate(2000, 12, 31));

    OrganisationUnit unit = createOrganisationUnit('A');

    organisationUnitIds.add(organisationUnitService.addOrganisationUnit(unit));

    dataValueService.addDataValue(
        createDataValue(dataElement, dataPeriod, unit, "100", categoryOptionCombo));

    Period periodA =
        createPeriod(new MonthlyPeriodType(), getDate(2000, 3, 1), getDate(2000, 3, 31));
    Period periodB =
        createPeriod(new MonthlyPeriodType(), getDate(2000, 4, 1), getDate(2000, 4, 30));
    Period periodC =
        createPeriod(new QuarterlyPeriodType(), getDate(2000, 3, 1), getDate(2000, 5, 31));

    periodIds.add(periodService.addPeriod(periodA));
    periodIds.add(periodService.addPeriod(periodB));
    periodIds.add(periodService.addPeriod(periodC));

    dataMartEngine.export(dataElementIds, indicatorIds, periodIds, organisationUnitIds);

    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodA, unit),
        DELTA);
    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodB, unit),
        DELTA);
    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodC, unit),
        DELTA);
  }
  public String execute() throws Exception {
    DataSet dataSet = dataSetService.getDataSet(dataSetId);

    DataEntryStatus dataStatus = new DataEntryStatus();
    dataStatus.setDataSet(dataSet);
    dataStatus.setMakeDefault(makeDefault);
    dataStatus.setPeriodType(dataSet.getPeriodType());

    exportReportService.saveDataEntryStatus(dataStatus);

    return SUCCESS;
  }
  private List<Period> getPeriodsForDataSet(int id) {
    DataSet dataSet = dataSetService.getDataSet(id);

    if (dataSet == null) {
      return new ArrayList<Period>();
    }

    CalendarPeriodType periodType = (CalendarPeriodType) dataSet.getPeriodType();
    List<Period> periods = periodType.generateLast5Years(new Date());
    FilterUtils.filter(periods, new PastAndCurrentPeriodFilter());
    Collections.reverse(periods);

    if (periods.size() > 10) {
      periods = periods.subList(0, 10);
    }

    return periods;
  }
  @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;
  }
  @RequestMapping(method = RequestMethod.POST, produces = "text/plain")
  public void saveDataValue(
      @RequestParam String de,
      @RequestParam String cc,
      @RequestParam String pe,
      @RequestParam String ou,
      @RequestParam String value,
      HttpServletResponse response) {
    DataElement dataElement = dataElementService.getDataElement(de);

    if (dataElement == null) {
      ContextUtils.conflictResponse(response, "Illegal data element identifier: " + de);
      return;
    }

    DataElementCategoryOptionCombo categoryOptionCombo =
        categoryService.getDataElementCategoryOptionCombo(cc);

    if (categoryOptionCombo == null) {
      ContextUtils.conflictResponse(response, "Illegal category option combo identifier: " + cc);
      return;
    }

    Period period = PeriodType.getPeriodFromIsoString(pe);

    if (period == null) {
      ContextUtils.conflictResponse(response, "Illegal period identifier: " + pe);
      return;
    }

    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(ou);

    if (organisationUnit == null) {
      ContextUtils.conflictResponse(response, "Illegal organisation unit identifier: " + ou);
      return;
    }

    if (dataSetService.isLocked(dataElement, period, organisationUnit, null)) {
      ContextUtils.conflictResponse(response, "Data set is locked");
      return;
    }

    value = StringUtils.trimToNull(value);

    String storedBy = currentUserService.getCurrentUsername();

    Date now = new Date();

    DataValue dataValue =
        dataValueService.getDataValue(organisationUnit, dataElement, period, categoryOptionCombo);

    if (dataValue == null) {
      if (value != null) {
        dataValue =
            new DataValue(
                dataElement,
                period,
                organisationUnit,
                value,
                storedBy,
                now,
                null,
                categoryOptionCombo);
        dataValueService.addDataValue(dataValue);
      }
    } else {
      dataValue.setValue(value);
      dataValue.setTimestamp(now);
      dataValue.setStoredBy(storedBy);

      dataValueService.updateDataValue(dataValue);
    }
  }
  @Override
  public void setUpTest() {
    mockDataValueBatchHandler = new MockBatchHandler<>();
    mockBatchHandlerFactory = new MockBatchHandlerFactory();
    mockBatchHandlerFactory.registerBatchHandler(
        DataValueBatchHandler.class, mockDataValueBatchHandler);
    setDependency(dataValueSetService, "batchHandlerFactory", mockBatchHandlerFactory);

    categoryOptionA = createCategoryOption('A');
    categoryOptionB = createCategoryOption('B');
    categoryA = createDataElementCategory('A', categoryOptionA, categoryOptionB);
    categoryComboA = createCategoryCombo('A', categoryA);
    ocDef = categoryService.getDefaultDataElementCategoryOptionCombo();

    ocA = createCategoryOptionCombo(categoryComboA, categoryOptionA);
    ocB = createCategoryOptionCombo(categoryComboA, categoryOptionB);
    deA = createDataElement('A');
    deB = createDataElement('B');
    deC = createDataElement('C');
    deD = createDataElement('D');
    dsA = createDataSet('A', new MonthlyPeriodType());
    ouA = createOrganisationUnit('A');
    ouB = createOrganisationUnit('B');
    ouC = createOrganisationUnit('C');
    peA =
        createPeriod(
            PeriodType.getByNameIgnoreCase(MonthlyPeriodType.NAME),
            getDate(2012, 1, 1),
            getDate(2012, 1, 31));
    peB =
        createPeriod(
            PeriodType.getByNameIgnoreCase(MonthlyPeriodType.NAME),
            getDate(2012, 2, 1),
            getDate(2012, 2, 29));

    ocA.setUid("kjuiHgy67hg");
    ocB.setUid("Gad33qy67g5");
    deA.setUid("f7n9E0hX8qk");
    deB.setUid("Ix2HsbDMLea");
    deC.setUid("eY5ehpbEsB7");
    dsA.setUid("pBOMPrpg1QX");
    ouA.setUid("DiszpKrYNg8");
    ouB.setUid("BdfsJfj87js");
    ouC.setUid("j7Hg26FpoIa");

    ocA.setCode("OC_A");
    ocB.setCode("OC_B");
    deA.setCode("DE_A");
    deB.setCode("DE_B");
    deC.setCode("DE_C");
    deD.setCode("DE_D");
    dsA.setCode("DS_A");
    ouA.setCode("OU_A");
    ouB.setCode("OU_B");
    ouC.setCode("OU_C");

    categoryService.addDataElementCategoryOption(categoryOptionA);
    categoryService.addDataElementCategoryOption(categoryOptionB);
    categoryService.addDataElementCategory(categoryA);
    categoryService.addDataElementCategoryCombo(categoryComboA);
    categoryService.addDataElementCategoryOptionCombo(ocA);
    categoryService.addDataElementCategoryOptionCombo(ocB);

    dataElementService.addDataElement(deA);
    dataElementService.addDataElement(deB);
    dataElementService.addDataElement(deC);
    dataElementService.addDataElement(deD);
    dataSetService.addDataSet(dsA);
    organisationUnitService.addOrganisationUnit(ouA);
    organisationUnitService.addOrganisationUnit(ouB);
    organisationUnitService.addOrganisationUnit(ouC);
    periodService.addPeriod(peA);
    periodService.addPeriod(peB);

    user = createUser('A');
    user.setOrganisationUnits(Sets.newHashSet(ouA, ouB));
    CurrentUserService currentUserService = new MockCurrentUserService(user);
    setDependency(dataValueSetService, "currentUserService", currentUserService);
  }
  public String execute() throws Exception {
    int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    navigationString = "Dashboard";
    orgUnitList = new ArrayList<OrganisationUnit>();

    if (aggOption == null || aggOption.trim().equals("")) {
      aggOption = AlertUtility.USEEXISTINGAGGDATA;
    }

    // Period Info

    Date toDay = new Date();
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(toDay);
    endCal.add(Calendar.MONTH, -1);
    endCal.set(Calendar.DATE, 1);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // String periodId = "Monthly_"+simpleDateFormat.format( cal.getTime() )+"_";

    if ((endCal.get(Calendar.YEAR) % 400 == 0 || endCal.get(Calendar.YEAR) % 4 == 0)
        && endCal.get(Calendar.MONTH) == 1) {
      endCal.set(Calendar.DATE, monthDays[Calendar.MONTH] + 1);
    } else {
      endCal.set(Calendar.DATE, monthDays[Calendar.MONTH]);
    }
    Date eDate = endCal.getTime();

    if (endCal.get(Calendar.MONTH) < Calendar.APRIL) {
      endCal.roll(Calendar.YEAR, -1);
    }
    endCal.set(Calendar.MONTH, Calendar.APRIL);
    endCal.set(Calendar.DATE, 1);

    // periodId += simpleDateFormat.format( cal.getTime() );
    Date sDate = endCal.getTime();

    List<Period> periodList =
        new ArrayList<Period>(periodService.getIntersectingPeriods(sDate, eDate));

    Collection<Integer> periodIds =
        new ArrayList<Integer>(getIdentifiers(Period.class, periodList));

    String periodIdsByComma = getCommaDelimitedString(periodIds);

    // Period selectedPeriod = periodService.getPeriodByExternalId( periodId );

    DataSet selectedDataSet = dataSetService.getDataSetByCode(DASHBOARD_DATASET);

    List<OrganisationUnit> rootOrgUnitList = new ArrayList<OrganisationUnit>();
    rootOrgUnitList.addAll(currentUserService.getCurrentUser().getOrganisationUnits());

    if (drillDownOrgUnitId == null) {
      if (rootOrgUnitList != null && rootOrgUnitList.size() > 0) {
        navigationString += " -> " + rootOrgUnitList.get(0).getName();
        selOrgUnit = rootOrgUnitList.get(0);
      } else {
        navigationString += " -> NO FACILITY";
      }
    } else {
      selOrgUnit =
          organisationUnitService.getOrganisationUnit(Integer.parseInt(drillDownOrgUnitId));
      navigationString += " -> " + selOrgUnit.getName();
    }

    navigationString +=
        " ( " + simpleDateFormat.format(sDate) + " TO " + simpleDateFormat.format(eDate) + " )";

    for (OrganisationUnit orgUnit : rootOrgUnitList) {
      List<OrganisationUnit> tempOuList = new ArrayList<OrganisationUnit>(orgUnit.getChildren());
      Collections.sort(tempOuList, new IdentifiableObjectNameComparator());

      orgUnitList.add(orgUnit);
      orgUnitList.addAll(tempOuList);
    }

    if (selectedDataSet == null || selOrgUnit == null || periodIdsByComma == null) {
      customDataEntryFormCode = " ";
    } else {
      customDataEntryFormCode =
          alertUtility.getCustomDataSetReport(
              selectedDataSet, selOrgUnit, periodIdsByComma, aggOption, format);
    }

    return SUCCESS;
  }
  @Transactional
  public void matchObject(int importObjectId, int existingObjectId) {
    ImportObject importObject = importObjectStore.getImportObject(importObjectId);

    Object object = importObject.getObject();

    // ---------------------------------------------------------------------
    // Updates the name of the import object to the name of the existing
    // object.
    // ---------------------------------------------------------------------

    if (object.getClass().equals(DataElement.class)) {
      DataElement element = (DataElement) object;

      element.setName(dataElementService.getDataElement(existingObjectId).getName());
    } else if (object.getClass().equals(DataElementGroup.class)) {
      DataElementGroup group = (DataElementGroup) object;

      group.setName(dataElementService.getDataElementGroup(existingObjectId).getName());
    } else if (object.getClass().equals(DataElementGroupSet.class)) {
      DataElementGroupSet groupSet = (DataElementGroupSet) object;

      groupSet.setName(dataElementService.getDataElementGroupSet(existingObjectId).getName());
    } else if (object.getClass().equals(IndicatorType.class)) {
      IndicatorType type = (IndicatorType) object;

      type.setName(indicatorService.getIndicatorType(existingObjectId).getName());
    } else if (object.getClass().equals(Indicator.class)) {
      Indicator indicator = (Indicator) object;

      indicator.setName(indicatorService.getIndicator(existingObjectId).getName());
    } else if (object.getClass().equals(IndicatorGroup.class)) {
      IndicatorGroup group = (IndicatorGroup) object;

      group.setName(indicatorService.getIndicatorGroup(existingObjectId).getName());
    } else if (object.getClass().equals(IndicatorGroupSet.class)) {
      IndicatorGroupSet groupSet = (IndicatorGroupSet) object;

      groupSet.setName(indicatorService.getIndicatorGroupSet(existingObjectId).getName());
    } else if (object.getClass().equals(DataDictionary.class)) {
      DataDictionary dictionary = (DataDictionary) object;

      dictionary.setName(dataDictionaryService.getDataDictionary(existingObjectId).getName());
    } else if (object.getClass().equals(DataSet.class)) {
      DataSet dataSet = (DataSet) object;

      dataSet.setName(dataSetService.getDataSet(existingObjectId).getName());
    } else if (object.getClass().equals(OrganisationUnit.class)) {
      OrganisationUnit unit = (OrganisationUnit) object;

      unit.setName(organisationUnitService.getOrganisationUnit(existingObjectId).getName());
    } else if (object.getClass().equals(OrganisationUnitGroup.class)) {
      OrganisationUnitGroup group = (OrganisationUnitGroup) object;

      group.setName(
          organisationUnitGroupService.getOrganisationUnitGroup(existingObjectId).getName());
    } else if (object.getClass().equals(OrganisationUnitGroupSet.class)) {
      OrganisationUnitGroupSet groupSet = (OrganisationUnitGroupSet) object;

      groupSet.setName(
          organisationUnitGroupService.getOrganisationUnitGroupSet(existingObjectId).getName());
    } else if (object.getClass().equals(OrganisationUnitLevel.class)) {
      OrganisationUnitLevel level = (OrganisationUnitLevel) object;

      level.setName(organisationUnitService.getOrganisationUnitLevel(existingObjectId).getName());
    } else if (object.getClass().equals(ValidationRule.class)) {
      ValidationRule validationRule = (ValidationRule) object;

      validationRule.setName(validationRuleService.getValidationRule(existingObjectId).getName());
    } else if (object.getClass().equals(Report.class)) {
      Report report = (Report) object;

      report.setName(reportService.getReport(existingObjectId).getName());
    } else if (object.getClass().equals(ReportTable.class)) {
      ReportTable reportTable = (ReportTable) object;

      reportTable.setName(reportTableService.getReportTable(existingObjectId).getName());
    } else if (object.getClass().equals(Chart.class)) {
      Chart chart = (Chart) object;

      chart.setName(chartService.getChart(existingObjectId).getName());
    } else if (object.getClass().equals(DataValue.class)) {
      DataValue dataValue = (DataValue) object;

      dataValue =
          updateDataValue(
              dataValue,
              dataValueService.getDataValue(
                  dataValue.getSource(),
                  dataValue.getDataElement(),
                  dataValue.getPeriod(),
                  dataValue.getOptionCombo()));
    }

    // ---------------------------------------------------------------------
    // Sets the status of the import object to match, these objects will
    // later be ignored on import all but is needed for matching of
    // associations.
    // ---------------------------------------------------------------------

    importObject.setStatus(ImportObjectStatus.MATCH);

    importObjectStore.updateImportObject(importObject);
  }