KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jfree > chart > axis > junit > SegmentedTimelineTests


1     /* ===========================================================
2  * JFreeChart : a free chart library for the Java(tm) platform
3  * ===========================================================
4  *
5  * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
6  *
7  * Project Info: http://www.jfree.org/jfreechart/index.html
8  *
9  * This library is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17  * License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this library; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
24  * in the United States and other countries.]
25  *
26  * ----------------------------
27  * SegmentedTimelineTests.java
28  * ----------------------------
29  * (C) Copyright 2003-2005, by Bill Kelemen and Contributors.
30  *
31  * Original Author: Bill Kelemen;
32  * Contributor(s): ;
33  *
34  * $Id: SegmentedTimelineTests.java,v 1.7 2005/03/29 12:54:59 mungady Exp $
35  *
36  * Changes
37  * -------
38  * 24-May-2003 : Version 1 (BK);
39  * 07-Jan-2005 : Added test for hashCode() method (DG);
40  *
41  */

42
43 package org.jfree.chart.axis.junit;
44
45 import java.io.ByteArrayInputStream JavaDoc;
46 import java.io.ByteArrayOutputStream JavaDoc;
47 import java.io.ObjectInput JavaDoc;
48 import java.io.ObjectInputStream JavaDoc;
49 import java.io.ObjectOutput JavaDoc;
50 import java.io.ObjectOutputStream JavaDoc;
51 import java.text.Format JavaDoc;
52 import java.text.NumberFormat JavaDoc;
53 import java.text.ParseException JavaDoc;
54 import java.text.SimpleDateFormat JavaDoc;
55 import java.util.ArrayList JavaDoc;
56 import java.util.Calendar JavaDoc;
57 import java.util.GregorianCalendar JavaDoc;
58 import java.util.Iterator JavaDoc;
59
60 import junit.framework.Test;
61 import junit.framework.TestCase;
62 import junit.framework.TestSuite;
63
64 import org.jfree.chart.axis.SegmentedTimeline;
65
66 /**
67  * JUnit Tests for the {@link SegmentedTimeline} class.
68  *
69  * @author Bill Kelemen
70  */

71 public class SegmentedTimelineTests extends TestCase {
72
73     /** These constants control test cycles in the validateXXXX methods. */
74     private static final int TEST_CYCLE_START = 0;
75
76     /** These constants control test cycles in the validateXXXX methods. */
77     private static final int TEST_CYCLE_END = 1000;
78
79     /** These constants control test cycles in the validateXXXX methods. */
80     private static final int TEST_CYCLE_INC = 55;
81
82     /** Number of ms in five years */
83     private static final long FIVE_YEARS
84         = 5 * 365 * SegmentedTimeline.DAY_SEGMENT_SIZE;
85
86     /** Number format object for ms tests. */
87     private static final NumberFormat JavaDoc NUMBER_FORMAT
88         = NumberFormat.getNumberInstance();
89
90     /** Date format object for Monday through Friday tests. */
91     private static final SimpleDateFormat JavaDoc DATE_FORMAT;
92
93     /** Date format object 9:00 AM to 4:00 PM tests. */
94     private static final SimpleDateFormat JavaDoc DATE_TIME_FORMAT;
95
96     /** Some ms exceptions for ms testing. */
97     private static final String JavaDoc[] MS_EXCEPTIONS =
98         {"0", "2", "4", "10", "15", "16", "17", "18", "19", "20", "21", "22",
99          "23", "24", "47", "58", "100", "101"};
100
101      /** Some ms4 exceptions for ms testing. */
102      private static final String JavaDoc[] MS2_BASE_TIMELINE_EXCEPTIONS =
103          {"0", "8", "16", "24", "32", "40", "48", "56", "64", "72", "80", "88",
104           "96", "104", "112", "120", "128", "136"};
105
106     /** US non-trading dates in 2000 through 2002 to test exceptions. */
107     private static final String JavaDoc[] US_HOLIDAYS =
108         {"2000-01-17", "2000-02-21", "2000-04-21", "2000-05-29", "2000-07-04",
109          "2000-09-04", "2000-11-23", "2000-12-25", "2001-01-01", "2001-01-15",
110          "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03",
111          "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22",
112          "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29",
113          "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"};
114
115      /** Some test exceptions for the fifteen min timeline. */
116      private static final String JavaDoc[] FIFTEEN_MIN_EXCEPTIONS =
117          {"2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00",
118           "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00",
119           "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00",
120           "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00",
121           "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00",
122           "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00",
123           "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00",
124           "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00",
125           "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00",
126           "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00",
127           "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00",
128           "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00",
129           "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00",
130           "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"};
131
132     /** Our 1-ms test timeline using 5 included and 2 excluded segments. */
133     private SegmentedTimeline msTimeline;
134
135     /**
136      * Our 1-ms test timeline (with baseTimeline) using 2 included and 2
137      * excluded segments.
138      */

139     private SegmentedTimeline ms2Timeline;
140
141     /**
142      * Our 4-ms test base timeline for ms2Timeline using 1 included and 1
143      * excluded segments
144      */

145     private SegmentedTimeline ms2BaseTimeline;
146
147     /** Our test Monday through Friday test timeline. */
148     private SegmentedTimeline mondayFridayTimeline;
149
150     /** Our 9:00 AM to 4:00 PM fifteen minute timeline. */
151     private SegmentedTimeline fifteenMinTimeline;
152
153     /** ms from 1970-01-01 to first monday after 2001-01-01. */
154     private Calendar JavaDoc monday;
155
156     /** ms from 1970-01-01 to 9 am first monday after 2001-01-01. */
157     private Calendar JavaDoc monday9am;
158
159     /** Static initialization block. */
160     static {
161         DATE_FORMAT = new SimpleDateFormat JavaDoc("yyyy-MM-dd");
162         DATE_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE);
163
164         DATE_TIME_FORMAT = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
165         DATE_TIME_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE);
166     }
167
168     /**
169      * Returns the tests as a test suite.
170      *
171      * @return The test suite.
172      */

