Пример #1
0
  public void testToDate2() {
    String[] dateStrings = {"Jan 11, 2002", "Jan 11, 2002", "Feb 12, 1981 6:17 AM"};
    String[] timeZoneIDs = {"GMT+00:00", "GMT-02:00", "GMT+03:00"};
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    Date[] resultDates = new Date[3];
    calendar.clear();
    calendar.set(2002, 0, 11, 0, 0, 0);
    resultDates[0] = calendar.getTime();
    calendar.clear();
    calendar.set(2002, 0, 11, 2, 0, 0);
    resultDates[1] = calendar.getTime();
    calendar.clear();
    calendar.set(1981, 1, 12, 3, 17, 0);
    resultDates[2] = calendar.getTime();

    for (int i = 0; i < dateStrings.length; i++) {
      try {
        Date dateResult =
            DataTypeUtil.toDate(dateStrings[i], ULocale.US, TimeZone.getTimeZone(timeZoneIDs[i]));
        assertEquals(dateResult, resultDates[i]);
      } catch (BirtException e) {
        fail("Should not throw Exception.");
      }
    }
  }
Пример #2
0
 /**
  * Overrides clone.
  *
  * @stable ICU 2.0
  */
 public Object clone() {
   try {
     TimeZone other = (TimeZone) super.clone();
     other.ID = ID;
     return other;
   } catch (CloneNotSupportedException e) {
     throw new IllegalStateException();
   }
 }
 @LayoutlibDelegate
 /*package*/ static long createDateIntervalFormat(
     String skeleton, String localeName, String tzName) {
   TimeZone prevDefaultTz = TimeZone.getDefault();
   TimeZone.setDefault(TimeZone.getTimeZone(tzName));
   DateIntervalFormat_Delegate newDelegate = new DateIntervalFormat_Delegate();
   newDelegate.mFormat = DateIntervalFormat.getInstance(skeleton, new ULocale(localeName));
   TimeZone.setDefault(prevDefaultTz);
   return sManager.addNewDelegate(newDelegate);
 }
Пример #4
0
  /**
   * Sets the <code>TimeZone</code> that is returned by the <code>getDefault</code> method. If
   * <code>zone</code> is null, reset the default to the value it had originally when the VM first
   * started.
   *
   * @param tz the new default time zone
   * @stable ICU 2.0
   */
  public static synchronized void setDefault(TimeZone tz) {
    defaultZone = tz;
    java.util.TimeZone jdkZone = null;
    if (defaultZone instanceof JavaTimeZone) {
      jdkZone = ((JavaTimeZone) defaultZone).unwrap();
    } else {
      // Keep java.util.TimeZone default in sync so java.util.Date
      // can interoperate with com.ibm.icu.util classes.

      if (tz != null) {
        if (tz instanceof com.ibm.icu.impl.OlsonTimeZone) {
          // Because of the lack of APIs supporting historic
          // zone offset/dst saving in JDK TimeZone,
          // wrapping ICU TimeZone with JDK TimeZone will
          // cause historic offset calculation in Calendar/Date.
          // JDK calendar implementation calls getRawOffset() and
          // getDSTSavings() when the instance of JDK TimeZone
          // is not an instance of JDK internal TimeZone subclass
          // (sun.util.calendar.ZoneInfo).  Ticket#6459
          String icuID = tz.getID();
          jdkZone = java.util.TimeZone.getTimeZone(icuID);
          if (!icuID.equals(jdkZone.getID())) {
            // JDK does not know the ID..
            jdkZone = null;
          }
        }
        if (jdkZone == null) {
          jdkZone = TimeZoneAdapter.wrap(tz);
        }
      }
    }
    java.util.TimeZone.setDefault(jdkZone);
  }
Пример #5
0
 /**
  * Constructs a <code>PersianCalendar</code> with the given date set in the default time zone with
  * the default <code>FORMAT</code> locale.
  *
  * @param year the value used to set the {@link #YEAR YEAR} time field in the calendar.
  * @param month the value used to set the {@link #MONTH MONTH} time field in the calendar. Note
  *     that the month value is 0-based. e.g., 0 for Farvardin.
  * @param date the value used to set the {@link #DATE DATE} time field in the calendar.
  * @see Category#FORMAT
  * @internal
  * @deprecated This API is ICU internal only.
  */
 @Deprecated
 public PersianCalendar(int year, int month, int date) {
   super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
   this.set(Calendar.YEAR, year);
   this.set(Calendar.MONTH, month);
   this.set(Calendar.DATE, date);
 }
Пример #6
0
  /**
   * Executes the scalar function toDate() on the given values. The list is expected to be of length
   * 1, and the value in it should be of an appropiate type. The method does not validate the
   * parameters, the user must check the parameters before calling this method.
   *
   * @param values A list with the values that the scalar function is performed on them.
   * @return A date value with the appropriate date.
   */
  public Value evaluate(List<Value> values) {
    Value value = values.get(0);
    Date date;
    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

    // If the given value is null, return a null date value.
    if (value.isNull()) {
      return DateValue.getNullValue();
    }
    DateValue dateValue;
    switch (value.getType()) {
      case DATE:
        dateValue = (DateValue) value;
        break;
      case DATETIME:
        dateValue =
            new DateValue((GregorianCalendar) (((DateTimeValue) value).getObjectToFormat()));
        break;
      case NUMBER:
        date = new Date((long) ((NumberValue) value).getValue());
        gc.setTime(date);
        dateValue = new DateValue(gc);
        break;
      default: // Should never get here.
        throw new RuntimeException("Value type was not found: " + value.getType());
    }
    return dateValue;
  }
Пример #7
0
 /**
  * Constructs a Persian calendar with the default time zone and locale and sets its time to the
  * specified date.
  *
  * @param year the Persian year.
  * @param month the Persian month (zero-based).
  * @param date the Persian day of month.
  */
 public PersianCalendar(int year, int month, int date) {
   super(TimeZone.getDefault(), ULocale.getDefault());
   set(ERA, AH);
   set(YEAR, year);
   set(MONTH, month);
   set(DATE, date);
 }
