public void testEndSection() throws Exception {
   ReportFormat rf = new ReportFormat();
   String endSection = "end";
   rf.setDocumentEndSection(endSection);
   ReportOutput result = runReportOnSampleData(rf);
   assertEquals("didn't output end section?", endSection, result.getDocumentEnd());
 }
  public void testTotalsInPageReport() throws Exception {
    MockMartusApp app = MockMartusApp.create();
    app.loadSampleData();

    ReportFormat rf = new ReportFormat();
    rf.setBulletinPerPage(true);
    rf.setTotalSection("Totals");

    RunReportOptions detailOnly = new RunReportOptions();
    detailOnly.hideDetail = false;
    detailOnly.printBreaks = false;
    ReportOutput details = runReportOnAppData(rf, app, detailOnly);
    assertEquals("", details.getPrintableDocument());

    RunReportOptions detailAndSummary = new RunReportOptions();
    detailAndSummary.hideDetail = false;
    detailAndSummary.printBreaks = true;
    ReportOutput both = runReportOnAppData(rf, app, detailAndSummary);
    assertEquals("Totals", both.getPrintableDocument());

    RunReportOptions summaryOnly = new RunReportOptions();
    summaryOnly.hideDetail = true;
    summaryOnly.printBreaks = true;
    ReportOutput summary = runReportOnAppData(rf, app, summaryOnly);
    assertEquals("Totals", summary.getPrintableDocument());
  }
  public void testBreakSection() throws Exception {
    String sampleDate = "2004-06-19";
    MockMartusApp app = createAppWithBulletinsForBreaks(sampleDate);
    ReportFormat rf = new ReportFormat();
    String breakSection =
        "$BreakLevel had $BreakCount\n"
            + "#foreach($x in [0..$BreakLevel])\n"
            + "$BreakFields.get($x).getLocalizedLabelHtml($localization): "
            + "$BreakFields.get($x).html($localization) "
            + "#end\n\n";
    rf.setBreakSection(breakSection);

    RunReportOptions options = new RunReportOptions();
    options.includePrivate = true;
    options.hideDetail = false;
    options.printBreaks = true;

    MiniLocalization localization = new MiniLocalization();
    String authorLabel = localization.getFieldLabelHtml(Bulletin.TAGAUTHOR);
    String summaryLabel = localization.getFieldLabelHtml(Bulletin.TAGSUMMARY);

    ReportOutput sortByAuthorSummary = runReportOnAppData(rf, app, options);
    assertEquals(
        "1 had 2\n"
            + authorLabel
            + ": a "
            + summaryLabel
            + ": 1 \n"
            + "1 had 1\n"
            + authorLabel
            + ": a "
            + summaryLabel
            + ": 2 \n"
            + "0 had 3\n"
            + authorLabel
            + ": a \n"
            + "1 had 1\n"
            + authorLabel
            + ": b "
            + summaryLabel
            + ": 2 \n"
            + "0 had 1\n"
            + authorLabel
            + ": b \n",
        sortByAuthorSummary.getPageText(0));

    MiniFieldSpec[] entryDateSorting = {
      new MiniFieldSpec(StandardFieldSpecs.findStandardFieldSpec(Bulletin.TAGENTRYDATE)),
    };

    String entryDateLabel = localization.getFieldLabelHtml(Bulletin.TAGENTRYDATE);
    String formattedDate = localization.convertStoredDateToDisplay(sampleDate);
    ReportOutput sortedByEntryDate = runReportOnAppData(rf, app, options, entryDateSorting);
    assertEquals(
        "0 had 4\n" + entryDateLabel + ": " + formattedDate + " \n",
        sortedByEntryDate.getPageText(0));

    options.printBreaks = false;
    assertEquals("Still had output?", "", runReportOnAppData(rf, app, options).getPageText(0));
  }
 public void testStartSection() throws Exception {
   ReportFormat rf = new ReportFormat();
   String startSection = "start";
   rf.setDocumentStartSection(startSection);
   ReportOutput result = runReportOnSampleData(rf);
   assertEquals("didn't output start section?", startSection, result.getDocumentStart());
 }
  public void testRunReport() throws Exception {
    MockMartusApp app = MockMartusApp.create();
    app.getLocalization().setCurrentLanguageCode(MiniLocalization.ENGLISH);
    app.loadSampleData();
    BulletinStore store = app.getStore();
    ReportFormat rf = new ReportFormat();
    rf.setDetailSection("$i. $bulletin.localId\n");
    ReportOutput result = new ReportOutput();
    Set leafUids = store.getAllBulletinLeafUids();
    SortableBulletinList list =
        new SortableBulletinList(app.getLocalization(), new MiniFieldSpec[0]);
    Iterator it = leafUids.iterator();
    while (it.hasNext()) {
      DatabaseKey key = DatabaseKey.createLegacyKey((UniversalId) it.next());
      list.add(BulletinLoader.loadFromDatabase(store.getDatabase(), key, app.getSecurity()));
    }

    RunReportOptions options = new RunReportOptions();
    rr.runReport(
        rf, store.getDatabase(), list, result, options, PoolOfReusableChoicesLists.EMPTY_POOL);
    result.close();
    StringBuffer expected = new StringBuffer();
    UniversalId[] uids = list.getSortedUniversalIds();
    for (int i = 0; i < uids.length; ++i) {
      expected.append(Integer.toString(i + 1));
      expected.append(". ");
      expected.append(uids[i].getLocalId());
      expected.append("\n");
    }
    assertEquals(new String(expected), result.getPageText(0));
  }
  public void testSummaryTotals() throws Exception {
    String sampleDate = "2004-06-19";
    MockMartusApp app = createAppWithBulletinsForBreaks(sampleDate);
    RunReportOptions options = new RunReportOptions();
    options.printBreaks = true;
    options.includePrivate = true;
    options.hideDetail = true;

    ReportFormat rf = new ReportFormat();
    rf.setTotalSection(
        "TOTALS $totals.count()\n"
            + "#foreach($summary1 in $totals.children())\n"
            + "1. $summary1.label(): $summary1.value() = $summary1.count()\n"
            + "#foreach($summary2 in $summary1.children())\n"
            + "2. $summary2.label(): $summary2.value() = $summary2.count()\n"
            + "#foreach($summary3 in $summary2.children())\n"
            + "3. $summary3.label(): $summary3.value() = $summary3.count()\n"
            + "#end\n"
            + "#end\n"
            + "#end\n");

    MiniLocalization localization = new MiniLocalization();
    String authorLabel = localization.getFieldLabelHtml(Bulletin.TAGAUTHOR);
    String summaryLabel = localization.getFieldLabelHtml(Bulletin.TAGSUMMARY);
    ReportOutput totals = runReportOnAppData(rf, app, options);
    assertEquals(
        "TOTALS 4\n"
            + "1. "
            + authorLabel
            + ": a = 3\n"
            + "2. "
            + summaryLabel
            + ": 1 = 2\n"
            + "2. "
            + summaryLabel
            + ": 2 = 1\n"
            + "1. "
            + authorLabel
            + ": b = 1\n"
            + "2. "
            + summaryLabel
            + ": 2 = 1\n",
        totals.getPageText(0));

    options.printBreaks = false;
    ReportOutput noTotals = runReportOnAppData(rf, app, options);
    assertEquals("printed total section?", "", noTotals.getPageText(0));

    rf.setBreakSection("BREAK");
    options.printBreaks = true;
    options.hideDetail = true;
    ReportOutput totalsOnly = runReportOnAppData(rf, app, options);
    assertNotContains("Still printed breaks?", "BREAK", totalsOnly.getPageText(0));
  }
  public void testCustomField() throws Exception {
    FieldSpec[] specs =
        new FieldSpec[] {
          FieldSpec.createStandardField("date", new FieldTypeDate()),
          FieldSpec.createStandardField("text", new FieldTypeNormal()),
          FieldSpec.createStandardField("multi", new FieldTypeMultiline()),
          FieldSpec.createStandardField("range", new FieldTypeDateRange()),
          FieldSpec.createStandardField("bool", new FieldTypeBoolean()),
          FieldSpec.createStandardField("language", new FieldTypeLanguage()),
          LegacyCustomFields.createFromLegacy("custom,Custom <label>"),
        };

    MockMartusApp app = MockMartusApp.create();
    app.getLocalization().setCurrentLanguageCode(MiniLocalization.ENGLISH);
    Bulletin b =
        new Bulletin(app.getSecurity(), new FieldSpecCollection(specs), new FieldSpecCollection());
    String sampleCustomData = "Robert Plant";
    b.set("custom", sampleCustomData);
    b.setAllPrivate(false);
    app.saveBulletin(b, app.getFolderDraftOutbox());

    SortableBulletinList list =
        new SortableBulletinList(app.getLocalization(), new MiniFieldSpec[0]);
    list.add(b);
    ReportFormat rf = new ReportFormat();
    rf.setDetailSection("$bulletin.field('custom')");
    ReportOutput result = new ReportOutput();
    RunReportOptions options = new RunReportOptions();
    rr.runReport(
        rf,
        app.getStore().getDatabase(),
        list,
        result,
        options,
        PoolOfReusableChoicesLists.EMPTY_POOL);
    result.close();

    assertEquals(sampleCustomData, result.getPageText(0));
  }
  public void testPageReport() throws Exception {
    MockMartusApp app = MockMartusApp.create();
    FieldSpec[] topFields = {
      FieldSpec.createStandardField(Bulletin.TAGAUTHOR, new FieldTypeNormal()),
      FieldSpec.createCustomField("tag2", "Label 2", new FieldTypeDate()),
    };
    Bulletin b =
        new Bulletin(
            app.getSecurity(),
            new FieldSpecCollection(topFields),
            StandardFieldSpecs.getDefaultBottomSectionFieldSpecs());
    b.set(topFields[0].getTag(), "First");
    b.set(topFields[1].getTag(), "2005-04-07");
    b.set(Bulletin.TAGPRIVATEINFO, "Secret");
    app.saveBulletin(b, app.getFolderDraftOutbox());

    Bulletin b2 =
        new Bulletin(
            app.getSecurity(),
            new FieldSpecCollection(topFields),
            StandardFieldSpecs.getDefaultBottomSectionFieldSpecs());
    b2.set(topFields[0].getTag(), "Second");
    b2.set(topFields[1].getTag(), "2003-03-29");
    b2.set(Bulletin.TAGPRIVATEINFO, "Another secret");
    app.saveBulletin(b2, app.getFolderDraftOutbox());

    ReportFormat rf = new ReportFormat();
    rf.setBulletinPerPage(true);
    rf.setHeaderSection("Header\n");
    rf.setFooterSection("Footer\n");
    rf.setFakePageBreakSection("----\n");
    rf.setDetailSection(
        "TOP:\n"
            + "#foreach($field in $bulletin.getTopFields())\n"
            + "$field.getLocalizedLabel($localization) $field.html($localization)\n"
            + "#end\n"
            + "BOTTOM:\n"
            + "#foreach($field in $bulletin.getBottomFields())\n"
            + "$field.getLocalizedLabel($localization) $field.html($localization)\n"
            + "#end\n"
            + "");
    String expected0 =
        "Header\n"
            + "TOP:\n"
            + "<field:author> First\n"
            + "Label 2 04/07/2005\n"
            + "BOTTOM:\n"
            + "<field:privateinfo> Secret\n"
            + "Footer\n";
    String expected1 =
        "Header\n"
            + "TOP:\n"
            + "<field:author> Second\n"
            + "Label 2 03/29/2003\n"
            + "BOTTOM:\n"
            + "<field:privateinfo> Another secret\n"
            + "Footer\n";

    RunReportOptions options = new RunReportOptions();
    options.includePrivate = true;
    ReportOutput result = runReportOnAppData(rf, app, options);
    assertEquals("Wrong page report output?", expected0, result.getPageText(0));
    assertEquals("Wrong page report output?", expected1, result.getPageText(1));
    assertEquals("Didn't set fake page break?", "----\n", result.getFakePageBreak());
  }
  public void testOmitDetail() throws Exception {
    String sampleDate = "2004-06-19";
    MockMartusApp app = createAppWithBulletinsForBreaks(sampleDate);
    RunReportOptions options = new RunReportOptions();
    options.includePrivate = true;
    options.printBreaks = true;

    ReportFormat rf = new ReportFormat();
    rf.setDocumentStartSection("Start ");
    rf.setDetailSection("Detail ");
    rf.setBreakSection("Break ");
    rf.setHeaderSection("Header ");
    rf.setFooterSection("Footer ");
    rf.setTotalBreakSection("TotalBreak ");
    rf.setTotalSection("Total ");
    rf.setDocumentEndSection("End ");
    rf.setFakePageBreakSection(". ");

    ReportOutput sortByAuthorSummaryWithDetail = runReportOnAppData(rf, app, options);
    assertEquals(
        "Start Header Detail Detail Break Detail Break Break Detail Break Break TotalBreak Footer . End ",
        sortByAuthorSummaryWithDetail.getPrintableDocument());

    options.hideDetail = true;
    ReportOutput sortByAuthorSummaryWithoutDetail = runReportOnAppData(rf, app, options);
    assertEquals("Start Total . End ", sortByAuthorSummaryWithoutDetail.getPrintableDocument());

    rf.setBulletinPerPage(true);
    options.hideDetail = false;
    ReportOutput pageWithDetail = runReportOnAppData(rf, app, options);
    assertEquals(
        "Start Header Detail Footer . Header Detail Footer . Header Detail Footer . Header Detail Footer . Total . End ",
        pageWithDetail.getPrintableDocument());

    options.hideDetail = true;
    ReportOutput pageWithoutDetail = runReportOnAppData(rf, app, options);
    assertEquals("Start Total . End ", pageWithoutDetail.getPrintableDocument());
  }
  public static String post(String name, Paste paste, ReportFormat format, ExpireDate expireDate) {
    if (name == null) name = "";

    String report_url = "";

    try {
      URL urls = new URL(POST_URL);
      HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);
      conn.setRequestMethod("POST");
      conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
      conn.setInstanceFollowRedirects(false);
      conn.setDoOutput(true);
      OutputStream out = conn.getOutputStream();

      byte[] data =
          ("api_option=paste"
                  + "&api_dev_key="
                  + URLEncoder.encode(API_KEY, "utf-8")
                  + "&api_paste_code="
                  + URLEncoder.encode(paste.toString(), "utf-8")
                  + "&api_paste_private="
                  + URLEncoder.encode("1", "utf-8")
                  + // 1 = unlisted, 0 = public, 2 = private (need to be logged in for that)
                  "&api_paste_name="
                  + URLEncoder.encode(name, "utf-8")
                  + "&api_paste_expire_date="
                  + URLEncoder.encode(expireDate.toString(), "utf-8")
                  + "&api_paste_format="
                  + URLEncoder.encode(format.toString(), "utf-8")
                  + "&api_user_key="
                  + URLEncoder.encode("", "utf-8"))
              .getBytes();

      out.write(data);
      out.flush();
      out.close();

      if (conn.getResponseCode() == 200) {
        InputStream receive = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(receive));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = reader.readLine()) != null) {
          response.append(line);
          response.append("\r\n");
        }
        reader.close();

        String result = response.toString().trim();

        if (!result.contains("http://")) {
          report_url = "Failed to post! (returned result: " + result;
        } else {
          report_url = result.trim();
        }
      } else {
        report_url = "Failed to post!";
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return report_url;
  }