173     public static Test suite() {
174         return new TestSuite(SegmentedTimelineTests.class);
175     }
176
177     /**
178      * Constructs a new set of tests.
179      *
180      * @param name the name of the tests.
181      */

182     public SegmentedTimelineTests(String JavaDoc name) {
183         super(name);
184     }
185
186     /**
187      * Sets up the fixture, for example, open a network connection.
188      * This method is called before a test is executed.
189      *
190      * @throws Exception if there is a problem.
191      */

192     protected void setUp() throws Exception JavaDoc {
193         // setup our test timelines
194
//
195
// Legend for comments below:
196
// <spaces> = Segments included in the final timeline
197
// EE = Excluded segments via timeline rules
198
// xx = Exception segments inherited from base timeline exclusions
199

200         // 1-ms test timeline using 5 included and 2 excluded segments.
201
//
202
// timeline start time = 0
203
// |
204
// v
205
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ..
206
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
207
// | | | | | |EE|EE| | | | | |EE|EE| | | | | | |EE|EE| <-- msTimeline
208
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
209
// \_________ ________/ \_/
210
// \/ |
211
// segment group segment size = 1 ms
212
//
213
this.msTimeline = new SegmentedTimeline(1, 5, 2);
214         this.msTimeline.setStartTime(0);
215
216         // 4-ms test base timeline for ms2Timeline using 1 included and 1
217
// excluded segments
218
//
219
// timeline start time = 0
220
// |
221
// v
222
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...
223
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
224
// | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline
225
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
226
// \__________ _________/ \____ _____/
227
// \/ \/
228
// segment group segment size = 4 ms
229
//
230
this.ms2BaseTimeline = new SegmentedTimeline(4, 1, 1);
231         this.ms2BaseTimeline.setStartTime(0);
232
233         // 1-ms test timeline (with a baseTimeline) using 2 included and 2
234
// excluded segments centered inside each base segment
235
//
236
// The ms2Timeline without a base would look like this:
237
//
238
// timeline start time = 1
239
// |
240
// v
241
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...
242
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
243
// |EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE| <-- ms2Timeline
244
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
245
// \____ _____/ \_/
246
// \/ |
247
// segment group segment size = 1 ms
248
//
249
// With the base timeline some originally included segments are now
250
// removed (see "xx" below):
251
//
252
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...
253
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
254
// |EE| | |EE|EE|xx|xx|EE|EE| | |EE|EE|xx|xx|EE|EE| | |EE| <-- ms2Timeline
255
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
256
// | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline
257
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
258
//
259
this.ms2Timeline = new SegmentedTimeline(1, 2, 2);
260         this.ms2Timeline.setStartTime(1);
261         this.ms2Timeline.setBaseTimeline(this.ms2BaseTimeline);
262
263         // test monday though friday timeline
264
this.mondayFridayTimeline
265             = SegmentedTimeline.newMondayThroughFridayTimeline();
266
267         // test 9am-4pm Monday through Friday timeline
268
this.fifteenMinTimeline
269             = SegmentedTimeline.newFifteenMinuteTimeline();
270
271         // find first Monday after 2001-01-01
272
Calendar JavaDoc cal = new GregorianCalendar JavaDoc(
273             SegmentedTimeline.NO_DST_TIME_ZONE
274         );
275         cal.set(2001, 0, 1, 0, 0, 0);
276         cal.set(Calendar.MILLISECOND, 0);
277         while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
278             cal.add(Calendar.DATE, 1);
279         }
280         this.monday = (Calendar JavaDoc) cal.clone();
281
282         // calculate 9am on the first Monday after 2001-01-01
283
cal.add(Calendar.HOUR, 9);
284         this.monday9am = (Calendar JavaDoc) cal.clone();
285     }
286
287     /**
288      * Tears down the fixture, for example, close a network connection.
289      * This method is called after a test is executed.
290      *
291      * @throws Exception if there is a problem.
292      */

293     protected void tearDown() throws Exception JavaDoc {
294         // does nothing
295
}
296
297     //////////////////////////////////////////////////////////////////////////
298
// test construction process
299
//////////////////////////////////////////////////////////////////////////
300

301     /**
302      * Tests that the new method that created the msTimeline segmented
303      * timeline did so correctly.
304      */

305     public void testMsSegmentedTimeline() {
306         // verify attributes set during object construction
307
assertEquals(1, this.msTimeline.getSegmentSize());
308         assertEquals(0, this.msTimeline.getStartTime());
309         assertEquals(5, this.msTimeline.getSegmentsIncluded());
310         assertEquals(2, this.msTimeline.getSegmentsExcluded());
311     }
312
313     /**
314      * Tests that the new method that created the ms2Timeline segmented
315      * timeline did so correctly.
316      */

317     public void testMs2SegmentedTimeline() {
318         // verify attributes set during object construction
319
assertEquals(1, this.ms2Timeline.getSegmentSize());
320         assertEquals(1, this.ms2Timeline.getStartTime());
321         assertEquals(2, this.ms2Timeline.getSegmentsIncluded());
322         assertEquals(2, this.ms2Timeline.getSegmentsExcluded());
323         assertEquals(this.ms2BaseTimeline, this.ms2Timeline.getBaseTimeline());
324     }
325
326     /**
327      * Tests that the factory method that creates Monday through Friday
328      * segmented timeline does so correctly.
329      */