Пример #8
0
  public void testToDate1() {
    String[] testStrings = {
      "1997",
      "1997-07",
      "1997-07-16",
      "1997-07-16T19:20+02",
      "1997-07-16T19:20:30GMT+01:00",
      "1997-07-16T19:20:30.045+01:00",
      "1997-07-16 19:20+01:00",
      "1997-07-16 19:20:30+01:00",
      "1997-07-16 19:20:30.045+01:00",
      "1997-07-16 19:20:30.045 GMT+01:00",
      "1997-07-16T19:20:30.045-01:00"
    };
    Calendar calendar = Calendar.getInstance();

    Date[] resultDates = new Date[11];

    calendar.clear();
    calendar.set(1997, 0, 1);
    resultDates[0] = calendar.getTime();
    calendar.set(1997, 6, 1);
    resultDates[1] = calendar.getTime();
    calendar.set(1997, 6, 16);
    resultDates[2] = calendar.getTime();

    calendar.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    calendar.set(1997, 6, 16, 17, 20, 0);
    resultDates[3] = calendar.getTime();
    calendar.set(1997, 6, 16, 18, 20, 30);
    resultDates[4] = calendar.getTime();
    calendar.set(1997, 6, 16, 18, 20, 30);
    calendar.set(Calendar.MILLISECOND, 45);
    resultDates[5] = calendar.getTime();
    calendar.set(1997, 6, 16, 18, 20, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    resultDates[6] = calendar.getTime();
    calendar.set(1997, 6, 16, 18, 20, 30);
    resultDates[7] = calendar.getTime();
    calendar.set(1997, 6, 16, 18, 20, 30);
    calendar.set(Calendar.MILLISECOND, 45);
    resultDates[8] = calendar.getTime();
    resultDates[9] = calendar.getTime();
    // "1997-07-16T19:20:30.45-01:00"
    calendar.set(1997, 6, 16, 20, 20, 30);
    calendar.set(Calendar.MILLISECOND, 45);
    resultDates[10] = calendar.getTime();

    for (int i = 0; i < testStrings.length; i++) {
      try {
        Date dateResult = DataTypeUtil.toDate(testStrings[i]);
        assertEquals(dateResult, resultDates[i]);
      } catch (BirtException e) {
        fail("Should not throw Exception.");
      }
    }
  }
Пример #9
0
 /**
  * Constructs a Persian calendar with the default time zone and locale and sets its time to the
  * specified time.
  *
  * @param year the Persian year.
  * @param month the Persian month (zero-based).
  * @param date the Persian day of month.
  * @param hour the hours part of time.
  * @param minute the minutes part of time.
  * @param second the seconds part of time.
  */
 public PersianCalendar(int year, int month, int date, int hour, int minute, int second) {
   super(TimeZone.getDefault(), ULocale.getDefault());
   set(ERA, AH);
   set(YEAR, year);
   set(MONTH, month);
   set(DATE, date);
   set(HOUR_OF_DAY, hour);
   set(MINUTE, minute);
   set(SECOND, second);
 }
Пример #10
0
 /**
  * Constructs a <code>PersianCalendar</code> with the given date and time set for the default time
  * zone with the default <code>FORMAT</code> locale.
  *
  * @param year the value used to set the {@link #YEAR YEAR} time field in the calendar.
  * @param month the value used to set the {@link #MONTH MONTH} time field in the calendar. Note
  *     that the month value is 0-based. e.g., 0 for Farvardin.
  * @param date the value used to set the {@link #DATE DATE} time field in the calendar.
  * @param hour the value used to set the {@link #HOUR_OF_DAY HOUR_OF_DAY} time field in the
  *     calendar.
  * @param minute the value used to set the {@link #MINUTE MINUTE} time field in the calendar.
  * @param second the value used to set the {@link #SECOND SECOND} time field in the calendar.
  * @see Category#FORMAT
  * @internal
  * @deprecated This API is ICU internal only.
  */
 @Deprecated
 public PersianCalendar(int year, int month, int date, int hour, int minute, int second) {
   super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
   this.set(Calendar.YEAR, year);
   this.set(Calendar.MONTH, month);
   this.set(Calendar.DATE, date);
   this.set(Calendar.HOUR_OF_DAY, hour);
   this.set(Calendar.MINUTE, minute);
   this.set(Calendar.SECOND, second);
 }
Пример #11
0
  private String generateDataTableJson(TimeChartData chartData) throws DataSourceException {
    DataTable data = new DataTable();
    ArrayList<ColumnDescription> cd = new ArrayList<ColumnDescription>();
    cd.add(new ColumnDescription("date", ValueType.DATETIME, "Date"));

    for (String serie : chartData.getSeries()) {
      cd.add(new ColumnDescription(serie, ValueType.NUMBER, serie));
    }
    data.addColumns(cd);
    try {

      for (TimeChartDataValue timeSerie : chartData.getValues()) {

        TableRow row = new TableRow();
        GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
        calendar.setTimeInMillis(
            TimeZone.getDefault().getOffset(timeSerie.getTimestamp().getTime())
                + timeSerie.getTimestamp().getTime());
        row.addCell(new TableCell(new DateTimeValue(calendar)));
        for (Double value : timeSerie.getValues()) {
          if (value != null) {
            row.addCell(value);
          } else {
            row.addCell(Value.getNullValueFromValueType(ValueType.NUMBER));
          }
        }
        data.addRow(row);
      }

    } catch (TypeMismatchException e) {
      System.out.println("Invalid type!");
    }
    Query query = new Query();
    DataSourceParameters parameters = new DataSourceParameters("");
    DataSourceRequest request = new DataSourceRequest(query, parameters, ULocale.UK);
    String generateResponse = DataSourceHelper.generateResponse(data, request);

    return generateResponse;
  }
  public static void replaceFieldTypesExample() {
    // Use repalceFieldTypes API to replace zone 'zzzz' with 'vvvv'
    System.out.println("========================================================================");
    System.out.println(" replaceFieldTypeExample()");
    System.out.println();
    System.out.println(" Use replaceFieldTypes API to replace zone 'zzzz' with 'vvvv");
    System.out.println("========================================================================");
    // ---replaceFieldTypesExample
    Date date = new GregorianCalendar(1999, 9, 13, 23, 58, 59).getTime();
    TimeZone zone = TimeZone.getTimeZone("Europe/Paris");
    ULocale locale = ULocale.FRANCE;
    DateTimePatternGenerator gen = DateTimePatternGenerator.getInstance(locale);
    SimpleDateFormat format = new SimpleDateFormat("EEEE d MMMM y HH:mm:ss zzzz", locale);
    format.setTimeZone(zone);
    String pattern = format.toPattern();
    System.out.println("Pattern before replacement:");
    System.out.println(pattern);
    System.out.println("Date/Time format in fr_FR:");
    System.out.println(format.format(date));
    // Replace zone "zzzz" in the pattern with "vvvv"
    String newPattern = gen.replaceFieldTypes(pattern, "vvvv");
    // Apply the new pattern
    format.applyPattern(newPattern);
    System.out.println("Pattern after replacement:");
    System.out.println(newPattern);
    System.out.println("Date/Time format in fr_FR:");
    System.out.println(format.format(date));

    /**
     * output of the sample code:
     * **************************************************************************************************
     * Pattern before replacement: EEEE d MMMM y HH:mm:ss zzzz Date/Time format in fr_FR: jeudi 14
     * octobre 1999 05:58:59 heure avancée d’Europe centrale Pattern after replacement: EEEE d MMMM
     * y HH:mm:ss vvvv Date/Time format in fr_FR: jeudi 14 octobre 1999 05:58:59 heure de l’Europe
     * centrale
     *
     * <p>************************************************************************************************
     */
    // ---replaceFieldTypesExample
  }
Пример #13
0
 /**
  * Constructs a Persian calendar with the default time zone and locale and sets its time to the
  * specified date-time.
  *
  * @param date the date of this calendar object.
  */
 public PersianCalendar(Date date) {
   super(TimeZone.getDefault(), ULocale.getDefault());
   setTime(date);
 }
Пример #14
0
 /**
  * Constructs a Persian calendar with the default time zone and the specified locale.
  *
  * @param locale the desired locale.
  */
 public PersianCalendar(ULocale locale) {
   this(TimeZone.getDefault(), locale);
 }
Пример #15
0
 /** Constructs a Persian calendar with the default time zone and locale. */
 public PersianCalendar() {
   this(TimeZone.getDefault(), ULocale.getDefault());
 }
Пример #16
0
 /**
  * Constructs a <code>PersianCalendar</code> based on the current time in the default time zone
  * with the given locale.
  *
  * @param aLocale the given locale.
  * @internal
  * @deprecated This API is ICU internal only.
  */
 @Deprecated
 public PersianCalendar(Locale aLocale) {
   this(TimeZone.getDefault(), aLocale);
 }
 public void testIcuTimezones() throws Exception {
   validateTimezoneIds(com.ibm.icu.util.TimeZone.getAvailableIDs());
 }
Пример #18
0
  @Before
  public void columnBindingSetUp() throws Exception {

    TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
  }
Пример #19
0
 /**
  * Returns true if this zone has the same rule and offset as another zone. That is, if this zone
  * differs only in ID, if at all. Returns false if the other zone is null.
  *
  * @param other the <code>TimeZone</code> object to be compared with
  * @return true if the other zone is not null and is the same as this one, with the possible
  *     exception of the ID
  * @stable ICU 2.0
  */
 public boolean hasSameRules(TimeZone other) {
   return other != null
       && getRawOffset() == other.getRawOffset()
       && useDaylightTime() == other.useDaylightTime();
 }
Пример #20
0
 /**
  * Constructs a <code>PersianCalendar</code> with the given date set in the default time zone with
  * the default <code>FORMAT</code> locale.
  *
  * @param date The date to which the new calendar is set.
  * @see Category#FORMAT
  * @internal
  * @deprecated This API is ICU internal only.
  */
 @Deprecated
 public PersianCalendar(Date date) {
   super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
   this.setTime(date);
 }
Пример #21
0
 /**
  * Constructs a default <code>PersianCalendar</code> using the current time in the default time
  * zone with the default <code>FORMAT</code> locale.
  *
  * @see Category#FORMAT
  * @internal
  * @deprecated This API is ICU internal only.
  */
 @Deprecated
 public PersianCalendar() {
   this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
 }
Пример #22
0
/**
 * Notice:
 *
 * <p>dataSetRow -> dataSetRow row -> row
 *
 * <p>Please notice: dataSetRow can only be used in the column binding. In other cases, only row is
 * allowed to be used.
 *
 * <p>Here simple or complicated test cases can be added easily.
 */
public class ColumnBindingTest extends APITestCase {
  private TimeZone currentTimeZone = TimeZone.getDefault();
  /**
   * Column info
   *
   * <p>COUNTRY,CITY,SALE_DATE,AMOUNT,ORDERED,NULL_COLUMN
   *
   * @throws Exception
   */

  /** */
  @Before
  public void columnBindingSetUp() throws Exception {

    TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
  }

  /** @throws Exception */
  @After
  public void columnBindingTearDown() throws Exception {
    TimeZone.setDefault(this.currentTimeZone);
  }

  /*
   * @see org.eclipse.birt.data.engine.api.APITestCase#getDataSourceInfo()
   */
  protected DataSourceInfo getDataSourceInfo() {
    return new DataSourceInfo(
        ConfigText.getString("Binding.TestData.TableName"),
        ConfigText.getString("Binding.TestData.TableSQL"),
        ConfigText.getString("Binding.TestData.TestDataFileName"));
  }

  /**
   * Without any transformation
   *
   * @throws Exception
   */
  @Test
  public void testBasic() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /**
   * Test the consistency of Data Type Info.
   *
   * @throws Exception
   */
  @Test
  public void testBasic1() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"AMOUNT1", "AMOUNT2"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.AMOUNT");
    se[0].setDataType(DataType.STRING_TYPE);
    se[1] = new ScriptExpression("row.AMOUNT1");
    se[1].setDataType(DataType.UNKNOWN_TYPE);
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      assertTrue(ri.getValue("AMOUNT2") instanceof String);
    }
  }

  /** @throws Exception */
  @Test
  public void testBasic2() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("row." + name[0]);
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testBindingNameWithDoubleQuote() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"test\"Column1", "test\"Column2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("row[\"test\\\"Column1\"]");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /**
   * Filtering on data set, without total
   *
   * @throws Exception
   */
  @Test
  public void testFilterOnDataSet() throws Exception {
    IBaseExpression baseExpr = new ScriptExpression("row.AMOUNT > 100");
    IFilterDefinition filterDefn = new FilterDefinition(baseExpr);
    this.dataSet.addFilter(filterDefn);

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /**
   * Filtering on data set, without total
   *
   * @throws Exception
   */
  @Test
  public void testFilterOnDateType() throws Exception {

    FilterDefinition filterDefn =
        new FilterDefinition(
            new ConditionalExpression(
                "row.SALE_DATE",
                ConditionalExpression.OP_BETWEEN,
                "\'2004-05-01 00:00:00\'",
                "\'2004-06-05 00:00:00\'"));
    this.dataSet.addFilter(filterDefn);

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "SALE_DATE"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.SALE_DATE");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /**
   * TODO: Filtering on data set, with total
   *
   * @throws Exception
   */
  @Test
  public void testFilterOnDataSet2() throws Exception {}

  /**
   * Computed column on data set, without total
   *
   * @throws Exception
   */
  @Test
  public void testComputedOnDataSet() throws Exception {
    IComputedColumn cc = new ComputedColumn("AMOUNT2", "row.AMOUNT*2");
    this.dataSet.addComputedColumn(cc);

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1", "AMOUNT2"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    se[3] = new ScriptExpression("dataSetRow.AMOUNT2");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /**
   * TODO: Filtering on data set, with total
   *
   * @throws Exception
   */
  @Test
  public void testComputedOnDataSet2() throws Exception {}

  /**
   * Sort on table
   *
   * @throws Exception
   */
  @Test
  public void testFilterOnTable() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    ScriptExpression filterExpr = new ScriptExpression("row.AMOUNT1>100");
    FilterDefinition filterDefn = new FilterDefinition(filterExpr);
    queryDefn.addFilter(filterDefn);

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }
  }

  /**
   * Test without data set
   *
   * @throws Exception
   */
  @Test
  public void testNoDataSet() throws Exception {
    String[] name = new String[] {"testColumn1", "testColumn2"};
    int[] dataType = new int[] {DataType.INTEGER_TYPE, DataType.DOUBLE_TYPE};
    ScriptExpression[] se =
        new ScriptExpression[] {
          new ScriptExpression("i=10", dataType[0]), new ScriptExpression("i=20", dataType[1]),
        };

    basicTestNoDataSet(name, dataType, se);

    this.checkOutputFile();
  }

  /**
   * Test without data set, with Java Script Object of NativeDate
   *
   * @throws Exception
   */
  @Test
  public void testNoDataSet2() throws Exception {
    String[] name = new String[] {"testColumn1", "testColumn2"};
    int[] dataType = new int[] {DataType.ANY_TYPE, DataType.ANY_TYPE};
    ScriptExpression[] se =
        new ScriptExpression[] {
          new ScriptExpression("new Date()", dataType[0]),
          new ScriptExpression("row[\"testColumn1\"].getFullYear( )", dataType[1]),
        };

    basicTestNoDataSet(name, dataType, se);
  }

  /**
   * Test without data set, with Java Script Object of NativeDate and DataType.DATE_TYPE
   *
   * @throws Exception
   */
  @Test
  public void testNoDataSet3() throws Exception {
    String[] name = new String[] {"testColumn1"};
    int[] dataType = new int[] {DataType.DATE_TYPE};
    ScriptExpression[] se =
        new ScriptExpression[] {
          new ScriptExpression("new Date()", dataType[0]),
        };

    basicTestNoDataSet(name, dataType, se);
  }

  /**
   * @param name
   * @param dataType
   * @param se
   * @throws BirtException
   */
  private void basicTestNoDataSet(String[] name, int[] dataType, ScriptExpression[] se)
      throws BirtException {
    DataEngine dataEngine =
        new DataEngineImpl(
            DataEngineContext.newInstance(DataEngineContext.DIRECT_PRESENTATION, null, null, null));
    QueryDefinition queryDefn = new QueryDefinition();

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = dataEngine.prepare(queryDefn).execute(null).getResultIterator();
    if (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        Object value = ri.getValue(name[i]);
        str += value;

        if (i < name.length - 1) str += ", ";

        if (dataType[i] == DataType.INTEGER_TYPE)
          assertTrue(value.getClass().equals(Integer.class));
        else if (dataType[i] == DataType.DOUBLE_TYPE)
          assertTrue(value.getClass().equals(Double.class));
        else if (dataType[i] == DataType.DATE_TYPE) assertTrue(value.getClass().equals(Date.class));
      }
      testPrintln(str);
    }
  }

  /** @throws Exception */
  @Test
  public void testNoDataSetWithNestedQuery() throws Exception {
    // outer query without data set
    String[] name = new String[] {"testColumn1"};
    IQueryResults queryResult = null;

    {
      int[] dataType = new int[] {DataType.DATE_TYPE};
      ScriptExpression[] se =
          new ScriptExpression[] {
            new ScriptExpression("new Date()", dataType[0]),
          };

      DataEngine myDataEngine =
          new DataEngineImpl(
              DataEngineContext.newInstance(
                  DataEngineContext.DIRECT_PRESENTATION, null, null, null));
      QueryDefinition queryDefn = new QueryDefinition();

      for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

      IResultIterator ri = myDataEngine.prepare(queryDefn).execute(null).getResultIterator();
      queryResult = ri.getQueryResults();
    }

    // inner query with data set
    QueryDefinition queryDefn2 = this.newReportQuery();
    for (int i = 0; i < name.length; i++)
      queryDefn2.addBinding(new Binding(name[i], new ScriptExpression("row._outer." + name[i])));

    IResultIterator ri2 =
        this.dataEngine.prepare(queryDefn2).execute(queryResult, null).getResultIterator();
    if (ri2.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        Object value = ri2.getValue(name[i]);
        str += value;

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }
    ri2.close();
  }

  /** @throws Exception */
  @Test
  public void testNoDataSetWithSubQuery() throws Exception {
    // outer query without data set
    int[] dataType = new int[] {DataType.DATE_TYPE};
    String[] name = new String[] {"testColumn1"};

    IResultIterator ri2 = null;
    {
      ScriptExpression[] se =
          new ScriptExpression[] {
            new ScriptExpression("new Date()", dataType[0]),
          };

      QueryDefinition queryDefn = new QueryDefinition();
      for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

      // sub query
      String subQueryName = "TEST";
      SubqueryDefinition subQueryDefn = new SubqueryDefinition(subQueryName, queryDefn);
      for (int i = 0; i < name.length; i++)
        subQueryDefn.addBinding(
            new Binding(name[i], new ScriptExpression("row._outer." + name[i], dataType[i])));
      queryDefn.addSubquery(subQueryDefn);

      DataEngine myDataEngine =
          new DataEngineImpl(
              DataEngineContext.newInstance(
                  DataEngineContext.DIRECT_PRESENTATION, null, null, null));
      IResultIterator ri = myDataEngine.prepare(queryDefn).execute(null).getResultIterator();
      ri.next();
      ri2 = ri.getSecondaryIterator(subQueryName, null);
    }

    if (ri2.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        Object value = ri2.getValue(name[i]);
        str += value;

        if (i < name.length - 1) str += ", ";

        if (dataType[0] == DataType.DATE_TYPE) assertTrue(value.getClass().equals(Date.class));
      }
      testPrintln(str);
    }
    ri2.close();
  }

  /** @throws Exception */
  @Test
  public void testAutoBinding() throws Exception {
    QueryDefinition queryDefn = newReportQuery(true);
    this.dataSet.addComputedColumn(new ComputedColumn("COUN\"TRY", "row[\"COUNTRY\"]"));

    // column mapping
    String[] name = new String[] {"COUN\"TRY", "CITY", "AMOUNT"};

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }
    ri.close();
    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testAccessGroupColumn() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    GroupDefinition groupDefn = new GroupDefinition("group1");
    groupDefn.setKeyColumn("testColumn1");
    String name2 = "testColumn3";
    ScriptExpression se2 = new ScriptExpression("Total.sum(dataSetRow.AMOUNT)");
    se2.setGroupName("group1");
    // groupDefn.addResultSetExpression( name2, se2 );
    queryDefn.addBinding(new Binding(name2, se2));

    queryDefn.addGroup(groupDefn);

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);
        str += ", ";
      }
      str += ri.getValue(name2);

      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testSpecialExpression() throws Exception {
    IComputedColumn cc = new ComputedColumn("AMOUNT2", "row.AMOUNT*2");
    this.dataSet.addComputedColumn(cc);

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("if ( 2<1 ){ true;  }else{ false;}");

    SortDefinition[] sortDefn = new SortDefinition[] {new SortDefinition()};
    sortDefn[0].setExpression("row.testColumn1");
    sortDefn[0].setSortDirection(ISortDefinition.SORT_DESC);

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));
    for (int i = 0; i < sortDefn.length; i++) {
      queryDefn.addSort(sortDefn[i]);
    }

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testSpecialExpression2() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"AMOUNT", "testColumn1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.AMOUNT");
    se[1] =
        new ScriptExpression(
            "if ( row.AMOUNT >200 ){ Total.runningSum(row.AMOUNT);  }else{ row.AMOUNT;}");

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testSpecialExpression3() throws Exception {
    QueryDefinition queryDefn = newReportQuery();
    // column mapping
    String[] name = new String[] {"AMOUNT", "testColumn1", "testColumn2"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.AMOUNT");
    se[1] =
        new ScriptExpression(
            "var p=dataSetRow.AMOUNT+1;if( p >200 ){\"A large amount!\";  } else{ \"A small amount!\";}");
    se[2] = new ScriptExpression("row[\"testColumn1\"]+dataSetRow.AMOUNT");

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);

        if (i < name.length - 1) str += ", ";
      }
      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testInvalidSort() throws Exception {
    for (int i = 0; i < 4; i++) this.testInvalidSort(i);
  }

  /** @throws Exception */
  private void testInvalidSort(int sortIndex) throws Exception {
    QueryDefinition queryDefn = newReportQuery();
    // column mapping
    String[] name = new String[] {"rownum1", "rownum2", "rownum3"};

    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("row.__rownum");
    se[1] = new ScriptExpression("row.rownum1");
    se[2] = new ScriptExpression("row[\"rownum2\"]");

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    SortDefinition[] sort = new SortDefinition[name.length + 1];
    sort[0] = new SortDefinition();
    sort[0].setExpression("row.rownum1");
    sort[1] = new SortDefinition();
    sort[1].setExpression("row.rownum2");
    sort[2] = new SortDefinition();
    sort[2].setExpression("row.rownum3");
    sort[3] = new SortDefinition();
    sort[3].setExpression("row.__rownum");

    queryDefn.addSort(sort[sortIndex]);

    try {
      executeQuery(queryDefn);
      fail("Should not arrive here");
    } catch (DataException e) {
    }
  }

  /** @throws Exception */
  @Test
  public void testInvalidFilter() throws Exception {
    for (int i = 0; i < 4; i++) this.testInvalidFilter(i);
  }

  /** @throws Exception */
  private void testInvalidFilter(int filterIndex) throws Exception {
    QueryDefinition queryDefn = newReportQuery();
    // column mapping
    String[] name = new String[] {"rownum1", "rownum2", "rownum3"};

    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("row.__rownum");
    se[1] = new ScriptExpression("row.rownum1");
    se[2] = new ScriptExpression("row[\"rownum2\"]");

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    FilterDefinition[] filter = new FilterDefinition[name.length + 1];
    filter[0] = new FilterDefinition(new ScriptExpression("row.rownum1 == 1"));
    filter[1] = new FilterDefinition(new ScriptExpression("row.rownum2 == 1"));
    filter[2] = new FilterDefinition(new ScriptExpression("row.rownum3 == 1"));
    filter[3] = new FilterDefinition(new ScriptExpression("row.__rownum == 1"));
    queryDefn.addFilter(filter[filterIndex]);

    try {
      executeQuery(queryDefn);
      fail("Should not arrive here");
    } catch (DataException e) {
    }
  }
  /** @throws Exception */
  @Test
  public void testGroup() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1", "testColumn2", "AMOUNT1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    se[1] = new ScriptExpression("dataSetRow.CITY");
    se[2] = new ScriptExpression("dataSetRow.AMOUNT");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    GroupDefinition groupDefn = new GroupDefinition("group1");
    groupDefn.setKeyColumn("testColumn1");
    String name2 = "testColumn3";
    ScriptExpression se2 = new ScriptExpression("Total.sum(dataSetRow.AMOUNT)");
    se2.setGroupName("group1");
    // groupDefn.addResultSetExpression( name2, new ColumnBindingExpression(se2) );
    queryDefn.addBinding(new Binding(name2, se2));
    queryDefn.addGroup(groupDefn);
    String name3 = "testColumn4";
    ScriptExpression se3 = new ScriptExpression("row[\"testColumn1\"]");
    GroupDefinition groupDefn1 = new GroupDefinition("group2");
    groupDefn1.setKeyColumn("testColumn4");
    se3.setGroupName("group2");
    // groupDefn1.addResultSetExpression( name3, new ColumnBindingExpression(se3) );
    queryDefn.addBinding(new Binding(name3, se3));
    queryDefn.addGroup(groupDefn1);

    IResultIterator ri = executeQuery(queryDefn);
    while (ri.next()) {
      String str = "";
      for (int i = 0; i < name.length; i++) {
        str += ri.getValue(name[i]);
        str += ", ";
      }
      str += ri.getValue(name2);

      testPrintln(str);
    }

    checkOutputFile();
  }

  /** @throws Exception */
  @Test
  public void testInvalidBinding() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("dataSetRow.COUNTRY");
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    if (ri.next()) {
      try {
        ri.getValue(name[0]);
      } catch (BirtException e) {
        assertTrue(e.getErrorCode() == ResourceConstants.INVALID_JS_EXPR);
      }
    }
    ri.close();
  }

  /** @throws Exception */
  @Test
  public void testBlankExpression() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"testColumn1"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression(null);

    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    DataException error = null;
    try {
      executeQuery(queryDefn);
      fail("Should not arrive here");
    } catch (DataException e) {
      //			assertTrue( e.getErrorCode( ) == ResourceConstants.EXPRESSION_CANNOT_BE_NULL_OR_BLANK );
      error = e;
    }

    assertNotNull(error);
  }

  // ----------------report document test---------------------

  private FileArchiveWriter archiveWriter;
  private FileArchiveReader archiveReader;

  private String[] rowExprName;
  private String[] totalExprName;

  private String queryResultID;
  private List expectedValue;

  private DataEngine myGenDataEngine;
  private DataEngine myPreDataEngine;

  /** @throws Exception */
  @Test
  public void testBasicReportDocument() throws Exception {
    String fileName = getOutputFolder() + "testData";
    DataEngineContext deContext1 = newContext(DataEngineContext.MODE_GENERATION, fileName);
    myGenDataEngine = DataEngine.newDataEngine(deContext1);

    myGenDataEngine.defineDataSource(this.dataSource);
    myGenDataEngine.defineDataSet(this.dataSet);

    this.genBasic();
    this.closeArchiveWriter();

    DataEngineContext deContext2 = newContext(DataEngineContext.MODE_PRESENTATION, fileName);
    myPreDataEngine = DataEngine.newDataEngine(deContext2);

    this.preBasic();
    this.closeArchiveReader();
    this.checkOutputFile();
  }

  /** @throws Exception */
  private void genBasic() throws Exception {
    expectedValue = new ArrayList();

    Context context = Context.enter();
    Scriptable scope = context.initStandardObjects();
    Context.exit();

    // ------------generation----------------
    QueryDefinition qd = newReportQuery();

    // prepare
    IBaseExpression[] rowBeArray = getRowExpr();
    IBinding[] totalBeArray = getAggrBinding();
    prepareExprNameAndQuery(rowBeArray, totalBeArray, qd);

    // generation
    IQueryResults qr = myGenDataEngine.prepare(qd).execute(scope);

    // important step
    queryResultID = qr.getID();

    IResultIterator ri = qr.getResultIterator();
    while (ri.next()) {
      for (int i = 0; i < rowBeArray.length; i++)
        expectedValue.add(ri.getValue(this.rowExprName[i]));

      for (int i = 0; i < totalBeArray.length; i++)
        expectedValue.add(ri.getValue(this.totalExprName[i]));
    }

    ri.close();
    qr.close();
    myGenDataEngine.shutdown();
  }

  /** @throws Exception */
  private void genSerializable() throws Exception {
    Context context = Context.enter();
    Scriptable scope = context.initStandardObjects();
    Context.exit();

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"serializable"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("new java.lang.StringBuffer(\"ss\")");
    se[0].setDataType(DataType.JAVA_OBJECT_TYPE);
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    // generation
    IQueryResults qr = myGenDataEngine.prepare(queryDefn).execute(scope);

    // important step
    queryResultID = qr.getID();

    IResultIterator ri = qr.getResultIterator();
    assertEquals(DataType.JAVA_OBJECT_TYPE, ri.getResultMetaData().getColumnType(1));
    while (ri.next()) {
      assertTrue(ri.getValue("serializable") instanceof StringBuffer);
      assertEquals("ss", ri.getValue("serializable").toString());
    }

    ri.close();
    qr.close();
    myGenDataEngine.shutdown();
  }

  /** @throws Exception */
  private void genUnserializable() throws Exception {
    Context context = Context.enter();
    Scriptable scope = context.initStandardObjects();
    Context.exit();

    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name = new String[] {"unserializable"};
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("new java.lang.ThreadGroup(\"ss\")");
    se[0].setDataType(DataType.JAVA_OBJECT_TYPE);
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    // generation
    IQueryResults qr = myGenDataEngine.prepare(queryDefn).execute(scope);

    // important step
    queryResultID = qr.getID();

    try {

      IResultIterator ri = qr.getResultIterator();
      assertEquals(DataType.JAVA_OBJECT_TYPE, ri.getResultMetaData().getColumnType(1));
      while (ri.next()) {
        assertTrue(ri.getValue("unserializable") instanceof ThreadGroup);
      }
      ri.close();
      assertTrue(false);
    } catch (Exception e) {
      // Currently, unserializable objects can't be saved in report doc
      e.printStackTrace();
    } finally {
      qr.close();
      myGenDataEngine.shutdown();
    }
  }

  /** @throws Exception */
  private void preSerializable() throws Exception {
    IQueryResults qr = myPreDataEngine.getQueryResults(queryResultID);

    IResultIterator ri = qr.getResultIterator();
    // Currently, org.eclipse.birt.data.engine.impl.document.ResultIterator#getResultMetaData() has
    // bug:
    // It returns meta data of data set instead of meta data of query
    // assertEquals( DataType.OBJECT_TYPE, ri.getResultMetaData( ).getColumnType( 1 ));
    int rowCount = 0;
    while (ri.next()) {
      assertTrue(ri.getValue("serializable") instanceof StringBuffer);
      assertEquals("ss", ri.getValue("serializable").toString());
      rowCount++;
    }
    assertTrue(rowCount > 0);
    ri.close();
    myPreDataEngine.shutdown();
  }

  /** @throws Exception */
  private void preBasic() throws Exception {
    IQueryResults qr = myPreDataEngine.getQueryResults(queryResultID);
    assert (qr.getResultMetaData() != null);

    IResultIterator ri = qr.getResultIterator();
    assert (ri.getResultMetaData() != null);

    checkResult1(ri);

    ri.close();
    myPreDataEngine.shutdown();
  }

  /** @throws Exception */
  @Test
  public void testDummy1Document() throws Exception {
    String fileName = getOutputFolder() + "testData";
    DataEngineContext deContext1 = newContext(DataEngineContext.MODE_GENERATION, fileName);
    myGenDataEngine = DataEngine.newDataEngine(deContext1);

    myGenDataEngine.defineDataSource(this.dataSource);
    myGenDataEngine.defineDataSet(this.dataSet);

    this.genDummy1();
    this.closeArchiveWriter();

    DataEngineContext deContext2 = newContext(DataEngineContext.MODE_PRESENTATION, fileName);
    myPreDataEngine = DataEngine.newDataEngine(deContext2);

    this.preDummy1();
    this.closeArchiveReader();
  }

  /**
   * Test Java Object data type
   *
   * @throws Exception
   */
  @Test
  public void testObjectTypeBasic() throws Exception {
    QueryDefinition queryDefn = newReportQuery();

    // column mapping
    String[] name =
        new String[] {
          "ObjectType",
        };
    ScriptExpression[] se = new ScriptExpression[name.length];
    se[0] = new ScriptExpression("new java.lang.StringBuffer(\"ss\")");
    se[0].setDataType(DataType.JAVA_OBJECT_TYPE);
    for (int i = 0; i < name.length; i++) queryDefn.addBinding(new Binding(name[i], se[i]));

    IResultIterator ri = executeQuery(queryDefn);
    assertEquals(DataType.JAVA_OBJECT_TYPE, ri.getResultMetaData().getColumnType(1));
    while (ri.next()) {
      assertTrue(ri.getValue("ObjectType") instanceof StringBuffer);
      assertEquals("ss", ri.getValue("ObjectType").toString());
    }
  }

  /** @throws Exception */
  @Test
  public void testSerializableObjectTypeInReportDocument() throws Exception {
    String fileName = getOutputFolder() + "testData";
    DataEngineContext deContext1 = newContext(DataEngineContext.MODE_GENERATION, fileName);
    myGenDataEngine = DataEngine.newDataEngine(deContext1);

    myGenDataEngine.defineDataSource(this.dataSource);
    myGenDataEngine.defineDataSet(this.dataSet);

    genSerializable();
    this.closeArchiveWriter();

    DataEngineContext deContext2 = newContext(DataEngineContext.MODE_PRESENTATION, fileName);
    myPreDataEngine = DataEngine.newDataEngine(deContext2);

    this.preSerializable();
    this.closeArchiveReader();
  }

  /** @throws Exception */
  @Test
  public void testUnserializableObjectTypeInReportDocument() throws Exception {
    String fileName = getOutputFolder() + "testData";
    DataEngineContext deContext1 = newContext(DataEngineContext.MODE_GENERATION, fileName);
    myGenDataEngine = DataEngine.newDataEngine(deContext1);

    myGenDataEngine.defineDataSource(this.dataSource);
    myGenDataEngine.defineDataSet(this.dataSet);

    genUnserializable();

    // this.closeArchiveWriter( );
    //
    //		DataEngineContext deContext2 = newContext( DataEngineContext.MODE_PRESENTATION,
    //				fileName );
    //		myPreDataEngine = DataEngine.newDataEngine( deContext2 );
    //
    //		this.preSerializable( );
    // this.closeArchiveReader( );
  }

  /** @throws Exception */
  private void genDummy1() throws Exception {
    expectedValue = new ArrayList();

    Context context = Context.enter();
    Scriptable scope = context.initStandardObjects();
    Context.exit();

    // ------------generation----------------
    QueryDefinition qd = new QueryDefinition();

    // prepare
    IBaseExpression[] rowBeArray = getDummyRowExpr();
    prepareExprNameAndQuery(rowBeArray, null, qd);

    // generation
    IQueryResults qr = myGenDataEngine.prepare(qd).execute(scope);

    // important step
    queryResultID = qr.getID();

    IResultIterator ri = qr.getResultIterator();
    while (ri.next()) {
      for (int i = 0; i < rowBeArray.length; i++)
        expectedValue.add(ri.getValue(this.rowExprName[i]));
    }

    ri.close();
    qr.close();
    myGenDataEngine.shutdown();
  }

  /** @throws Exception */
  private void preDummy1() throws Exception {
    IQueryResults qr = myPreDataEngine.getQueryResults(queryResultID);
    assert (qr.getResultMetaData() != null);

    IResultIterator ri = qr.getResultIterator();
    assert (ri.getResultMetaData() != null);

    checkResult1(ri);

    ri.close();
    myPreDataEngine.shutdown();
  }

  /** @return row expression array */
  private IBaseExpression[] getDummyRowExpr() {
    // row test
    int num = 1;
    IBaseExpression[] rowBeArray = new IBaseExpression[num];
    rowBeArray[0] = new ScriptExpression("new Date()", DataType.DATE_TYPE);

    this.rowExprName = new String[rowBeArray.length];
    this.rowExprName[0] = "Date";

    return rowBeArray;
  }

  /** @throws Exception */
  @Test
  public void testDummy2Document() throws Exception {
    String fileName = getOutputFolder() + "testData";
    DataEngineContext deContext1 = newContext(DataEngineContext.MODE_GENERATION, fileName);
    myGenDataEngine = DataEngine.newDataEngine(deContext1);

    myGenDataEngine.defineDataSource(this.dataSource);
    myGenDataEngine.defineDataSet(this.dataSet);

    this.genDummy2();
    this.closeArchiveWriter();

    DataEngineContext deContext2 = newContext(DataEngineContext.MODE_PRESENTATION, fileName);
    myPreDataEngine = DataEngine.newDataEngine(deContext2);

    this.preDummy2();
    this.closeArchiveReader();
  }

  private String subName = "subName";

  /** @throws Exception */
  private void genDummy2() throws Exception {
    expectedValue = new ArrayList();

    Context context = Context.enter();
    Scriptable scope = context.initStandardObjects();
    Context.exit();

    // ------------generation----------------
    QueryDefinition qd = new QueryDefinition();

    // prepare
    IBaseExpression[] rowBeArray = getDummyRowExpr();
    prepareExprNameAndQuery(rowBeArray, null, qd);

    // prepare sub query
    SubqueryDefinition subQueryDefn = new SubqueryDefinition(subName, qd);
    qd.addSubquery(subQueryDefn);
    IBaseExpression[] rowBeArray2 = getDummyRowExpr();
    prepareExprNameAndQuery(rowBeArray2, null, subQueryDefn);

    // generation
    IQueryResults qr = myGenDataEngine.prepare(qd).execute(scope);

    // important step
    queryResultID = qr.getID();

    IResultIterator ri = qr.getResultIterator();
    while (ri.next()) {
      for (int i = 0; i < rowBeArray.length; i++)
        expectedValue.add(ri.getValue(this.rowExprName[i]));

      IResultIterator ri2 = ri.getSecondaryIterator(subName, scope);
      while (ri2.next()) {
        for (int i = 0; i < rowBeArray2.length; i++)
          expectedValue.add(ri2.getValue(this.rowExprName[i]));
      }
      ri2.close();
    }

    ri.close();
    qr.close();
    myGenDataEngine.shutdown();
  }

  /** @throws Exception */
  private void preDummy2() throws Exception {
    IQueryResults qr = myPreDataEngine.getQueryResults(queryResultID);
    assert (qr.getResultMetaData() != null);

    IResultIterator ri = qr.getResultIterator();
    assert (ri.getResultMetaData() != null);

    checkResult2(ri);

    ri.close();
    myPreDataEngine.shutdown();
  }

  /**
   * @param type
   * @param fileName
   * @return
   * @throws BirtException
   */
  private DataEngineContext newContext(int type, String fileName) throws BirtException {

    switch (type) {
      case DataEngineContext.MODE_GENERATION:
        {
          try {
            archiveWriter = new FileArchiveWriter(fileName);
            archiveWriter.initialize();
          } catch (IOException e) {
            throw new IllegalArgumentException(e.getMessage());
          }
          return DataEngineContext.newInstance(
              DataEngineContext.MODE_GENERATION, null, null, archiveWriter);
        }
      case DataEngineContext.MODE_PRESENTATION:
        {
          try {
            archiveReader = new FileArchiveReader(fileName);
            archiveReader.open();
          } catch (IOException e) {
            throw new IllegalArgumentException(e.getMessage());
          }
          return DataEngineContext.newInstance(
              DataEngineContext.MODE_PRESENTATION, null, archiveReader, null);
        }
      default:
        throw new IllegalArgumentException("" + type);
    }
  }

  /** @return row expression array */
  private IBaseExpression[] getRowExpr() {
    // row test
    int num = 4;
    IBaseExpression[] rowBeArray = new IBaseExpression[num];
    rowBeArray[0] = new ScriptExpression("dataSetRow.COUNTRY");
    rowBeArray[1] = new ScriptExpression("dataSetRow.CITY");
    rowBeArray[2] = new ScriptExpression("dataSetRow.SALE_DATE");
    rowBeArray[3] = new ScriptExpression("dataSetRow.AMOUNT");

    this.rowExprName = new String[rowBeArray.length];
    this.rowExprName[0] = "COUNTRY_1";
    this.rowExprName[1] = "CITY_1";
    this.rowExprName[2] = "SALE_NAME_1";
    this.rowExprName[3] = "AMOUNT_1";

    return rowBeArray;
  }

  /**
   * @return aggregation expression array
   * @throws DataException
   */
  private IBinding[] getAggrBinding() throws DataException {
    int num2 = 2;
    totalExprName = new String[num2];
    this.totalExprName[0] = "TOTAL_COUNT_1";
    this.totalExprName[1] = "TOTAL_AMOUNT_1";

    IBinding[] totalBeArray = new IBinding[num2];
    totalBeArray[0] = new Binding(this.totalExprName[0]);
    totalBeArray[0].setAggrFunction("COUNT");
    totalBeArray[1] = new Binding(this.totalExprName[1], new ScriptExpression("row.AMOUNT_1"));
    totalBeArray[1].setAggrFunction("SUM");

    return totalBeArray;
  }

  /**
   * Add expression on the row of group
   *
   * @param rowBeArray
   * @param totalBeArray
   * @param qd
   * @throws DataException
   */
  private void prepareExprNameAndQuery(
      IBaseExpression[] rowBeArray, IBinding[] totalBeArray, BaseQueryDefinition qd)
      throws DataException {
    int num = rowBeArray.length;

    for (int i = 0; i < num; i++) qd.addBinding(new Binding(this.rowExprName[i], rowBeArray[i]));

    if (totalBeArray != null) {
      int num2 = totalBeArray.length;
      for (int i = 0; i < num2; i++) qd.addBinding(totalBeArray[i]);
    }
  }

  /**
   * Only check the result of the expectedValue of the result set
   *
   * @param data.it
   * @param ri
   * @throws DataException
   * @throws BirtException
   */
  private void checkResult1(IResultIterator ri) throws BirtException {
    Iterator it = this.expectedValue.iterator();

    while (ri.next()) {
      String str = "";
      for (int i = 0; i < rowExprName.length; i++) {
        Object ob1 = it.next();
        Object ob2 = ri.getValue(this.rowExprName[i]);
        assertEquals(ob1, ob2);
        str += " " + ob2.toString();
      }

      if (totalExprName != null) {
        for (int i = 0; i < totalExprName.length; i++) {
          Object ob1 = it.next();
          Object ob2 = ri.getValue(this.totalExprName[i]);
          assertEquals(ob1, ob2);
          str += " " + ob2.toString();
        }
      }

      this.testPrintln("row result set: " + str);
    }
  }

  /**
   * @param ri
   * @throws BirtException
   */
  private void checkResult2(IResultIterator ri) throws BirtException {
    Iterator it = this.expectedValue.iterator();

    while (ri.next()) {
      String str = "";
      for (int i = 0; i < rowExprName.length; i++) {
        Object ob1 = it.next();
        Object ob2 = ri.getValue(this.rowExprName[i]);
        assertEquals(ob1, ob2);
        str += " " + ob2.toString();
      }

      IResultIterator ri2 = ri.getSecondaryIterator(subName, null);
      while (ri2.next()) {
        for (int i = 0; i < rowExprName.length; i++) {
          Object ob1 = it.next();
          Object ob2 = ri2.getValue(this.rowExprName[i]);
          assertEquals(ob1, ob2);
          str += " " + ob2.toString();
        }
      }

      if (totalExprName != null) {
        for (int i = 0; i < totalExprName.length; i++) {
          Object ob1 = it.next();
          Object ob2 = ri.getValue(this.totalExprName[i]);
          assertEquals(ob1, ob2);
          str += " " + ob2.toString();
        }
      }

      this.testPrintln("row result set: " + str);
    }
  }

  /** @throws DataException */
  private void closeArchiveWriter() throws DataException {
    if (archiveWriter != null)
      try {
        archiveWriter.finish();
      } catch (IOException e) {
        throw new DataException("error", e);
      }
  }

  /** @throws DataException */
  private void closeArchiveReader() throws DataException {
    if (archiveReader != null)
      try {
        archiveReader.close();
      } catch (IOException e) {
        throw new DataException("error", e);
      }
  }
}
 /**
  * Construct a <code>DangiCalendar</code> with the default time zone and locale.
  *
  * @internal
  * @deprecated This API is ICU internal only.
  */
 public DangiCalendar() {
   this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
 }
