Debian Codegraph @

src/test/java/org/astrogrid/samp/bridge/BridgeTest.java

raw
1 package org.astrogrid.samp.bridge;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.InetAddress;
9 import java.net.URL;
10 import java.util.HashSet;
11 import java.util.HashMap;
12 import java.util.Iterator;
13 import java.util.Map;
14 import java.util.Random;
15 import java.util.Set;
16 import java.util.logging.Level;
17 import java.util.logging.Logger;
18 import junit.framework.TestCase;
19 import org.astrogrid.samp.Client;
20 import org.astrogrid.samp.Message;
21 import org.astrogrid.samp.Metadata;
22 import org.astrogrid.samp.Response;
23 import org.astrogrid.samp.Subscriptions;
24 import org.astrogrid.samp.TestProfile;
25 import org.astrogrid.samp.bridge.Bridge;
26 import org.astrogrid.samp.client.AbstractMessageHandler;
27 import org.astrogrid.samp.client.ClientProfile;
28 import org.astrogrid.samp.client.HubConnection;
29 import org.astrogrid.samp.client.HubConnector;
30 import org.astrogrid.samp.client.ResultHandler;
31 import org.astrogrid.samp.client.SampException;
32 import org.astrogrid.samp.httpd.UtilServer;
33 import org.astrogrid.samp.xmlrpc.StandardTestProfile;
34 import org.astrogrid.samp.xmlrpc.XmlRpcKit;
35
36 public class BridgeTest extends TestCase {
37
38 private final static String ECHO_MTYPE = "test.echo";
39
40 public void setUp() {
41 Logger.getLogger( "org.astrogrid.samp" ).setLevel( Level.WARNING );
42 Logger.getLogger( "org.astrogrid.samp.xmlrpc.internal" )
43 .setLevel( Level.SEVERE );
44 Logger.getLogger( "org.astrogrid.samp.xmlrpc.StandardHubProfile" )
45 .setLevel( Level.SEVERE );
46 }
47
48 public void testBridge()
49 throws IOException, SampException, InterruptedException {
50 bridgeTest( 2 );
51 bridgeTest( 4 );
52 }
53
54 public void testExport() throws IOException {
55 File file = File.createTempFile( "test", ".txt" );
56 file.deleteOnExit();
57 OutputStream out = new FileOutputStream( file );
58 byte[] text = new byte[] { (byte) 'g', (byte) 'u', (byte) 'r', };
59 out.write( text );
60 out.close();
61
62 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
63 UrlExporter exporter1 = new UrlExporter( hostname, true );
64 UrlExporter exporter2 = new UrlExporter( hostname, false );
65 assertEquals( "http://" + hostname + "/gur",
66 exporter1.exportString( "http://127.0.0.1/gur" ) );
67
68 String rawUrl = file.toURL().toString()
69 // fix broken file.toURL()
70 .replaceFirst( "^file:/\\b", "file://localhost/" );
71 URL expUrl1 = new URL( exporter1.exportString( rawUrl ) );
72 URL expUrl2 = new URL( exporter2.exportString( rawUrl ) );
73 assertEquals( "http", expUrl1.getProtocol() );
74 assertEquals( "file", expUrl2.getProtocol() );
75 assertEquals( rawUrl, expUrl2.toString() );
76
77 InputStream expIn1 = expUrl1.openStream();
78 InputStream expIn2 = expUrl2.openStream();
79 for ( int i = 0; i < text.length; i++ ) {
80 assertEquals( expIn1.read(), text[ i ] );
81 assertEquals( expIn2.read(), text[ i ] );
82 }
83 expIn1.close();
84 expIn2.close();
85
86 file.delete();
87 }
88
89 private void bridgeTest( int nhub )
90 throws IOException, SampException, InterruptedException {
91 Random random = new Random( 232323 );
92 XmlRpcKit kit = XmlRpcKit.getInstance();
93
94 // Set up N hubs with one client each.
95 // Clients all have similar (not identical) metadata, and all
96 // subscribe to MTYPE_ECHO.
97 TestProfile[] profiles = new TestProfile[ nhub ];
98 HubConnector[] connectors = new HubConnector[ nhub ];
99 HubConnection[] connections = new HubConnection[ nhub ];
100 for ( int ih = 0; ih < nhub; ih++ ) {
101 final int ih1 = ih + 1;
102 final char iha = (char) ( ih + 'A' );
103 TestProfile profile = new StandardTestProfile( random, kit ) {
104 public String toString() {
105 return "P." + iha;
106 }
107 };
108 profiles[ ih ] = profile;
109 profile.startHub();
110
111 HubConnector connector = new HubConnector( profile );
112 connectors[ ih ] = connector;
113 Metadata meta = new Metadata();
114 meta.setName( "Client " + ih1 );
115 meta.put( "client.id", "C" + ih1 );
116 connector.declareMetadata( meta );
117 connector.addMessageHandler( new EchoMessageHandler() );
118 connector.declareSubscriptions( connector.computeSubscriptions() );
119 connections[ ih ] = connector.getConnection();
120 assertNotNull( connections[ ih ] );
121 }
122
123 // Wait for all metadata and subscriptions.
124 for ( int ih = 0; ih < nhub; ih++ ) {
125 Map clientMap = connectors[ ih ].getClientMap();
126 synchronized ( clientMap ) {
127 while ( ! hasAtts( clientMap, true, true ) ) {
128 clientMap.wait();
129 }
130 }
131 }
132
133 // Check no (other) subscribed clients, one other client (the hub).
134 for ( int ih = 0; ih < nhub; ih++ ) {
135 HubConnection connection = connections[ ih ];
136 assertEquals( 0, connection.getSubscribedClients( ECHO_MTYPE )
137 .size() );
138 assertEquals( 1, connection.getRegisteredClients().length );
139 }
140
141 // Start bridge.
142 Bridge bridge = new Bridge( profiles );
143 bridge.start();
144
145 // Wait for all metadata and subscriptions from bridge start.
146 for ( int ih = 0; ih < nhub; ih++ ) {
147 Map clientMap = connectors[ ih ].getClientMap();
148 synchronized ( clientMap ) {
149 while ( ! hasAtts( clientMap, true, true ) ) {
150 clientMap.wait();
151 }
152 }
153 }
154
155 // Check that all proxy and bridge clients we expect to have appeared
156 // are present and correct.
157 for ( int ih = 0; ih < nhub; ih++ ) {
158 HubConnection connection = connections[ ih ];
159 Map clientMap = connectors[ ih ].getClientMap();
160
161 assertEquals( nhub - 1,
162 connection.getSubscribedClients( ECHO_MTYPE )
163 .size() );
164 assertEquals( ( nhub - 1 ) + 2,
165 connection.getRegisteredClients().length );
166
167 assertEquals( ( nhub - 1 ), getProxyCount( clientMap ) );
168 assertTrue( hasBridge( clientMap ) );
169
170 Set srcSet = new HashSet();
171 for ( Iterator it = clientMap.values().iterator(); it.hasNext(); ) {
172 Client client = (Client) it.next();
173 srcSet.add( client.getMetadata().get( "bridge.proxy.source" ) );
174 }
175 assertTrue( srcSet.contains( null ) );
176 assertEquals( nhub, srcSet.size() );
177 }
178
179 // Send one echo broadcast from each client. This should get
180 // anwered over the bridge from all the remote clients.
181 EchoResultHandler[] resultHandlers = new EchoResultHandler[ nhub ];
182 for ( int ih = 0; ih < nhub; ih++ ) {
183 Map echoContent = new HashMap();
184 echoContent.put( "text", "gur" );
185 echoContent.put( "index", "ix" + ( ih + 1 ) );
186 Message msg = new Message( ECHO_MTYPE, echoContent );
187 resultHandlers[ ih ] = new EchoResultHandler( echoContent );
188 connectors[ ih ].callAll( msg, resultHandlers[ ih ], 5 );
189 }
190
191 // Check the right number of results are in.
192 for ( int ih = 0; ih < nhub; ih++ ) {
193 EchoResultHandler handler = resultHandlers[ ih ];
194 synchronized ( handler ) {
195 while ( ! handler.isDone_ ) {
196 handler.wait();
197 }
198 }
199 assertEquals( nhub - 1, handler.okResults_ );
200 }
201
202 // Stop the bridge.
203 bridge.stop();
204
205 // Check all clients have gone away.
206 for ( int ih = 0; ih < nhub; ih++ ) {
207 Map clientMap = connectors[ ih ].getClientMap();
208 synchronized ( clientMap ) {
209 while ( getProxyCount( clientMap ) > 0 ||
210 hasBridge( clientMap ) ) {
211 clientMap.wait();
212 }
213 }
214 assertEquals( 2, clientMap.size() );
215 }
216 }
217
218 private boolean hasAtts( Map clientMap,
219 boolean wantMeta, boolean wantSubs ) {
220 for ( Iterator it = clientMap.values().iterator(); it.hasNext(); ) {
221 Client client = (Client) it.next();
222 if ( wantMeta ) {
223 Metadata meta = client.getMetadata();
224 if ( meta == null || meta.isEmpty() ) {
225 return false;
226 }
227 }
228 if ( wantSubs ) {
229 Subscriptions subs = client.getSubscriptions();
230 if ( subs == null || subs.isEmpty() ) {
231 return false;
232 }
233 }
234 }
235 return true;
236 }
237
238 private int getProxyCount( Map clientMap ) {
239 int nProxy = 0;
240 for ( Iterator it = clientMap.values().iterator(); it.hasNext(); ) {
241 Client client = (Client) it.next();
242 if ( client.getMetadata().containsKey( "bridge.proxy.source" ) ) {
243 nProxy++;
244 }
245 }
246 return nProxy;
247 }
248
249 private boolean hasBridge( Map clientMap ) {
250 for ( Iterator it = clientMap.values().iterator(); it.hasNext(); ) {
251 Client client = (Client) it.next();
252 if ( client.getMetadata().getName().equalsIgnoreCase( "bridge" ) ) {
253 return true;
254 }
255 }
256 return false;
257 }
258
259 private static class EchoMessageHandler extends AbstractMessageHandler {
260 EchoMessageHandler() {
261 super( ECHO_MTYPE );
262 }
263 public Map processCall( HubConnection conn, String senderId,
264 Message msg ) {
265 return msg.getParams();
266 }
267 }
268
269 private static class EchoResultHandler implements ResultHandler {
270 private final Map expectedResult_;
271 int okResults_;
272 boolean isDone_;
273
274 EchoResultHandler( Map expectedResult ) {
275 expectedResult_ = new HashMap( expectedResult );
276 }
277
278 public synchronized void result( Client responder, Response response ) {
279 if ( response.isOK() ) {
280 Map result = response.getResult();
281 if ( expectedResult_.equals( response.getResult() ) ) {
282 okResults_++;
283 }
284 else {
285 System.err.println( "echo mismatch" );
286 }
287 }
288 else {
289 System.err.println( "echo error response" );
290 }
291 }
292
293 public synchronized void done() {
294 isDone_ = true;
295 notifyAll();
296 }
297 }
298 }