330     public void testMondayThroughFridaySegmentedTimeline() {
331         // verify attributes set during object construction
332
assertEquals(
333             SegmentedTimeline.DAY_SEGMENT_SIZE,
334             this.mondayFridayTimeline.getSegmentSize()
335         );
336         assertEquals(
337             SegmentedTimeline.FIRST_MONDAY_AFTER_1900,
338             this.mondayFridayTimeline.getStartTime()
339         );
340         assertEquals(5, this.mondayFridayTimeline.getSegmentsIncluded());
341         assertEquals(2, this.mondayFridayTimeline.getSegmentsExcluded());
342     }
343
344     /**
345      * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM
346      * segmented axis does so correctly.
347      */

348     public void testFifteenMinSegmentedTimeline() {
349         assertEquals(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE,
350                 this.fifteenMinTimeline.getSegmentSize());
351         assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900 + 36
352                      * this.fifteenMinTimeline.getSegmentSize(),
353                      this.fifteenMinTimeline.getStartTime());
354         assertEquals(28, this.fifteenMinTimeline.getSegmentsIncluded());
355         assertEquals(68, this.fifteenMinTimeline.getSegmentsExcluded());
356     }
357
358     //////////////////////////////////////////////////////////////////////////
359
// test one-segment and adjacent segments
360
//////////////////////////////////////////////////////////////////////////
361

362     /**
363      * Tests one segment of the ms timeline. Internal indices
364      * inside one segment as well as adjacent segments are verified.
365      */

366     public void testMsSegment() {
367         verifyOneSegment(this.msTimeline);
368     }
369
370     /**
371      * Tests one segment of the ms timeline. Internal indices
372      * inside one segment as well as adjacent segments are verified.
373      */

374     public void testMs2Segment() {
375         verifyOneSegment(this.ms2Timeline);
376     }
377
378     /**
379      * Tests one segment of the Monday through Friday timeline. Internal indices
380      * inside one segment as well as adjacent segments are verified.
381      */

382     public void testMondayThroughFridaySegment() {
383         verifyOneSegment(this.mondayFridayTimeline);
384     }
385
386     /**
387      * Tests one segment of the Fifteen timeline. Internal indices
388      * inside one segment as well as adjacent segments are verified.
389      */

390     public void testFifteenMinSegment() {
391         verifyOneSegment(this.fifteenMinTimeline);
392     }
393
394     /**
395      * Tests one segment of the Monday through Friday timeline. Internal indices
396      * inside one segment as well as adjacent segments are verified.
397      * @param timeline the timeline to use for verifications.
398      */

399     public void verifyOneSegment(SegmentedTimeline timeline) {
400         
401         for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END;
402              testCycle += TEST_CYCLE_INC) {
403
404             // get two consecutive segments for various tests
405
SegmentedTimeline.Segment segment1 = timeline.getSegment(
406                 this.monday.getTime().getTime() + testCycle
407             );
408             SegmentedTimeline.Segment segment2 =
409                 timeline.getSegment(segment1.getSegmentEnd() + 1);
410
411             // verify segments are consecutive and correct
412
assertEquals(
413                 segment1.getSegmentNumber() + 1, segment2.getSegmentNumber()
414             );
415             assertEquals(
416                 segment1.getSegmentEnd() + 1, segment2.getSegmentStart()
417             );
418             assertEquals(
419                 segment1.getSegmentStart() + timeline.getSegmentSize() - 1,
420                 segment1.getSegmentEnd()
421             );
422             assertEquals(
423                 segment1.getSegmentStart() + timeline.getSegmentSize(),
424                 segment2.getSegmentStart()
425             );
426             assertEquals(
427                 segment1.getSegmentEnd() + timeline.getSegmentSize(),
428                 segment2.getSegmentEnd()
429             );
430
431             // verify various indices inside a segment are the same segment
432
long delta;
433             if (timeline.getSegmentSize() > 1000000) {
434                 delta = timeline.getSegmentSize() / 10000;
435             }
436             else if (timeline.getSegmentSize() > 100000) {
437                 delta = timeline.getSegmentSize() / 1000;
438             }
439             else if (timeline.getSegmentSize() > 10000) {
440                 delta = timeline.getSegmentSize() / 100;
441             }
442             else if (timeline.getSegmentSize() > 1000) {
443                 delta = timeline.getSegmentSize() / 10;
444             }
445             else if (timeline.getSegmentSize() > 100) {
446                 delta = timeline.getSegmentSize() / 5;
447             }
448             else {
449                 delta = 1;
450             }
451
452             long start = segment1.getSegmentStart() + delta;
453             long end = segment1.getSegmentStart()
454                        + timeline.getSegmentSize() - 1;
455             SegmentedTimeline.Segment lastSeg = timeline.getSegment(
456                 segment1.getSegmentStart()
457             );
458             SegmentedTimeline.Segment seg;
459             for (long i = start; i < end; i += delta) {
460                 seg = timeline.getSegment(i);
461                 assertEquals(
462                     lastSeg.getSegmentNumber(), seg.getSegmentNumber()
463                 );
464                 assertEquals(lastSeg.getSegmentStart(), seg.getSegmentStart());
465                 assertEquals(lastSeg.getSegmentEnd(), seg.getSegmentEnd());
466                 assertTrue(lastSeg.getMillisecond() < seg.getMillisecond());
467                 lastSeg = seg;
468             }
469
470             // try next segment
471
seg = timeline.getSegment(end + 1);
472             assertEquals(segment2.getSegmentNumber(), seg.getSegmentNumber());
473             assertEquals(segment2.getSegmentStart(), seg.getSegmentStart());
474             assertEquals(segment2.getSegmentEnd(), seg.getSegmentEnd());
475         }
476     }
477
478     //////////////////////////////////////////////////////////////////////////
479
// test inc methods
480
//////////////////////////////////////////////////////////////////////////
481