Пример #24
0
 /** @throws Exception */
 @After
 public void columnBindingTearDown() throws Exception {
   TimeZone.setDefault(this.currentTimeZone);
 }
Пример #25
0
@SourceMonitored
public class TimeDurationTests extends GenericTestCaseBase {
  private static final Calendar zero = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

  static {
    zero.clear();
    zero.setTimeInMillis(0);
  }

  public TimeDurationTests(String name) {
    super(name);
  }

  protected void setUp() throws Exception {
    super.setUp();
  }

  protected void tearDown() throws Exception {
    super.tearDown();
  }

  private static <T extends Comparable<T>> int doCompare(T comparable, T other) {
    return comparable.compareTo(other);
  }

  private static void assertDurationFields(
      String label,
      int years,
      int months,
      int days,
      int hours,
      int minutes,
      int seconds,
      int milliseconds,
      String string,
      TimeDuration duration,
      boolean isNegative,
      boolean isZero) {
    assertEquals(label + ".years()", years, duration.years());
    assertEquals(label + ".months()", months, duration.months());
    assertEquals(label + ".days()", days, duration.days());
    assertEquals(label + ".hours()", hours, duration.hours());
    assertEquals(label + ".minutes()", minutes, duration.minutes());
    assertEquals(label + ".seconds()", seconds, duration.seconds());
    assertEquals(label + ".milliseconds()", milliseconds, duration.milliseconds());
    assertEquals(label + ".isNegative()", isNegative, duration.isNegative());
    assertEquals(label + ".toString()", string, duration.toString());
    assertEquals(
        label + ".equals(from/to long)",
        duration,
        TimeDuration.fromLong(TimeDuration.toLong(duration)));
    assertEquals(
        label + ".equals(from/to number)",
        duration,
        TimeDuration.fromNumber(TimeDuration.toLong(duration)));
    assertEquals(label + ".isZero", isZero, duration.isZero());
    if (isZero) {
      assertEquals(
          label + ".compareTo(zero) == 0", 0, doCompare(TimeDuration.ZeroTimeDuration, duration));
      assertEquals(
          label + ".compareTo(zero) == 0", 0, doCompare(duration, TimeDuration.ZeroTimeDuration));
    } else {
      assertNotSame(
          label + ".compareTo(zero) != 0", 0, doCompare(TimeDuration.ZeroTimeDuration, duration));
      assertNotSame(
          label + ".compareTo(zero) != 0", 0, doCompare(duration, TimeDuration.ZeroTimeDuration));
    }
  }