Example #11
0
  /**
   * Expects the following servlet params: type,format,session,start,end,criterion,groupByCriterion
   *
   * <p>Type, format, criterion, and groupByCriterion are taken from the enums: ReportType,
   * ReportFormat, and ReportingCriterion. GroupByCriterion can also have the value "None". Start
   * and end are in milliseconds. Session is a session id string.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    User user = this.getUserFromSession(Param.session.getRaw(req));
    if (user == null) {
      throw new RuntimeException("User was null");
    }

    /* Parse all params
     */
    final String reportType = Param.type.get(req);
    final ReportFormat format = ReportFormat.valueOf(Param.format.get(req));
    final long start = Long.parseLong(Param.start.get(req));
    final long end = Long.parseLong(Param.end.get(req));
    final Period period = new Period(start, end);
    final ReportingCriterion criterion = ReportingCriterion.valueOf(Param.criterion.get(req));
    final Units displayUnits = Units.getDefaultDisplayUnits();

    ReportingCriterion groupByCriterion = null;
    // GroupByCriterion can optionally have value "None"; check for it
    String groupByParam = req.getParameter(Param.groupByCriterion.name());
    if (groupByParam != null && !groupByParam.equalsIgnoreCase("NONE")) {
      groupByCriterion = ReportingCriterion.valueOf(Param.groupByCriterion.get(req));
    }
    LOG.info(
        String.format(
            "Params: type:%s format:%s period:%s" + "criterion:%s groupBy:%s",
            reportType, format, period, criterion, groupByCriterion));

    /* Set servlet response content type, etc, based upon report format.
     */
    setContentTypeHeader(res, format, Param.type.get(req));

    /* Generate the report and send it thru the OutputStream
     */
    if (user.isSystemAdmin()) {
      // Generate report of all accounts
      ReportGenerator.getInstance()
          .generateReport(
              reportType,
              format,
              period,
              criterion,
              groupByCriterion,
              displayUnits,
              res.getOutputStream(),
              null);
    } else if (user.isAccountAdmin()) {
      String accountId;
      try {
        accountId = user.getAccount().getAccountNumber();
      } catch (AuthException aex) {
        throw new RuntimeException("Auth failed");
      }
      // Generate report of this account only
      ReportGenerator.getInstance()
          .generateReport(
              reportType,
              format,
              period,
              criterion,
              groupByCriterion,
              displayUnits,
              res.getOutputStream(),
              accountId);
    } else {
      throw new RuntimeException("Only admins and account owners can generate reports");
    }
  }