482     /**
483      * Tests the inc methods on the msTimeline.
484      */

485     public void testMsInc() {
486         verifyInc(this.msTimeline);
487     }
488
489     /**
490      * Tests the inc methods on the msTimeline.
491      */

492     public void testMs2Inc() {
493         verifyInc(this.ms2Timeline);
494     }
495
496     /**
497      * Tests the inc methods on the Monday through Friday timeline.
498      */

499     public void testMondayThroughFridayInc() {
500         verifyInc(this.mondayFridayTimeline);
501     }
502
503     /**
504      * Tests the inc methods on the Fifteen minute timeline.
505      */

506     public void testFifteenMinInc() {
507         verifyInc(this.fifteenMinTimeline);
508     }
509
510     /**
511      * Tests the inc methods.
512      * @param timeline the timeline to use for verifications.
513      */

514     public void verifyInc(SegmentedTimeline timeline) {
515         for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END;
516              testCycle += TEST_CYCLE_INC) {
517
518             long m = timeline.getSegmentSize();
519             SegmentedTimeline.Segment segment = timeline.getSegment(testCycle);
520             SegmentedTimeline.Segment seg1 = segment.copy();
521             for (int i = 0; i < 1000; i++) {
522
523                 // test inc() method
524
SegmentedTimeline.Segment seg2 = seg1.copy();
525                 seg2.inc();
526
527                 if ((seg1.getSegmentEnd() + 1) != seg2.getSegmentStart()) {
528                     // logically consecutive segments non-physically consecutive
529
// (with non-contained time in between)
530
assertTrue(
531                         !timeline.containsDomainRange(
532                             seg1.getSegmentEnd() + 1, seg2.getSegmentStart() - 1
533                         )
534                     );
535                     assertEquals(
536                         0, (seg2.getSegmentStart() - seg1.getSegmentStart()) % m
537                     );
538                     assertEquals(
539                         0, (seg2.getSegmentEnd() - seg1.getSegmentEnd()) % m
540                     );
541                     assertEquals(
542                         0, (seg2.getMillisecond() - seg1.getMillisecond()) % m
543                     );
544                 }
545                 else {
546                     // physically consecutive
547
assertEquals(
548                         seg1.getSegmentStart() + m, seg2.getSegmentStart()
549                     );
550                     assertEquals(
551                         seg1.getSegmentEnd() + m, seg2.getSegmentEnd()
552                     );
553                     assertEquals(
554                         seg1.getMillisecond() + m, seg2.getMillisecond()
555                     );
556                 }
557
558                 // test inc(n) method
559
SegmentedTimeline.Segment seg3 = seg1.copy();
560                 SegmentedTimeline.Segment seg4 = seg1.copy();
561
562                 for (int j = 0; j < i; j++) {
563                     seg3.inc();
564                 }
565                 seg4.inc(i);
566
567                 assertEquals(seg3.getSegmentStart(), seg4.getSegmentStart());
568                 assertEquals(seg3.getSegmentEnd(), seg4.getSegmentEnd());
569                 assertEquals(seg3.getMillisecond(), seg4.getMillisecond());
570
571                 // go to another segment to continue test
572
seg1.inc();
573             }
574         }
575     }
576
577     //////////////////////////////////////////////////////////////////////////
578
// main include and excluded segments
579
//////////////////////////////////////////////////////////////////////////
580

581     /**
582      * Tests that the msTimeline's included and excluded
583      * segments are being calculated correctly.
584      */

585     public void testMsIncludedAndExcludedSegments() {
586         verifyIncludedAndExcludedSegments(this.msTimeline, 0);
587     }
588
589     /**
590      * Tests that the ms2Timeline's included and excluded
591      * segments are being calculated correctly.
592      */

593     public void testMs2IncludedAndExcludedSegments() {
594         verifyIncludedAndExcludedSegments(this.ms2Timeline, 1);
595     }
596
597     /**
598      * Tests that the Monday through Friday timeline's included and excluded
599      * segments are being calculated correctly. The test is performed starting
600      * on the first monday after 1/1/2000 and for five years.
601      */

602     public void testMondayThroughFridayIncludedAndExcludedSegments() {
603         verifyIncludedAndExcludedSegments(
604             this.mondayFridayTimeline, this.monday.getTime().getTime()
605         );
606     }
607
608     /**
609      * Tests that the Fifteen-Min timeline's included and excluded
610      * segments are being calculated correctly. The test is performed starting
611      * on the first monday after 1/1/2000 and for five years.
612      */

613     public void testFifteenMinIncludedAndExcludedSegments() {
614         verifyIncludedAndExcludedSegments(
615             this.fifteenMinTimeline, this.monday9am.getTime().getTime()
616         );
617     }
618
619     /**
620      * Tests that a timeline's included and excluded segments are being
621      * calculated correctly.
622      *
623      * @param timeline the timeline to verify
624      * @param n the first segment number to start verifying
625      */

