KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > CLIHandlerTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans;
21
22 import java.io.*;
23 import java.util.logging.Level JavaDoc;
24 import org.netbeans.junit.*;
25 import java.util.*;
26 import java.util.logging.Logger JavaDoc;
27 import org.openide.util.RequestProcessor;
28
29 /**
30  * Test the command-line-interface handler.
31  * @author Jaroslav Tulach
32  */

33 public class CLIHandlerTest extends NbTestCase {
34
35     private static ByteArrayInputStream nullInput = new ByteArrayInputStream(new byte[0]);
36     private static ByteArrayOutputStream nullOutput = new ByteArrayOutputStream();
37
38     
39     private Logger JavaDoc LOG;
40     
41     public CLIHandlerTest(String JavaDoc name) {
42         super(name);
43     }
44     
45     public static junit.framework.Test suite() {
46         //return new CLIHandlerTest("testFileExistsHasPortButNotTheKey");
47
return new NbTestSuite(CLIHandlerTest.class);
48     }
49     
50     protected void setUp() throws Exception JavaDoc {
51         LOG = Logger.getLogger("TEST-" + getName());
52         
53         super.setUp();
54
55         // all handlers shall be executed immediatelly
56
CLIHandler.finishInitialization (false);
57         
58         // setups a temporary file
59
String JavaDoc p = getWorkDirPath ();
60         if (p == null) {
61             p = System.getProperty("java.io.tmpdir");
62         }
63         String JavaDoc tmp = p;
64         assertNotNull(tmp);
65         System.getProperties().put("netbeans.user", tmp);
66         
67         File f = new File(tmp, "lock");
68         if (f.exists()) {
69             assertTrue("Clean up previous mess", f.delete());
70             assertTrue(!f.exists());
71         }
72     }
73     
74     protected Level JavaDoc logLevel() {
75         return Level.FINEST;
76     }
77     
78     
79     public void testFileExistsButItCannotBeRead() throws Exception JavaDoc {
80         // just creates the file and blocks
81
InitializeRunner runner = new InitializeRunner(10);
82         
83         // blocks when operation fails
84
InitializeRunner second = new InitializeRunner(85);
85         
86         for (int i = 0; i < 3; i++) {
87             second.next();
88         }
89         
90         // finishes the code
91
runner.next();
92         
93         assertNotNull("Runner succeeded to allocate the file", runner.resultFile());
94         
95         // let the second code go on as well
96
second.next();
97         
98         assertEquals("The same file has been allocated", runner.resultFile(), second.resultFile());
99     }
100     
101     public void testFileExistsButTheServerCannotBeContacted() throws Exception JavaDoc {
102         // start the server and block
103
InitializeRunner runner = new InitializeRunner(65);
104         
105         assertNotNull("File created", runner.resultFile());
106         assertTrue("Port allocated", runner.resultPort() != 0);
107         
108         // blocks when operation fails
109
InitializeRunner second = new InitializeRunner(85);
110         // second try should be ok
111
second.next();
112         
113         assertNotNull("Previous file deleted and new one created", second.resultFile());
114         assertTrue("Another port allocated", second.resultPort() != runner.resultPort());
115         
116         
117     }
118     
119     public void testFileExistsHasPortButNotTheKey() throws Exception JavaDoc {
120         // start the server and block
121
Integer JavaDoc block = new Integer JavaDoc(97);
122         InitializeRunner runner;
123         synchronized (block) {
124             runner = new InitializeRunner(block, true);
125             // the initialization code can finish without reaching 97
126
runner.waitResult();
127         }
128         
129         assertTrue("Port allocated", runner.resultPort() != 0);
130         
131         // blocks after read the keys from the file
132
InitializeRunner second = new InitializeRunner(94);
133
134         // let the CLI Secure Handler finish
135
synchronized (block) {
136             block.notifyAll();
137         }
138         // let the test go beyond 97 to the end of file
139
assertNotNull("File created", runner.resultFile());
140         
141         
142         // let the second finish
143
second.next();
144         
145         assertEquals("Still the same file", runner.resultFile(), second.resultFile());
146         assertEquals("Another port allocated", second.resultPort(), runner.resultPort());
147     }
148
149     
150     public void testHelpIsPrinted() throws Exception JavaDoc {
151         class UserDir extends CLIHandler {
152             private int cnt;
153             private boolean doCheck;
154             
155             public UserDir() {
156                 super(WHEN_BOOT);
157             }
158             
159             protected int cli(Args args) {
160                 if (!doCheck) {
161                     return 0;
162                 }
163                 
164                 cnt++;
165                 
166                 for (String JavaDoc a : args.getArguments()) {
167                     if ("--help".equals(a)) {
168                         return 0;
169                     }
170                 }
171                 return 5;
172             }
173             
174             protected void usage(PrintWriter w) {
175                 w.println("this is a help");
176             }
177         }
178         UserDir ud = new UserDir();
179
180         ByteArrayOutputStream os = new ByteArrayOutputStream();
181         
182         CLIHandler.Status res = cliInitialize(new String JavaDoc[] { "--help" }, new CLIHandler[] { ud }, nullInput, os, nullOutput);
183         assertEquals("Help returns 2", 2, res.getExitCode());
184         
185         if (os.toString().indexOf("help") == -1) {
186             fail("There should be some help text:\n" + os);
187         }
188     }
189
190     public void testHelpIsPassedToRunningServer() throws Exception JavaDoc {
191         class UserDir extends CLIHandler implements Runnable JavaDoc {
192             private int cnt;
193             private int usage;
194             private boolean doCheck;
195             private CLIHandler.Status res;
196             
197             public UserDir() {
198                 super(WHEN_BOOT);
199             }
200             
201             protected int cli(Args args) {
202                 if (!doCheck) {
203                     return 0;
204                 }
205                 
206                 cnt++;
207                 
208                 for (String JavaDoc a : args.getArguments()) {
209                     if ("--help".equals(a)) {
210                         return 0;
211                     }
212                 }
213                 return 5;
214             }
215             
216             protected void usage(PrintWriter w) {
217                 usage++;
218             }
219             
220             public void run() {
221                 res = cliInitialize(new String JavaDoc[] { }, new CLIHandler[] { this }, nullInput, nullOutput, nullOutput);
222             }
223         }
224         UserDir ud = new UserDir();
225         
226         RequestProcessor.getDefault().post(ud).waitFinished();
227         assertNotNull(ud.res);
228         
229         assertNotNull("File created", ud.res.getLockFile());
230         assertTrue("Port allocated", ud.res.getServerPort() != 0);
231         
232         ud.doCheck = true;
233         CLIHandler.Status res = cliInitialize(new String JavaDoc[] { "--help" }, new CLIHandler[0], nullInput, nullOutput, nullOutput);
234         
235         assertEquals("Ok exec of help", 2, res.getExitCode());
236         
237         assertEquals("No cli called", 0, ud.cnt);
238         assertEquals("Usage called", 1, ud.usage);
239         
240     }
241     
242     public void testFileExistsButTheServerCannotBeContactedAndWeDoNotWantToCleanTheFileOnSameHost() throws Exception JavaDoc {
243         // start the server and block
244
InitializeRunner runner = new InitializeRunner(65);
245         
246         assertNotNull("File created", runner.resultFile());
247         assertTrue("Port allocated", runner.resultPort() != 0);
248         
249         CLIHandler.Status res = CLIHandler.initialize(
250             new CLIHandler.Args(new String JavaDoc[0], nullInput, nullOutput, nullOutput, ""),
251             null, Collections.EMPTY_LIST, false, false, null
252         );
253         
254         assertNotNull("Previous file deleted and new one created", res.getLockFile());
255         assertTrue("Another port allocated", res.getServerPort() != runner.resultPort());
256     }
257     
258     public void testFileExistsButTheServerCannotBeContactedAndWeDoNotWantToCleanTheFileOnOtherHost() throws Exception JavaDoc {
259         // start the server and block
260
InitializeRunner runner = new InitializeRunner(65);
261         
262         assertNotNull("File created", runner.resultFile());
263         assertTrue("Port allocated", runner.resultPort() != 0);
264         
265         File f = runner.resultFile();
266         byte[] arr = new byte[(int)f.length()];
267         int len = arr.length;
268         assertTrue("We know that the size of the file should be int + key_length + 4 for ip address: ", len >=14 && len <= 18);
269         FileInputStream is = new FileInputStream(f);
270         assertEquals("Fully read", arr.length, is.read(arr));
271         is.close();
272         
273         byte[] altarr = new byte[18];
274         for (int i = 0; i < 18; i++) {
275             altarr[i] = i<14? arr[i]: 1;
276         }
277         
278         // change the IP at the end of the file
279
FileOutputStream os = new FileOutputStream(f);
280         os.write(altarr);
281         os.close();
282         
283         CLIHandler.Status res = CLIHandler.initialize(
284             new CLIHandler.Args(new String JavaDoc[0], nullInput, nullOutput, nullOutput, ""),
285             null, Collections.EMPTY_LIST, false, false, null
286         );
287         
288         assertEquals ("Cannot connect because the IP is different", CLIHandler.Status.CANNOT_CONNECT, res.getExitCode());
289     }
290     
291     public void testFileExistsButTheKeyIsNotRecognized() throws Exception JavaDoc {
292         // start the server be notified when it accepts connection
293
InitializeRunner runner = new InitializeRunner(65);
294         
295         assertNotNull("File created", runner.resultFile());
296         assertTrue("Port allocated", runner.resultPort() != 0);
297         
298         int s = (int)runner.resultFile().length();
299         byte[] copy = new byte[s];
300         FileInputStream is = new FileInputStream(runner.resultFile());
301         assertEquals("Read fully", s, is.read(copy));
302         is.close();
303         
304         // change one byte in the key
305
copy[4 + 2]++;
306         
307         FileOutputStream os = new FileOutputStream(runner.resultFile());
308         os.write(copy);
309         os.close();
310         
311         // try to connect to previous server be notified as soon as it
312
// sends request
313
InitializeRunner second = new InitializeRunner(30);
314         
315         // handle the request, say NO
316
runner.next();
317         
318         // read the reply and allocate new port
319
second.next();
320         
321         assertNotNull("Previous file deleted and new one created", second.resultFile());
322         assertTrue("Another port allocated", second.resultPort() != runner.resultPort());
323     }
324     
325     public void testCLIHandlersCanChangeLocationOfLockFile() throws Exception JavaDoc {
326         File f = File.createTempFile("suffix", "tmp").getParentFile();
327         final File dir = new File(f, "subdir");
328         dir.delete();
329         assertTrue(dir.exists() || dir.mkdir());
330         
331         class UserDir extends CLIHandler {
332             private int cnt;
333             
334             public UserDir() {
335                 super(WHEN_BOOT);
336             }
337             
338             protected int cli(Args args) {
339                 cnt++;
340                 System.setProperty("netbeans.user", dir.toString());
341                 return 0;
342             }
343             
344             protected void usage(PrintWriter w) {}
345         }
346         UserDir ud = new UserDir();
347         
348         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], ud, nullInput, nullOutput, nullOutput, null);
349         
350         assertEquals("Our command line handler is called once", 1, ud.cnt);
351         assertEquals("Lock file is created in dir", dir, res.getLockFile().getParentFile());
352         
353         dir.delete();
354     }
355     
356     public void testCLIHandlerCanStopEvaluation() throws Exception JavaDoc {
357         class H extends CLIHandler {
358             private int cnt;
359             
360             public H() {
361                 super(WHEN_INIT);
362             }
363             
364             protected int cli(Args args) {
365                 cnt++;
366                 return 1;
367             }
368             
369             protected void usage(PrintWriter w) {}
370         }
371         H h1 = new H();
372         H h2 = new H();
373         
374         
375         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], new H[] {
376             h1, h2
377         }, nullInput, nullOutput, nullOutput);
378         
379         assertEquals("CLI evaluation failed with return code of h1", 1, res.getExitCode());
380         assertEquals("First one executed", 1, h1.cnt);
381         assertEquals("Not the second one", 0, h2.cnt);
382     }
383     
384     public void testWhenInvokedTwiceParamsGoToTheFirstHandler() throws Exception JavaDoc {
385         final String JavaDoc[] template = { "Ahoj", "Hello" };
386         final String JavaDoc currentDir = "MyDir";
387         
388         class H extends CLIHandler {
389             private int cnt;
390             
391             public H() {
392                 super(WHEN_INIT);
393             }
394             
395             protected int cli(Args args) {
396                 String JavaDoc[] a = args.getArguments();
397                 String JavaDoc[] t = template;
398                 
399                 assertEquals("Same length", t.length, a.length);
400                 assertEquals("First is same", t[0], a[0]);
401                 assertEquals("Second is same", t[1], a[1]);
402                 assertEquals("Current dir is fine", currentDir, args.getCurrentDirectory().toString());
403                 return ++cnt;
404             }
405             
406             protected void usage(PrintWriter w) {}
407         }
408         H h1 = new H();
409         
410         
411         CLIHandler.Status res = cliInitialize(template, h1, nullInput, nullOutput, nullOutput, null, currentDir);
412         
413         assertEquals("First one executed", 1, h1.cnt);
414         assertEquals("CLI evaluation failed with return code of h1", 1, res.getExitCode());
415         
416         res = cliInitialize(template, java.util.Collections.EMPTY_LIST, nullInput, nullOutput, nullOutput, null, currentDir);
417         assertEquals("But again executed h1", 2, h1.cnt);
418         assertEquals("Now the result is 2 as cnt++ was increased", 2, res.getExitCode());
419         
420     }
421
422     public void testServerWaitsBeforeFinishInitializationIsCalledOn () throws Exception JavaDoc {
423         // this tests will not execute handlers immediatelly
424
CLIHandler.finishInitialization (true);
425         
426         class H extends CLIHandler implements Runnable JavaDoc {
427             public volatile int cnt;
428             public volatile int afterFinish = -1;
429             
430             public H () {
431                 super (CLIHandler.WHEN_INIT);
432             }
433             
434             protected int cli (Args args) {
435                 cnt++;
436                 LOG.info("Increased cnt to: " + cnt + " by thread " + Thread.currentThread());
437                 return afterFinish;
438             }
439             
440             public void run () {
441                 // cnt will be two as once the first cliInitialize will
442
// invoke the handler and once the second cliInitialize
443
// using the Server
444
afterFinish = 2;
445                 CLIHandler.finishInitialization (false);
446             }
447             
448             protected void usage (PrintWriter w) {}
449         }
450         H h = new H ();
451         
452         CLIHandler.Status res = cliInitialize (new String JavaDoc[0], h, nullInput, nullOutput, nullOutput, null);
453         assertEquals ("Returns 0 as no finishInitialization is called", 0, res.getExitCode ());
454         // after two seconds it calls finishInitialization
455
RequestProcessor.Task task = RequestProcessor.getDefault ().post (h, 7000); // 7s is higher than socket timeout
456
res = cliInitialize (new String JavaDoc[0], h, nullInput, nullOutput, nullOutput, null);
457         
458         assertEquals ("Returns 2 as afterFinish needed to be set to 2 before" +
459         " calling finishInitialization", 2, res.getExitCode ());
460
461         long time = System.currentTimeMillis ();
462         task.waitFinished ();
463         time = System.currentTimeMillis () - time;
464         
465         if (time > 1000) {
466             fail ("The waitFinished should return almost immediatelly. But was: " + time);
467         }
468         
469         if (h.afterFinish != h.cnt) {
470             // in order to find out whether the failures in issue #44833
471
// are not caused just by threading issues, let's wait another
472
// few seconds and print the results of h.afterFinish and h.cnt
473
// if they will be the same then just replace the initial condition
474
// by say that h.afterFinish == 2 and h.cnt > 1 is ok
475
Thread.sleep (5000);
476             fail ("H is not executed before finishInitialization is called :" + h.afterFinish + " cnt: " + h.cnt);
477         }
478         
479     }
480     
481     public void testServerIsNotBlockedByLongRequests() throws Exception JavaDoc {
482         class H extends CLIHandler {
483             private int cnt = -1;
484             public int toReturn;
485             
486             public H() {
487                 super(CLIHandler.WHEN_INIT);
488             }
489             
490             protected synchronized int cli(Args args) {
491                 try {
492                     // this simulates really slow, but computing task
493
Thread.sleep (6555);
494                 } catch (InterruptedException JavaDoc ex) {
495                     throw new IllegalStateException JavaDoc ();
496                 }
497                 notifyAll();
498                 cnt++;
499                 return toReturn;
500             }
501             
502             protected void usage(PrintWriter w) {}
503         }
504         H h = new H();
505         
506         h.toReturn = 7;
507         final Integer JavaDoc blockOn = new Integer JavaDoc(99);
508         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], h, nullInput, nullOutput, nullOutput, blockOn);
509         assertEquals("Called once, increased -1 to 0", 0, h.cnt);
510         assertEquals("Result is provided by H", 7, res.getExitCode());
511         
512         // blocks after connection established, before returning the result
513
class R implements Runnable JavaDoc {
514             CLIHandler.Status res;
515             public void run() {
516                 res = cliInitialize(new String JavaDoc[0], Collections.EMPTY_LIST, nullInput, nullOutput, nullOutput, blockOn);
517             }
518         }
519         R r = new R();
520         RequestProcessor.Task task;
521         synchronized (h) {
522             h.toReturn = 5;
523             task = new org.openide.util.RequestProcessor("Blocking request").post(r);
524             h.wait();
525             assertEquals("Connects to the h", 1, h.cnt);
526             if (r.res != null) {
527                 fail ("The handler should not be finished, as it blocks in '99' but it is and the result is " + r.res.getExitCode ());
528             }
529         }
530         
531         // while R is blocked, run another task
532
h.toReturn = 0;
533         res = cliInitialize(new String JavaDoc[0], Collections.EMPTY_LIST, nullInput, nullOutput, nullOutput, null);
534         assertEquals("Called once, increased to 2", 2, h.cnt);
535         assertEquals("Result is provided by H, H gives 0, changes into -1 right now", -1, res.getExitCode());
536         
537         synchronized (blockOn) {
538             // let the R task go on
539
blockOn.notifyAll();
540         }
541         task.waitFinished();
542         assertNotNull("Now it is finished", r.res);
543         assertEquals("Result is -1, if this fails: this usually means that the server is blocked by some work and the task R started new server to handle its request",
544             5, r.res.getExitCode());
545         assertEquals("H called three times (but counting from -1)", 2, h.cnt);
546     }
547     
548     public void testReadingOfInputWorksInHandler() throws Exception JavaDoc {
549         final byte[] template = { 1, 2, 3, 4 };
550         
551         class H extends CLIHandler {
552             private byte[] arr;
553             
554             public H() {
555                 super(WHEN_INIT);
556             }
557             
558             protected int cli(Args args) {
559                 try {
560                     InputStream is = args.getInputStream();
561                     arr = new byte[is.available() / 2];
562                     if (arr.length > 0) {
563                         assertEquals("Read amount is the same", arr.length, is.read(arr));
564                     }
565                     is.close();
566                 } catch (IOException ex) {
567                     fail("There is an exception: " + ex);
568                 }
569                 return 0;
570             }
571             
572             protected void usage(PrintWriter w) {}
573         }
574         H h1 = new H();
575         H h2 = new H();
576         
577         // why twice? first attempt is direct, second thru the socket server
578
for (int i = 0; i < 2; i++) {
579             CLIHandler.Status res = cliInitialize(
580                 new String JavaDoc[0], new H[] { h1, h2 }, new ByteArrayInputStream(template), nullOutput, nullOutput);
581             
582             assertNotNull("Attempt " + i + ": " + "Can be read", h1.arr);
583             assertEquals("Attempt " + i + ": " + "Read two bytes", 2, h1.arr.length);
584             assertEquals("Attempt " + i + ": " + "First is same", template[0], h1.arr[0]);
585             assertEquals("Attempt " + i + ": " + "Second is same", template[1], h1.arr[1]);
586             
587             assertNotNull("Attempt " + i + ": " + "Can read as well", h2.arr);
588             assertEquals("Attempt " + i + ": " + "Just one char", 1, h2.arr.length);
589             assertEquals("Attempt " + i + ": " + "And is the right one", template[2], h2.arr[0]);
590             
591             h1.arr = null;
592             h2.arr = null;
593         }
594     }
595     
596     public void testReadingMoreThanAvailableIsOk () throws Exception JavaDoc {
597         final byte[] template = { 1, 2, 3, 4 };
598         
599         class H extends CLIHandler {
600             private byte[] arr;
601             
602             public H() {
603                 super(WHEN_INIT);
604             }
605             
606             protected int cli(Args args) {
607                 try {
608                     InputStream is = args.getInputStream();
609                     arr = new byte[8];
610                     assertEquals("Read amount is the maximum of template", template.length, is.read(arr));
611                     is.close();
612                 } catch (IOException ex) {
613                     fail("There is an exception: " + ex);
614                 }
615                 return 0;
616             }
617             
618             protected void usage(PrintWriter w) {}
619         }
620         H h1 = new H();
621         
622         // why twice? first attempt is direct, second thru the socket server
623
for (int i = 0; i < 2; i++) {
624             CLIHandler.Status res = cliInitialize(
625                 new String JavaDoc[0], new H[] { h1 }, new ByteArrayInputStream(template), nullOutput, nullOutput);
626             
627             assertNotNull("Attempt " + i + ": " + "Can be read", h1.arr);
628             assertEquals("Attempt " + i + ": " + "First is same", template[0], h1.arr[0]);
629             assertEquals("Attempt " + i + ": " + "Second is same", template[1], h1.arr[1]);
630             assertEquals("Attempt " + i + ": " + "3rd is same", template[2], h1.arr[2]);
631             assertEquals("Attempt " + i + ": " + "4th is same", template[3], h1.arr[3]);
632             
633             h1.arr = null;
634         }
635     }
636     
637     
638     public void testWritingToOutputIsFine() throws Exception JavaDoc {
639         final byte[] template = { 1, 2, 3, 4 };
640         
641         class H extends CLIHandler {
642             public H() {
643                 super(WHEN_INIT);
644             }
645             
646             protected int cli(Args args) {
647                 try {
648                     OutputStream os = args.getOutputStream();
649                     os.write(template);
650                     os.close();
651                     
652                     os = args.getErrorStream();
653                     os.write(0);
654                     os.write(1);
655                     os.write(2);
656                     os.write(3);
657                     os.write(4);
658                     os.close();
659                 } catch (IOException ex) {
660                     fail("There is an exception: " + ex);
661                 }
662                 return 0;
663             }
664             
665             protected void usage(PrintWriter w) {}
666         }
667         H h1 = new H();
668         H h2 = new H();
669         
670         // why twice? first attempt is direct, second thru the socket server
671
for (int i = 0; i < 2; i++) {
672             ByteArrayOutputStream os = new ByteArrayOutputStream();
673             ByteArrayOutputStream err = new ByteArrayOutputStream();
674             
675             CLIHandler.Status res = cliInitialize(
676                 new String JavaDoc[0], new H[] { h1, h2 }, nullInput, os, err);
677             
678             byte[] arr = os.toByteArray();
679             assertEquals("Double size of template", template.length * 2, arr.length);
680             
681             for (int pos = 0; pos < arr.length; pos++) {
682                 assertEquals(pos + ". is the same", template[pos % template.length], arr[pos]);
683             }
684             
685             byte[] errArr = err.toByteArray();
686             assertEquals("5 bytes", 10, errArr.length);
687             for (int x = 0; x < errArr.length; x++) {
688                 assertEquals(errArr[x], x % 5);
689             }
690         }
691     }
692
693     public void testGetInetAddressDoesNotBlock () throws Exception JavaDoc {
694         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], Collections.EMPTY_LIST, nullInput, nullOutput, nullOutput, Integer.valueOf(27));
695         assertEquals("CLIHandler init finished" ,0, res.getExitCode());
696     }
697     
698     public void testServerCanBeStopped () throws Exception JavaDoc {
699         class H extends CLIHandler {
700             private int cnt = -1;
701             public int toReturn;
702             
703             public H() {
704                 super(CLIHandler.WHEN_INIT);
705             }
706             
707             protected synchronized int cli(Args args) {
708                 notifyAll();
709                 cnt++;
710                 return toReturn;
711             }
712             
713             protected void usage(PrintWriter w) {}
714         }
715         H h = new H();
716         
717         h.toReturn = 7;
718         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], h, nullInput, nullOutput, nullOutput, null);
719         assertEquals("Called once, increased -1 to 0", 0, h.cnt);
720         assertEquals("Result is provided by H", 7, res.getExitCode());
721         
722         CLIHandler.stopServer ();
723         
724         h.toReturn = 5;
725         h.cnt = -1;
726         res = cliInitialize(new String JavaDoc[0], Collections.EMPTY_LIST, nullInput, nullOutput, nullOutput, null);
727         assertEquals("Not called -1", -1, h.cnt);
728         // right now the handler will not be called, if there is anything else
729
// to do, let's wait for such requirements
730
}
731
732     public void testHostNotFound64004 () throws Exception JavaDoc {
733         class H extends CLIHandler {
734             private int cnt;
735             public int toReturn;
736             
737             public H() {
738                 super(CLIHandler.WHEN_INIT);
739             }
740             
741             protected synchronized int cli(Args args) {
742                 notifyAll();
743                 cnt++;
744                 return toReturn;
745             }
746             
747             protected void usage(PrintWriter w) {}
748         }
749         H h = new H();
750         
751         // handlers shall not be executed immediatelly
752
CLIHandler.finishInitialization(true);
753         
754         h.toReturn = 7;
755         CLIHandler.Status res = cliInitialize(new String JavaDoc[0], h, nullInput, nullOutput, nullOutput, new Integer JavaDoc(667));
756         // finish all calls
757
int newRes = CLIHandler.finishInitialization(false);
758         
759         assertEquals("Called once, increased", 1, h.cnt);
760         assertEquals("Result is provided by H", 7, newRes);
761     }
762     
763     //
764
// Utility methods
765
//
766