  private static TimeDuration assertDurationLoop(
      String label,
      Calendar right,
      int years,
      int months,
      int days,
      int hours,
      int minutes,
      int seconds,
      int milliseconds,
      TimeDuration lastString,
      boolean isNegative) {
    StringBuilder sb = new StringBuilder();
    sb.append(years != 0 ? years : "");
    sb.append(':').append(months != 0 ? months : "");
    sb.append(':').append(days != 0 ? days : "");
    sb.append(':').append(hours != 0 ? hours : "");
    sb.append(':').append(minutes != 0 ? minutes : "");
    sb.append(':').append(seconds != 0 ? seconds : "");
    sb.append(':').append(milliseconds != 0 ? milliseconds : "");
    String durationString =
        years
            + ":"
            + months
            + ":"
            + days
            + ":"
            + hours
            + ":"
            + minutes
            + ":"
            + seconds
            + ":"
            + milliseconds;
    TimeDuration stringDuration = TimeDuration.parseDuration(sb.toString());
    right.setTimeInMillis(0);
    if (years != 0) {
      right.set(Calendar.YEAR, 1970 + Math.abs(years));
    }
    if (months != 0) {
      right.set(Calendar.MONTH, Math.abs(months));
    }
    right.set(Calendar.DAY_OF_MONTH, Math.abs(days) + 1);
    if (hours != 0) {
      right.set(Calendar.HOUR, Math.abs(hours));
    }
    if (minutes != 0) {
      right.set(Calendar.MINUTE, Math.abs(minutes));
    }
    if (seconds != 0) {
      right.set(Calendar.SECOND, Math.abs(seconds));
    }
    if (milliseconds != 0) {
      right.set(Calendar.MILLISECOND, Math.abs(milliseconds));
    }
    TimeDuration calDuration =
        isNegative ? new TimeDuration(right, zero) : new TimeDuration(zero, right);
    assertDurationFields(
        label + "(parseString[0])",
        years,
        months,
        days,
        hours,
        minutes,
        seconds,
        milliseconds,
        durationString,
        TimeDuration.parseDuration(durationString),
        isNegative,
        false);
    assertDurationFields(
        label + "(parseString)",
        years,
        months,
        days,
        hours,
        minutes,
        seconds,
        milliseconds,
        durationString,
        stringDuration,
        isNegative,
        false);
    assertDurationFields(
        label + "(cal)",
        years,
        months,
        days,
        hours,
        minutes,
        seconds,
        milliseconds,
        durationString,
        calDuration,
        isNegative,
        false);
    Calendar added = calDuration.addToCalendar((Calendar) zero.clone());
    TimeDuration addDuration = new TimeDuration(zero, added);
    assertDurationFields(
        label + "(cal[add])",
        years,
        months,
        days,
        hours,
        minutes,
        seconds,
        milliseconds,
        durationString,
        addDuration,
        isNegative,
        false);
    assertEquals(label + ".compareTo(string, cal)", 0, doCompare(stringDuration, calDuration));
    assertEquals(
        label + ".compareTo(string, string)", 0, doCompare(stringDuration, stringDuration));
    assertEquals(label + ".compareTo(cal, cal)", 0, doCompare(calDuration, calDuration));
    assertEquals(label + ".compareTo(cal, string)", 0, doCompare(calDuration, stringDuration));
    assertEquals(label + ".equals(cal, cal)", calDuration, calDuration);
    assertEquals(label + ".equals(cal, string)", calDuration, stringDuration);
    assertEquals(label + ".equals(string, cal)", stringDuration, calDuration);
    assertEquals(label + ".equals(string, string)", stringDuration, stringDuration);
    assertFalse(
        label + ".not-equals(string, this)", stringDuration.equals(TimeDurationTests.class));
    if (lastString != null) {
      assertFalse(label + ".not-equals(string, lastString)", stringDuration.equals(lastString));
    }
    return stringDuration;
  }

