-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCommandLineInterface.java
More file actions
2116 lines (1829 loc) · 93.4 KB
/
CommandLineInterface.java
File metadata and controls
2116 lines (1829 loc) · 93.4 KB
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
/*
* Copyright (c) Mirth Corporation. All rights reserved.
*
* http://www.mirthcorp.com
*
* The software in this package is published under the terms of the MPL license a copy of which has
* been included with this distribution in the LICENSE.txt file.
*/
package com.mirth.connect.cli;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.PropertiesConfigurationLayout;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import com.mirth.connect.client.core.BrandingConstants;
import com.mirth.connect.client.core.Client;
import com.mirth.connect.client.core.ClientException;
import com.mirth.connect.client.core.ListHandlerException;
import com.mirth.connect.client.core.PaginatedEventList;
import com.mirth.connect.client.core.PaginatedMessageList;
import com.mirth.connect.client.core.PropertiesConfigurationUtil;
import com.mirth.connect.client.core.UnauthorizedException;
import com.mirth.connect.donkey.model.channel.DeployedState;
import com.mirth.connect.donkey.model.message.ContentType;
import com.mirth.connect.donkey.model.message.Message;
import com.mirth.connect.donkey.model.message.attachment.Attachment;
import com.mirth.connect.donkey.util.xstream.SerializerException;
import com.mirth.connect.model.Channel;
import com.mirth.connect.model.ChannelDependency;
import com.mirth.connect.model.ChannelMetadata;
import com.mirth.connect.model.ChannelStatistics;
import com.mirth.connect.model.DashboardStatus;
import com.mirth.connect.model.InvalidChannel;
import com.mirth.connect.model.LoginStatus;
import com.mirth.connect.model.MessageImportResult;
import com.mirth.connect.model.ServerConfiguration;
import com.mirth.connect.model.ServerEvent;
import com.mirth.connect.model.User;
import com.mirth.connect.model.alert.AlertModel;
import com.mirth.connect.model.codetemplates.CodeTemplate;
import com.mirth.connect.model.codetemplates.CodeTemplateLibrary;
import com.mirth.connect.model.codetemplates.CodeTemplateLibrarySaveResult;
import com.mirth.connect.model.codetemplates.CodeTemplateLibrarySaveResult.CodeTemplateUpdateResult;
import com.mirth.connect.model.converters.ObjectXMLSerializer;
import com.mirth.connect.model.filters.EventFilter;
import com.mirth.connect.model.filters.MessageFilter;
import com.mirth.connect.util.ConfigurationProperty;
import com.mirth.connect.util.MessageExporter;
import com.mirth.connect.util.MessageImporter;
import com.mirth.connect.util.MessageImporter.MessageImportException;
import com.mirth.connect.util.MessageImporter.MessageImportInvalidPathException;
import com.mirth.connect.util.messagewriter.AttachmentSource;
import com.mirth.connect.util.messagewriter.MessageWriter;
import com.mirth.connect.util.messagewriter.MessageWriterException;
import com.mirth.connect.util.messagewriter.MessageWriterFactory;
import com.mirth.connect.util.messagewriter.MessageWriterOptions;
public class CommandLineInterface {
private String DEFAULT_CHARSET = "UTF-8";
private Client client;
private boolean debug;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy_HH-mm-ss.SS");
private String currentUser = new String();
private PrintWriter out;
private PrintWriter err;
public CommandLineInterface(String[] args) {
out = new PrintWriter(System.out, true);
err = new PrintWriter(System.out, true);
run(args);
}
public static void main(String[] args) {
System.setProperty("log4j2.configurationFile", "log4j2-cli.properties");
new CommandLineInterface(args);
}
@SuppressWarnings("static-access")
private void run(String[] args) {
Option serverOption = OptionBuilder.withArgName("address").hasArg().withDescription("server address").create("a");
Option userOption = OptionBuilder.withArgName("user").hasArg().withDescription("user login").create("u");
Option passwordOption = OptionBuilder.withArgName("password").hasArg().withDescription("user password").create("p");
Option scriptOption = OptionBuilder.withArgName("script").hasArg().withDescription("script file").create("s");
Option versionOption = OptionBuilder.withArgName("version").hasArg().withDescription("version").create("v");
Option configOption = OptionBuilder.withArgName("config file").hasArg().withDescription("path to default configuration [default: mirth-cli-config.properties]").create("c");
Option helpOption = new Option("h", "help");
Option debugOption = new Option("d", "debug");
Options options = new Options();
options.addOption(configOption);
options.addOption(serverOption);
options.addOption(userOption);
options.addOption(passwordOption);
options.addOption(scriptOption);
options.addOption(versionOption);
options.addOption(helpOption);
options.addOption(debugOption);
CommandLineParser parser = new GnuParser();
try {
CommandLine line = parser.parse(options, args);
// Bail out early if they just want help
if (line.hasOption("h")) {
new HelpFormatter().printHelp("Shell", options);
System.exit(0);
}
Properties configDefaults = new Properties();
try {
configDefaults.load(new FileInputStream(line.getOptionValue("c", "conf" + File.separator + "mirth-cli-config.properties")));
} catch (IOException e) {
// Only error out if they tried to load the config
if (line.hasOption("c")) {
error("We could not find the file: " + line.getOptionValue("c"), null);
System.exit(2);
}
}
String server = line.getOptionValue("a", configDefaults.getProperty("address"));
String user = line.getOptionValue("u", configDefaults.getProperty("user"));
String password = line.getOptionValue("p", configDefaults.getProperty("password"));
String script = line.getOptionValue("s", configDefaults.getProperty("script"));
if ((server != null) && (user != null) && (password != null)) {
runShell(server, user, password, script, line.hasOption("d"));
} else {
new HelpFormatter().printHelp("Shell", options);
error("all of address, user, password, and version options must be supplied as arguments or in the default configuration file", null);
System.exit(2);
}
} catch (ParseException e) {
error("Could not parse input arguments.", e);
System.exit(2);
}
}
private void runShell(String server, String user, String password, String script, boolean debug) {
try {
client = new Client(server);
this.debug = debug;
LoginStatus loginStatus = null;
try {
loginStatus = client.login(user, password);
} catch (UnauthorizedException ex) {
if (ex.getResponse() instanceof LoginStatus status && status.isSuccess()) {
loginStatus = status;
}
}
finally {
if (loginStatus == null) {
error("Could not login to server");
System.exit(70);
}
else if (!loginStatus.isSuccess()) {
error("Could not login to server. Please check your username and password and try again.", null); System.exit(77);
}
}
String serverVersion = client.getVersion();
try {
ObjectXMLSerializer.getInstance().init(serverVersion);
} catch (Exception e) {
}
out.println(String.format("Connected to %s Server @ %s (%s)", BrandingConstants.PRODUCT_NAME, server, serverVersion));
currentUser = StringUtils.defaultString(loginStatus.getUpdatedUsername(), user);
if (script != null) {
runScript(script);
} else {
runConsole();
}
client.logout();
client.close();
out.println("Disconnected from server.");
} catch (ClientException ce) {
ce.printStackTrace();
} catch (IOException ioe) {
error("Could not load script file.", ioe);
} catch (URISyntaxException e) {
error("Invalid server address.", e);
}
}
private void runScript(String script) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(script));
String statement = null;
try {
while ((statement = reader.readLine()) != null) {
out.println("Executing statement: " + statement);
executeStatement(statement);
}
} catch (Quit e) {
// do nothing
} finally {
reader.close();
}
}
private void runConsole() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String statement = null;
writePrompt();
try {
while ((statement = reader.readLine()) != null) {
executeStatement(statement);
writePrompt();
}
out.println(); // want newline before "Disconnected" message
} catch (Quit e) {
// do nothing
} finally {
reader.close();
}
}
private void error(String message, Throwable t) {
err.println("Error: " + message);
if ((t != null) && debug) {
err.println(ExceptionUtils.getStackTrace(t));
}
}
private void writePrompt() {
out.print("$");
out.flush();
}
private void executeStatement(String command) {
try {
Token[] arguments = tokenizeCommand(command);
if (arguments.length >= 1) {
Token arg1 = arguments[0];
if (arg1 == Token.HELP) {
commandHelp(arguments);
return;
} else if (arg1 == Token.USER) {
if (arguments.length < 2) {
error("invalid number of arguments.", null);
return;
}
Token arg2 = arguments[1];
if (arg2 == Token.LIST) {
commandUserList(arguments);
} else if (arg2 == Token.ADD) {
commandUserAdd(arguments);
} else if (arg2 == Token.REMOVE) {
commandUserRemove(arguments);
} else if (arg2 == Token.CHANGEPW) {
commandUserChangePassword(arguments);
}
} else if (arg1 == Token.DEPLOY) {
commandDeploy(arguments);
} else if (arg1 == Token.EXPORTCFG) {
commandExportConfig(arguments);
} else if (arg1 == Token.IMPORTCFG) {
commandImportConfig(arguments);
} else if (arg1 == Token.IMPORT) {
commandImport(arguments);
} else if (arg1 == Token.IMPORTALERTS) {
commandImportAlerts(arguments);
} else if (arg1 == Token.EXPORTALERTS) {
commandExportAlerts(arguments);
} else if (arg1 == Token.IMPORTSCRIPTS) {
commandImportScripts(arguments);
} else if (arg1 == Token.EXPORTSCRIPTS) {
commandExportScripts(arguments);
} else if (arg1 == Token.IMPORTCODETEMPLATES) {
// Deprecated, remove in 3.4
error("The importcodetemplates command is deprecated. Please use \"codetemplate [library] import path [force]\" instead.", null);
if (!hasInvalidNumberOfArguments(arguments, 2)) {
commandImportCodeTemplates(arguments[1].getText(), true);
}
} else if (arg1 == Token.EXPORTCODETEMPLATES) {
// Deprecated, remove in 3.4
error("The exportcodetemplates command is deprecated. Please use \"codetemplate [library] export id|name|* path\" instead.", null);
if (!hasInvalidNumberOfArguments(arguments, 2)) {
commandExportCodeTemplateLibraries("*", arguments[1].getText());
}
} else if (arg1 == Token.IMPORTMESSAGES) {
commandImportMessages(arguments);
} else if (arg1 == Token.EXPORTMESSAGES) {
commandExportMessages(arguments);
} else if (arg1 == Token.IMPORTMAP) {
commandImportMap(arguments);
} else if (arg1 == Token.EXPORTMAP) {
commandExportMap(arguments);
} else if (arg1 == Token.STATUS) {
commandStatus(arguments);
} else if (arg1 == Token.EXPORT) {
commandExport(arguments);
} else if (arg1 == Token.CHANNEL) {
String syntax = "invalid number of arguments. Syntax is: channel start|stop|pause|resume|stats|remove|enable|disable <id|name>, channel rename <id|name> newname, or channel list|stats";
if (arguments.length < 2) {
error(syntax, null);
return;
} else if (arguments.length < 3 && arguments[1] != Token.LIST && arguments[1] != Token.STATS) {
error(syntax, null);
return;
}
Token comm = arguments[1];
if (comm == Token.STATS && arguments.length < 3) {
commandAllChannelStats(arguments);
} else if (comm == Token.LIST) {
commandChannelList(arguments);
} else if (comm == Token.DISABLE) {
commandChannelDisable(arguments);
} else if (comm == Token.ENABLE) {
commandChannelEnable(arguments);
} else if (comm == Token.REMOVE) {
commandChannelRemove(arguments);
} else if (comm == Token.START) {
commandChannelStart(arguments);
} else if (comm == Token.STOP) {
commandChannelStop(arguments);
} else if (comm == Token.HALT) {
commandChannelHalt(arguments);
} else if (comm == Token.PAUSE) {
commandChannelPause(arguments);
} else if (comm == Token.RESUME) {
commandChannelResume(arguments);
} else if (comm == Token.STATS) {
commandChannelStats(arguments);
} else if (comm == Token.RENAME) {
commandChannelRename(arguments);
} else if (comm == Token.DEPLOY) {
commandChannelDeploy(arguments);
} else if (comm == Token.UNDEPLOY) {
commandChannelUndeploy(arguments);
} else {
error("unknown channel command " + comm, null);
}
} else if (arg1 == Token.CODE_TEMPLATE) {
if (arguments.length < 2) {
error("Invalid number of arguments. Syntax is: codetemplate library list [includecodetemplates], codetemplate list, codetemplate [library] import path [force], codetemplate export id|name path, codetemplate library export id|name|* path, codetemplate remove id|name, or codetemplate library remove id|name|*", null);
return;
}
Token arg2 = arguments[1];
if (arg2 == Token.LIBRARY) {
if (arguments.length < 3) {
error("Invalid number of arguments. Syntax is: codetemplate library list [includecodetemplates], codetemplate library import path [force], codetemplate library export id|name|* path, or codetemplate library remove id|name|*", null);
return;
}
Token arg3 = arguments[2];
if (arg3 == Token.LIST) {
commandListCodeTemplateLibraries(arguments.length > 3 && StringUtils.equalsIgnoreCase(arguments[3].getText(), "includecodetemplates"));
} else if (arg3 == Token.IMPORT) {
if (arguments.length < 4) {
error("Invalid number of arguments. Syntax is: codetemplate library import path [force]", null);
return;
}
commandImportCodeTemplateLibraries(arguments[3].getText(), arguments.length > 4 && StringUtils.equalsIgnoreCase(arguments[4].getText(), "force"));
} else if (arg3 == Token.EXPORT) {
if (arguments.length < 5) {
error("Invalid number of arguments. Syntax is: codetemplate library export id|name|* path", null);
return;
}
commandExportCodeTemplateLibraries(arguments[3].getText(), arguments[4].getText());
} else if (arg3 == Token.REMOVE) {
if (arguments.length < 4) {
error("Invalid number of arguments. Syntax is: codetemplate library remove id|name|*", null);
return;
}
commandRemoveCodeTemplateLibraries(arguments[3].getText());
} else {
error("Unknown code template library command " + arg3 + ". Syntax is: codetemplate library list [includecodetemplates], codetemplate library import path [force], codetemplate library export id|name|* path, or codetemplate library remove id|name|*", null);
return;
}
} else if (arg2 == Token.LIST) {
commandListCodeTemplates();
} else if (arg2 == Token.IMPORT) {
if (arguments.length < 3) {
error("Invalid number of arguments. Syntax is: codetemplate import path [force]", null);
return;
}
commandImportCodeTemplates(arguments[2].getText(), arguments.length > 3 && StringUtils.equalsIgnoreCase(arguments[3].getText(), "force"));
} else if (arg2 == Token.EXPORT) {
if (arguments.length < 4) {
error("Invalid number of arguments. Syntax is: codetemplate export id|name path", null);
return;
}
commandExportCodeTemplate(arguments[2].getText(), arguments[3].getText());
} else if (arg2 == Token.REMOVE) {
if (arguments.length < 3) {
error("Invalid number of arguments. Syntax is: codetemplate remove id|name", null);
return;
}
commandRemoveCodeTemplate(arguments[2].getText());
} else {
error("Unknown code template command " + arg2 + ". Syntax is: codetemplate library list [includecodetemplates], codetemplate list, codetemplate [library] import path [force], codetemplate export id|name path, codetemplate library export id|name|* path, codetemplate remove id|name, or codetemplate library remove id|name|*", null);
return;
}
} else if (arg1 == Token.CLEARALLMESSAGES) {
commandClearAllMessages(arguments);
} else if (arg1 == Token.RESETSTATS) {
commandResetstats(arguments);
} else if (arg1 == Token.DUMP) {
if (arguments.length >= 2) {
Token arg2 = arguments[1];
if (arg2 == Token.STATS) {
commandDumpStats(arguments);
} else if (arg2 == Token.EVENTS) {
commandDumpEvents(arguments);
} else {
error("unknown dump command: " + arg2, null);
}
} else {
error("missing dump commands.", null);
}
} else if (arg1 == Token.QUIT) {
throw new Quit();
} else {
error("unknown command: " + command, null);
}
}
} catch (ClientException e) {
e.printStackTrace(err);
}
}
private boolean hasInvalidNumberOfArguments(Token[] arguments, int expected) {
if ((arguments.length - 1) < expected) {
error("invalid number of arguments.", null);
return true;
}
return false;
}
/** Split <code>command</code> into an array of tokens. */
private Token[] tokenizeCommand(String command) {
List<Token> tokens = new ArrayList<Token>();
StringBuilder currentToken = null; // not in a token yet
char[] chars = command.toCharArray();
boolean inQuotes = false;
for (int idx = 0; idx < chars.length; idx++) {
char ch = chars[idx];
if (currentToken == null) { // currently between tokens
if (ch == ' ') {
// ignore spaces between tokens (including leading space)
continue;
} else {
// start a new token
currentToken = new StringBuilder();
}
}
if (inQuotes && ch != '"') {
// add another char (possibly space) to the current token
currentToken.append(ch);
} else if (inQuotes && ch == '"') {
// no longer in quotes: ignore the " char and switch modes
inQuotes = false;
} else if (!inQuotes && ch == '"') {
// now in quotes: ignore the " char and switch modes
inQuotes = true;
} else if (!inQuotes && ch == ' ') {
// end of current token
addToken(tokens, currentToken);
currentToken = null;
} else if (!inQuotes && ch == '#') {
// start of comment: stop tokenizing now (ie. treat it as end of
// line)
break;
} else if (!inQuotes) {
// any other char outside of quotes: just append to current
// token
currentToken.append(ch);
} else {
// impossible state because of the first two clauses above
throw new IllegalStateException("impossible state in tokenizer: inQuotes=" + inQuotes + ", char=" + ch);
}
}
addToken(tokens, currentToken);
// out.println("token list: " + tokens);
Token[] arguments = new Token[tokens.size()];
tokens.toArray(arguments);
return arguments;
}
private void addToken(List<Token> tokens, StringBuilder currentText) {
if (currentText == null || StringUtils.isEmpty(currentText.toString())) {
// empty or commented line
return;
}
String text = currentText.toString();
Token token = Token.getKeyword(text);
if (token == null) {
try {
token = Token.intToken(text);
} catch (NumberFormatException e) {
token = Token.stringToken(text);
}
}
tokens.add(token);
}
private void commandHelp(Token[] arguments) {
out.println("Available Commands:");
out.println("status\n\tReturns status of deployed channels\n");
out.println("deploy [timeout]\n\tDeploys all Channels with optional timeout (in seconds)\n");
out.println("import \"path\" [force]\n\tImports channel specified by <path>. Optional 'force' overwrites existing channels.\n");
out.println("export id|\"name\"|* \"path\"\n\tExports the specified channel to <path>\n");
out.println("importcfg \"path\" [nodeploy] [overwriteconfigmap]\n\tImports configuration specified by <path>. Optional 'nodeploy' stops channels from being deployed after importing. Optional 'overwriteconfigmap' will overwrite the Configuration Map.\n");
out.println("exportcfg \"path\"\n\tExports the configuration to <path>\n");
out.println("importalert \"path\" [force]\n\tImports alert specified by <path>. Optional 'force' overwrites existing alerts.\n");
out.println("exportalert id|\"name\"|* \"path\"\n\tExports the specified alert to <path>\n");
out.println("importscripts \"path\"\n\tImports global script specified by <path>\n");
out.println("exportscripts \"path\"\n\tExports global script to <path>\n");
out.println("codetemplate library list [includecodetemplates]\n\tLists all code template libraries. Optional 'includecodetemplates' additionally lists the code templates within each library.\n");
out.println("codetemplate list\n\tLists all code templates.\n");
out.println("codetemplate [library] import path [force]\n\tImports code templates or libraries (with the 'library' option).\n");
out.println("codetemplate library export id|name|* path\n\tExports all matched code template libraries to <path>.\n");
out.println("codetemplate export id|name path\n\tExports a single code template to <path>.\n");
out.println("codetemplate library remove id|name|*\n\tRemoves all matched code template libraries.\n");
out.println("codetemplate remove id|name\n\tRemoves a single code template.\n");
out.println("importmessages \"path\" id\n\tImports messages specified by <path> into the channel specified by <id>\n");
out.println("exportmessages \"path/file-pattern\" id [xml|xml-attach|raw|processedraw|transformed|encoded|response] [pageSize]\n\tExports all messages for channel specified by <id> to <path>\n");
out.println("importmap \"path\"\n\tImports configuration map specified by <path>\n");
out.println("exportmap \"path\"\n\tExports configuration map to <path>\n");
out.println("channel undeploy|deploy|start|stop|halt|pause|resume|stats id|\"name\"|*\n\tPerforms specified channel action\n");
out.println("channel remove|enable|disable id|\"name\"|*\n\tRemove, enable or disable specified channel\n");
out.println("channel list\n\tLists all Channels\n");
out.println("clearallmessages\n\tRemoves all messages from all Channels (running channels will be restarted)\n");
out.println("resetstats [lifetime]\n\tRemoves all stats from all Channels. Optional 'lifetime' includes resetting lifetime stats.\n");
out.println("dump stats|events \"path\"\n\tDumps stats or events to specified file\n");
out.println("user list\n\tReturns a list of the current users\n");
out.println("user add username \"password\" \"firstName\" \"lastName\" \"organization\" \"email\"\n\tAdds the specified user\n");
out.println("user remove id|username\n\tRemoves the specified user\n");
out.println("user changepw id|username \"newpassword\"\n\tChanges the specified user's password\n");
out.println(String.format("quit\n\tQuits %s Shell", BrandingConstants.PRODUCT_NAME));
}
private void commandUserList(Token[] arguments) throws ClientException {
List<User> users = client.getAllUsers();
out.println("ID\tUser Name\tName\t\t\tEmail");
for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
User user = iter.next();
out.println(user.getId() + "\t" + user.getUsername() + "\t\t" + user.getFirstName() + "\t\t" + user.getLastName() + "\t\t" + user.getOrganization() + "\t\t" + user.getEmail());
}
}
private void commandUserAdd(Token[] arguments) throws ClientException {
if (arguments.length < 8) {
error("invalid number of arguments. Syntax is user add username \"password\" \"firstName\" \"lastName\" \"organization\" \"email\"", null);
return;
}
String username = arguments[2].getText();
if (username.length() < 1) {
error("unable to add user: username too short.", null);
return;
}
String password = arguments[3].getText();
String firstName = arguments[4].getText();
String lastName = arguments[5].getText();
String organization = arguments[6].getText();
String email = arguments[7].getText();
User user = new User();
user.setUsername(username);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setOrganization(organization);
user.setEmail(email);
List<User> users = client.getAllUsers();
for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
User luser = iter.next();
if (luser.getUsername().equalsIgnoreCase(username)) {
error("unable to add user: username in use.", null);
return;
}
}
try {
List<String> responses = client.checkUserPassword(password);
if (responses != null) {
for (String response : responses) {
out.println(response);
}
return;
}
client.createUser(user);
// Get the new user object that contains the user id
User newUser = client.getUser(username);
responses = client.updateUserPassword(newUser.getId(), password);
if (responses != null) {
System.out.println("User \"" + username + "\" has been created but the password could not be set:");
for (String response : responses) {
out.println(response);
}
} else {
out.println("User \"" + username + "\" added successfully.");
}
} catch (Exception e) {
error("unable to add user \"" + username + "\": " + e, e);
}
}
private void commandUserRemove(Token[] arguments) throws ClientException {
if (arguments.length < 3) {
error("invalid number of arguments. Syntax is user remove username|id", null);
return;
}
String key = arguments[2].getText();
if (key.equalsIgnoreCase(currentUser)) {
error("cannot remove current user.", null);
return;
}
List<User> users = client.getAllUsers();
for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
User user = iter.next();
if (user.getId().toString().equalsIgnoreCase(key) || user.getUsername().equalsIgnoreCase(key)) {
client.removeUser(user.getId());
out.println("User \"" + user.getUsername() + "\" successfully removed.");
return;
}
}
}
private void commandUserChangePassword(Token[] arguments) throws ClientException {
if (arguments.length < 4) {
error("invalid number of arguments. Syntax is user changepw username|id \"newpassword\"", null);
return;
}
String key = arguments[2].getText();
String newPassword = arguments[3].getText();
List<User> users = client.getAllUsers();
for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
User user = iter.next();
if (user.getId().toString().equalsIgnoreCase(key) || user.getUsername().equalsIgnoreCase(key)) {
List<String> responses = client.updateUserPassword(user.getId(), newPassword);
if (responses != null) {
for (String response : responses) {
out.println(response);
}
} else {
out.println("User \"" + user.getUsername() + "\" password updated.");
}
return;
}
}
}
private void commandDeploy(Token[] arguments) throws ClientException {
out.println("Deploying Channels");
List<Channel> channels = client.getAllChannels();
Map<String, ChannelMetadata> metadataMap = client.getChannelMetadata();
boolean hasChannels = false;
for (Channel channel : channels) {
ChannelMetadata metadata = metadataMap.get(channel.getId());
if (!(channel instanceof InvalidChannel) && metadata != null && metadata.isEnabled()) {
hasChannels = true;
break;
}
}
client.redeployAllChannels();
if (hasChannels) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<DashboardStatus> channelStatus = client.getAllChannelStatuses();
int limit = 60; // 30 second limit
if (arguments.length > 1 && arguments[1] instanceof IntToken) {
limit = ((IntToken) arguments[1]).getValue() * 2; // multiply
// by two
// because
// our sleep
// is 500ms
}
while (channelStatus.size() == 0 && limit > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
channelStatus = client.getAllChannelStatuses();
limit--;
}
if (limit > 0) {
out.println("Channels Deployed");
} else {
out.println("Deployment Timed out");
}
} else {
out.println("No Channels to Deploy");
}
}
private void commandExportConfig(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
String path = arguments[1].getText();
ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
try {
ServerConfiguration configuration = client.getServerConfiguration();
String backupDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
configuration.setDate(backupDate);
File fXml = new File(path);
out.println("Exporting Configuration");
String configurationXML = serializer.serialize(configuration);
FileUtils.writeStringToFile(fXml, configurationXML);
} catch (IOException e) {
error("unable to write file " + path + ": " + e, e);
}
out.println("Configuration Export Complete.");
}
private void commandImportConfig(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
String path = arguments[1].getText();
File fXml = new File(path);
boolean deploy = true;
boolean overwriteConfigMap = false;
if (arguments.length >= 3) {
if (arguments[2] == Token.NODEPLOY) {
deploy = false;
} else if (arguments[2] == Token.OVERWRITECONFIGMAP) {
overwriteConfigMap = true;
}
if (arguments.length >= 4) {
if (arguments[3] == Token.NODEPLOY) {
deploy = false;
} else if (arguments[3] == Token.OVERWRITECONFIGMAP) {
overwriteConfigMap = true;
}
}
}
ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
try {
client.setServerConfiguration(serializer.deserialize(FileUtils.readFileToString(fXml), ServerConfiguration.class), deploy, overwriteConfigMap);
} catch (IOException e) {
error("cannot read " + path, e);
return;
}
out.println("Configuration Import Complete.");
}
private void commandImport(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
String path = arguments[1].getText();
boolean force = false;
if (arguments.length >= 3 && arguments[2] == Token.FORCE) {
force = true;
}
File fXml = new File(path);
doImportChannel(fXml, force);
}
private void commandImportAlerts(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
String path = arguments[1].getText();
boolean force = false;
if (arguments.length >= 3 && arguments[2] == Token.FORCE) {
force = true;
}
File fXml = new File(path);
doImportAlert(fXml, force);
}
private void commandExportAlerts(Token[] arguments) throws ClientException {
if (arguments.length < 3) {
error("invalid number of arguments. Syntax is: export id|name|* \"path\"", null);
return;
}
Token key = arguments[1];
String path = arguments[2].getText();
ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
List<AlertModel> alerts = client.getAllAlerts();
if (key == Token.WILDCARD) {
for (AlertModel alert : alerts) {
try {
File fXml = new File(path + alert.getName() + ".xml");
out.println("Exporting " + alert.getName());
String alertXML = serializer.serialize(alert);
FileUtils.writeStringToFile(fXml, alertXML);
} catch (IOException e) {
error("unable to write file " + path + ": " + e, e);
}
}
out.println("Export Complete.");
return;
} else {
File fXml = new File(path);
StringToken skey = Token.stringToken(key.getText());
for (AlertModel alert : alerts) {
if (skey.equalsIgnoreCase(alert.getName()) != skey.equalsIgnoreCase(alert.getId())) {
out.println("Exporting " + alert.getName());
String alertXML = serializer.serialize(alert);
try {
FileUtils.writeStringToFile(fXml, alertXML);
} catch (IOException e) {
error("unable to write file " + path + ": " + e, e);
}
out.println("Export Complete.");
return;
}
}
}
}
private void commandExportScripts(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
String path = arguments[1].getText();
File fXml = new File(path);
try {
String scriptsXml = serializer.serialize(client.getGlobalScripts());
out.println("Exporting scripts");
FileUtils.writeStringToFile(fXml, scriptsXml);
} catch (IOException e) {
error("unable to write file " + path + ": " + e, e);
}
out.println("Script Export Complete.");
}
private void commandImportScripts(Token[] arguments) throws ClientException {
if (hasInvalidNumberOfArguments(arguments, 1)) {
return;
}
String path = arguments[1].getText();
File fXml = new File(path);
doImportScript(fXml);
out.println("Scripts Import Complete");
}
private void commandListCodeTemplateLibraries(boolean includeCodeTemplates) throws ClientException {
List<CodeTemplateLibrary> libraries = client.getCodeTemplateLibraries(null, includeCodeTemplates);
int maxLibraryNameLength = 4;
for (CodeTemplateLibrary library : libraries) {
if (library.getName().length() > maxLibraryNameLength) {
maxLibraryNameLength = library.getName().length();
}
}
int maxCodeTemplateNameLength = 4;
if (includeCodeTemplates) {
for (CodeTemplateLibrary library : libraries) {
for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
if (codeTemplate.getName().length() > maxCodeTemplateNameLength) {
maxCodeTemplateNameLength = codeTemplate.getName().length();
}
}
}
}
boolean showLibraryHeader = true;
for (CodeTemplateLibrary library : libraries) {
if (showLibraryHeader) {
out.printf("%-" + maxLibraryNameLength + "s %-36s %-8s %s\n", "Name", "Id", "Revision", "Last Modified");
out.printf("%-" + maxLibraryNameLength + "s %-36s %-8s %s\n", StringUtils.repeat('-', maxLibraryNameLength), StringUtils.repeat('-', 36), StringUtils.repeat('-', 8), StringUtils.repeat('-', 19));
showLibraryHeader = false;
}
out.printf("%-" + maxLibraryNameLength + "s %-36s %-8d %tF %<tT\n", library.getName(), library.getId(), library.getRevision(), library.getLastModified());
if (includeCodeTemplates && library.getCodeTemplates().size() > 0) {
out.println();
listCodeTemplates(library.getCodeTemplates(), true, maxCodeTemplateNameLength);
out.println();
showLibraryHeader = true;
}
}
}
private void commandImportCodeTemplateLibraries(String path, boolean force) throws ClientException {
try {
List<CodeTemplateLibrary> libraries = ObjectXMLSerializer.getInstance().deserializeList(FileUtils.readFileToString(new File(path)), CodeTemplateLibrary.class);
removeInvalidItems(libraries, CodeTemplateLibrary.class);
if (libraries.isEmpty()) {
out.println("No code template libraries found in file \"" + path + "\".");
return;
}
Map<String, CodeTemplateLibrary> libraryMap = new HashMap<String, CodeTemplateLibrary>();
for (CodeTemplateLibrary library : client.getCodeTemplateLibraries(null, false)) {
libraryMap.put(library.getId(), library);
}
Map<String, CodeTemplate> codeTemplateMap = new HashMap<String, CodeTemplate>();
for (CodeTemplateLibrary library : libraries) {
library = new CodeTemplateLibrary(library);
CodeTemplateLibrary matchingLibrary = libraryMap.get(library.getId());
if (matchingLibrary != null) {
library.getEnabledChannelIds().addAll(matchingLibrary.getEnabledChannelIds());
library.getDisabledChannelIds().addAll(matchingLibrary.getDisabledChannelIds());
library.getDisabledChannelIds().removeAll(library.getEnabledChannelIds());
for (CodeTemplate serverCodeTemplate : matchingLibrary.getCodeTemplates()) {
boolean found = false;
for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
if (serverCodeTemplate.getId().equals(codeTemplate.getId())) {
found = true;
break;
}
}
if (!found) {
library.getCodeTemplates().add(serverCodeTemplate);
}
}
}
for (CodeTemplate codeTemplate : library.getCodeTemplates()) {