767     private static CLIHandler.Status cliInitialize(String JavaDoc[] args, CLIHandler handler, InputStream is, OutputStream os, OutputStream err, Integer JavaDoc lock) {
768         return cliInitialize(args, handler, is, os, err, lock, System.getProperty ("user.dir"));
769     }
770     private static CLIHandler.Status cliInitialize(String JavaDoc[] args, CLIHandler handler, InputStream is, OutputStream os, OutputStream err, Integer JavaDoc lock, String JavaDoc currentDir) {
771         return cliInitialize(args, Collections.nCopies(1, handler), is, os, err, lock, currentDir);
772     }
773     private static CLIHandler.Status cliInitialize(String JavaDoc[] args, CLIHandler[] arr, InputStream is, OutputStream os, OutputStream err) {
774         return cliInitialize(args, Arrays.asList(arr), is, os, err, null);
775     }
776     private static CLIHandler.Status cliInitialize(String JavaDoc[] args, List coll, InputStream is, OutputStream os, java.io.OutputStream JavaDoc err, Integer JavaDoc lock) {
777         return cliInitialize (args, coll, is, os, err, lock, System.getProperty ("user.dir"));
778     }
779     private static CLIHandler.Status cliInitialize(String JavaDoc[] args, List coll, InputStream is, OutputStream os, java.io.OutputStream JavaDoc err, Integer JavaDoc lock, String JavaDoc currentDir) {
780         return CLIHandler.initialize(new CLIHandler.Args(args, is, os, err, currentDir), lock, coll, false, true, null);
781     }
782     
783     private static final class InitializeRunner extends Object JavaDoc implements Runnable JavaDoc {
784         private Integer JavaDoc block;
785         private String JavaDoc[] args;
786         private CLIHandler handler;
787         private CLIHandler.Status result;
788         private boolean noEnd;
789         
790         public InitializeRunner(int till) throws InterruptedException JavaDoc {
791             this(new String JavaDoc[0], null, till);
792         }
793
794         public InitializeRunner(int till, boolean noEnd) throws InterruptedException JavaDoc {
795             this(new String JavaDoc[0], null, till, noEnd);
796         }
797         
798         public InitializeRunner(Integer JavaDoc till, boolean noEnd) throws InterruptedException JavaDoc {
799             this(new String JavaDoc[0], null, till, noEnd);
800         }
801         public InitializeRunner(String JavaDoc[] args, CLIHandler h, int till) throws InterruptedException JavaDoc {
802             this(args, h, new Integer JavaDoc(till));
803         }
804         public InitializeRunner(String JavaDoc[] args, CLIHandler h, Integer JavaDoc till) throws InterruptedException JavaDoc {
805             this(args, h, till, false);
806         }
807
808         private InitializeRunner(String JavaDoc[] args, CLIHandler h, Integer JavaDoc till, boolean noEnd) throws InterruptedException JavaDoc {
809             this.args = args;
810             this.block = till;
811             this.handler = h;
812             this.noEnd = noEnd;
813             
814             synchronized (block) {
815                 new RequestProcessor("InitializeRunner blocks on " + till).post(this);
816                 block.wait();
817             }
818         }
819         
820         public void run() {
821             synchronized (block) {
822                 result = CLIHandler.initialize(
823                     new CLIHandler.Args(args, nullInput, nullOutput, nullOutput, ""),
824                     block,
825                     handler == null ? java.util.Collections.EMPTY_LIST : java.util.Collections.nCopies(1, handler),
826                     false,
827                     true,
828                     null
829                 );
830                 if (!noEnd) {
831                     // we are finished, wake up guys in next() if any
832
block.notifyAll();
833                 }
834             }
835             synchronized (this) {
836                 notifyAll();
837             }
838         }
839         
840         /** Executes the code to next invocation */
841         public void next() throws InterruptedException JavaDoc {
842             synchronized (block) {
843                 block.notify();
844                 block.wait();
845             }
846         }
847         
848         /** Has already the resutl?
849          */

850         public boolean hasResult() {
851             return result != null;
852         }
853         
854         public boolean waitResult() throws InterruptedException JavaDoc {
855             synchronized (this) {
856                 for (int i = 0; i < 10; i++) {
857                     if (result != null) {
858                         return true;
859                     }
860                     wait(1000);
861                 }
862             }
863             fail("No result produced: " + result);
864             return true;
865         }
866         
867         /** Gets the resultFile, if there is some,
868          */

869         public File resultFile() {
870             if (result == null) {
871                 fail("No result produced");
872             }
873             return result.getLockFile();
874         }
875         
876         /** Gets the port, if there is some,
877          */

878         public int resultPort() {
879             if (result == null) {
880                 fail("No result produced");
881             }
882             return result.getServerPort();
883         }
884     } // end of InitializeRunner
885

886 }
887
Popular Tags