1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
|
/* ServerAccess.java
Copyright (C) 2011, 2012 Red Hat, Inc.
This file is part of IcedTea.
IcedTea is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.
IcedTea is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with IcedTea; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
*/
package net.sourceforge.jnlp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.jnlp.browsertesting.Browser;
import net.sourceforge.jnlp.browsertesting.BrowserFactory;
import net.sourceforge.jnlp.browsertesting.Browsers;
import net.sourceforge.jnlp.closinglisteners.AutoErrorClosingListener;
import net.sourceforge.jnlp.closinglisteners.AutoOkClosingListener;
import org.junit.Assert;
/**
*
* This class provides access to virtual server and stuff around.
* It can find unoccupied port, start server, provides its singleton instantiation, launch parallel instantiations,
* read location of installed (tested javaws) see javaws.build.bin java property,
* location of server www root on file system (see test.server.dir java property),
* stubs for launching javaws and for locating resources and read resources.
*
* It can also execute processes with timeout (@see PROCESS_TIMEOUT) (used during launching javaws)
* Some protected apis are exported because public classes in this package are put to be tested by makefile.
*
* There are included test cases which show some basic usages.
*
*
*/
public class ServerAccess {
public static enum AutoClose {
CLOSE_ON_EXCEPTION, CLOSE_ON_CORRECT_END, CLOSE_ON_BOTH
}
public static final long NANO_TIME_DELIMITER=1000000l;
/**
* java property which value containing path to default (makefile by) directory with deployed resources
*/
public static final String TEST_SERVER_DIR = "test.server.dir";
/**
* java property which value containing path to installed (makefile by) javaws binary
*/
public static final String JAVAWS_BUILD_BIN = "javaws.build.bin";
/** property to set the different then default browser
*/
public static final String USED_BROWSERS = "used.browsers";
public static final String DEFAULT_LOCALHOST_NAME = "localhost";
/**
* server instance singleton
*/
private static ServerLauncher server;
/**
* inner version of engine
*/
private static final String version = "5";
/**
* timeout to read 'remote' resources
* This can be changed in runtime, but will affect all following tasks
*/
public static int READ_TIMEOUT = 1000;
/**
* timeout in ms to let process to finish, before assassin will kill it.
* This can be changed in runtime, but will affect all following tasks
*/
public static long PROCESS_TIMEOUT = 20 * 1000;//ms
/**
* this flag is indicating whether output of executeProcess should be logged. By default true.
*/
public static boolean PROCESS_LOG = true;
public static boolean LOGS_REPRINT = false;
private Browser currentBrowser;
public static final String UNSET_BROWSER="unset_browser";
/**
* main method of this class prints out random free port
* or runs server
* param "port" prints out the port
* nothing or number will run server on random(or on number specified)
* port in -Dtest.server.dir
*/
public static void main(String[] args) throws Exception {
if (args.length > 0 && args[0].equalsIgnoreCase("port")) {
int i = findFreePort();
System.out.println(i);
System.exit(0);
} else {
int port = 44321;
if (args.length > 0) {
port=new Integer(args[0]);
}
getIndependentInstance(port);
while (true) {
Thread.sleep(1000);
}
}
}
/**
* utility method to find random free port
*
* @return - found random free port
* @throws IOException - if socket can't be opened or no free port exists
*/
public static int findFreePort()
throws IOException {
ServerSocket findPortTestingSocket = new ServerSocket(0);
int port = findPortTestingSocket.getLocalPort();
findPortTestingSocket.close();
return port;
}
public static final String HEADLES_OPTION="-headless";
public static final String VERBOSE_OPTION="-verbose";
/**
* we would like to have an singleton instance ASAP
*/
public ServerAccess() {
getInstance();
}
/**
*
* @return cached instance. If none, then creates new
*/
public static ServerLauncher getInstance() {
if (server == null) {
server = getIndependentInstance();
}
return server;
}
/**
*
* @return new not cached iserver instance on random port,
* useful for testing application loading from different url then base
*/
public static ServerLauncher getIndependentInstance() {
return getIndependentInstance(true);
}
public static ServerLauncher getIndependentInstance(boolean daemon) {
String dir = (System.getProperty(TEST_SERVER_DIR));
try{
return getIndependentInstance(dir, findFreePort(),daemon);
}catch (Exception ex){
throw new RuntimeException(ex);
}
}
/**
*
* @return new not cached iserver instance on random port,
* useful for testing application loading from different url then base
*/
public static ServerLauncher getIndependentInstance(int port) {
return getIndependentInstance(port, true);
}
public static ServerLauncher getIndependentInstance(int port,boolean daemon) {
String dir = (System.getProperty(TEST_SERVER_DIR));
return getIndependentInstance(dir,port,daemon);
}
/**
*
* @return new not cached iserver instance on random port upon custom www root directory,
* useful for testing application loading from different url then base
*/
public static ServerLauncher getIndependentInstance(String dir, int port) {
return getIndependentInstance(dir, port, true);
}
public static ServerLauncher getIndependentInstance(String dir, int port,boolean daemon) {
if (dir == null || dir.trim().length() == 0 || !new File(dir).exists() || !new File(dir).isDirectory()) {
throw new RuntimeException("test.server.dir property must be set to valid directory!");
}
try {
ServerLauncher lServerLuncher = new ServerLauncher(port, new File(dir));
Thread r=new Thread(lServerLuncher);
r.setDaemon(daemon);
r.start();
return lServerLuncher;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
*
* @return - value passed inside as javaws binary location. See JAVAWS_BUILD_BIN
*/
public String getJavawsLocation() {
return System.getProperty(JAVAWS_BUILD_BIN);
}
/**
*
* @return - bianry from where to lunch current browser
*/
public String getBrowserLocation() {
if (this.currentBrowser==null) return UNSET_BROWSER;
return this.currentBrowser.getBin();
}
public List<String> getBrowserParams() {
if (this.currentBrowser==null) return null;
List<String> l1=this.currentBrowser.getComaptibilitySwitches();
List<String> l2=this.currentBrowser.getDefaultSwitches();
List<String> l= new ArrayList();
if (l1!=null)l.addAll(l1);
if (l2!=null)l.addAll(l2);
return l;
}
public Browsers getCurrentBrowsers() {
if (currentBrowser==null) return null;
return currentBrowser.getID();
}
public Browser getCurrentBrowser() {
return currentBrowser;
}
public void setCurrentBrowser(Browsers currentBrowser) {
this.currentBrowser = BrowserFactory.getFactory().getBrowser(currentBrowser);
if (this.currentBrowser == null) {
LoggingBottleneck.getDefaultLoggingBottleneck().setLoggedBrowser(UNSET_BROWSER);
} else {
LoggingBottleneck.getDefaultLoggingBottleneck().setLoggedBrowser(this.currentBrowser.getID().toString());
}
}
public void setCurrentBrowser(Browser currentBrowser) {
this.currentBrowser = currentBrowser;
if (this.currentBrowser == null) {
LoggingBottleneck.getDefaultLoggingBottleneck().setLoggedBrowser(UNSET_BROWSER);
} else {
LoggingBottleneck.getDefaultLoggingBottleneck().setLoggedBrowser(this.currentBrowser.getID().toString());
}
}
/**
*
* @return - value passed inside as javaws binary location as file. See JAVAWS_BUILD_BIN
*/
public File getJavawsFile() {
return new File(System.getProperty(JAVAWS_BUILD_BIN));
}
/**
*
* @return port on which is running cached server. If non singleton instance is running, new is created.
*/
public int getPort() {
if (server == null) {
getInstance();
}
//if (!server.isRunning()) throw new RuntimeException("Server mysteriously died");
return server.getPort();
}
/**
*
* @return directory upon which is running cached server. If non singleton instance is running, new is created.
*/
public File getDir() {
if (server == null) {
getInstance();
}
// if (!server.isRunning()) throw new RuntimeException("Server mysteriously died");
return server.getDir();
}
/**
*
* @return url pointing to cached server resource. If non singleton instance is running, new is created.
*/
public URL getUrl(String resource) throws MalformedURLException {
if (server == null) {
getInstance();
}
//if (!server.isRunning()) throw new RuntimeException("Server mysteriously died");
return server.getUrl(resource);
}
/**
*
* @return url pointing to cached server . If non singleton instance is running, new is created.
*/
public URL getUrl() throws MalformedURLException {
return getUrl("");
}
/**
*
* @return whether cached server is alive. If non singleton instance is running, new is created.
*/
public boolean isRunning() {
if (server == null) {
getInstance();
}
//if (!server.isRunning()) throw new RuntimeException("Server mysteriously died");
return server.isRunning();
}
/**
* Return resource from cached server
*
* @param resource to be located on cached server
* @return individual bytes of resource
* @throws IOException if connection can't be established or resource does not exist
*/
public ByteArrayOutputStream getResourceAsBytes(String resource) throws IOException {
return getResourceAsBytes(getUrl(resource));
}
/**
* Return resource from cached server
*
* @param resource to be located on cached server
* @return string constructed from resource
* @throws IOException if connection can't be established or resource does not exist
*/
public String getResourceAsString(String resource) throws IOException {
return getResourceAsString(getUrl(resource));
}
/**
* utility method which can read bytes of any stream
*
* @param input stream to be read
* @return individual bytes of resource
* @throws IOException if connection can't be established or resource does not exist
*/
public static ByteArrayOutputStream getBytesFromStream(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer;
}
/**
* utility method which can read from any stream as one long String
*
* @param input stream
* @return stream as string
* @throws IOException if connection can't be established or resource does not exist
*/
public static String getContentOfStream(InputStream is,String encoding) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
StringBuilder sb = new StringBuilder();
while (true) {
String s = br.readLine();
if (s == null) {
break;
}
sb.append(s).append("\n");
}
return sb.toString();
} finally {
is.close();
}
}
/**
* utility method which can read from any stream as one long String
*
* @param input stream
* @return stream as string
* @throws IOException if connection can't be established or resource does not exist
*/
public static String getContentOfStream(InputStream is) throws IOException {
return getContentOfStream(is, "UTF-8");
}
/**
* utility method which can read bytes of resource from any url
*
* @param resource to be located on any url
* @return individual bytes of resource
* @throws IOException if connection can't be established or resource does not exist
*/
public static ByteArrayOutputStream getResourceAsBytes(URL u) throws IOException {
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.connect();
return getBytesFromStream(connection.getInputStream());
}
/**
* utility method which can read string of resource from any url
*
* @param resource to be located on any url
* @return resource as string
* @throws IOException if connection can't be established or resource does not exist
*/
public static String getResourceAsString(URL u) throws IOException {
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.connect();
return getContentOfStream(connection.getInputStream());
}
/**
* helping dummy method to save String as file
*
* @param content
* @param f
* @throws IOException
*/
public static void saveFile(String content, File f) throws IOException {
saveFile(content, f, "utf-8");
}
public static void saveFile(String content, File f,String encoding) throws IOException {
Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),encoding));
output.write(content);
output.flush();
output.close();
}
/**
* wrapping method to executeProcess (eg: javaws -headless http://localhost:port/resource)
* will execute default javaws (@see JAVAWS_BUILD_BIN) upon default url upon cached server (@see SERVER_NAME @see getPort(), @see getInstance())
* with parameter -headless (no gui, no asking)
* @param resource name of resource
* @return result what left after running this process
* @throws Exception
*/
public ProcessResult executeJavawsHeadless(String resource) throws Exception {
return executeJavawsHeadless(null, resource);
}
public ProcessResult executeJavawsHeadless(String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeJavawsHeadless(null, resource,stdoutl,stderrl,null);
}
/**
* wrapping method to executeProcess (eg: javaws arg arg -headless http://localhost:port/resource)
* will execute default javaws (@see JAVAWS_BUILD_BIN) upon default url upon cached server (@see SERVER_NAME @see getPort(), @see getInstance())
* with parameter -headless (no gui, no asking)
* @param resource name of resource
* @param otherargs other arguments to be added to headless one
* @return result what left after running this process
* @throws Exception
*/
public ProcessResult executeJavawsHeadless(List<String> otherargs, String resource) throws Exception {
return executeJavawsHeadless(otherargs, resource,null,null,null);
}
public ProcessResult executeJavawsHeadless(List<String> otherargs, String resource, String[] vars) throws Exception {
return executeJavawsHeadless(otherargs, resource,null,null,vars);
}
public ProcessResult executeJavawsHeadless(List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl,String[] vars) throws Exception {
if (otherargs == null) {
otherargs = new ArrayList<String>(1);
}
List<String> headlesList = new ArrayList<String>(otherargs);
headlesList.add(HEADLES_OPTION);
return executeJavaws(headlesList, resource,stdoutl,stderrl,vars);
}
/**
* wrapping method to executeProcess (eg: javaws http://localhost:port/resource)
* will execute default javaws (@see JAVAWS_BUILD_BIN) upon default url upon cached server (@see SERVER_NAME @see getPort(), @see getInstance())
* @param resource name of resource
* @return result what left after running this process
* @throws Exception
*/
public ProcessResult executeJavaws(String resource) throws Exception {
return executeJavaws(null, resource);
}
public ProcessResult executeJavaws(String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeJavaws(null, resource,stdoutl,stderrl);
}
public net.sourceforge.jnlp.ProcessResult executeBrowser(String string, AutoClose autoClose) throws Exception {
ClosingListener errClosing = null;
ClosingListener outClosing = null;
if (autoClose == AutoClose.CLOSE_ON_BOTH || autoClose == AutoClose.CLOSE_ON_EXCEPTION){
errClosing=new AutoErrorClosingListener();
}
if (autoClose == AutoClose.CLOSE_ON_BOTH || autoClose == AutoClose.CLOSE_ON_CORRECT_END){
outClosing=new AutoOkClosingListener();
}
return executeBrowser(string, outClosing, errClosing);
}
public ProcessResult executeBrowser(String resource) throws Exception {
return executeBrowser(getBrowserParams(), resource);
}
public ProcessResult executeBrowser(String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeBrowser(getBrowserParams(), resource, stdoutl, stderrl);
}
/**
* wrapping method to executeProcess (eg: javaws arg arg http://localhost:port/resource)
* will execute default javaws (@see JAVAWS_BUILD_BIN) upon default url upon cached server (@see SERVER_NAME @see getPort(), @see getInstance()))
* @param resource name of resource
* @param otherargs other arguments to be added
* @return result what left after running this process
* @throws Exception
*/
public ProcessResult executeJavaws(List<String> otherargs, String resource) throws Exception {
return executeProcessUponURL(getJavawsLocation(), otherargs, getUrlUponThisInstance(resource));
}
public ProcessResult executeJavaws(List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcessUponURL(getJavawsLocation(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl);
}
public ProcessResult executeJavaws(List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl,String[] vars) throws Exception {
return executeProcessUponURL(getJavawsLocation(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl,vars);
}
public ProcessResult executeBrowser(List<String> otherargs, String resource) throws Exception {
return executeProcessUponURL(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource));
}
public ProcessResult executeBrowser(List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcessUponURL(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl);
}
public ProcessResult executeBrowser(Browser b,List<String> otherargs, String resource) throws Exception {
return executeProcessUponURL(b.getBin(), otherargs, getUrlUponThisInstance(resource));
}
public ProcessResult executeBrowser(Browser b,List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcessUponURL(b.getBin(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl);
}
/**
* Create resource on http, on 'localhost' on port on which this cached instance is running
* @param resource
* @return
* @throws MalformedURLException
*/
public URL getUrlUponThisInstance(String resource) throws MalformedURLException {
getInstance();
return getUrlUponInstance(server, resource);
}
/**
* Ctreate resource on http, on 'localhost' on port on which this instance is running
* @param resource
* @return
* @throws MalformedURLException
*/
public static URL getUrlUponInstance(ServerLauncher instance,String resource) throws MalformedURLException {
return instance.getUrl(resource);
}
/**
* wrapping method to executeProcess (eg: javaws arg arg arg url)
* will execute default javaws (@see JAVAWS_BUILD_BIN) upon any server
* @param u url of resource upon any server
* @param javaws arguments
* @return result what left after running this process
* @throws Exception
*/
public ProcessResult executeJavawsUponUrl(List<String> otherargs, URL u) throws Exception {
return executeProcessUponURL(getJavawsLocation(), otherargs, u);
}
public ProcessResult executeJavawsUponUrl(List<String> otherargs, URL u,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcessUponURL(getJavawsLocation(), otherargs, u,stdoutl,stderrl);
}
/**
* wrapping utility method to executeProcess (eg: any_binary arg arg arg url)
*
* will execute any process upon url upon any server
* @param u url of resource upon any server
* @param javaws arguments
* @return result what left after running this process
* @throws Exception
*/
public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u) throws Exception {
return executeProcessUponURL(toBeExecuted, otherargs, u,null,null);
}
public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcessUponURL(toBeExecuted, otherargs, u, stdoutl, stderrl, null);
}
public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u,ContentReaderListener stdoutl,ContentReaderListener stderrl,String[] vars) throws Exception {
Assert.assertNotNull(u);
Assert.assertNotNull(toBeExecuted);
Assert.assertTrue(toBeExecuted.trim().length() > 1);
if (otherargs == null) {
otherargs = new ArrayList<String>(1);
}
List<String> urledArgs = new ArrayList<String>(otherargs);
urledArgs.add(0, toBeExecuted);
urledArgs.add(u.toString());
return executeProcess(urledArgs, stdoutl, stderrl,vars);
}
public static ProcessResult executeProcess(final List<String> args) throws Exception {
return executeProcess(args, null);
}
public static ProcessResult executeProcess(final List<String> args,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
return executeProcess(args, null,stdoutl,stderrl);
}
public static ProcessResult executeProcess(final List<String> args,ContentReaderListener stdoutl,ContentReaderListener stderrl,String[] vars) throws Exception {
return executeProcess(args, null,stdoutl,stderrl,vars);
}
/**
* utility method to lunch process, get its stdout/stderr, its return value and to kill it if running to long (@see PROCESS_TIMEOUT)
*
*
* Small bacground:
* This method creates thread inside which exec will be executed. Then creates assassin thread with given timeout to kill the previously created thread if necessary.
* Starts assassin thread, starts process thread. Wait until process is running, then starts content readers.
* Closes input of process.
* Wait until process is running (no matter if it terminate itself (correctly or badly), or is terminated by its assassin.
* Construct result from readed stdout, stderr, process return value, assassin successfully
*
* @param args binary with args to be executed
* @param dir optional, directory where this process will run
* @return what left from process - process itself, its stdout, stderr and return value and whether it was terminated by assassin.
* @throws Exception
*/
public static ProcessResult executeProcess(final List<String> args,File dir) throws Exception {
return executeProcess(args, dir, null, null);
}
private static String createConnectionMessage(ThreadedProcess t) {
return "Connecting " + t.getCommandLine();
}
/**
* Proceed message s to logging with request to reprint to System.err
* @param s
*/
public static void logErrorReprint(String s) {
log(s, false, true);
}
/**
* Proceed message s to logging with request to reprint to System.out
* @param s
*/
public static void logOutputReprint(String s) {
log(s, true, false);
}
/**
* Proceed message s to logging withhout request to reprint
* @param s
*/
public static void logNoReprint(String s) {
log(s, false, false);
}
private static void log(String message, boolean printToOut, boolean printToErr) {
String idded;
StackTraceElement ste = getTestMethod();
String fullId = ste.getClassName() + "." + ste.getMethodName();
fullId = LoggingBottleneck.getDefaultLoggingBottleneck().modifyMethodWithForBrowser(ste.getMethodName(), ste.getClassName());
if (message.contains("\n")) {
idded = fullId + ": \n" + message + "\n" + fullId + " ---";
} else {
idded = fullId + ": " + message;
}
if (LOGS_REPRINT) {
if (printToOut) {
System.out.println(idded);
}
if (printToErr) {
System.err.println(idded);
}
}
LoggingBottleneck.getDefaultLoggingBottleneck().logIntoPlaintextLog(idded, printToOut,printToErr);
LoggingBottleneck.getDefaultLoggingBottleneck().addToXmlLog(message,printToOut,printToErr,ste);
}
public static void logException(Throwable t){
logException(t, true);
}
public static void logException(Throwable t, boolean print){
try{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
log(sw.toString(), false, print);
pw.close();
sw.close();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
private static StackTraceElement getTestMethod() {
return getTestMethod(Thread.currentThread().getStackTrace());
}
private static StackTraceElement getTestMethod(StackTraceElement[] stack) {
//0 is always thread
//1 is net.sourceforge.jnlp.ServerAccess
StackTraceElement result = stack[1];
String baseClass = stack[1].getClassName();
int i = 2;
for (; i < stack.length; i++) {
result = stack[i];//at least moving up
if(stack[i].getClassName().contains("$")){
continue;
}
if (!baseClass.equals(stack[i].getClassName())) {
break;
}
}
//if nothing left in stack then we have been in ServerAccess already
//so the target method is the highest form it and better to return it
//rather then die to ArrayOutOfBounds
if(i >= stack.length){
return result;
}
//now we are out of net.sourceforge.jnlp.ServerAccess
//method we need (the test) is highest from following class
baseClass = stack[i].getClassName();
for (; i < stack.length; i++) {
if(stack[i].getClassName().contains("$")){
continue;
}
if (!baseClass.equals(stack[i].getClassName())) {
break;
}
result = stack[i];
}
return result;
}
public static ProcessResult executeProcess(final List<String> args, File dir, ContentReaderListener stdoutl, ContentReaderListener stderrl) throws Exception {
return executeProcess(args, dir, stdoutl, stderrl,null);
}
public static ProcessResult executeProcess(final List<String> args, File dir, ContentReaderListener stdoutl, ContentReaderListener stderrl,String[] vars) throws Exception {
ThreadedProcess t = new ThreadedProcess(args, dir,vars);
if (PROCESS_LOG) {
String connectionMesaage = createConnectionMessage(t);
log(connectionMesaage, true, true);
}
ProcessAssasin pa = new ProcessAssasin(t, PROCESS_TIMEOUT);
setUpClosingListener(stdoutl, pa, t);
setUpClosingListener(stderrl, pa, t);
pa.start();
t.start();
while (t.getP() == null && t.deadlyException == null) {
Thread.sleep(100);
}
if (t.deadlyException != null) {
pa.setCanRun(false);
return new ProcessResult("", "", null, true, Integer.MIN_VALUE, t.deadlyException);
}
ContentReader crs = new ContentReader(t.getP().getInputStream(),stdoutl);
ContentReader cre = new ContentReader(t.getP().getErrorStream(),stderrl);
OutputStream out = t.getP().getOutputStream();
if (out != null) {
out.close();
}
new Thread(crs).start();
new Thread(cre).start();
while (t.isRunning()) {
Thread.sleep(100);
}
while (!t.isDestoyed()) {
Thread.sleep(100);
}
pa.setCanRun(false);
// ServerAccess.logOutputReprint(t.getP().exitValue()); when process is killed, this throws exception
ProcessResult pr=new ProcessResult(crs.getContent(), cre.getContent(), t.getP(), pa.wasTerminated(), t.getExitCode(), null);
if (PROCESS_LOG) {
log(pr.stdout, true, false);
log(pr.stderr, false, true);
}
return pr;
}
private static void setUpClosingListener(ContentReaderListener listener, ProcessAssasin pa, ThreadedProcess t) {
if (listener != null && (listener instanceof ClosingListener)) {
((ClosingListener) listener).setAssasin(pa);
((ClosingListener) listener).setProcess(t);
}
}
/**
* this is temprary solution until refactoring is fully done
* Use net.sourceforge.jnlp.ProcessResult instead
*/
@Deprecated
public static class ProcessResult extends net.sourceforge.jnlp.ProcessResult {
public ProcessResult(String stdout, String stderr, Process process, boolean wasTerminated, Integer r, Throwable deadlyException) {
super(stdout, stderr, process, wasTerminated, r, deadlyException);
}
}
}
|