  public static void assertDuration(
      String label,
      int years,
      int months,
      int days,
      int hours,
      int minutes,
      int seconds,
      int milliseconds) {
    TimeDuration lastString = null;
    Calendar right = (Calendar) zero.clone();
    for (int i = 1; i < 12; i++) {
      lastString =
          assertDurationLoop(
              i + " " + label,
              right,
              i * years,
              i * months,
              i * days,
              i * hours,
              i * minutes,
              i * seconds,
              i * milliseconds,
              lastString,
              false);
    }
    lastString = null;
    for (int i = -2; i > -12; i--) {
      lastString =
          assertDurationLoop(
              i + " " + label,
              right,
              i * years,
              i * months,
              i * days,
              i * hours,
              i * minutes,
              i * seconds,
              i * milliseconds,
              lastString,
              true);
    }
  }

  public void testDuration() throws Exception {
    Calendar now = Calendar.getInstance();
    TimeDuration zeroDuration = TimeDuration.ZeroTimeDuration;
    assertFalse("zero equals null", zeroDuration.equals(null));
    Calendar newTime = (Calendar) now.clone();
    zeroDuration.addToCalendar(newTime);
    assertEquals("zero same calendar", now, newTime);
    assertDurationFields(
        "zero(same zero calendar)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        new TimeDuration(zero, zero),
        false,
        true);
    assertDurationFields(
        "zero(same now calendar)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        new TimeDuration(now, now),
        false,
        true);
    assertDurationFields(
        "zero(empty parse)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        TimeDuration.parseDuration(""),
        false,
        true);
    assertDurationFields(
        "zero(zero parse)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        TimeDuration.parseDuration("0:0:0:0:0:0:0"),
        false,
        true);
    assertDurationFields(
        "zero(from null number)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        TimeDuration.fromNumber(null),
        false,
        true);
    assertDurationFields(
        "zero(from null number)",
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        "0:0:0:0:0:0:0",
        TimeDuration.fromNumber(null),
        false,
        true);
    assertDuration("millisecond", 0, 0, 0, 0, 0, 0, 1);
    assertDuration("second", 0, 0, 0, 0, 0, 1, 0);
    assertDuration("minute", 0, 0, 0, 0, 1, 0, 0);
    assertDuration("hour", 0, 0, 0, 1, 0, 0, 0);
    assertDuration("day", 0, 0, 1, 0, 0, 0, 0);
    assertDuration("month", 0, 1, 0, 0, 0, 0, 0);
    assertDuration("year", 1, 0, 0, 0, 0, 0, 0);
    Calendar start = new com.ibm.icu.util.GregorianCalendar(1967, 1, 1, 0, 0, 0);
    start.set(Calendar.MILLISECOND, 0);
    Calendar end = (Calendar) start.clone();
    end.add(Calendar.MILLISECOND, 1);
    end.add(Calendar.SECOND, 1);
    end.add(Calendar.MINUTE, 1);
    end.add(Calendar.HOUR_OF_DAY, 1);
    end.add(Calendar.DAY_OF_MONTH, 1);
    end.add(Calendar.MONTH, 1);
    end.add(Calendar.YEAR, 1);
    assertDurationFields(
        "pre-epoch elapsed time",
        1,
        1,
        1,
        1,
        1,
        1,
        1,
        "1:1:1:1:1:1:1",
        new TimeDuration(start, end),
        false,
        false);
  }
}
Пример #26
0
  /**
   * {@link IntlAbstractOperations#JDK_TIMEZONE_NAMES}
   *
   * @param tzdataDir the tzdata directory
   * @throws IOException if an I/O error occurs
   */
  static void jdkTimezoneNames(Path tzdataDir) throws IOException {
    Pattern pZone = Pattern.compile("Zone\\s+([a-zA-Z0-9_+\\-/]+)\\s+.*");
    Pattern pLink =
        Pattern.compile("Link\\s+([a-zA-Z0-9_+\\-/]+)\\s+([a-zA-Z0-9_+\\-/]+)(?:\\s+#.*)?");
    Pattern pFileName = Pattern.compile("[a-z0-9]+");

    HashSet<String> ignoreFiles = new HashSet<>(Arrays.asList("backzone"));
    TreeSet<String> names = new TreeSet<>();
    TreeMap<String, String> links = new TreeMap<>();

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(tzdataDir)) {
      for (Path path : stream) {
        String filename = Objects.requireNonNull(path.getFileName()).toString();
        if (pFileName.matcher(filename).matches() && !ignoreFiles.contains(filename)) {
          try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            for (String line; (line = reader.readLine()) != null; ) {
              if (line.startsWith("Zone")) {
                Matcher m = pZone.matcher(line);
                if (!m.matches()) {
                  System.out.println(line);
                }
                String name = m.group(1);
                boolean changed = names.add(name);
                assert changed : line;
              } else if (line.startsWith("Link")) {
                Matcher m = pLink.matcher(line);
                if (!m.matches()) {
                  System.out.println(line);
                }
                String target = m.group(1);
                String source = m.group(2);
                boolean changed = links.put(source, target) == null;
                assert changed : String.format("%s: %s", filename, line);
              }
            }
          }
        }
      }
    }

    TreeSet<String> allnames = new TreeSet<>();
    allnames.addAll(names);
    for (Map.Entry<String, String> link : links.entrySet()) {
      assert allnames.contains(link.getValue());
      boolean changed = allnames.add(link.getKey());
      assert changed : link;
    }

    TreeSet<String> ids =
        new TreeSet<>(TimeZone.getAvailableIDs(SystemTimeZoneType.ANY, null, null));
    for (String id : new HashSet<>(ids)) {
      if (id.startsWith("SystemV/")) {
        ids.remove(id);
      }
    }

    System.out.println(allnames);
    System.out.println(ids.size());
    System.out.println(allnames.size());

    TreeSet<String> jdkTimeZones = new TreeSet<>(ids);
    jdkTimeZones.removeAll(allnames);
    for (String name : jdkTimeZones) {
      System.out.printf("\"%s\",", name);
    }
  }