626     public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline,
627                                                   long n) {
628         // clear any exceptions in this timeline
629
timeline.setExceptionSegments(new java.util.ArrayList JavaDoc());
630
631         // test some included and excluded segments
632
SegmentedTimeline.Segment segment = timeline.getSegment(n);
633         for (int i = 0; i < 1000; i++) {
634             int d = (i % timeline.getGroupSegmentCount());
635             if (d < timeline.getSegmentsIncluded()) {
636                 // should be an included segment
637
assertTrue(segment.inIncludeSegments());
638                 assertTrue(!segment.inExcludeSegments());
639                 assertTrue(!segment.inExceptionSegments());
640             }
641             else {
642                 // should be an excluded segment
643
assertTrue(!segment.inIncludeSegments());
644                 assertTrue(segment.inExcludeSegments());
645                 assertTrue(!segment.inExceptionSegments());
646             }
647             segment.inc();
648         }
649     }
650
651     //////////////////////////////////////////////////////////////////////////
652
// test exception segments
653
//////////////////////////////////////////////////////////////////////////
654

655     /**
656      * Tests methods related to exceptions methods in the msTimeline.
657      *
658      * @throws ParseException if there is a parsing error.
659      */

660     public void testMsExceptionSegments() throws ParseException JavaDoc {
661         verifyExceptionSegments(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT);
662     }
663
664     /**
665      * Tests methods related to exceptions methods in the ms2BaseTimeline.
666      *
667      * @throws ParseException if there is a parsing error.
668      */

669     public void testMs2BaseTimelineExceptionSegments() throws ParseException JavaDoc {
670         verifyExceptionSegments(
671             this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT
672         );
673     }
674
675     /**
676      * Tests methods related to exceptions methods in the mondayFridayTimeline.
677      *
678      * @throws ParseException if there is a parsing error.
679      */

680     public void testMondayThoughFridayExceptionSegments()
681         throws ParseException JavaDoc {
682         verifyExceptionSegments(
683             this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT
684         );
685     }
686
687     /**
688      * Tests methods related to exceptions methods in the fifteenMinTimeline.
689      *
690      * @throws ParseException if there is a parsing error.
691      */

692     public void testFifteenMinExceptionSegments() throws ParseException JavaDoc {
693         verifyExceptionSegments(
694             this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT
695         );
696     }
697
698     /**
699      * Tests methods related to adding exceptions.
700      *
701      * @param timeline the timeline to verify
702      * @param exceptionString array of Strings that represent the exceptions
703      * @param fmt Format object that can parse the exceptionString strings
704      *
705      * @throws ParseException if there is a parsing error.
706      */

707     public void verifyExceptionSegments(SegmentedTimeline timeline,
708                                         String JavaDoc[] exceptionString,
709                                         Format JavaDoc fmt)
710         throws ParseException JavaDoc {
711
712         // fill in the exceptions
713
long[] exception = verifyFillInExceptions(
714             timeline, exceptionString, fmt
715         );
716
717         int m = exception.length;
718
719         // verify list of exceptions
720
assertEquals(exception.length, timeline.getExceptionSegments().size());
721         SegmentedTimeline.Segment lastSegment
722             = timeline.getSegment(exception[m - 1]);
723         for (int i = 0; i < m; i++) {
724             SegmentedTimeline.Segment segment
725                 = timeline.getSegment(exception[i]);
726             assertTrue(segment.inExceptionSegments());
727             // include current exception and last one
728
assertEquals(m - i, timeline.getExceptionSegmentCount(
729                 segment.getSegmentStart(), lastSegment.getSegmentEnd()));
730             // exclude current exception and last one
731
assertEquals(
732                 Math.max(0, m - i - 2), timeline.getExceptionSegmentCount(
733                 exception[i] + 1, exception[m - 1] - 1)
734             );
735         }
736
737     }
738
739     //////////////////////////////////////////////////////////////////////////
740
// test timeline translations
741
//////////////////////////////////////////////////////////////////////////
742

743     /**
744      * Tests translations for 1-ms timeline
745      *
746      * @throws ParseException if there is a parsing error.
747      */

748     public void testMsTranslations() throws ParseException JavaDoc {
749         verifyFillInExceptions(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT);
750         verifyTranslations(this.msTimeline, 0);
751     }
752
753     /**
754      * Tests translations for the base timeline used for the ms2Timeline
755      *
756      * @throws ParseException if there is a parsing error.
757      */

758     public void testMs2BaseTimelineTranslations() throws ParseException JavaDoc {
759         verifyFillInExceptions(
760             this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT
761         );
762         verifyTranslations(this.ms2BaseTimeline, 0);
763     }
764
765     /**
766      * Tests translations for the Monday through Friday timeline
767      *
768      * @throws ParseException if there is a parsing error.
769      */

770     public void testMs2Translations() throws ParseException JavaDoc {
771         fillInBaseTimelineExceptions(
772             this.ms2Timeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT
773         );
774         fillInBaseTimelineExclusionsAsExceptions(this.ms2Timeline, 0, 5000);
775         verifyTranslations(this.ms2Timeline, 1);
776     }
777
778     /**
779      * Tests translations for the Monday through Friday timeline
780      *
781      * @throws ParseException if there is a parsing error.
782      */

783     public void testMondayThroughFridayTranslations() throws ParseException JavaDoc {
784         verifyFillInExceptions(
785             this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT
786         );
787         verifyTranslations(
788             this.mondayFridayTimeline, this.monday.getTime().getTime()
789         );
790     }
791
792     /**
793      * Tests translations for the Fifteen Min timeline
794      *
795      * @throws ParseException if there is a parsing error.
796      */

