01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.async.impl;
06:
07: import com.tc.async.api.OrderedEventContext;
08: import com.tc.async.api.Sink;
09: import com.tc.logging.TCLogging;
10: import com.tc.test.TCTestCase;
11:
12: import java.security.SecureRandom;
13: import java.util.ArrayList;
14:
15: public class OrderedSinkTest extends TCTestCase {
16:
17: public void testBasic() throws Exception {
18: MockSink des = new MockSink();
19: Sink s = new OrderedSink(
20: TCLogging.getLogger(OrderedSink.class), des);
21:
22: OrderedEventContext oc = new MyOrderedEventContext(1);
23: s.add(oc);
24: assertEvents(des, 1, 1);
25:
26: oc = new MyOrderedEventContext(3);
27: s.add(oc);
28: assertTrue(des.queue.isEmpty());
29:
30: oc = new MyOrderedEventContext(4);
31: s.add(oc);
32: assertTrue(des.queue.isEmpty());
33:
34: oc = new MyOrderedEventContext(2);
35: s.add(oc);
36: assertEvents(des, 2, 3);
37:
38: oc = new MyOrderedEventContext(2);
39: boolean failed = false;
40: try {
41: s.add(oc);
42: failed = true;
43: } catch (AssertionError ae) {
44: // Excepted
45: }
46: assertFalse(failed);
47: }
48:
49: public void testComplex() throws Exception {
50: MockSink des = new MockSink();
51: Sink s = new OrderedSink(
52: TCLogging.getLogger(OrderedSink.class), des);
53:
54: ArrayList l = createOrderedEvents(1000);
55: SecureRandom r = new SecureRandom();
56:
57: while (!l.isEmpty()) {
58: int idx = r.nextInt(l.size());
59: OrderedEventContext oc = (OrderedEventContext) l
60: .remove(idx);
61: s.add(oc);
62: }
63:
64: assertEvents(des, 1, 1000);
65: }
66:
67: private ArrayList createOrderedEvents(int count) {
68: ArrayList al = new ArrayList(count);
69: for (int i = 1; i <= count; i++) {
70: al.add(new MyOrderedEventContext(i));
71: }
72: return al;
73: }
74:
75: private void assertEvents(MockSink des, int id, int count) {
76: while (count-- > 0) {
77: MyOrderedEventContext oc = (MyOrderedEventContext) des.queue
78: .remove(0);
79: assertEquals(id++, oc.getSequenceID());
80: }
81: assertTrue(des.queue.isEmpty());
82: }
83:
84: private static class MyOrderedEventContext implements
85: OrderedEventContext {
86:
87: long id;
88:
89: public MyOrderedEventContext(int i) {
90: id = i;
91: }
92:
93: public long getSequenceID() {
94: return id;
95: }
96:
97: }
98: }
|