1 /***
2 *
3 * Copyright 2005 LogicBlaze, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 **/
18 package org.logicblaze.lingo.example;
19
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import junit.framework.Assert;
24
25 /***
26 * @version $Revision: 1.2 $
27 */
28 public class TestResultListener extends Assert implements ResultListener {
29 private List results = new ArrayList();
30 private Object semaphore = new Object();
31 private boolean stopped;
32 private Exception onException;
33
34 public void onResult(String data) {
35 System.out.println("Our remote callback has been invoked with: " + data);
36
37 synchronized (semaphore) {
38 results.add(data);
39 semaphore.notifyAll();
40 }
41 }
42
43
44 public void stop() {
45 stopped = true;
46 }
47
48 public void onException(Exception e) {
49 onException = e;
50 }
51
52 public Exception getOnException() {
53 return onException;
54 }
55
56 public boolean isStopped() {
57 return stopped;
58 }
59
60 public void waitForAsyncResponses(int messageCount) {
61 System.out.println("Waiting for: " + messageCount + " responses to arrive");
62
63 long start = System.currentTimeMillis();
64
65 for (int i = 0; i < 10; i++) {
66 try {
67 if (hasReceivedResponses(messageCount)) {
68 break;
69 }
70 synchronized (semaphore) {
71 semaphore.wait(1000);
72 }
73 }
74 catch (InterruptedException e) {
75 System.out.println("Caught: " + e);
76 }
77 }
78 long end = System.currentTimeMillis() - start;
79
80 System.out.println("End of wait for " + end + " millis");
81
82 List results = getResults();
83 assertEquals("Incorrect number of messages received: " + results, messageCount, results.size());
84 }
85
86 public List getResults() {
87 synchronized (semaphore) {
88 return new ArrayList(results);
89 }
90 }
91
92 protected boolean hasReceivedResponse() {
93 return getResults().isEmpty();
94 }
95
96 protected boolean hasReceivedResponses(int messageCount) {
97 return getResults().size() >= messageCount;
98 }
99
100 }