797     public void testFifteenMinTranslations() throws ParseException JavaDoc {
798         verifyFillInExceptions(
799             this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT
800         );
801         fillInBaseTimelineExceptions(
802             this.fifteenMinTimeline, US_HOLIDAYS, DATE_FORMAT
803         );
804         fillInBaseTimelineExclusionsAsExceptions(
805             this.fifteenMinTimeline,
806             this.monday9am.getTime().getTime(),
807             this.monday9am.getTime().getTime() + FIVE_YEARS
808         );
809         verifyTranslations(
810             this.fifteenMinTimeline, this.monday9am.getTime().getTime()
811         );
812     }
813
814     /**
815      * Tests translations between timelines.
816      *
817      * @param timeline the timeline to use for verifications.
818      * @param startTest ??.
819      */

820     public void verifyTranslations(SegmentedTimeline timeline, long startTest) {
821         for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END;
822              testCycle += TEST_CYCLE_INC) {
823
824             long millisecond = startTest + testCycle
825                                * timeline.getSegmentSize();
826             SegmentedTimeline.Segment segment
827                 = timeline.getSegment(millisecond);
828             
829             for (int i = 0; i < 1000; i++) {
830                 long translatedValue
831                     = timeline.toTimelineValue(segment.getMillisecond());
832                 long newValue = timeline.toMillisecond(translatedValue);
833
834                 if (segment.inExcludeSegments()
835                         || segment.inExceptionSegments()) {
836                     // the reverse transformed value will be in the start of the
837
// next non-excluded and non-exception segment
838
SegmentedTimeline.Segment tempSegment = segment.copy();
839                     tempSegment.moveIndexToStart();
840                     do {
841                         tempSegment.inc();
842                     }
843                     while (!tempSegment.inIncludeSegments());
844                     assertEquals(tempSegment.getMillisecond(), newValue);
845                 }
846
847                 else {
848                     assertEquals(segment.getMillisecond(), newValue);
849                 }
850                 segment.inc();
851             }
852         }
853     }
854
855     //////////////////////////////////////////////////////////////////////////
856
// test serialization
857
//////////////////////////////////////////////////////////////////////////
858

859     /**
860      * Serialize an instance, restore it, and check for equality.
861      */

862     public void testSerialization() {
863         verifySerialization(this.msTimeline);
864         verifySerialization(this.ms2Timeline);
865         verifySerialization(this.ms2BaseTimeline);
866         verifySerialization(SegmentedTimeline.newMondayThroughFridayTimeline());
867         verifySerialization(SegmentedTimeline.newFifteenMinuteTimeline());
868     }
869
870     /**
871      * Tests serialization of an instance.
872      * @param a1 The timeline to verify the serialization
873      */

874     private void verifySerialization(SegmentedTimeline a1) {
875         SegmentedTimeline a2 = null;
876
877         try {
878             ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
879             ObjectOutput JavaDoc out = new ObjectOutputStream JavaDoc(buffer);
880             out.writeObject(a1);
881             out.close();
882
883             ObjectInput JavaDoc in = new ObjectInputStream JavaDoc(
884                 new ByteArrayInputStream JavaDoc(buffer.toByteArray())
885             );
886             a2 = (SegmentedTimeline) in.readObject();
887             in.close();
888         }
889         catch (Exception JavaDoc e) {
890             System.out.println(e.toString());
891         }
892         assertEquals(a1, a2);
893     }
894
895     /**
896      * Adds an array of exceptions to the timeline. The timeline exception list
897      * is first cleared.
898      * @param timeline The timeline where the exceptions will be stored
899      * @param exceptionString The exceptions to load
900      * @param fmt The date formatter to use to parse each exceptions[i] value
901      * @throws ParseException If there is any exception parsing each
902      * exceptions[i] value.
903      * @return An array of Dates[] containing each exception date.
904      */

905     private long[] verifyFillInExceptions(SegmentedTimeline timeline,
906                                          String JavaDoc[] exceptionString,
907                                          Format JavaDoc fmt) throws ParseException JavaDoc {
908         // make sure there are no exceptions
909
timeline.setExceptionSegments(new java.util.ArrayList JavaDoc());
910         assertEquals(0, timeline.getExceptionSegments().size());
911
912         // add our exceptions and store locally in ArrayList of Longs
913
ArrayList JavaDoc exceptionList = new ArrayList JavaDoc();
914         for (int i = 0; i < exceptionString.length; i++) {
915             long e;
916             if (fmt instanceof NumberFormat JavaDoc) {
917                 e = ((NumberFormat JavaDoc) fmt).parse(exceptionString[i]).longValue();
918             }
919             else {
920                 e = timeline.getTime(
921                     ((SimpleDateFormat JavaDoc) fmt).parse(exceptionString[i])
922                 );
923             }
924             // only add an exception if it is currently an included segment
925
SegmentedTimeline.Segment segment = timeline.getSegment(e);
926             if (segment.inIncludeSegments()) {
927                 timeline.addException(e);
928                 exceptionList.add(new Long JavaDoc(e));
929                 assertEquals(
930                     exceptionList.size(), timeline.getExceptionSegments().size()
931                 );
932                 assertTrue(segment.inExceptionSegments());
933             }
934         }
935
936         // make array of exceptions
937
long[] exception = new long[exceptionList.size()];
938         int i = 0;
939         for (Iterator JavaDoc iter = exceptionList.iterator(); iter.hasNext();) {
940             Long JavaDoc l = (Long JavaDoc) iter.next();
941             exception[i++] = l.longValue();
942         }
943
944         return (exception);
945
946     }
947
948     /**
949      * Adds an array of exceptions relative to the base timeline.
950      *
951      * @param timeline The timeline where the exceptions will be stored
952      * @param exceptionString The exceptions to load
953      * @param fmt The date formatter to use to parse each exceptions[i] value
954      * @throws ParseException If there is any exception parsing each
955      * exceptions[i] value.
956      */

