-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExecuteShellCommand.java
2570 lines (2312 loc) · 73.8 KB
/
ExecuteShellCommand.java
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package knižnica.podpora;
// Toto je jedna z externých podporných tried, ku ktorým nie je priamo
// vyhotovená dokumentácia. Je to trieda, ktorú implementoval autor
// programovacieho rámca podľa predchádzajúcich projektov, aby mohol
// implementovať v programovacom rámci relatívne komplexnú funkcionalitu
// príkazu triedy Svet: spustiProces(String príkaz, String... argumenty).
// Licencia a príklady použitia sú uvedené nižšie v anglickom jazyku.
//
// (Above Slovak note tells the students the basics about this class and its
// licensing. — This source code is released under the same terms as the whole
// package knižnica.)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import javax.swing.SwingUtilities;
/**
* <p>This abstract class is intended to implement custom command line.
* It manages environment variables, current path, external processes
* including standard input and output (that can be buffered and possibly
* send from one process to another like some kind of discrete pipe). Only
* one process can be handled by one instance at a time.</p>
*
* <p>This class has been developed as a hidden part of the GRobot
* framework, thus the framework’s class Svet contains the basic
* implementation that may serve as an example (if analysed narrowly).</p>
*
* @author Roman Horváth
* @version 6. 10. 2018
*/
abstract public class ExecuteShellCommand
{
// Language strings constants.
protected final static int CANNOT_EXECUTE = 0;
protected final static int CLEARED = 1;
protected final static int COMMAND = 2;
protected final static int COMMAND_MAPPING = 3;
protected final static int COMMANDS_MAP = 4;
protected final static int DELETED = 5;
protected final static int DUPLICATE_REQUEST = 6;
protected final static int ENCODING = 7;
protected final static int ENCODING_FOR = 8;
protected final static int ENCODING_CHANGED = 9;
protected final static int ENCODING_KEEPED = 10;
protected final static int ENCODING_RESTORED = 11;
protected final static int ENCODINGS_MAP = 12;
protected final static int ERROR_MESSAGE = 13;
protected final static int ERROR_OCCURED = 14;
protected final static int EXECUTE = 15;
protected final static int EXIT_CODE = 16;
protected final static int INPUT = 17;
protected final static int IS_EMPTY = 18;
protected final static int MAPPED_COMMAND_USE = 19;
protected final static int MAPPING = 20;
protected final static int MORE_PROCESSES = 21;
protected final static int SET = 22;
protected final static int STREAM_READ_ERROR = 23;
protected final static int STREAM_WRITE_ERROR = 24;
// Language strings.
protected final static String[] langstring = new String[25]; static
{
langstring[CANNOT_EXECUTE] = "Cannot execute";
langstring[CLEARED] = "cleared"; // mapping
langstring[COMMAND] = "command"; // mapping
langstring[COMMAND_MAPPING] = "Mapping of command"; // mapping
langstring[COMMANDS_MAP] = "Commands map"; // mapping
langstring[DELETED] = "deleted"; // mapping
langstring[DUPLICATE_REQUEST] = "Duplicate request";
langstring[ENCODING] = "Current encoding";
langstring[ENCODING_FOR] = "Individual encoding for"; // mapping
langstring[ENCODING_CHANGED] = "Encoding changed";
langstring[ENCODING_KEEPED] = "Encoding keeped";
langstring[ENCODING_RESTORED] = "Encoding restored";
langstring[ENCODINGS_MAP] = "Encodings map"; // mapping
langstring[ERROR_MESSAGE] = "Error message"; // cannot execute
langstring[ERROR_OCCURED] = "Error occured"; // cannot execute
langstring[EXECUTE] = "execute"; // duplicate request
langstring[EXIT_CODE] = "Exit code";
langstring[INPUT] = "input"; // duplicate request
langstring[IS_EMPTY] = "is empty"; // mapping
langstring[MAPPED_COMMAND_USE] = "Using mapped command";
langstring[MAPPING] = "mapping"; // mapping
langstring[MORE_PROCESSES] = "more than one process"; // cannot execute
langstring[SET] = "set"; // mapping
langstring[STREAM_READ_ERROR] = "Stream read error";
langstring[STREAM_WRITE_ERROR] = "Stream write error";
}
// Global map of environment variables.
private final static TreeMap<String, String> originalEnvironment =
new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); static
{
Map<String, String> envMap = System.getenv();
if (null != envMap) originalEnvironment.putAll(envMap);
}
// Global variable storing the running path of current process (JVM).
private final static String defaultPath; static
{
String getPath = ".";
try { getPath = new File(".").getCanonicalPath(); }
catch (Throwable t) { /*ignore*/ }
defaultPath = getPath;
}
// Current path – if not null overrides the default path (which is the
// current JVM running path).
private String currentPath = null;
// Global variable storing the current user name.
private final static String userName; static
{
String getUserName = null;
try { getUserName = System.getProperty("user.name"); }
catch (Throwable t) { /*ignore*/ }
userName = getUserName;
}
// Global variable storing the localhost machine name.
private final static String localHostName; static
{
String getLocalHostName = null;
try
{
InetAddress localHost = InetAddress.getLocalHost();
getLocalHostName = localHost.getHostName();
}
catch (Throwable t) { /*ignore*/ }
localHostName = getLocalHostName;
}
// Global refference to empty array of strings.
private final static String[] emptyRefStringArray = new String[0];
// Global constant for end of line character.
private final static char EOL = '\n';
// Global instance of ExpressionProcessor (used by the “setVariable”
// method).
private final static ExpressionProcessor expression =
new ExpressionProcessor();
/**
* <p>Default date format. Use its method applyPattern or
* applyLocalizedPattern to adjust the format.</p>
*/
public final static SimpleDateFormat dateFormat =
new SimpleDateFormat("dd. MM. yyyy");
/**
* <p>Default time format. Use its method applyPattern or
* applyLocalizedPattern to adjust the format.</p>
*/
public final static SimpleDateFormat timeFormat =
new SimpleDateFormat("HH:mm:ss");
// Local map of environment variables.
private final TreeMap<String, String> internalEnvironment =
new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
// Local list of executable files extensions.
private final TreeSet<String> pathExt = new TreeSet<String>(
String.CASE_INSENSITIVE_ORDER); { resetPathExt(); }
// Resets the content of the “pathExt” set.
private void resetPathExt()
{
pathExt.clear();
String getPathExt = getVariable("PATHEXT");
if (null != getPathExt)
{
String[] extSet = getPathExt.
split(File.pathSeparator);
for (String ext : extSet)
if (null != ext && !ext.isEmpty())
pathExt.add(ext);
}
}
// Map of encodigns customized for selected commands.
private final TreeMap<String, String> encodingsMap =
new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
// Map of commands (substitutions).
private final TreeMap<String, String> commandsMap =
new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
// Prompt and title…
private String defaultPrompt = "\n%CD%>"; // Prompt to be saved in config.
private String promptString = "\n%CD%>";
private String defaultTitle = null; // Title to be saved in config.
private String titleString = null;
// Flag signaling that this instance awaits an extra input.
private boolean waitingForExtraInput = false;
// Flag signaling that the next extra input should be evaluated as
// expression.
private boolean evaluateExtraInput = false;
// Last extra input string (the read started by the “startExtraInput”
// method and finished in the “writeInput” method.
private String lastExtraInput = "";
// Current error level. E.g. result code of build-in command, last exit
// code of a finished process…
private int errorLevel = 0;
// Current encoding, default encoding and encoding backup.
private String currentEncoding = "UTF-8";
private String defaultEncoding = "UTF-8";
private String restoreEncoding = null;
// Stored last executed shell command line.
private String runCommand = null;
// Stored last executed shell command arguments.
private String[] runArguments = null;
// Stored last actual command array used to run the process.
private String[] commandArray = null;
// Stored the environment variables array used at a time of launching
// the currently running process.
private String[] runEnvironment = null;
// A thread of currently running process.
private Thread runningThread = null;
// Currently running process.
private Process runningProcess = null;
// Input stream of currently running process.
private BufferedWriter inputWriter = null;
// Error output stream of currently running process.
private StreamPrinter errorPrinter = null;
// Output stream of currently running process.
private StreamPrinter outputPrinter = null;
/**
* <p>Splits entered command to array of strings. The result contains
* array of strings split by escape rules. See the “makeCommandArray”
* method.</p>
*
* @param command command to be split
* @return split command
*/
public static String[] splitCommand(String command)
{
// See the “makeCommandArray” method’s body for more explanatory
// comments.
Vector<String> cmdArray = new Vector<String>();
if (-1 == command.indexOf('"') &&
-1 == command.indexOf('\\') &&
-1 == command.indexOf(' ') &&
-1 == command.indexOf('^'))
{
cmdArray.add(command);
}
else
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < command.length(); ++i)
{
char ch = command.charAt(i);
if (' ' == ch)
{
cmdArray.add(builder.toString());
builder.setLength(0);
}
else if ('\\' == ch && (i + 1) < command.length())
{
ch = command.charAt(++i);
if ('"' == ch || ' ' == ch)
builder.append(ch);
else
{
builder.append('\\');
builder.append(ch);
}
}
else if ('^' == ch && (i + 1) < command.length())
{
ch = command.charAt(++i);
if ('"' == ch || '^' == ch || '&' == ch ||
'<' == ch || '>' == ch || '|' == ch)
builder.append(ch);
else
{
builder.append('^');
builder.append(ch);
}
}
else if ('"' == ch)
{
for (++i; i < command.length(); ++i)
{
ch = command.charAt(i);
if ('"' == ch) break;
if ((i + 1) < command.length())
{
if ('\\' == ch)
{
ch = command.charAt(++i);
if ('"' == ch)
builder.append(ch);
else
{
builder.append('\\');
builder.append(ch);
}
}
else if ('^' == ch)
{
ch = command.charAt(++i);
if ('"' == ch || '^' == ch || '&' == ch ||
'<' == ch || '>' == ch || '|' == ch)
builder.append(ch);
else
{
builder.append('^');
builder.append(ch);
}
}
else
builder.append(ch);
}
else
builder.append(ch);
}
}
else
builder.append(ch);
}
if (0 != builder.length())
cmdArray.add(builder.toString());
}
return cmdArray.toArray(emptyRefStringArray);
}
/**
* <p>This static method creates the command/arguments array of strings
* to be executed. Arguments in the “argStrings” parameter are processed
* as space-separated list, but the spaces in selected elements may be
* preserved using quotes or escape sequences. The first valid string is
* considered as the executable command and the others are its command
* line arguments.</p>
*
* <p>The strings passed as arguments to this method are not joined
* together. Each string is processed as standalone
* (space-separated/quoted/escaped) list. Not only spaces, but also
* some other reserved characters may be preserved using two methods
* (mentioned already): quotes (e.g. "foo bar" foo "bar" means three
* arguments: foo bar, foo, bar) and escape sequences using the
* backslash (\) or the caret (^) character – see the “execute” method
* for the complete list of valid escape sequences.</p>
*
* <p>If the “command” parameter is null, it is ignored and next split
* string in the “argStrings” list becomes the command. If some other
* parameter is null, the next parameter will be preserved without any
* processing (even if it’s null – two subsequent nulls will create one
* null string in the returned array).</p>
*
* @param command the string that becomes the command (executable) or null
* @param argStrings the list of command line arguments; except, if the
* first parameter is null, it includes the executable, too
* @return the array of string representing the command line array, usually
*/
public static String[] makeCommandArray(String command, String... argStrings)
{
Vector<String> cmdArray = new Vector<String>();
StringBuilder builder = new StringBuilder();
if (null != command) cmdArray.add(command);
boolean nextIsFull = false;
for (String argString : argStrings)
{
if (nextIsFull)
{
cmdArray.add(argString);
nextIsFull = false;
}
else if (null == argString)
{
nextIsFull = true;
}
else if (-1 == argString.indexOf('"') &&
-1 == argString.indexOf('\\') &&
-1 == argString.indexOf(' ') &&
-1 == argString.indexOf('^'))
{
cmdArray.add(argString);
}
else
{
builder.setLength(0);
for (int i = 0; i < argString.length(); ++i)
{
char ch = argString.charAt(i);
if (' ' == ch)
{
// Space will break the argument into two separate
// elements of the final array.
cmdArray.add(builder.toString());
builder.setLength(0);
}
else if ('\\' == ch && (i + 1) < argString.length())
{
// Backslash within command line has special
// behaviour. It backslashes only two characters:
// the quotation mark (") and the space ( ).
ch = argString.charAt(++i);
if ('"' == ch || ' ' == ch)
builder.append(ch);
else
{
builder.append('\\');
builder.append(ch);
}
}
else if ('^' == ch && (i + 1) < argString.length())
{
// The caret acts like another escape character.
// It escapes the characters listed below:
ch = argString.charAt(++i);
if ('"' == ch || '^' == ch || '&' == ch ||
'<' == ch || '>' == ch || '|' == ch)
builder.append(ch);
else
{
// Invalid escape sequences are kept intouched.
builder.append('^');
builder.append(ch);
}
}
else if ('"' == ch)
{
// Quotation mark joins everything until next
// quotation mark unless it is an escaped one.
for (++i; i < argString.length(); ++i)
{
ch = argString.charAt(i);
if ('"' == ch) break;
if ((i + 1) < argString.length())
{
if ('\\' == ch)
{
ch = argString.charAt(++i);
if ('"' == ch)
// (Only quotes can be escaped here.)
builder.append(ch);
else
{
builder.append('\\');
builder.append(ch);
}
}
else if ('^' == ch)
{
ch = argString.charAt(++i);
if ('"' == ch || '^' == ch || '&' == ch ||
'<' == ch || '>' == ch || '|' == ch)
builder.append(ch);
else
{
builder.append('^');
builder.append(ch);
}
}
else
builder.append(ch);
}
else
builder.append(ch);
}
}
else
builder.append(ch);
}
if (0 != builder.length())
cmdArray.add(builder.toString());
}
}
return cmdArray.toArray(emptyRefStringArray);
}
/**
* <p>Attempts to match the command with at least one of the entered
* matches. The comparison is case insensitive. If at least one
* match is positive, the return value is array containing three elements.
* The first element is the code of match type (see below), the second
* element is the index of matching argument, and the third element
* is the length of the match (pointing to the start of the command’s
* arguments and thus further called as the arguments’ pointer). In case
* of no match the null is returned.</p>
*
* <p>Only non-empty non-null arguments are considered. The match may
* be one of this three types: 1. the whole command match (in that case
* the arguments’ pointer will be equal to the length of the command),
* 2. the match with the command separated from the arguments by at
* least one space (in that case the first space will not be included
* in the arguments’ pointer), or 3. the match with the command not
* separated from the arguments at all (in that case the arguments’
* pointer will be equal to the lenght of the matching string).</p>
*
* @param command the command (possibly with arguments) to match
* @param matches list of strings to be matched with
* @return index of arguments’ start or −1
*/
public static int[] matchCommand(String command, String... matches)
{
if (null == command || command.isEmpty()) return null;
command = command.toLowerCase();
int i = -1;
for (String match : matches)
{
++i;
if (null == match || match.isEmpty()) continue;
match = match.toLowerCase();
if (command.equals(match))
return new int[] {1, i, match.length()};
if (command.startsWith(match + " "))
return new int[] {2, i, 1 + match.length()};
if (command.startsWith(match))
return new int[] {3, i, match.length()};
}
return null;
}
/**
* <p>Encloses the string in quotation marks if it contains space or
* quotation mark. The quotation marks inside are escaped by
* backslashes.</p>
*
* @param string string to be quoted or kept
* @return original string or quoted string
*/
public static String quoteSpacedString(String string)
{
if (-1 == string.indexOf(' ') &&
-1 == string.indexOf('"')) return string;
return "\"" + string.replace("\"", "\\\"") + "\"";
}
/**
* <p>Escapes new lines (and backslashes) by the backslash characters.
* Used on expanding the %PROMPT% virtual variable’s value.</p>
*
* @param value string to be escaped
* @return escaped string
*/
public static String escapeNewLines(String value)
{
if (-1 != value.indexOf('\n') || -1 != value.indexOf('\r') ||
-1 != value.indexOf('\\'))
{
StringBuilder escaped = new StringBuilder(value);
int indexOf = 0;
while (-1 != (indexOf = escaped.indexOf("\\", indexOf)))
{
escaped.replace(indexOf, indexOf + 1, "\\\\");
indexOf += 2;
}
indexOf = 0;
while (-1 != (indexOf = escaped.indexOf("\n", indexOf)))
escaped.replace(indexOf, indexOf + 1, "\\n");
indexOf = 0;
while (-1 != (indexOf = escaped.indexOf("\r", indexOf)))
escaped.replace(indexOf, indexOf + 1, "\\r");
value = escaped.toString();
}
return value;
}
/**
* <p>Returns the stack trace of specified throwable object as
* string.</p>
*
* @param t any throwable instance
* @return string containing stack trace of t
*/
public static String stackTraceToString(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
/**
* <p>Sends strings and the new line character (EOL) to the debugging
* stream.</p>
*
* @param strings strings to send
*/
public void debugLine(Object... strings)
{
debug(strings);
debug(EOL);
}
/**
* <p>Logs strings and puts new line character (EOL) to the end.</p>
*
* @param strings strings to be logged
*/
public void logLine(Object... strings)
{
log(strings);
log(EOL);
}
/**
* <p>Logs error strings and puts new line character (EOL) to the
* end.</p>
*
* @param strings strings to be put to current error log
*/
public void errLine(Object... strings)
{
err(strings);
err(EOL);
}
/**
* <p>Writes out error strings to standard error and puts new line
* character (EOL) after them.</p>
*
* @param strings strings to be put to current error stream
*/
public void errorLine(Object... strings)
{
error(strings);
error(EOL);
}
/**
* <p>Writes out the strings to standard output and puts new line
* character (EOL) after them.</p>
*
* @param strings strings to be put to current output stream
*/
public void outputLine(Object... strings)
{
output(strings);
output(EOL);
}
/**
* <p>Should take such action that corresponds to the application’s
* main window title change.</p>
*
* @param title the new window title
*/
abstract public void title(String title);
/**
* <p>Should return the current version of the implementation.</p>
*/
abstract public String getVersion();
/**
* <p>Starts extra input announced by specified prompt. The method may
* return the new value for the %READ% variable or returns null if the
* value should be processed (received) later by manual invoke of the
* “writeInput” method. This input may be triggered by the “setVariable”
* method (see its description for more information).</p>
*
* @param prompt the prompt for the extra input
* @return the new value or null
*/
abstract public String startExtraInput(String prompt);
/**
* <p>Finishes the extra input allowing to modify the entered value or
* cancel the process. This method receives the value to be stored in
* the %READ% variable. This is the last chance to modify or cancel the
* input. If the string should be accepted, the modified or original
* string must be returned. If this method returns the null value, the
* value of the %READ% variable stays untouched.</p>
*
* @param value the new value to be stored in the %READ% variable
* @return the original or modified value; null means “cancel”
*/
abstract public String finishExtraInput(String value);
/**
* <p>Should clear (or reset) the debugging stream. Triggered on each
* invoke of method that uses the stream.</p>
*
* @param method method that triggered this event
*/
abstract public void clearDebug(String method);
/**
* <p>Should clear (or reset) the log. Triggered on each invoke of method
* that uses the log.</p>
*
* @param method method that triggered this event
*/
abstract public void clearLog(String method);
/**
* <p>Should clear (or reset) the error log. Triggered on each invoke of
* method that uses the error log.</p>
*
* @param method method that triggered this event
*/
abstract public void clearErr(String method);
/**
* <p>Should clear the error buffer (or put ASCII code 12 to the buffer).
* Triggered by the last ASCII code 12 within one line sent to the error
* stream.</p>
*/
abstract public void clearError();
/**
* <p>Should clear the output buffer (or put ASCII code 12 to the
* buffer). Triggered by the last ASCII code 12 within one line sent to
* the output stream.</p>
*/
abstract public void clearOutput();
/**
* <p>Should redirect the strings to the debugging stream. (This
* implementation does not produce lots of debugging messages. There
* are only few connected to the “execute” method.)</p>
*
* @param strings strings to send
*/
abstract public void debug(Object... strings);
/**
* <p>Should put strings to the log. These are the messages
* produced by this class internally.</p>
*
* @param strings strings to be logged
*/
abstract public void log(Object... strings);
/**
* <p>Should put strings to the error log. These are the messages
* produced by this class internally.</p>
*
* @param strings strings to be put to current error log
*/
abstract public void err(Object... strings);
/**
* <p>Should put strings to the output error buffer catching from
* the current process.</p>
*
* @param strings strings to be put to current error stream
*/
abstract public void error(Object... strings);
/**
* <p>Should put strings to the standard output buffer catching from
* the current process.</p>
*
* @param strings strings to be put to current output stream
*/
abstract public void output(Object... strings);
/**
* <p>Invoked after the last executed process terminates its
* activity. Receives its exit code.</p>
*
* @param exitCode exit code of the process that finished recently
*/
abstract public void processEnded(int exitCode);
/**
* <p>The thread class for handling the standard output and standard error
* streams of currently active process.</p>
*/
public class StreamPrinter extends Thread implements Closeable
{
private final InputStream is;
private final boolean errorFlag;
private boolean forceBreak = false;
// Reads everything from “is” until empty.
StreamPrinter(InputStream is, boolean errorFlag)
{
this.is = is;
this.errorFlag = errorFlag;
}
public void run()
{
try
{
InputStreamReader isr =
new InputStreamReader(
is, currentEncoding);
BufferedReader br =
new BufferedReader(isr);
String line;
while (null != (line = br.readLine()))
{
if (forceBreak) break;
// Handle the clear screen…
if (-1 != line.indexOf((char)12))
{
int lastIndexOf = line.lastIndexOf((char)12);
String linePart = line.substring(0, lastIndexOf);
line = line.substring(1 + lastIndexOf);
if (errorFlag)
{
error(linePart);
clearError();
if (!line.isEmpty())
errorLine(line);
}
else
{
output(linePart);
clearOutput();
if (!line.isEmpty())
outputLine(line);
}
}
else
{
if (errorFlag)
errorLine(line);
else
outputLine(line);
}
}
}
catch (IOException ioe)
{
errLine(langstring[STREAM_READ_ERROR], '.',
EOL, ioe.getMessage());
debugLine(stackTraceToString(ioe));
}
}
public void close()
{
forceBreak = true;
}
}
/**
* <p>Checks if there is some process active. Returns true if there is
* a process currently active (running).</p>
*
* @return true if a process is currently running
*/
public boolean isProcessRunning()
{ return null != runningThread; }
/**
* <p>If there is a process running, this method returns the string
* that was passed to the “execute” method that launched the process
* as its “command” parameter. This may be null even if the process
* is running. In that case the method took for the command the first
* element of the “arguments” array – see the “getRunArguments”
* method.</p>
*
* @return null or the string passed to the “execute” method when it
* launched the current process
*/
public String getRunCommand()
{ return runCommand; }
/**
* <p>If there is a process running, this method returns the array
* of strings that was passed to the “execute” method that launched
* the process as its “arguments” parameter. This may be null even if
* the process is running. In that case the method took for the command
* the first element of the “arguments” array – see the “getRunArguments”
* method.</p>
*
* @return null or the array passed to the “execute” method when it
* launched the current process
*/
public String[] getRunArguments()
{ return runArguments; }
/**
* <p>If there is a process running, this method returns the actual
* command array used to run the process. The first element of the
* array is the executable and the other elements are the arguments.
* If there is no process running, the method returns null.</p>
*
* @return the actual command array used to create current process
*/
public String[] getCommandArray()
{ return commandArray; }
/**
* <p>If there is a process running, this method returns the
* environment variables array used at a time of launching the
* currently running process. If there is no process running, the
* method returns null.</p>
*
* @return the array of environment variables used at a time of
* launching the current process
*/
public String[] getRunEnvironment()
{ return runEnvironment; }
/**
* <p>Gets instance of the currently running process or null. The
* returned instance may be used e.g. to kill the process.</p>
*
* @return the instance of currently running process
*/
public Process getRunningProcess()
{ return runningProcess; }
/**
* <p>Expands the string searching for local, global, and virtual
* environment variables. The few virtual variables are (to be more
* schematic their names are enclosed in % already):</p>
*
* <ul>
* <li>%ERRORLEVEL% – return code of last executed process/command that
* has finished already (the exit code of last finished process or
* internal command in some cases),</li>