/** Utilities class to convert report parameter value between object and string. */
public class ReportParameterConverter {

  private String format = null;
  private ULocale uLocale = null;
  private TimeZone timeZone = TimeZone.getDefault();

  private StringFormatter sf = null;
  private DateFormatter df = null;
  private NumberFormatter nf = null;

  /**
   * @param format format to format report parameter, or recover parameter value as object given a
   *     string as report parameter value
   * @param locale the locale to format/parse the parameter value
   */
  public ReportParameterConverter(String format, Locale locale) {
    this(format, ULocale.forLocale(locale));
  }

  /**
   * Constructor.
   *
   * @param format
   * @param uLocale
   */
  public ReportParameterConverter(String format, ULocale uLocale) {
    this(format, uLocale, null);
  }

  /**
   * Constructor.
   *
   * @param format
   * @param uLocale
   * @param timeZone
   */
  public ReportParameterConverter(String format, ULocale uLocale, TimeZone timeZone) {
    this.format = format;
    this.uLocale = uLocale;
    if (timeZone != null) {
      this.timeZone = timeZone;
    }
  }

  /**
   * Get string formatter.
   *
   * @return StringFormatter object
   */
  private StringFormatter getStringFormatter() {
    if (sf == null && uLocale != null) {
      sf = new StringFormatter(uLocale);
      if (format != null) {
        sf.applyPattern(format);
      }
    }
    return sf;
  }

