public Collection<RenderingMode> getRenderingModes(ReportDefinition definition) {
   List<RenderingMode> ret = new ArrayList<RenderingMode>();
   if (definition.getName().contains("Appointment")) {
     ret.add(new RenderingMode(this, this.getLabel(), this.getLabel(), Integer.MAX_VALUE - 5));
   }
   return ret;
 }
  @Override
  public boolean canRender(ReportDefinition reportDefinition) {

    if (reportDefinition.getName().contains("Appointment")) {
      return true;
    }
    return false;
  }
  private void createDataSetDefinition(ReportDefinition reportDefinition) {
    // Create new dataset definition
    RowPerPatientDataSetDefinition dataSetDefinition = new RowPerPatientDataSetDefinition();
    dataSetDefinition.setName("Chemotherapy Daily Patient List");

    dataSetDefinition.addFilter(
        Cohorts.createInProgramParameterizableByDate("Oncology", oncologyProgram),
        ParameterizableUtil.createParameterMappings("onDate=${endDate}"));

    SortCriteria sortCriteria = new SortCriteria();
    sortCriteria.addSortElement("familyName", SortDirection.ASC);
    dataSetDefinition.setSortCriteria(sortCriteria);

    dataSetDefinition.addParameter(new Parameter("endDate", "Monday", Date.class));

    // Add Columns
    dataSetDefinition.addColumn(
        RowPerPatientColumns.getFirstNameColumn("givenName"), new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getMiddleNameColumn("middleName"), new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getFamilyNameColumn("familyName"), new HashMap<String, Object>());

    dataSetDefinition.addColumn(RowPerPatientColumns.getIMBId("id"), new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getDrugRegimenInformationParameterized("regimen", false, false),
        ParameterizableUtil.createParameterMappings("asOfDate=${endDate},untilDate=${endDate}"));
    dataSetDefinition.addColumn(
        RowPerPatientColumns.getDrugRegimenInformationParameterized(
            "regimenDrugs", chemotherapy, false, true),
        ParameterizableUtil.createParameterMappings("asOfDate=${endDate},untilDate=${endDate}"));

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getStateOfPatient("diagnosis", oncologyProgram, diagnosis, null),
        new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getMostRecent("telephone", telephone, null),
        new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getMostRecent("telephone2", telephone2, null),
        new HashMap<String, Object>());

    dataSetDefinition.addColumn(
        RowPerPatientColumns.getAccompRelationship("accompagnateur"),
        new HashMap<String, Object>());

    Map<String, Object> mappings = new HashMap<String, Object>();
    mappings.put("endDate", "${endDate}");

    reportDefinition.addDataSetDefinition("dataSet", dataSetDefinition, mappings);
  }
  private ReportDefinition createReportDefinition() {

    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setName("ONC-Chemotherapy Daily Expected Patient List");

    UpcomingChemotherapyCohortDefinition baseCohort = new UpcomingChemotherapyCohortDefinition();
    baseCohort.setChemotherapyIndication(chemotherapy);
    baseCohort.addParameter(new Parameter("asOfDate", "asOfDate", Date.class));
    baseCohort.addParameter(new Parameter("untilDate", "untilDate", Date.class));

    reportDefinition.setBaseCohortDefinition(
        baseCohort,
        ParameterizableUtil.createParameterMappings("asOfDate=${endDate},untilDate=${endDate}"));
    reportDefinition.addParameter(new Parameter("endDate", "Date", Date.class));
    createDataSetDefinition(reportDefinition);

    h.saveReportDefinition(reportDefinition);

    return reportDefinition;
  }
  /** Tests that the Report and associated ReportDesigns are successfully saved */
  @Test
  public void shouldSetupReport() throws Exception {
    List<ReportDefinition> l = getReportDefinitionService().getDefinitions(getReportName(), true);
    Assert.assertEquals(0, l.size());

    ReportDefinition reportDefinition = setupReport();
    Assert.assertEquals(getReportName(), reportDefinition.getName());

    ReportService rs = Context.getService(ReportService.class);
    List<ReportDesign> designs = rs.getReportDesigns(reportDefinition, null, false);

    Assert.assertEquals(getReportDesignNames().size(), designs.size());
    int numMatches = 0;
    for (ReportDesign rd : designs) {
      if (getReportDesignNames().contains(rd.getName())) {
        numMatches++;
      }
    }
    Assert.assertEquals(getReportDesignNames().size(), numMatches);
  }
  @Test
  public void test() throws Exception {
    ReportDefinition rd = builder.build(report);

    // Run report on all patients for June 2012
    EvaluationContext context =
        ReportingTestUtils.reportingContext(
            Arrays.asList(2, 6, 7, 8, 999),
            TestUtils.date(2012, 6, 1),
            TestUtils.date(2012, 6, 30));

    ReportData data = Context.getService(ReportDefinitionService.class).evaluate(rd, context);

    // ReportingTestUtils.printReport(data);

    Assert.assertThat(data.getDataSets().size(), is(1));

    // Check that report definition can be serialized/de-serialized
    Context.getService(ReportDefinitionService.class).saveDefinition(rd);
    Context.getService(ReportDefinitionService.class).getDefinition(rd.getId());
  }
  @RequestMapping(method = RequestMethod.POST)
  public void process(
      final @RequestParam(required = false, value = "cohort") Integer cohortId,
      final @RequestParam(required = true, value = "template") MultipartFile template,
      final HttpServletResponse response)
      throws IOException, EvaluationException {

    EvaluationContext context = new EvaluationContext();
    context.addParameterValue("currentDate", new Date());
    if (cohortId != null) {
      context.setBaseCohort(Context.getCohortService().getCohort(cohortId));
    }

    PatientDataSetDefinition definition = new PatientDataSetDefinition();

    definition.addColumn(
        "id", new PatientIdDataDefinition(), StringUtils.EMPTY, new ObjectFormatter());

    ListConverter listConverter = new ListConverter();
    listConverter.setMaxNumberOfItems(1);

    PatientIdentifierDataDefinition preferredIdentifier = new PatientIdentifierDataDefinition();
    preferredIdentifier.addType(Context.getPatientService().getPatientIdentifierType(1));
    definition.addColumn("identifier", preferredIdentifier, StringUtils.EMPTY, listConverter);

    definition.addColumn(
        "name",
        new PreferredNameDataDefinition(),
        StringUtils.EMPTY,
        new ObjectFormatter("{familyName}, {givenName}"));

    AgeDataDefinition ageOnDate = new AgeDataDefinition();
    ageOnDate.addParameter(new Parameter("effectiveDate", "effective date", Date.class));
    definition.addColumn("age", ageOnDate, "effectiveDate=${currentDate}", new AgeConverter());

    definition.addColumn(
        "birthdate",
        new BirthdateDataDefinition(),
        StringUtils.EMPTY,
        new BirthdateConverter("dd-MMM-yyyy"));
    definition.addColumn(
        "gender", new GenderDataDefinition(), StringUtils.EMPTY, new ObjectFormatter());

    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setName("Test Report");
    reportDefinition.addDataSetDefinition("PatientDataSetDefinition", definition, null);

    final ReportDesign design = new ReportDesign();
    design.setName("Test Report Design With Excel Template Renderer");
    design.setReportDefinition(reportDefinition);
    design.setRendererType(ExcelTemplateRenderer.class);

    Properties properties = new Properties();
    properties.put("repeatingSections", "sheet:1,dataset:PatientDataSetDefinition");
    design.setProperties(properties);

    ReportDesignResource resource = new ReportDesignResource();
    resource.setName("excel-template.xls");
    InputStream inputStream = template.getInputStream();
    resource.setContents(IOUtils.toByteArray(inputStream));
    IOUtils.closeQuietly(inputStream);
    design.addResource(resource);

    ExcelTemplateRenderer renderer =
        new ExcelTemplateRenderer() {
          public ReportDesign getDesign(String argument) {
            return design;
          }
        };

    ReportDefinitionService rs = Context.getService(ReportDefinitionService.class);
    ReportData data = rs.evaluate(reportDefinition, context);

    CsvReportRenderer csvReportRenderer = new CsvReportRenderer();
    csvReportRenderer.render(data, "output:csv", System.out);

    File file = File.createTempFile("excel", "summary");
    BufferedOutputStream bufferedOutputStream =
        new BufferedOutputStream(new FileOutputStream(file));
    renderer.render(data, "output:xls", bufferedOutputStream);
    bufferedOutputStream.close();

    response.setHeader("Content-Disposition", "attachment; filename=patient-summary.xls");
    response.setContentType("application/vnd.ms-excel");
    response.setContentLength((int) file.length());

    FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    if (file.delete()) log.info("Temporary file deleted!");
  }
  @Override
  public ReportDefinition getReportDefinition() {

    String nullString = null;
    ObjectFormatter nullStringConverter = new ObjectFormatter();
    MohCoreService service = Context.getService(MohCoreService.class);

    ReportDefinition report = new PeriodIndicatorReportDefinition();
    report.setName("MOH 361A Report");

    // set up the DSD
    PatientDataSetDefinition dsd = new PatientDataSetDefinition();
    dsd.setName("allPatients");

    // set up parameters
    Parameter facility = new Parameter();
    facility.setName("facility");
    facility.setType(MOHFacility.class);

    // add to report and data set definition
    report.addParameter(facility);
    dsd.addParameter(facility);

    // sort by serial number, then by date
    dsd.addSortCriteria("Transfer Status", SortCriteria.SortDirection.ASC);
    dsd.addSortCriteria("Date Chronic HIV Care Started", SortCriteria.SortDirection.ASC);
    dsd.addSortCriteria("Serial Number", SortCriteria.SortDirection.ASC);

    // set up the columns ...

    // patient id ... until we get this thing working proper
    dsd.addColumn("Person ID", new PersonIdDataDefinition(), nullString);

    // a. serial number
    dsd.addColumn("Serial Number", new SerialNumberDataDefinition(), "facility=${facility}");

    // b. date chronic HIV+ care started
    EnrollmentDateDataDefinition enrollmentDate = new EnrollmentDateDataDefinition();
    dsd.addColumn("Date Chronic HIV Care Started", enrollmentDate, nullString);

    // extra column to help understand reason for including in this cohort
    dsd.addColumn(
        "First Encounter Date At Facility",
        new FirstEncounterAtFacilityDataDefinition(),
        "facility=${facility}",
        new EncounterDatetimeConverter());

    // c. Unique Patient Number
    PatientIdentifierType pit = service.getCCCNumberIdentifierType();
    CohortRestrictedPatientIdentifierDataDefinition cccColumn =
        new CohortRestrictedPatientIdentifierDataDefinition("CCC", pit);
    cccColumn.setIncludeFirstNonNullOnly(true);
    dsd.addColumn("Unique Patient Number", cccColumn, nullString);

    // AMRS Universal ID
    CohortRestrictedPatientIdentifierDataDefinition uidColumn =
        new CohortRestrictedPatientIdentifierDataDefinition(
            "AMRS Universal ID", Context.getPatientService().getPatientIdentifierType(8));
    uidColumn.setIncludeFirstNonNullOnly(true);
    dsd.addColumn("AMRS Universal ID", uidColumn, nullString);

    // AMRS Medical Record Number
    CohortRestrictedPatientIdentifierDataDefinition mrnColumn =
        new CohortRestrictedPatientIdentifierDataDefinition(
            "AMRS Medical Record Number", Context.getPatientService().getPatientIdentifierType(3));
    mrnColumn.setIncludeFirstNonNullOnly(true);
    dsd.addColumn("AMRS Medical Record Number", mrnColumn, nullString);

    // d. Patient's Name
    dsd.addColumn("Name", new CohortRestrictedPreferredNameDataDefinition(), nullString);

    // e1. Date of Birth
    dsd.addColumn(
        "Date of Birth",
        new CohortRestrictedBirthdateDataDefinition(),
        nullString,
        new BirthdateConverter(MOHReportUtil.DATE_FORMAT));

    // e2. Age at Enrollment

    MappedData<EnrollmentDateDataDefinition> mappedDef =
        new MappedData<EnrollmentDateDataDefinition>();
    mappedDef.setParameterizable(enrollmentDate);
    mappedDef.addConverter(new DateConverter());
    CohortRestrictedAgeAtDateOfOtherDataDefinition ageAtEnrollment =
        new CohortRestrictedAgeAtDateOfOtherDataDefinition();
    ageAtEnrollment.setEffectiveDateDefinition(mappedDef);
    dsd.addColumn("Age at Enrollment", ageAtEnrollment, nullString, new DecimalAgeConverter(2));

    // f. Sex
    dsd.addColumn("Sex", new CohortRestrictedGenderDataDefinition(), nullString);

    // g. Entry point: From where?
    PersonAttributeType pat =
        Context.getPersonService()
            .getPersonAttributeTypeByName(MohEvaluableNameConstants.POINT_OF_HIV_TESTING);
    dsd.addColumn(
        "Entry Point",
        new CohortRestrictedPersonAttributeDataDefinition("entryPoint", pat),
        nullString,
        new EntryPointConverter());

    // h. Confirmed HIV+ Date
    dsd.addColumn("Confirmed HIV Date", enrollmentDate, nullString);

    //		// i. PEP Start / Stop Date
    //		LogicDataDefinition columnI = new LogicDataDefinition();
    //		columnI.setLogicQuery("\"MOH PEP Start Stop Date\"");
    //		dsd.addColumn("PEP Start / Stop Date", columnI, nullString);
    //
    //		// j. Reasons for PEP use:
    //		LogicDataDefinition columnJ = new LogicDataDefinition();
    //		columnJ.setLogicQuery("\"MOH Reasons For PEP\"");
    //		dsd.addColumn("Reasons for PEP Use", columnJ, nullString);

    // k. CTX startdate and stopdate:
    dsd.addColumn("CTX Start Stop Date", new CtxStartStopDataDefinition(), nullString);

    // l. Fluconazole startdate and stopdate
    dsd.addColumn(
        "Fluconazole Start Stop Date", new FluconazoleStartStopDataDefinition(), nullString);

    // m. TB treatment startdate and stopdate
    dsd.addColumn("TB Treatment Start Stop Date", new TbStartStopDataDefinition(), nullString);

    // n. Pregnancy Yes?, Due date, PMTCT refer
    dsd.addColumn(
        "Pregnancy EDD and Referral",
        new PmtctPregnancyDataDefinition(),
        nullString,
        new PMTCTDatesConverter());

    // o. LTFU / TO / Dead and date when the event occurred
    dsd.addColumn("LTFU TO DEAD", new LTFUTODeadDataDefinition(), nullString, nullStringConverter);

    // p. WHO clinical Stage and date
    dsd.addColumn(
        "WHO Clinical Stage",
        new FirstWHOStageDataDefinition(),
        nullString,
        new WHOStageAndDateConverter());

    // q. Date medically eligible for ART
    EligibilityForARTDataDefinition eligibility = new EligibilityForARTDataDefinition();
    dsd.addColumn(
        "Date Medically Eligible for ART",
        eligibility,
        nullString,
        new ARVPatientSnapshotDateConverter());

    // r. Reason Medically Eligible for ART
    dsd.addColumn(
        "Reason Medically Eligible for ART",
        eligibility,
        nullString,
        new ARVPatientSnapshotReasonConverter());

    // s. Date ART started (Transfer to ART register)
    dsd.addColumn("Date ART Started", new DateARTStartedDataDefinition(), nullString);

    // additional columns for troubleshooting
    LastHIVEncounterDataDefinition lastHIVEncounter = new LastHIVEncounterDataDefinition();
    dsd.addColumn(
        "Last HIV Encounter Date", lastHIVEncounter, nullString, new EncounterDatetimeConverter());
    dsd.addColumn(
        "Last HIV Encounter Location",
        lastHIVEncounter,
        nullString,
        new EncounterLocationConverter());

    // informative column for the destination clinics
    dsd.addColumn(
        "Last Return to Clinic Date",
        new LastRTCDateDataDefinition(),
        nullString,
        new ObsValueDatetimeConverter());

    // transfer status column (used for sorting, not needed in output)
    dsd.addColumn("Transfer Status", new TransferStatusDataDefinition(), nullString);

    Map<String, Object> mappings = new HashMap<String, Object>();
    mappings.put("facility", "${facility}");
    report.addDataSetDefinition(dsd, mappings);

    return report;
  }