KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > tests > EncryptMessageOrderTestCase


1 package org.jgroups.tests;
2
3 import junit.framework.TestCase;
4 import org.apache.commons.logging.Log;
5 import org.apache.commons.logging.LogFactory;
6 import org.jgroups.Header;
7 import org.jgroups.JChannel;
8 import org.jgroups.Message;
9 import org.jgroups.MessageListener;
10 import org.jgroups.blocks.PullPushAdapter;
11
12 import java.io.IOException JavaDoc;
13 import java.io.ObjectInput JavaDoc;
14 import java.io.ObjectOutput JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.Vector JavaDoc;
17
18 /**
19  * This test case checks ordering of messages using the Encrypt protocol
20  * using <code>UDP</code>protocols. It can be run
21  * as JUnit test case or in the command line. Parameters are:
22  * <ul>
23  * <li><code>-sleep n</code> - means that after each message sending, sender
24  * thread will sleep for <code>n</code> milliseconds;
25  * <li><code>-msg_num n</code> - <code>n</code> is number of messages to send;
26  * <li><code>-debug</code> - pop-up protocol debugger;
27  * </ul>
28  * $Id: EncryptMessageOrderTestCase.java,v 1.1 2007/07/04 07:29:33 belaban Exp $
29  */

30 public class EncryptMessageOrderTestCase extends TestCase {
31
32     public static int MESSAGE_NUMBER=5 * 100;
33
34     public static boolean SLEEP_BETWEEN_SENDING=false;
35
36     public static int SLEEP_TIME=1;
37
38     String JavaDoc groupName = "ENCRYPT_ORDER_TEST";
39
40     boolean orderCounterFailure = false;
41
42     protected Log log=LogFactory.getLog(this.getClass());
43
44     public static final String JavaDoc properties ="EncryptNoKeyStore.xml";
45
46
47     /**
48      * Constructor to create test case.
49      */

50     public EncryptMessageOrderTestCase(String JavaDoc string) {
51         super(string);
52     }
53
54     protected JChannel channel1;
55     protected PullPushAdapter adapter1;
56
57     protected JChannel channel2;
58     protected PullPushAdapter adapter2;
59
60     /**
61      * Print selected options before test starts.
62      */

63     protected static void printSelectedOptions() {
64         System.out.println("will sleep : " + SLEEP_BETWEEN_SENDING);
65         if(SLEEP_BETWEEN_SENDING)
66             System.out.println("sleep time : " + SLEEP_TIME);
67
68         System.out.println("msg num : " + MESSAGE_NUMBER);
69
70
71     }
72
73     /**
74      * Set up unit test. It might add protocol
75      * stack debuggers if such option was selected at startup.
76      */

77     protected void setUp() throws Exception JavaDoc {
78         super.setUp();
79         printSelectedOptions();
80
81         
82  
83
84         channel1=new JChannel(properties);
85         System.out.print("Connecting to channel...");
86         channel1.connect(groupName);
87         System.out.println("channel1 connected, view is " + channel1.getView());
88
89         adapter1=new PullPushAdapter(channel1);
90
91         // sleep one second before second member joins
92
try {
93             Thread.sleep(1000);
94         }
95         catch(InterruptedException JavaDoc ex) {
96         }
97
98             channel2=new JChannel(properties);
99             channel2.connect(groupName);
100             System.out.println("channel2 connected, view is " + channel2.getView());
101
102             adapter2=new PullPushAdapter(channel2);
103
104             // sleep one second before processing continues
105
try {
106                 Thread.sleep(1000);
107             }
108             catch(InterruptedException JavaDoc ex) {
109             }
110
111     }
112
113     /**
114      * Tears down test case. This method closes all opened channels.
115      */

116     protected void tearDown() throws Exception JavaDoc {
117         super.tearDown();
118         
119         adapter2.stop();
120         channel2.close();
121
122         adapter1.stop();
123         channel1.close();
124     }
125
126     protected boolean finishedReceiving;
127
128     /**
129      * Test method. This method adds a message listener to the PullPushAdapter
130      * on channel 1, and starts sending specified number of messages into
131      * channel 1 or 2 depending if we are in loopback mode or not. Each message
132      * containg timestamp when it was created. By measuring time on message
133      * delivery we can calculate message trip time. Listener is controlled by
134      * two string messages "start" and "stop". After sender has finished to
135      * send messages, it waits until listener receives all messages or "stop"
136      * message. Then test is finished and calculations are showed.
137      * <p/>
138      * Also we calculate how much memory
139      * was allocated before excuting a test and after executing a test.
140      */

141     public void testLoad() {
142         try {
143             final String JavaDoc startMessage="start";
144             final String JavaDoc stopMessage="stop";
145
146             final Object JavaDoc mutex=new Object JavaDoc();
147
148             final Vector JavaDoc receivedTimes=new Vector JavaDoc(MESSAGE_NUMBER);
149             final Vector JavaDoc normalMessages=new Vector JavaDoc(MESSAGE_NUMBER);
150             final Vector JavaDoc tooQuickMessages=new Vector JavaDoc();
151             final Vector JavaDoc tooSlowMessages=new Vector JavaDoc();
152
153             adapter1.setListener(new MessageListener() {
154                 private boolean started=false;
155                 private boolean stopped=false;
156
157                 private long counter = 0L;
158                 
159                 public byte[] getState() {
160                     return null;
161                 }
162
163                 public void setState(byte[] state) {
164                 }
165
166                 public void receive(Message jgMessage) {
167                     Object JavaDoc message=jgMessage.getObject();
168
169                     if(startMessage.equals(message)) {
170                         started=true;
171                         finishedReceiving=false;
172                     }
173                     else if(stopMessage.equals(message)) {
174                         stopped=true;
175                         finishedReceiving=true;
176
177                         synchronized(mutex) {
178                             mutex.notifyAll();
179                         }
180
181                     }
182                     else if(message instanceof Long JavaDoc) {
183                         Long JavaDoc travelTime=new Long JavaDoc(System.currentTimeMillis() - ((Long JavaDoc)message).longValue());
184
185                         try {
186                             assertEquals(counter, ((EncryptOrderTestHeader)((Message)jgMessage).getHeader("EncryptOrderTest")).seqno);
187                             counter++;
188                         } catch (Exception JavaDoc e){
189                             log.warn(e);
190                             orderCounterFailure =true;
191                         }
192                         if(!started)
193                             tooQuickMessages.add(message);
194                         else if(started && !stopped) {
195                             receivedTimes.add(travelTime);
196                             normalMessages.add(message);
197                         }
198                         else
199                             tooSlowMessages.add(message);
200                     }
201                 }
202             });
203
204             System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
205             System.out.println("Total memory: " + Runtime.getRuntime().totalMemory());
206             System.out.println("Starting sending messages.");
207
208             long time=System.currentTimeMillis();
209
210             Message startJgMessage=new Message();
211             startJgMessage.setObject(startMessage);
212
213             JChannel sender= channel2;
214
215             sender.send(startJgMessage);
216
217             for(int i=0; i < MESSAGE_NUMBER; i++) {
218                 Long JavaDoc message=new Long JavaDoc(System.currentTimeMillis());
219
220                 
221                 Message jgMessage=new Message();
222                 jgMessage.putHeader("EncryptOrderTest", new EncryptOrderTestHeader(i));
223                 jgMessage.setObject(message);
224
225                 sender.send(jgMessage);
226
227                 if(i % 1000 == 0)
228                     System.out.println("sent " + i + " messages.");
229
230                 if(SLEEP_BETWEEN_SENDING)
231                     org.jgroups.util.Util.sleep(1, true);
232             }
233
234             Message stopJgMessage=new Message();
235             stopJgMessage.setObject(stopMessage);
236             sender.send(stopJgMessage);
237
238             time=System.currentTimeMillis() - time;
239
240             System.out.println("Finished sending messages. Operation took " + time);
241
242             synchronized(mutex) {
243
244                 int received=0;
245
246                 while(!finishedReceiving) {
247                     mutex.wait(1000);
248
249                     if(receivedTimes.size() != received) {
250                         received=receivedTimes.size();
251
252                         System.out.println();
253                         System.out.print("Received " + receivedTimes.size() + " messages.");
254                     }
255                     else {
256                         System.out.print(".");
257                     }
258                 }
259             }
260
261             try {
262                 Thread.sleep(1000);
263             }
264             catch(Exception JavaDoc ex) {
265             }
266
267             double avgDeliveryTime=-1.0;
268             long maxDeliveryTime=Long.MIN_VALUE;
269             long minDeliveryTime=Long.MAX_VALUE;
270
271             Iterator JavaDoc iterator=receivedTimes.iterator();
272             while(iterator.hasNext()) {
273                 Long JavaDoc message=(Long JavaDoc)iterator.next();
274
275                 if(avgDeliveryTime == -1.0)
276                     avgDeliveryTime=message.longValue();
277                 else
278                     avgDeliveryTime=(avgDeliveryTime + message.doubleValue()) / 2.0;
279
280                 if(message.longValue() > maxDeliveryTime)
281                     maxDeliveryTime=message.longValue();
282
283                 if(message.longValue() < minDeliveryTime)
284                     minDeliveryTime=message.longValue();
285             }
286
287             System.out.println("Sent " + MESSAGE_NUMBER + " messages.");
288             System.out.println("Received " + receivedTimes.size() + " messages.");
289             System.out.println("Average delivery time " + avgDeliveryTime + " ms");
290             System.out.println("Minimum delivery time " + minDeliveryTime + " ms");
291             System.out.println("Maximum delivery time " + maxDeliveryTime + " ms");
292             System.out.println("Received " + tooQuickMessages.size() + " too quick messages");
293             System.out.println("Received " + tooSlowMessages.size() + " too slow messages");
294         }
295         catch(Exception JavaDoc ex) {
296             ex.printStackTrace();
297         }
298
299         System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
300         System.out.println("Total memory: " + Runtime.getRuntime().totalMemory());
301
302         System.out.println("Performing GC");
303
304         Runtime.getRuntime().gc();
305
306         try {
307             Thread.sleep(2000);
308         }
309         catch(InterruptedException JavaDoc ex) {
310         }
311
312         System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
313         System.out.println("Total memory: " + Runtime.getRuntime().totalMemory());
314
315         assertTrue("Message ordering is incorrect - check log output",(!orderCounterFailure));
316     }
317     
318     
319
320     /**
321      * Main method to start a test case from the command line. Parameters are:
322      * <ul>
323      * <li><code>-sleep n</code> - means that after each message sending, sender
324      * thread will sleep for <code>n</code> milliseconds;
325      * <li><code>-msg_num n</code> - <code>n</code> is number of messages to send;;
326      * <li><code>-debug</code> - pop-up protocol debugger;
327      * </ul>
328      */

329     public static void main(String JavaDoc[] args) {
330         for(int i=0; i < args.length; i++) {
331             if("-sleep".equals(args[i])) {
332                 SLEEP_BETWEEN_SENDING=true;
333                 if(!(i < args.length - 1))
334                     throw new RuntimeException JavaDoc("You have to specify sleep time");
335
336                 try {
337                     SLEEP_TIME=Integer.parseInt(args[++i]);
338                 }
339                 catch(NumberFormatException JavaDoc nfex) {
340                     throw new RuntimeException JavaDoc("Cannot parse sleep time");
341                 }
342
343             }
344             else if("-msg_num".equals(args[i])) {
345                 if(!(i < args.length - 1))
346                     throw new RuntimeException JavaDoc("You have to specify messages number");
347
348                 try {
349                     MESSAGE_NUMBER=Integer.parseInt(args[++i]);
350                 }
351                 catch(NumberFormatException JavaDoc nfex) {
352                     throw new RuntimeException JavaDoc("Cannot parse messages number");
353                 }
354
355             }
356            
357             else if("-help".equals(args[i])) {
358                 help();
359                 return;
360             }
361         }
362
363         junit.textui.TestRunner.run(EncryptMessageOrderTestCase.class);
364     }
365
366     static void help() {
367         System.out.println("EncryptOrderTest [-help] [-sleep <sleep time between sends (ms)>] " +
368                 " [-msg_num <number of msgs to send>]");
369     }
370     
371     public static class EncryptOrderTestHeader extends Header{
372
373       long seqno = -1; // either reg. NAK_ACK_MSG or first_seqno in retransmissions
374

375       public EncryptOrderTestHeader(){}
376
377       public EncryptOrderTestHeader(long seqno){
378
379          this.seqno = seqno;
380       }
381
382       public int size(){
383          return 512;
384       }
385
386       public void writeExternal(ObjectOutput JavaDoc out) throws IOException JavaDoc{
387
388          out.writeLong(seqno);
389       }
390
391       public void readExternal(ObjectInput JavaDoc in) throws IOException JavaDoc, ClassNotFoundException JavaDoc{
392
393          seqno = in.readLong();
394
395       }
396
397       public EncryptOrderTestHeader copy(){
398          EncryptOrderTestHeader ret = new EncryptOrderTestHeader(seqno);
399          return ret;
400       }
401
402       public String JavaDoc toString(){
403          StringBuffer JavaDoc ret = new StringBuffer JavaDoc();
404          ret.append("[ENCRYPT_ORDER_TEST: seqno=" + seqno);
405          ret.append(']');
406
407          return ret.toString();
408       }
409    }
410
411 }
412
Popular Tags