957     private void fillInBaseTimelineExceptions(SegmentedTimeline timeline,
958                                              String JavaDoc[] exceptionString,
959                                              Format JavaDoc fmt) throws ParseException JavaDoc {
960         SegmentedTimeline baseTimeline = timeline.getBaseTimeline();
961         for (int i = 0; i < exceptionString.length; i++) {
962             long e;
963             if (fmt instanceof NumberFormat JavaDoc) {
964                 e = ((NumberFormat JavaDoc) fmt).parse(exceptionString[i]).longValue();
965             }
966             else {
967                 e = timeline.getTime(
968                     ((SimpleDateFormat JavaDoc) fmt).parse(exceptionString[i])
969                 );
970             }
971             timeline.addBaseTimelineException(e);
972
973             // verify all timeline segments included in the
974
// baseTimeline.segment are now exceptions
975
SegmentedTimeline.Segment segment1 = baseTimeline.getSegment(e);
976             for (SegmentedTimeline.Segment segment2
977                 = timeline.getSegment(segment1.getSegmentStart());
978                  segment2.getSegmentStart() <= segment1.getSegmentEnd();
979                  segment2.inc()) {
980                 if (!segment2.inExcludeSegments()) {
981                     assertTrue(segment2.inExceptionSegments());
982                 }
983             }
984
985         }
986     }
987
988     /**
989      * Adds new exceptions to a timeline. The exceptions are the excluded
990      * segments from its base timeline.
991      *
992      * @param timeline the timeline.
993      * @param from the start.
994      * @param to the end.
995      */

996     private void fillInBaseTimelineExclusionsAsExceptions(
997             SegmentedTimeline timeline, long from, long to) {
998
999         // add the base timeline exclusions as timeline's esceptions
1000
timeline.addBaseTimelineExclusions(from, to);
1001
1002        // validate base timeline exclusions added as timeline's esceptions
1003
for (SegmentedTimeline.Segment segment1
1004                = timeline.getBaseTimeline().getSegment(from);
1005             segment1.getSegmentStart() <= to;
1006             segment1.inc()) {
1007
1008            if (segment1.inExcludeSegments()) {
1009
1010                // verify all timeline segments included in the
1011
// baseTimeline.segment are now exceptions
1012
for (SegmentedTimeline.Segment segment2
1013                     = timeline.getSegment(segment1.getSegmentStart());
1014                     segment2.getSegmentStart() <= segment1.getSegmentEnd();
1015                     segment2.inc()) {
1016                    if (!segment2.inExcludeSegments()) {
1017                        assertTrue(segment2.inExceptionSegments());
1018                    }
1019                }
1020            }
1021        }
1022    }
1023
1024    /**
1025     * Confirm that cloning works.
1026     */

1027    public void testCloning() {
1028        SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2);
1029        SegmentedTimeline l2 = null;
1030        try {
1031            l2 = (SegmentedTimeline) l1.clone();
1032        }
1033        catch (CloneNotSupportedException JavaDoc e) {
1034            System.err.println("Failed to clone.");
1035        }
1036        assertTrue(l1 != l2);
1037        assertTrue(l1.getClass() == l2.getClass());
1038        assertTrue(l1.equals(l2));
1039    }
1040
1041    /**
1042     * Confirm that the equals method can distinguish all the required fields.
1043     */

1044    public void testEquals() {
1045        
1046        SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2);
1047        SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2);
1048        assertTrue(l1.equals(l2));
1049        
1050        l1 = new SegmentedTimeline(1000, 5, 2);
1051        l2 = new SegmentedTimeline(1001, 5, 2);
1052        assertFalse(l1.equals(l2));
1053        
1054        l1 = new SegmentedTimeline(1000, 5, 2);
1055        l2 = new SegmentedTimeline(1000, 4, 2);
1056        assertFalse(l1.equals(l2));
1057        
1058        l1 = new SegmentedTimeline(1000, 5, 2);
1059        l2 = new SegmentedTimeline(1000, 5, 1);
1060        assertFalse(l1.equals(l2));
1061        
1062        l1 = new SegmentedTimeline(1000, 5, 2);
1063        l2 = new SegmentedTimeline(1000, 5, 2);
1064        
1065        // start time...
1066
l1.setStartTime(1234L);
1067        assertFalse(l1.equals(l2));
1068        l2.setStartTime(1234L);
1069        assertTrue(l1.equals(l2));
1070
1071    }
1072    
1073    /**
1074     * Two objects that are equal are required to return the same hashCode.
1075     */

1076    public void testHashCode() {
1077        SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2);
1078        SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2);
1079        assertTrue(l1.equals(l2));
1080        int h1 = l1.hashCode();
1081        int h2 = l2.hashCode();
1082        assertEquals(h1, h2);
1083    }
1084    
1085    /**
1086     * Serialize an instance, restore it, and check for equality.
1087     */

