Debian Codegraph @

src/java/org/astrogrid/samp/test/ReplyCollector.java

raw
1 package org.astrogrid.samp.test;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Map;
11 import java.util.Set;
12 import org.astrogrid.samp.Response;
13 import org.astrogrid.samp.client.CallableClient;
14 import org.astrogrid.samp.client.HubConnection;
15 import org.astrogrid.samp.client.SampException;
16
17 /**
18 * Partial implementation of {@link CallableClient} which handles the
19 * <code>receiveReply</code> method.
20 * This takes care of matching up replies with calls and is intended for
21 * use with test classes. Some assertions are made within this class
22 * to check that replies match with messages sent. Call-type messages
23 * must be sent using this object's <code>call</code> and <code>callAll</code>
24 * methods, rather than directly on the <code>HubConnection</code>,
25 * to ensure that the internal state stays correct.
26 *
27 * @author Mark Taylor
28 * @since 18 Jul 2008
29 */
30 abstract class ReplyCollector implements CallableClient {
31
32 private final HubConnection connection_;
33 private final Set sentSet_;
34 private final Map replyMap_;
35 private boolean allowTagReuse_;
36
37 /**
38 * Constructor.
39 *
40 * @param connection hub connection
41 * @param allowTagReuse if true clients may reuse tags;
42 * if false any such attempt generates an exception
43 */
44 public ReplyCollector( HubConnection connection ) {
45 connection_ = connection;
46 sentSet_ = Collections.synchronizedSet( new HashSet() );
47 replyMap_ = Collections.synchronizedMap( new HashMap() );
48 }
49
50 /**
51 * Determines whether clients are permitted to reuse tags for different
52 * messages. If true, any such attempt generates an exception.
53 *
54 * @param allow whether to allow tag reuse
55 */
56 public void setAllowTagReuse( boolean allow ) {
57 allowTagReuse_ = allow;
58 }
59
60 /**
61 * Performs a <code>call</code> method on this collector's hub connection.
62 * Additional internal state is updated.
63 * Although it is legal as far as SAMP goes, the <code>msgTag</code>
64 * must not be one which was used earlier for the same recipient.
65 *
66 * @param recipientId public-id of client to receive message
67 * @param msgTag arbitrary string tagging this message for caller's
68 * benefit
69 * @param msg {@link org.astrogrid.samp.Message}-like map
70 * @return message ID
71 */
72 public String call( String recipientId, String msgTag, Map msg )
73 throws SampException {
74 Object key = createKey( recipientId, msgTag );
75 if ( ! allowTagReuse_ && sentSet_.contains( key ) ) {
76 throw new IllegalArgumentException( "Key " + key + " reused" );
77 }
78 sentSet_.add( key );
79 return connection_.call( recipientId, msgTag, msg );
80 }
81
82 /**
83 * Performs a <code>callAll</code> method on this collector's
84 * hub connection.
85 * Additional internal state is updated.
86 * Although it is legal as far as SAMP goes, the <code>msgTag</code>
87 * must not be one which was used for an earlier broadcast.
88 *
89 * @param msgTag arbitrary string tagging this message for caller's
90 * benefit
91 * @param msg {@link org.astrogrid.samp.Message}-like map
92 * @return message ID
93 */
94 public Map callAll( String msgTag, Map msg ) throws SampException {
95 Object key = createKey( null, msgTag );
96 if ( ! allowTagReuse_ && sentSet_.contains( key ) ) {
97 throw new IllegalArgumentException( "Key " + key + " reused" );
98 }
99 sentSet_.add( key );
100 return connection_.callAll( msgTag, msg );
101 }
102
103 public void receiveResponse( String responderId, String msgTag,
104 Response response ) {
105 Object key = createKey( responderId, msgTag );
106 Object result;
107 try {
108 if ( ! allowTagReuse_ && replyMap_.containsKey( key ) ) {
109 throw new TestException( "Response for " + key
110 + " already received" );
111 }
112 else if ( ! sentSet_.contains( key ) &&
113 ! sentSet_.contains( createKey( null, msgTag ) ) ) {
114 throw new TestException( "Message " + key + " never sent" );
115 }
116 result = response;
117 }
118 catch ( TestException e ) {
119 result = e;
120 }
121 synchronized ( replyMap_ ) {
122 if ( ! replyMap_.containsKey( key ) ) {
123 replyMap_.put( key, new ArrayList() );
124 }
125 ((List) replyMap_.get( key )).add( result );
126 replyMap_.notifyAll();
127 }
128 }
129
130 /**
131 * Returns the total number of unretrieved replies so far collected by
132 * this object.
133 *
134 * @return reply count
135 */
136 public int getReplyCount() {
137 int count = 0;
138 synchronized ( replyMap_ ) {
139 for ( Iterator it = replyMap_.values().iterator(); it.hasNext(); ) {
140 count += ((List) it.next()).size();
141 }
142 }
143 return count;
144 }
145
146 /**
147 * Waits for a reply to a message sent earlier
148 * using <code>call</code> or <code>callAll</code>.
149 * Blocks until such a response is received.
150 *
151 * @param responderId client ID of client providing response
152 * @param msgTag tag which was used to send the message
153 * @return response
154 */
155 public Response waitForReply( String responderId, String msgTag ) {
156 Object key = createKey( responderId, msgTag );
157 try {
158 synchronized ( replyMap_ ) {
159 while ( ! replyMap_.containsKey( key ) ||
160 ((List) replyMap_.get( key )).isEmpty() ) {
161 replyMap_.wait();
162 }
163 }
164 }
165 catch ( InterruptedException e ) {
166 throw new Error( "Interrupted", e );
167 }
168 return getReply( responderId, msgTag );
169 }
170
171 /**
172 * Gets the reply to a message sent earlier
173 * using <code>call</code> or <code>callAll</code>.
174 * Does not block; if no such response has been received so far,
175 * returns null.
176 *
177 * @param responderId client ID of client providing response
178 * @param msgTag tag which was used to send the message
179 * @return response
180 */
181 public Response getReply( String responderId, String msgTag ) {
182 Object key = createKey( responderId, msgTag );
183 synchronized ( replyMap_ ) {
184 List list = (List) replyMap_.get( key );
185 Object result = list == null || list.isEmpty()
186 ? null
187 : list.remove( 0 );
188 if ( result == null ) {
189 return null;
190 }
191 else if ( result instanceof Response ) {
192 return (Response) result;
193 }
194 else if ( result instanceof Throwable ) {
195 throw new TestException( (Throwable) result );
196 }
197 else {
198 throw new AssertionError();
199 }
200 }
201 }
202
203 /**
204 * Returns an opaque object suitable for use as a map key
205 * based on a recipient ID and message tag.
206 *
207 * @param recipientId recipient ID
208 * @param msgTag message tag
209 */
210 private static Object createKey( String recipientId, String msgTag ) {
211 return Arrays.asList( new String[] { recipientId, msgTag } );
212 }
213 }