  /**
   * Get number formatter.
   *
   * @return NumberFormatter object
   */
  private NumberFormatter getNumberFormatter() {
    if (nf == null && uLocale != null) {
      nf = new NumberFormatter(uLocale);
      if (format != null) {
        nf.applyPattern(format);
      }
    }
    return nf;
  }

  /**
   * Get date formatter.
   *
   * @return DateFormatter object
   */
  private DateFormatter getDateFormatter() {
    if (df == null && uLocale != null) {
      df = new DateFormatter(uLocale, timeZone);
      if (format != null) {
        df.applyPattern(format);
      }
    }
    return df;
  }

  /**
   * Convert report parameter value object into string.
   *
   * @param reportParameterObj report parameter value object.
   * @return parameter value in string.
   */
  public String format(Object reportParameterObj) {
    String reportParameterValue = null;

    if (reportParameterObj != null && uLocale != null) {
      if (reportParameterObj instanceof String) {
        StringFormatter sf = getStringFormatter();
        if (sf != null) {
          reportParameterValue = sf.format((String) reportParameterObj);
        } else {
          reportParameterValue = reportParameterObj.toString();
        }
      } else if (reportParameterObj instanceof Date) {
        DateFormatter df = getDateFormatter();
        if (df != null) {
          reportParameterValue = df.format((Date) reportParameterObj);
        } else {
          reportParameterValue = reportParameterObj.toString();
        }
      } else if (reportParameterObj instanceof Double) {
        NumberFormatter nf = getNumberFormatter();
        if (nf != null) {
          reportParameterValue = nf.format(((Double) reportParameterObj).doubleValue());
        } else {
          reportParameterValue = reportParameterObj.toString();
        }
      } else if (reportParameterObj instanceof BigDecimal) {
        NumberFormatter nf = getNumberFormatter();
        if (nf != null) {
          reportParameterValue = nf.format((BigDecimal) reportParameterObj);
        } else {
          reportParameterValue = reportParameterObj.toString();
        }
      } else if (reportParameterObj instanceof Boolean) {
        reportParameterValue = ((Boolean) reportParameterObj).toString();
      } else if (reportParameterObj instanceof Number) {
        NumberFormatter nf = getNumberFormatter();
        if (nf != null) {
          reportParameterValue = nf.format(((Number) reportParameterObj));
        } else {
          reportParameterValue = reportParameterObj.toString();
        }
      } else {
        reportParameterValue = (reportParameterObj.toString());
      }
    }

    return reportParameterValue;
  }