1088    public void testSerialization2() {
1089
1090        SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2);
1091        SegmentedTimeline l2 = null;
1092
1093        try {
1094            ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
1095            ObjectOutput JavaDoc out = new ObjectOutputStream JavaDoc(buffer);
1096            out.writeObject(l1);
1097            out.close();
1098
1099            ObjectInput JavaDoc in = new ObjectInputStream JavaDoc(
1100                new ByteArrayInputStream JavaDoc(buffer.toByteArray())
1101            );
1102            l2 = (SegmentedTimeline) in.readObject();
1103            in.close();
1104        }
1105        catch (Exception JavaDoc e) {
1106            System.out.println(e.toString());
1107        }
1108        boolean b = l1.equals(l2);
1109        assertTrue(b);
1110
1111    }
1112
1113    //////////////////////////////////////////////////////////////////////////
1114
// utility methods
1115
//////////////////////////////////////////////////////////////////////////
1116

1117    /**
1118     * Tests a basic segmented timeline.
1119     */

1120    public void testBasicSegmentedTimeline() {
1121        SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3);
1122        stl.setStartTime(946684800000L); // 1-Jan-2000
1123
assertFalse(stl.containsDomainValue(946684799999L));
1124        assertTrue(stl.containsDomainValue(946684800000L));
1125        assertTrue(stl.containsDomainValue(946684800019L));
1126        assertFalse(stl.containsDomainValue(946684800020L));
1127        assertFalse(stl.containsDomainValue(946684800049L));
1128        assertTrue(stl.containsDomainValue(946684800050L));
1129        assertTrue(stl.containsDomainValue(946684800069L));
1130        assertFalse(stl.containsDomainValue(946684800070L));
1131        assertFalse(stl.containsDomainValue(946684800099L));
1132        assertTrue(stl.containsDomainValue(946684800100L));
1133        
1134        assertEquals(0, stl.toTimelineValue(946684800000L));
1135        assertEquals(19, stl.toTimelineValue(946684800019L));
1136        assertEquals(20, stl.toTimelineValue(946684800020L));
1137        assertEquals(20, stl.toTimelineValue(946684800049L));
1138        assertEquals(20, stl.toTimelineValue(946684800050L));
1139        assertEquals(39, stl.toTimelineValue(946684800069L));
1140        assertEquals(40, stl.toTimelineValue(946684800070L));
1141        assertEquals(40, stl.toTimelineValue(946684800099L));
1142        assertEquals(40, stl.toTimelineValue(946684800100L));
1143        
1144        assertEquals(946684800000L, stl.toMillisecond(0));
1145        assertEquals(946684800019L, stl.toMillisecond(19));
1146        assertEquals(946684800050L, stl.toMillisecond(20));
1147        assertEquals(946684800069L, stl.toMillisecond(39));
1148        assertEquals(946684800100L, stl.toMillisecond(40));
1149        
1150    }
1151    
1152    /**
1153     * Tests a basic time line with one exception.
1154     */

1155    public void testSegmentedTimelineWithException1() {
1156        SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3);
1157        stl.setStartTime(946684800000L); // 1-Jan-2000
1158
stl.addException(946684800050L);
1159        assertFalse(stl.containsDomainValue(946684799999L));
1160        assertTrue(stl.containsDomainValue(946684800000L));
1161        assertTrue(stl.containsDomainValue(946684800019L));
1162        assertFalse(stl.containsDomainValue(946684800020L));
1163        assertFalse(stl.containsDomainValue(946684800049L));
1164        assertFalse(stl.containsDomainValue(946684800050L));
1165        assertFalse(stl.containsDomainValue(946684800059L));
1166        assertTrue(stl.containsDomainValue(946684800060L));
1167        assertTrue(stl.containsDomainValue(946684800069L));
1168        assertFalse(stl.containsDomainValue(946684800070L));
1169        assertFalse(stl.containsDomainValue(946684800099L));
1170        assertTrue(stl.containsDomainValue(946684800100L));
1171
1172        //long v = stl.toTimelineValue(946684800020L);
1173
assertEquals(0, stl.toTimelineValue(946684800000L));
1174        assertEquals(19, stl.toTimelineValue(946684800019L));
1175        assertEquals(20, stl.toTimelineValue(946684800020L));
1176        assertEquals(20, stl.toTimelineValue(946684800049L));
1177        assertEquals(20, stl.toTimelineValue(946684800050L));
1178        assertEquals(29, stl.toTimelineValue(946684800069L));
1179        assertEquals(30, stl.toTimelineValue(946684800070L));
1180        assertEquals(30, stl.toTimelineValue(946684800099L));
1181        assertEquals(30, stl.toTimelineValue(946684800100L));
1182
1183        assertEquals(946684800000L, stl.toMillisecond(0));
1184        assertEquals(946684800019L, stl.toMillisecond(19));
1185        assertEquals(946684800060L, stl.toMillisecond(20));
1186        assertEquals(946684800069L, stl.toMillisecond(29));
1187        assertEquals(946684800100L, stl.toMillisecond(30));
1188
1189    }
1190
1191    //////////////////////////////////////////////////////////////////////////
1192
// main method only for debug
1193
//////////////////////////////////////////////////////////////////////////
1194

1195    /**
1196     * Only use to debug JUnit suite.
1197     *
1198     * @param args ignored.
1199     *
1200     * @throws Exception if there is some problem.
1201     */

1202    public static void main(String JavaDoc[] args) throws Exception JavaDoc {
1203        SegmentedTimelineTests test = new SegmentedTimelineTests("Test");
1204        test.setUp();
1205        test.testMondayThoughFridayExceptionSegments();
1206        test.tearDown();
1207    }
1208
1209}
1210
Popular Tags