-
Notifications
You must be signed in to change notification settings - Fork 6
/
Builtin.java
1181 lines (951 loc) · 30 KB
/
Builtin.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 biz.aQute.gogo.commands.provider;
import static java.nio.file.Files.newOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Descriptor;
import org.apache.felix.service.command.Parameter;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import aQute.lib.converter.Converter;
import aQute.lib.fileset.FileSet;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.libg.glob.Glob;
import biz.aQute.gogo.commands.dtoformatter.DTOFormatter;
/**
* gosh built-in commands.
*/
public class Builtin {
private static final String EXCEPTION = "exception";
private static final String[] packages = {
"java.lang", "java.io", "java.net", "java.util"
};
final List<String> imports = new ArrayList<>();
{
imports.addAll(Arrays.asList(packages));
}
final BundleContext context;
final DTOFormatter dtof;
public Builtin(BundleContext context, DTOFormatter dtof) {
this.context = context;
this.dtof = dtof;
dtof.build(Class.class)
.inspect()
.method("name")
.format("bundle", this::loader)
.format("super", Class::getSuperclass)
.line()
.method("name")
.format("bundle", this::loader)
.part()
.as(c -> c.getName());
}
/**
* NEW
*/
@Descriptor("Create a new object, constructor parameters can be passed")
public Object _new(CommandSession session,
//@formatter:off
@Parameter(presentValue = "true", absentValue = "false", names= {"-a", "--accessible"})
@Descriptor("Make the constructor accessible")
boolean accessible,
@Descriptor("The class or its name")
Object _class,
@Descriptor("The constructor arguments. The first matching constructor is used")
Object ...argv
//@formatter:on
) throws Throwable {
Class<?> clazz = null;
if (_class instanceof Class<?>) {
clazz = (Class<?>) _class;
} else {
clazz = loadClass(session, _class.toString());
}
constructor: for (Constructor<?> c : clazz.getConstructors()) {
if (!accessible && !c.isAccessible()) {
continue constructor;
}
c.setAccessible(accessible);
if (c.getParameterCount() != argv.length)
continue;
java.lang.reflect.Parameter[] parameters = c.getParameters();
for (int i = 0; i < c.getParameterCount(); i++) {
Object value = argv[i];
Class<?> type = parameters[i].getType();
if (!type.isInstance(value))
continue constructor;
}
try {
return c.newInstance(argv);
} catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
// Try to match by converting parameters
constructor: for (Constructor<?> c : clazz.getConstructors()) {
Type[] types = c.getGenericParameterTypes();
if (types.length != argv.length) {
continue;
}
Object[] parameters = new Object[types.length];
for (int i = 0; i < argv.length; ++i) {
try {
parameters[i] = Converter.cnv(types[i], argv[i]);
} catch (Exception e) {
continue constructor;
}
}
try {
return c.newInstance(parameters);
} catch (InvocationTargetException ite) {
// ignore, look for next
}
}
throw new IllegalArgumentException(
"can't coerce " + Arrays.asList(argv) + " to any of " + Arrays.asList(clazz.getConstructors()));
}
/**
* IMPORT
*/
@Descriptor("Add to the imports that are searched for loadclass")
public List<String> imports(String... packages) {
if (packages.length == 0)
return imports;
imports.addAll(Arrays.asList(packages));
return Collections.emptyList();
}
/**
* VARS
*/
@Descriptor("Show the session variables")
public Object vars(CommandSession session,
// @formatter:off
@Descriptor("show all variables, including private variables starting with '.', s")
@Parameter(absentValue = "false", presentValue="true", names = {
"-a", "--all"
})
boolean all,
@Descriptor("Globs, if one of the globs match, the variable is shown. Providing no globs will list all except for private variables")
Glob ...globs
// @formatter:on
) {
Map<String, Object> variables = getVariables(session);
if (all && globs.length == 0)
return variables;
variables = variables.entrySet()
.stream()
.filter(e -> !e.getKey()
.startsWith("."))
.filter(e -> {
if (globs.length == 0)
return true;
for (Glob g : globs) {
if (g.matches(e.getKey()))
return true;
}
return false;
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (globs.length == 1) {
return variables.values()
.iterator()
.next();
}
return variables;
}
/**
* TAC
*/
@Descriptor("Copy the input to a file")
public void tac(CommandSession session,
//@formatter:off
@Descriptor("If the output file exists, append the output instead of creating a new file")
@Parameter(absentValue = "false", presentValue="true", names = {
"-a", "--append"
})
boolean append,
@Descriptor("Show progress")
@Parameter(absentValue = "false", presentValue="true", names = {
"-p", "--progress"
})
boolean progress,
@Descriptor("The output file. If this is relative, it will be resolved against the current Gogo directory")
File file
//@formatter:off
) throws IOException {
Path path = makeAbsolute(session, file);
OutputStream out = newOutputStream(path, append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
List<Function<Character,String>> ops = new ArrayList<>();
if ( progress )
ops.add( progress(session) );
copy(System.in, out, ops);
}
@Descriptor("Copy a file to stdout, the unix cat command")
public void cat(CommandSession session,
// @formatter:off
@Descriptor("Number the non-blank output lines, starting at 0.")
@Parameter(absentValue="false", presentValue="true", names = {"-n", "--number"})
boolean number,
@Descriptor("Print non visible characters as \\uXXXX")
@Parameter(absentValue="false", presentValue="true", names = {"-u", "--unprintable"})
boolean unprintable,
@Descriptor("Squeeze multiple adjacent empty lines, causing the output to be single spaced.")
@Parameter(absentValue="false", presentValue="true", names = {"-s", "--squeeze"})
boolean squeeze,
@Descriptor("Print out each character in hex")
@Parameter(absentValue="false", presentValue="true", names = {"-h", "--hex"})
boolean hex,
@Descriptor("The input files, relative to the Gogo sessions current directory. If no file is specified, copy from stdin")
File ... inputs
//@formatter:on
) throws Exception {
List<Function<Character, String>> ops = getOps(number, unprintable, squeeze, hex);
if (inputs.length == 0)
copy(System.in, System.out, ops);
for (File input : inputs) {
Path path = makeAbsolute(session, input);
InputStream in = IO.stream(path);
copy(in, System.out, ops);
}
System.out.println();
}
@Descriptor("Echo the arguments to the command line")
public void echo(
// @formatter:off
@Parameter(absentValue="false", presentValue="true",names={"-s","--skip"})
@Descriptor("Skip space between arguments")
boolean skip,
@Descriptor("Any arguments to print. Arguments will be printed with a space separator unless -s is set")
Object... args
// @formatter:on
) {
String del = "";
for (Object o : args) {
o = unescape(o);
System.out.printf("%s%s", del, o);
if (!skip)
del = " ";
}
System.out.println();
}
@Descriptor("Return a unicode character based on a hex value or named")
public char u(
@Descriptor("The hexaddecimal value for a character or one of tab,cr,bs,ff,lf,nl,esc")
String hex) {
switch (hex.toLowerCase()) {
case "tab" :
return '\t';
case "cr" :
return '\r';
case "bs" :
return '\b';
case "ff" :
return '\f';
case "lf" :
case "nl" :
return '\n';
case "esc" :
return '\u001B';
}
return (char) Integer.parseInt(hex, 16);
}
@Descriptor("Grep input or files for matching glob expressions")
public boolean grep(CommandSession session,
//@formatter:off
@Descriptor("Select non-matching lines")
@Parameter(absentValue="false", presentValue="true",names= {"-v", "--negate", "--invert-match"})
boolean negate,
@Descriptor("Show relative filename")
@Parameter(absentValue="false", presentValue="true",names= {"-r", "--relative"})
boolean relative,
@Descriptor("Ignore case")
@Parameter(absentValue="false", presentValue="true",names= {"-i", "--ignorecase"})
boolean ignorecase,
@Descriptor("Suppress all normal output")
@Parameter(absentValue="false", presentValue="true",names= {"-q", "--silent"})
boolean quiet,
@Descriptor("Provide line & file name for matches")
@Parameter(absentValue="false", presentValue="true",names= {"-n", "--number"})
boolean number,
@Descriptor("A glob expression")
String match,
@Descriptor("Files to search, this can use ant like globbing for files")
String...files
//@formatter:on
) throws IOException {
int flags = 0;
if (ignorecase) {
flags |= Pattern.CASE_INSENSITIVE;
}
Glob glob = new Glob(match, flags);
Predicate<String> matches;
if (negate) {
matches = s -> glob.finds(s) < 0;
} else {
matches = s -> glob.finds(s) >= 0;
}
List<Function<Character, String>> ops = new ArrayList<>();
boolean found = false;
if (files.length == 0)
found = grep(System.in, System.out, matches, quiet, number ? "" : null);
else {
Collection<File> fileset = files(session, session.currentDir()
.toFile(), files);
for (File f : fileset) {
InputStream in = IO.stream(f);
found |= grep(in, System.out, matches, quiet,
number ? (relative ? f.getName() : f.getAbsolutePath()) : null);
}
}
return found;
}
@Descriptor("Map each element")
public List<Object> each(CommandSession session,
//@formatter:off
@Descriptor("A collection or array of any object passed as the the first argument ($1 or $it). This function is normally referred to as 'map'")
Collection<Object> list,
@Descriptor("The closure that is executed for each object in the list. The closure can use $it to refer to the object. The resulting value will be returned in a list at the same position as $it")
org.apache.felix.service.command.Function closure
//@formatter:on
) throws Exception {
List<Object> results = new ArrayList<>();
for (Object x : list) {
Object value = closure.execute(session, Collections.singletonList(x));
results.add(value);
}
return results;
}
@Descriptor("Filter a list")
public List<Object> filter(CommandSession session,
//@formatter:off
@Descriptor("A collection or array of any object passed as the the first argument ($1 or $it). This function is normally referred to as 'map'")
Collection<Object> list,
@Descriptor("The closure that is executed for each object in the list. The closure can use $it to refer to the object. The resulting value will be returned in a list at the same position as $it")
org.apache.felix.service.command.Function closure
//@formatter:on
) throws Exception {
List<Object> results = new ArrayList<>();
for (Object x : list) {
Object value = closure.execute(session, Collections.singletonList(x));
if (isTrue(value))
results.add(x);
}
return results;
}
@Descriptor("if condition if-action else-action –– The condition and actions can be a normal object or a function. In the case of a function it is executed and the resulting value is used.")
public Object _if(CommandSession session,
//@formatter:off
@Descriptor("The condition. If a function, it will be executed and the result is used")
Object condition,
@Descriptor("The result when the condition is true. If a function, it will be executed and the result is used")
Object action,
@Descriptor("The result when the condition is false. If a function, it will be executed and the result is used")
Object elseAction
//@formatter:on
) throws Exception {
if (isTrue(execute(session, condition)))
return execute(session, action);
else
return execute(session, elseAction);
}
@Descriptor("if condition if-action –– The condition and actions can be a normal object or a function. In the case of a function it is executed and the resulting value is used. If the condition is false, null is returned")
public Object _if(CommandSession session,
//@formatter:off
@Descriptor("The condition. If a function, it will be executed and the result is used")
Object condition,
@Descriptor("The result when the condition is true. If a function, it will be executed and the result is used")
Object action
//@formatter:on
) throws Exception {
return _if(session, condition, action, null);
}
@Descriptor("a greater than b")
public boolean gt(String a, String b) {
return a.compareTo(b) > 0;
}
@Descriptor("a greater than b")
public boolean gt(long a, long b) {
return a > b;
}
@Descriptor("Greater Than or Equal")
public boolean gte(long n1, long n2) {
return n1 >= n2;
}
@Descriptor("Greater Than or Equal")
public boolean gte(String n1, String n2) {
return n1.compareTo(n2) >= 0;
}
@Descriptor("Greater Than or Equal")
public boolean gte(double n1, double n2, double epsilon) {
return n1 > (n2 - epsilon) || eq(n1, n2, epsilon);
}
@Descriptor("Equal with epsilon")
public boolean eq(double n1, double n2, double epsilon) {
return n1 > n2 - epsilon && n1 < n2 + epsilon;
}
@Descriptor("Compare equal")
public boolean eq(long n1, long n2) {
return n1 == n2;
}
@Descriptor("Compare equal")
public boolean eq(@Descriptor("Ignore case")
@Parameter(absentValue = "false", presentValue = "true", names = {
"-i", "--ignorecase"
})
boolean ignorecase, String n1, String n2) {
if (ignorecase)
return n1.toLowerCase()
.compareTo(n2.toLowerCase()) == 0;
else
return n1.compareTo(n2) == 0;
}
@Descriptor("Less Than")
public boolean lt(long n1, long n2) {
return n1 < n2;
}
@Descriptor("Less than")
public boolean lt(String n1, String n2) {
return n1.compareTo(n2) < 0;
}
@Descriptor("Less Than or Equal")
public boolean lte(long n1, long n2) {
return n1 <= n2;
}
@Descriptor("Less than or Equal")
public boolean lte(String n1, String n2) {
return n1.compareTo(n2) <= 0;
}
@Descriptor("Add numbers together")
public long plus(
@Descriptor("Numbers to add")
long... others) {
long acc = 0;
for (int i = 0; i < others.length; i++)
acc += others[i];
return acc;
}
@Descriptor("Subtract")
public long sub(long n1, long n2) {
return n1 - n2;
}
@Descriptor("Multiply")
public long mul(long... others) {
long acc = 1;
for (int i = 0; i < others.length; i++)
acc *= others[i];
return acc;
}
@Descriptor("Divide")
public long div(long n1, long n2) {
return n1 / n2;
}
@Descriptor("Modulo")
public Object mod(long n1, long n2) {
return n1 % n2;
}
@Descriptor("Not a Number (NaN)")
public double nan() {
return Double.NaN;
}
@Descriptor("not expr –– The expression can be a normal object or a function. In the case of a function it is executed and the resulting value is used.")
public boolean not(CommandSession session, Object value) throws Exception {
return !isTrue(execute(session, value));
}
@Descriptor("throw a message as an IllegalArgumentException")
public void _throw(
//@formatter:off
@Descriptor("The message to throw.")
String message
//@formatter:on
) {
throw new IllegalArgumentException(message);
}
@Descriptor("throw the last throw exception")
public void _throw(CommandSession session) throws Throwable {
Object exception = session.get(EXCEPTION);
if (exception instanceof Throwable)
throw (Throwable) exception;
else
throw new IllegalArgumentException("exception not set or not Throwable.");
}
@Descriptor("run a function but catch any exceptions. If an exception is thrown, it is placed in `exception`. If an exception is thrown, null will be returned")
public Object _try(CommandSession session,
//@formatter:off
@Descriptor("The function will be called but any exceptions are ignored.")
org.apache.felix.service.command.Function func
//@formatter:off
) {
try {
return execute(session, func);
} catch (Exception e) {
session.put(EXCEPTION, e);
return null;
}
}
@Descriptor("run a function and catch the exceptions. If an exception is thrown, it is placed in `exception` and passed as a parameter to the error function")
public Object _try(CommandSession session,
//@formatter:off
@Descriptor("The function will be called but any exceptions are forwarded to the error, if it is a function")
org.apache.felix.service.command.Function func,
@Descriptor("Return value when an exception is thrown. If error is a function, it is called and passed the exception thrown")
Object error
//@formatter:off
) throws Exception {
try {
return execute(session, func);
} catch (Exception e) {
session.put(EXCEPTION, e);
return execute(session, error, e);
}
}
@Descriptor("Run a function while the executed condition returns true")
public void _while(CommandSession session,
//@formatter:off
@Descriptor("The condition function, repeats as long as this returns true")
org.apache.felix.service.command.Function condition,
@Descriptor("The body function, repeats as long as the condtions is true")
org.apache.felix.service.command.Function ifTrue
//@formatter:off
) throws Exception {
while (isTrue(condition.execute(session, null))) {
ifTrue.execute(session, null);
}
}
@Descriptor("Excecute a script from a URL")
public void source(CommandSession session,
//@formatter:off
@Parameter(absentValue="false", presentValue="true", names= {"-x", "--xtrace"})
@Descriptor("Trace the commands while executing")
boolean xtrace,
@Descriptor("The url to source the script from")
URL url
//@formatter:off
) throws Exception {
source0(session, xtrace, IO.collect(url.openStream()));
}
@Descriptor("Excecute scripts from files. File names are relative from the current Gogo dir. If no files are specified, the script is read from System.in")
public void source(CommandSession session,
//@formatter:off
@Parameter(absentValue="false", presentValue="true", names= {"-x", "--xtrace"})
@Descriptor("Trace the commands while executing")
boolean xtrace,
@Descriptor("File specifications. It is possible to use ant like file set expressions. If no files are specified, System.in is read")
String... files
//@formatter:on
) throws Exception {
if (files.length == 0) {
source0(session, xtrace, IO.collect(System.in));
} else {
Collection<File> fs = files(session, session.currentDir()
.toFile(), files);
for (File f : fs) {
source0(session, xtrace, IO.collect(f));
}
}
}
@Descriptor("Excecute scripts from files. File names are relative from the current Gogo dir. If no files are specified, the script is read from System.in")
public void source(CommandSession session,
//@formatter:off
@Parameter(absentValue="false", presentValue="true", names= {"-x", "--xtrace"})
@Descriptor("Trace the commands while executing")
boolean xtrace,
@Descriptor("A line to execute")
String source
//@formatter:on
) throws Exception {
source0(session, xtrace, source);
}
@Descriptor("Return an array of longs")
public long[] range(long lowInclusive, long highExclusive) {
if (lowInclusive >= highExclusive)
return new long[0];
long[] result = new long[(int) (highExclusive - lowInclusive)];
for (int i = 0; i < result.length; i++)
result[i] = i + lowInclusive;
return result;
}
@Descriptor("Add a service to the variables. You can then use this service to invoke its methods as commands. This service is not tracked so there is a checked out copy thatt can disappear")
public Object service(String service) throws Exception {
ServiceReference<?>[] refs = context.getServiceReferences((String) null, "(objectClass=*" + service + ")");
if (refs == null) {
System.out.println("No such service");
return null;
}
if (refs.length > 1) {
System.out.println("Multiple services");
return null;
}
ServiceReference<?> ref = refs[0];
return context.getService(ref);
}
@Descriptor("repeat a command until a key is hit")
public void repeat(
//@formatter:off
CommandSession session,
@Descriptor("Repeat period in seconds, must be > 0. Default is 1")
@Parameter(absentValue = "1", names = {"-p","--period"} )
int period,
@Descriptor("Update screen with the result.")
@Parameter(absentValue = "false", presentValue="true", names = {"-u","--update"} )
boolean update,
String ... args
//@formatter:on
) throws Exception {
String line = Stream.of(args)
.collect(Collectors.joining(" "));
while (true) {
if (update)
cls(session);
Object execute = session.execute(line);
String format = session.format(execute, org.apache.felix.service.command.Converter.INSPECT)
.toString();
session.getConsole()
.println(format);
session.getConsole()
.flush();
if (anykey(session, period) != 0)
return;
}
}
@Descriptor("Show the amount of free memory")
public long freeMemory(
//@formatter:off
@Descriptor("Run a gc first")
@Parameter(absentValue = "false", presentValue="true", names = {"-g","--gc"} )
boolean gc
//@formatter:on
) {
if ( gc )
System.gc();
return Runtime.getRuntime()
.freeMemory();
}
@Descriptor("Return a key that is hit")
public int anykey(
//@formatter:off
CommandSession session,
@Descriptor("Repeat period in seconds, must be > 0. Default is 1")
@Parameter(absentValue = "1", names = {"-p","--period"} )
int period
//@formatter:on
) throws IOException, InterruptedException {
long deadline = System.currentTimeMillis() + period * 1000;
while (System.currentTimeMillis() < deadline) {
if (session.getKeyboard()
.available() > 0) {
return session.getKeyboard()
.read();
}
Thread.sleep(100);
}
return 0;
}
@Descriptor("Clear the screen")
public void cls(CommandSession session) {
session.getConsole()
.append("\u001B[2J")
.flush();
}
@Descriptor("Provide a null value")
public Object _null() {
return null;
}
private void source0(CommandSession session, boolean xtrace, String script) throws Exception {
String replace = script.replace("\\\r?\n", " ");
for (String line : Strings.splitLines(replace)) {
if (xtrace)
System.out.println("x: " + line);
session.execute(line);
}
}
private Object execute(CommandSession session, Object value, Object... args) throws Exception {
if (value instanceof org.apache.felix.service.command.Function) {
return ((org.apache.felix.service.command.Function) value).execute(session, Arrays.asList(args));
}
return value;
}
@Descriptor("Get files relative to the current directory based on ant like expressions")
public List<File> files(CommandSession session, String files) {
return files(session, session.currentDir()
.toFile(), files);
}
@Descriptor("Get files relative to the given directory based on ant like expressions")
public List<File> files(CommandSession session, File base, String files) {
return Stream.of(files)
.flatMap(f -> new FileSet(base, f).getFiles()
.stream())
.collect(Collectors.toList());
}
private Collection<File> files(CommandSession session, File base, String[] files) {
List<File> result = new ArrayList<>();
for (String spec : files) {
result.addAll(files(session, base, spec));
}
return result;
}
private boolean grep(InputStream in, PrintStream out, Predicate<String> matches, boolean quiet, String fileName)
throws IOException {
BufferedReader reader = IO.reader(in);
int count = 0;
String line;
boolean found = false;
while ((line = reader.readLine()) != null) {
if (matches.test(line)) {
found = true;
if (!quiet) {
if (fileName != null) {
out.printf("%s:%04d | ", fileName, count);
}
out.println(line);
}
}
count++;
}
return found;
}
private List<Function<Character, String>> getOps(boolean number, boolean unprintable, boolean squeeze,
boolean hex) {
List<Function<Character, String>> ops = new ArrayList<>();
if (hex) {
class Hex {
int count = 0;
String del = "";
}
Hex h = new Hex();
ops.add((c) -> {
String result = "";
if (h.count % 16 == 0) {
result = String.format("%s%04X", h.del, h.count);
h.del = "\n";
}
h.count++;
return result.concat(String.format(" %04X", (int) c));
});
}
if (number) {
class Number {
boolean first = true;
int line = 0;
}
Number n = new Number();
ops.add((c) -> {
if (n.first) {
n.first = false;
n.line++;
return " 0 " + c;
} else {
if (c == '\n') {
return String.format("\n%4d ", n.line++);
}
}
return c.toString();
});
}
if (unprintable) {
ops.add((c) -> {
if (isPrintable(c)) {
return c.toString();
}
return String.format("\\u%04X", (char) c);
});
}
if (squeeze) {
class Squeeze {
char last = 0;
}
Squeeze s = new Squeeze();
ops.add((c) -> {
if (c != '\n' || c != '\r' || s.last != '\n')
return c.toString();
if (c == '\r')
return "\r";
if (s.last == '\n') {
return "";
}
s.last = c;
return c.toString();
});
}
return ops;
}
@SuppressWarnings("unchecked")
private Map<String, Object> getVariables(CommandSession session) {
try {
Class<? extends CommandSession> clazz = session.getClass();
Method method = clazz.getMethod("getVariables");
return (Map<String, Object>) method.invoke(session);
} catch (Exception e) {
return Collections.emptyMap();