  /**
   * Convert report parameter from string into object. Need to be pointed out is it return a Double
   * object when the value type is Float.
   *
   * @param reportParameterValue report parameter value in string.
   * @param parameterValueType report parameter type.
   * @return parameter value object.
   */
  public Object parse(String reportParameterValue, int parameterValueType) {
    Object parameterValueObj = null;

    if (reportParameterValue != null && uLocale != null) {
      switch (parameterValueType) {
        case IScalarParameterDefn.TYPE_STRING:
          {
            StringFormatter sf = getStringFormatter();
            if (sf == null) {
              parameterValueObj = null;
              break;
            }

            try {
              parameterValueObj = sf.parser(reportParameterValue);
            } catch (ParseException e) {
              parameterValueObj = reportParameterValue;
            }
            break;
          }

        case IScalarParameterDefn.TYPE_DATE_TIME:
          {
            parameterValueObj = parseDateTime(reportParameterValue);
            break;
          }

        case IScalarParameterDefn.TYPE_FLOAT:
          {
            NumberFormatter nf = getNumberFormatter();
            if (nf == null) {
              parameterValueObj = null;
              break;
            }

            try {
              Number num = nf.parse(reportParameterValue);

              if (num != null) {
                parameterValueObj = new Double(num.toString());
              }
            } catch (ParseException e) {
              nf.applyPattern("General Number");

              try {
                Number num = nf.parse(reportParameterValue);

                if (num != null) {
                  parameterValueObj = new Double(num.toString());
                }
              } catch (ParseException ex) {
                parameterValueObj = null;
              }
            }

            break;
          }

        case IScalarParameterDefn.TYPE_DECIMAL:
          {
            NumberFormatter nf = getNumberFormatter();
            if (nf == null) {
              parameterValueObj = null;
              break;
            }

            try {
              Number num = nf.parse(reportParameterValue);

              if (num != null) {
                parameterValueObj = new BigDecimal(num.toString());
              }
            } catch (ParseException e) {
              nf.applyPattern("General Number");

              try {
                Number num = nf.parse(reportParameterValue);

                if (num != null) {
                  parameterValueObj = new BigDecimal(num.toString());
                }
              } catch (ParseException ex) {
                parameterValueObj = null;
              }
            }

            break;
          }

        case IScalarParameterDefn.TYPE_BOOLEAN:
          {
            parameterValueObj = Boolean.valueOf(reportParameterValue);
            break;
          }

        case IScalarParameterDefn.TYPE_DATE:
          {
            try {
              parameterValueObj = java.sql.Date.valueOf(reportParameterValue);
            } catch (IllegalArgumentException ie) {
              parameterValueObj = parseDateTime(reportParameterValue);
              if (parameterValueObj != null) {
                parameterValueObj = new java.sql.Date(((Date) parameterValueObj).getTime());
              }
            }
            break;
          }

        case IScalarParameterDefn.TYPE_TIME:
          {
            try {
              parameterValueObj = java.sql.Time.valueOf(reportParameterValue);
            } catch (IllegalArgumentException ie) {
              parameterValueObj = parseDateTime(reportParameterValue);
              if (parameterValueObj != null) {
                parameterValueObj = new java.sql.Time(((Date) parameterValueObj).getTime());
              }
            }
            break;
          }

          // can use class DataTypeUtil to convert
        case IScalarParameterDefn.TYPE_INTEGER:
          {
            NumberFormatter nf = getNumberFormatter();
            if (nf == null) {
              parameterValueObj = null;
              break;
            }

            try {
              Number num = nf.parse(reportParameterValue);

              if (num != null) {
                parameterValueObj = Integer.valueOf(num.intValue());
              }
            } catch (ParseException ex) {
              nf.applyPattern("General Number");

              try {
                Number num = nf.parse(reportParameterValue);

                if (num != null) {
                  parameterValueObj = Integer.valueOf(num.intValue());
                }
              } catch (ParseException pex) {
                try {
                  parameterValueObj = Integer.valueOf(reportParameterValue);
                } catch (NumberFormatException nfe) {
                  parameterValueObj = null;
                }
              }
            }
          }
      }
    }

    return parameterValueObj;
  }

  /**
   * Parse the input string to an object.
   *
   * @param reportParameterValue input string to parse
   * @return an object
   */
  protected Object parseDateTime(String reportParameterValue) {
    DateFormatter df = getDateFormatter();
    if (df == null) {
      return null;
    }

    try {
      return df.parse(reportParameterValue);
    } catch (ParseException e) {
      df = new DateFormatter("Short Date", uLocale);
      try {
        return df.parse(reportParameterValue);
      } catch (ParseException ex) {
        df = new DateFormatter("Medium Time", uLocale);
        try {
          return df.parse(reportParameterValue);
        } catch (ParseException exx) {
          return null;
        }
      }
    }
  }
}
 /**
  * Construct a <code>DangiCalendar</code> with the give date set in the default time zone with the
  * default locale.
  *
  * @param date The date to which the new calendar is set.
  * @internal
  * @deprecated This API is ICU internal only.
  */
 public DangiCalendar(Date date) {
   this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
   setTime(date);
 }
  /**
   * {@icu} Checks if the time zone has equivalent transitions in the time range. This method
   * returns true when all of transition times, from/to standard offsets and DST savings used by
   * this time zone match the other in the time range.
   *
   * @param tz The instance of <code>TimeZone</code>
   * @param start The start time of the evaluated time range (inclusive)
   * @param end The end time of the evaluated time range (inclusive)
   * @param ignoreDstAmount When true, any transitions with only daylight saving amount changes will
   *     be ignored, except either of them is zero. For example, a transition from rawoffset
   *     3:00/dstsavings 1:00 to rawoffset 2:00/dstsavings 2:00 is excluded from the comparison, but
   *     a transtion from rawoffset 2:00/dstsavings 1:00 to rawoffset 3:00/dstsavings 0:00 is
   *     included.
   * @return true if the other time zone has the equivalent transitions in the time range. When tz
   *     is not a <code>BasicTimeZone</code>, this method returns false.
   * @stable ICU 3.8
   */
  public boolean hasEquivalentTransitions(
      TimeZone tz, long start, long end, boolean ignoreDstAmount) {
    if (hasSameRules(tz)) {
      return true;
    }
    if (!(tz instanceof BasicTimeZone)) {
      return false;
    }

    // Check the offsets at the start time
    int[] offsets1 = new int[2];
    int[] offsets2 = new int[2];

    getOffset(start, false, offsets1);
    tz.getOffset(start, false, offsets2);

    if (ignoreDstAmount) {
      if ((offsets1[0] + offsets1[1] != offsets2[0] + offsets2[1])
          || (offsets1[1] != 0 && offsets2[1] == 0)
          || (offsets1[1] == 0 && offsets2[1] != 0)) {
        return false;
      }
    } else {
      if (offsets1[0] != offsets2[0] || offsets1[1] != offsets2[1]) {
        return false;
      }
    }

    // Check transitions in the range
    long time = start;
    while (true) {
      TimeZoneTransition tr1 = getNextTransition(time, false);
      TimeZoneTransition tr2 = ((BasicTimeZone) tz).getNextTransition(time, false);

      if (ignoreDstAmount) {
        // Skip a transition which only differ the amount of DST savings
        while (true) {
          if (tr1 != null
              && tr1.getTime() <= end
              && (tr1.getFrom().getRawOffset() + tr1.getFrom().getDSTSavings()
                  == tr1.getTo().getRawOffset() + tr1.getTo().getDSTSavings())
              && (tr1.getFrom().getDSTSavings() != 0 && tr1.getTo().getDSTSavings() != 0)) {
            tr1 = getNextTransition(tr1.getTime(), false);
          } else {
            break;
          }
        }
        while (true) {
          if (tr2 != null
              && tr2.getTime() <= end
              && (tr2.getFrom().getRawOffset() + tr2.getFrom().getDSTSavings()
                  == tr2.getTo().getRawOffset() + tr2.getTo().getDSTSavings())
              && (tr2.getFrom().getDSTSavings() != 0 && tr2.getTo().getDSTSavings() != 0)) {
            tr2 = ((BasicTimeZone) tz).getNextTransition(tr2.getTime(), false);
          } else {
            break;
          }
        }
      }

      boolean inRange1 = false;
      boolean inRange2 = false;
      if (tr1 != null) {
        if (tr1.getTime() <= end) {
          inRange1 = true;
        }
      }
      if (tr2 != null) {
        if (tr2.getTime() <= end) {
          inRange2 = true;
        }
      }
      if (!inRange1 && !inRange2) {
        // No more transition in the range
        break;
      }
      if (!inRange1 || !inRange2) {
        return false;
      }
      if (tr1.getTime() != tr2.getTime()) {
        return false;
      }
      if (ignoreDstAmount) {
        if (tr1.getTo().getRawOffset() + tr1.getTo().getDSTSavings()
                != tr2.getTo().getRawOffset() + tr2.getTo().getDSTSavings()
            || tr1.getTo().getDSTSavings() != 0 && tr2.getTo().getDSTSavings() == 0
            || tr1.getTo().getDSTSavings() == 0 && tr2.getTo().getDSTSavings() != 0) {
          return false;
        }
      } else {
        if (tr1.getTo().getRawOffset() != tr2.getTo().getRawOffset()
            || tr1.getTo().getDSTSavings() != tr2.getTo().getDSTSavings()) {
          return false;
        }
      }
      time = tr1.getTime();
    }
    return true;
  }