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  /***
24   * @version $Revision: 1.1 $
25   */
26  public class TestResultListener implements ResultListener {
27      private List results = new ArrayList();
28      private Object semaphore = new Object();
29      private boolean stopped;
30      private Exception onException;
31  
32      public synchronized void onResult(String data) {
33          results.add(data);
34          synchronized (semaphore) {
35              semaphore.notifyAll();
36          }
37      }
38  
39      // lifecycle end methods
40      public void stop() {
41          stopped = true;
42      }
43  
44      public void onException(Exception e) {
45          onException = e;
46      }
47  
48  
49      public Exception getOnException() {
50          return onException;
51      }
52  
53      public List getResults() {
54          return results;
55      }
56  
57      public boolean isStopped() {
58          return stopped;
59      }
60  
61      public void waitForAsyncResponses(int messageCount) {
62          System.out.println("Waiting for: " + messageCount + " responses to arrive");
63  
64          long start = System.currentTimeMillis();
65  
66          for (int i = 0; i < 10; i++) {
67              try {
68                  if (hasReceivedResponses(messageCount)) {
69                      break;
70                  }
71                  synchronized (semaphore) {
72                      semaphore.wait(1000);
73                  }
74              }
75              catch (InterruptedException e) {
76                  System.out.println("Caught: " + e);
77              }
78          }
79          long end = System.currentTimeMillis() - start;
80  
81          System.out.println("End of wait for " + end + " millis");
82      }
83  
84      protected boolean hasReceivedResponse() {
85          return results.isEmpty();
86      }
87  
88      protected synchronized boolean hasReceivedResponses(int messageCount) {
89          return results.size() >= messageCount;
90      }
91  
92  }