061c1f7b816ab732849e5c314337e6e327772e67
[cli.git] / main / src / main / java / org / onap / cli / main / OnapCli.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.cli.main;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27
28 import org.apache.commons.io.IOUtils;
29 import org.onap.cli.fw.cmd.OnapCommand;
30 import org.onap.cli.fw.conf.OnapCommandConfig;
31 import org.onap.cli.fw.conf.OnapCommandConstants;
32 import org.onap.cli.fw.error.OnapCommandException;
33 import org.onap.cli.fw.error.OnapCommandHelpFailed;
34 import org.onap.cli.fw.error.OnapCommandInvalidSample;
35 import org.onap.cli.fw.error.OnapCommandWarning;
36 import org.onap.cli.fw.input.OnapCommandParameter;
37 import org.onap.cli.fw.output.OnapCommandPrintDirection;
38 import org.onap.cli.fw.output.OnapCommandResult;
39 import org.onap.cli.fw.output.OnapCommandResultAttribute;
40 import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
41 import org.onap.cli.fw.output.OnapCommandResultType;
42 import org.onap.cli.fw.registrar.OnapCommandRegistrar;
43 import org.onap.cli.fw.store.OnapCommandExecutionStore;
44 import org.onap.cli.fw.store.OnapCommandExecutionStore.ExecutionStoreContext;
45 import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
46 import org.onap.cli.main.conf.OnapCliConstants;
47 import org.onap.cli.main.interactive.StringCompleter;
48 import org.onap.cli.main.utils.OnapCliArgsParser;
49 import org.onap.cli.sample.yaml.SampleYamlGenerator;
50 import org.open.infc.grpc.Result;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 import jline.TerminalFactory;
55 import jline.console.ConsoleReader;
56
57 /**
58  * OCLIP Command Line Interface (CLI).
59  *
60  */
61 public class OnapCli {
62
63     private static Logger log = LoggerFactory.getLogger(OnapCli.class);
64
65     private List<String> args = new ArrayList<>();
66
67     private List<String> argsParamFile = new ArrayList<>();
68
69     private String product = null;
70
71     private String profile = null;
72
73     private String paramFile = null;
74
75     private String rpcHost = null;
76
77     private String rpcPort = null;
78
79     private boolean printHelp = false;
80
81     private boolean printVersion = false;
82
83     private String requestId = null;
84
85     private String cmdName = null;
86
87     private int exitCode = -1;
88
89     public OnapCli(String[] args) {
90         this.setArgs(args);
91     }
92
93     public OnapCli() {
94     }
95
96     public void resetExitCode() {
97         this.exitCode = -1;
98     }
99
100     public void setArgs(String [] args) {
101         //--help --version --requestId --rpc-host xxx --rpc-port xxx --product xxx --profile xxx --param-file xxx CMD blah blah
102
103         int cmdIdx = 0; //index of CMD
104         while(args.length > cmdIdx) {
105             //no options given, directly command name invoked
106             if (!args[cmdIdx].startsWith("-")) {
107                 break;
108             }
109
110             if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCommandConstants.RPC_PRODUCT))) {
111                 this.product = args[++cmdIdx];
112                 cmdIdx++; //move to next option
113             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCommandConstants.RPC_PROFILE))) {
114                 this.profile = args[++cmdIdx];
115                 cmdIdx++; //move to next option
116             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCommandConstants.RPC_HOST))) {
117                 this.rpcHost = args[++cmdIdx];
118                 cmdIdx++; //move to next option
119             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCommandConstants.RPC_PORT))) {
120                 this.rpcPort = args[++cmdIdx];
121                 cmdIdx++; //move to next option
122             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCliConstants.PARAM_PARAM_FILE_LONG))) {
123                 this.paramFile = args[++cmdIdx];
124                 cmdIdx++; //move to next option
125             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCommandConstants.RPC_REQID))) {
126                 this.requestId = args[++cmdIdx];
127                 cmdIdx++; //move to next option
128             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCliConstants.PARAM_HELP_LOGN)) ||
129                     args[cmdIdx].equals(OnapCommandParameter.printShortOption(OnapCliConstants.PARAM_HELP_SHORT))) {
130                 this.printHelp = true;
131                 cmdIdx++; //move to next option
132             } else if (args[cmdIdx].equals(OnapCommandParameter.printLongOption(OnapCliConstants.PARAM_VERSION_LONG)) ||
133                     args[cmdIdx].equals(OnapCommandParameter.printShortOption(OnapCliConstants.PARAM_VERSION_SHORT))) {
134                 this.printVersion = true;
135                 cmdIdx++; //move to next option
136             }
137         }
138
139         if (args.length > cmdIdx) {
140             this.cmdName = args[cmdIdx];
141             cmdIdx ++;
142         }
143
144         this.args.clear();
145
146         //add all args starting from the command name
147         for (int i=cmdIdx; i<args.length; i++) {
148             this.args.add(args[i]);
149         }
150     }
151
152     private void exitSuccessfully() {
153         this.exitCode = OnapCliConstants.EXIT_SUCCESS;
154     }
155
156     private void exitFailure() {
157         this.exitCode = OnapCliConstants.EXIT_FAILURE;
158     }
159
160     protected void print(String msg) {
161         System.out.println(msg); //NOSONAR
162     }
163
164     protected void printerr(String msg) {
165         System.err.println(msg); //NOSONAR
166     }
167
168     private void print(Throwable throwable) {
169         String error = throwable.getMessage() != null ? throwable.getMessage() : "";
170         this.print(error);
171         log.error(error, throwable);
172     }
173
174     private String getShortOption(String opt) {
175         return OnapCommandParameter.printShortOption(opt);
176     }
177
178     private String getLongOption(String opt) {
179         return OnapCommandParameter.printLongOption(opt);
180     }
181
182     public int getExitCode() {
183         return this.exitCode;
184     }
185
186     /**
187      * Handles help. --help or -h
188      */
189     public void handleHelp() {
190         try {
191             if (this.printHelp) {
192                 this.print(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("oclip-readme.txt")));
193                 String help = OnapCommandRegistrar.getRegistrar().getHelp();
194                 this.print(help);
195                 this.exitSuccessfully();
196             }
197         } catch (Exception e) {
198             this.print(e);
199             this.exitFailure();
200         }
201     }
202
203     /**
204      * Handles version. --version or -v
205      */
206     public void handleVersion() {
207         try {
208             if (this.printVersion) {
209                 String version = OnapCommandRegistrar.getRegistrar().getVersion();
210                 this.print(version);
211                 this.exitSuccessfully();
212             }
213         } catch (Exception e) {
214             this.print(e);
215             this.exitFailure();
216         }
217     }
218
219
220     /**
221      * Handles profile. --profile
222      */
223     public void handleProfile() {
224         try {
225             if (this.profile != null) {
226                 OnapCommandRegistrar.getRegistrar().setProfile(
227                         this.profile,
228                         new ArrayList<String>(),
229                         new ArrayList<String>());
230             }
231         } catch (Exception e) {
232             this.print(e);
233             this.exitFailure();
234         }
235     }
236
237     /**
238      * Handles batch command. --param-file
239      */
240     public void handleBatchCommand() {
241         try {
242             if (this.paramFile != null) {
243                 //Read YAML and loop thru it
244                 // one
245                 // - param-long-option-1: value
246                 // - param-long-option-1: value
247                 // - positional-arg1
248                 // - positional-arg2
249                 // two
250                 // - param-long-option-1: value
251                 // - param-long-option-1: value
252                 // - positional-arg1
253                 // - positional-arg2
254                 try {
255                     Map<String, Object> values = (Map<String, Object>) OnapCommandDiscoveryUtils.loadYaml(this.paramFile);
256
257                     for (Entry<String, Object> cmdsParam: values.entrySet()) {
258                         for (Object param: (List)cmdsParam.getValue()) {
259                             if (param instanceof Map) { //optional args
260                                 Map <String, String> paramMap = (Map<String, String>) param;
261                                 String paramName = paramMap.keySet().iterator().next();
262                                 Object paramValue = paramMap.get(paramName);
263                                 argsParamFile.add(this.getLongOption(paramName));
264                                 argsParamFile.add(paramValue.toString());
265                             } else { //positional args
266                                 argsParamFile.add(param.toString());
267                             }
268                         }
269                     }
270
271                 } catch (Exception e) { // NOSONAR
272                     this.print("Failed to read param file " + this.paramFile);
273                     this.print(e);
274                 }
275             }
276         } catch (Exception e) {
277             this.print(e);
278             this.exitFailure();
279         }
280     }
281
282     public void verifyCommand(OnapCommand cmd) throws OnapCommandException {
283
284         OnapCliArgsParser.populateParams(cmd.getParameters(), args);
285
286         Optional<OnapCommandParameter> contextOptArg = cmd.getParameters().stream()
287                 .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
288                 .findFirst();
289
290         List<Map<String, Object>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(
291                 cmd.getName(),
292                 cmd.getInfo().getProduct());
293
294         OnapCommandResult testSuiteResult = new OnapCommandResult();
295         testSuiteResult.setType(OnapCommandResultType.TABLE);
296         testSuiteResult.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
297         testSuiteResult.setIncludeTitle(true);
298
299         OnapCommandResultAttribute sampleFileAtt = new OnapCommandResultAttribute();
300         OnapCommandResultAttribute sampleIdAtt = new OnapCommandResultAttribute();
301         OnapCommandResultAttribute resultAtt = new OnapCommandResultAttribute();
302
303         sampleFileAtt.setName("Test");
304         sampleIdAtt.setName("SampleId");
305         resultAtt.setName("Result");
306
307         testSuiteResult.setRecords(Arrays.asList(sampleFileAtt,
308                 sampleIdAtt,
309                 resultAtt));
310
311         for (Map<String, ?> sampleTest : testSuite) {
312
313             sampleFileAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID));
314             sampleIdAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_ID));
315
316             cmd = OnapCommandRegistrar.getRegistrar().get(cmd.getName(),
317                     cmd.getInfo().getProduct());
318             List<String> arguments = (List<String>) sampleTest.get(OnapCommandConstants.VERIFY_INPUT);
319
320             OnapCliArgsParser.populateParams(cmd.getParameters(), arguments);
321             this.print("\n***************Test Command: \n" + sampleTest.get(OnapCommandConstants.VERIFY_INPUT).toString());
322
323             cmd.getParametersMap().get(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG).setValue(Boolean.TRUE);
324
325             Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream()
326                     .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
327                     .findFirst();
328
329             if (contextOpt.isPresent()) {
330                 HashMap<String, Object> map = new HashMap<>();
331
332                 Object moco = sampleTest.get(OnapCommandConstants.VERIFY_MOCO);
333                 if (moco == null) {
334                     continue;
335                 }
336                 map.put(OnapCommandConstants.VERIFY_MOCO, moco);
337
338                 if (contextOptArg.isPresent()) {
339                     OnapCommandParameter contextArg = contextOptArg.get();
340                     map.putAll((Map) contextArg.getValue());
341                 }
342
343                 contextOpt.get().setValue(map);
344             }
345
346             OnapCommandResult testResult = cmd.execute();
347             String actualOutput = testResult.print().trim();
348             String expectedOutput = (String) sampleTest.get(OnapCommandConstants.VERIFY_OUPUT);
349             expectedOutput = expectedOutput == null ? "" : expectedOutput.trim();
350
351             if (actualOutput.equals(expectedOutput)) {
352                 resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_PASS);
353             } else {
354                 resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_FAIL);
355             }
356             this.printerr(testResult.getDebugInfo());
357             this.print("\n***************Expected Output: \n" + expectedOutput);
358             this.print("\n***************Actual Output: \n" + actualOutput);
359         }
360
361         this.print(testSuiteResult.print());
362     }
363
364     /**
365      * Handles Interactive Mode.
366      */
367     public void handleInteractive() { // NOSONAR
368         if (this.cmdName == null) {
369             ConsoleReader console = null;
370             try {
371                 OnapCommandRegistrar.getRegistrar().setInteractiveMode(true);
372                 console = createConsoleReader();
373                 String line = null;
374
375                 while ((line = console.readLine()) != null) {
376                     line = line.trim();
377                     if (OnapCliConstants.PARAM_INTERACTIVE_EXIT.equalsIgnoreCase(line)) {
378                         break;
379                     } else if (OnapCliConstants.PARAM_INTERACTIVE_CLEAR.equalsIgnoreCase(line)) {
380                         console.clearScreen();
381                         continue;
382                     }
383                     this.args = new ArrayList<>();
384                     this.args.addAll(Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)));
385
386                     if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
387                         if (args.size() == 1) {
388                             this.print("Please use it in the form of use <product-version>.\nSupported versions: " +
389                                     OnapCommandRegistrar.getRegistrar().getAvailableProductVersions());
390                         } else {
391                             try {
392                                 OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(args.get(1));
393                                 console = createConsoleReader();
394                             } catch (OnapCommandException e) {
395                                 this.print(e);
396                             }
397                         }
398
399                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
400                         try {
401                             this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
402                             this.print(OnapCli.getDirectiveHelp());
403                         } catch (OnapCommandException e) {
404                             this.print(e);
405                         }
406
407                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
408                         this.printVersion = true;
409                         handleVersion();
410
411                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) {
412                         if (args.size() == 1) {
413                             this.print("Please use it in the form of 'profile <profile-name>'\n");
414                             this.print("Available profiles: ");
415                             this.print(OnapCommandRegistrar.getRegistrar().getUserProfiles().toString());
416                         } else {
417                             this.profile = args.get(1);
418                             handleProfile();
419                         }
420
421                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) {
422                         if (args.size() > 1) {
423                             String [] paramEntry = args.get(1).trim().split("=", 2);
424                             if (paramEntry.length == 2) {
425                                 OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim());
426                             } else {
427                                 this.print("Please use it in the form of 'set <param-name>=<param-value>'");
428                             }
429                         } else {
430                             this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString());
431                         }
432
433                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) {
434                         if (args.size() > 1) {
435                             for (int i = 1; i <args.size(); i++) {
436                                 OnapCommandRegistrar.getRegistrar().removeParamCache(args.get(i));
437                             }
438                         }
439                     } else {
440                         if (args.size() == 1 && args.get(0).trim().isEmpty()) {
441                             //Ignore blanks // NOSONAR
442                             continue;
443                         }
444
445                         this.setArgs(this.args.toArray(new String [] {}));
446                         handleCommand();
447                     }
448                 }
449             } catch (IOException e) { // NOSONAR
450                 this.print("Failed to read console, " + e.getMessage());
451             } catch (OnapCommandException e) {
452                 this.print(e);
453                 this.exitFailure();
454             } finally {
455                 try {
456                     TerminalFactory.get().restore();
457                 } catch (Exception e) { // NOSONAR
458                 }
459                 this.exitSuccessfully();
460             }
461         }
462     }
463
464     /**
465      * Handles command.
466      */
467     public void handleCommand() {
468         OnapCommand cmd = null;
469         if (this.cmdName != null) {
470             try {
471                 if (this.product != null) {
472                     cmd = OnapCommandRegistrar.getRegistrar().get(this.cmdName, this.product);
473                 } else {
474                     cmd = OnapCommandRegistrar.getRegistrar().get(this.cmdName);
475                 }
476             } catch (Exception e) {
477                 this.print(e);
478                 this.exitFailure();
479                 return;
480             }
481
482             ExecutionStoreContext executionStoreContext = null;
483
484             try {
485                 //Registrar identified this command marked with rpc as true and it will make direct RPC command call...
486                 if (cmd.isRpc() && !this.cmdName.equals("schema-rpc")) {
487                     this.handleRpcCommand(cmd);
488                     return;
489                 }
490
491                 // verify
492                 if(args.contains(OnapCommandConstants.VERIFY_LONG_OPTION)
493                         || args.contains(OnapCommandConstants.VERIFY_SHORT_OPTION)) {
494                     verifyCommand(cmd);
495                     this.exitSuccessfully();
496                     return;
497                 }
498                 // check for help or version
499                 if (args.size() == 2) {
500                     if (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(1))
501                             || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(1))) {
502                         String help = cmd.printHelp();
503                         this.print(help);
504                         this.exitSuccessfully();
505                         return;
506                     } else if (this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG).equals(args.get(1))
507                             || this.getShortOption(OnapCliConstants.PARAM_VERSION_SHORT).equals(args.get(1))) {
508                         String version = cmd.printVersion();
509                         this.print(version);
510                         this.exitSuccessfully();
511                         return;
512                     }
513                 }
514
515                 //refer params from profile
516                 if (this.profile != null) {
517
518                     Map<String, String> paramCache = new HashMap<>(); //NOSONAR
519                     if (this.product == null)
520                         paramCache = OnapCommandRegistrar.getRegistrar().getParamCache();
521                     else
522                         paramCache = OnapCommandRegistrar.getRegistrar().getParamCache(this.product);
523
524                     for (OnapCommandParameter param: cmd.getParameters()) {
525                         if (paramCache.containsKey(
526                                 cmd.getInfo().getService() + ":" + cmd.getName() + ":" + param.getLongOption())) {
527                             param.setValue(paramCache.get(
528                                     cmd.getInfo().getService() + ":" + cmd.getName() + ":" + param.getLongOption()));
529                         } else if (paramCache.containsKey(
530                                 cmd.getInfo().getService() + ":" + param.getLongOption())) {
531                             param.setValue(paramCache.get(
532                                     cmd.getInfo().getService() + ":" + param.getLongOption()));
533                         } else if (paramCache.containsKey(param.getLongOption())) {
534                             param.setValue(paramCache.get(param.getLongOption()));
535                         }
536                     }
537                 }
538
539                 //load the parameters value from the map read from param-file
540                 if (!this.argsParamFile.isEmpty()) {
541                     OnapCliArgsParser.populateParams(cmd.getParameters(), this.argsParamFile);
542                 }
543
544                 OnapCliArgsParser.populateParams(cmd.getParameters(), this.args);
545
546                 //start the execution
547                     if (this.requestId != null && this.product != null && !this.requestId.isEmpty()&& !(this.product.equalsIgnoreCase("open-cli") &&
548                             this.cmdName.equalsIgnoreCase("execution-list"))) {
549                         String input = cmd.getArgsJson(true);
550                         executionStoreContext = OnapCommandExecutionStore.getStore().storeExectutionStart(
551                                 this.requestId,
552                                 cmd.getInfo().getProduct(),
553                                 cmd.getInfo().getService(),
554                                 this.cmdName,
555                                 this.profile,
556                                 input);
557                     }
558
559                 cmd.setExecutionContext(executionStoreContext);
560                 OnapCommandResult result = cmd.execute();
561
562                 this.handleTracking(cmd);
563
564                 if (result.isPassed()) {
565                     this.exitSuccessfully();
566                     generateSmapleYaml(cmd);
567                 } else {
568                     this.exitFailure();
569                 }
570             } catch (OnapCommandWarning w) {
571                 if (cmd.getExecutionContext() != null) {
572                     OnapCommandExecutionStore.getStore().storeExectutionEnd(
573                             cmd.getExecutionContext(),
574                             w.getMessage(),
575                             null,
576                             cmd.getResult().getDebugInfo(),
577                             cmd.getResult().isPassed());
578                 }
579
580                 this.print(w);
581                 this.printerr(cmd.getResult().getDebugInfo());
582                 this.exitSuccessfully();
583             } catch (Exception e) {
584                 if (executionStoreContext != null) {
585                     OnapCommandExecutionStore.getStore().storeExectutionEnd(
586                             executionStoreContext,
587                             null,
588                             e.getMessage(),
589                             cmd.getResult().getDebugInfo(),
590                             false);
591                 }
592
593                 this.print(e);
594                 this.printerr(cmd.getResult().getDebugInfo());
595                 this.exitFailure();
596             }
597         }
598     }
599
600     public void handleTracking(OnapCommand cmd) throws OnapCommandException {
601         if (cmd.getResult().isDebug())
602             this.printerr(cmd.getResult().getDebugInfo());
603
604         String printOut = cmd.getResult().print();
605         this.print(printOut);
606
607         if (cmd.getExecutionContext() != null) {
608             OnapCommandExecutionStore.getStore().storeExectutionEnd(
609                     cmd.getExecutionContext(),
610                     printOut,
611                     null,
612                     cmd.getResult().getDebugInfo(),
613                     cmd.getResult().isPassed());
614         }
615     }
616     /**
617      * When user invokes cli with RPC arguments...
618      */
619     public void handleRpc() {
620         if (this.rpcHost != null && this.rpcPort != null && this.product != null) {
621             try {
622                 OnapCommand cmd = OnapCommandRegistrar.getRegistrar().get("schema-rpc", "open-cli");
623                 cmd.getParametersMap().get(OnapCommandConstants.RPC_HOST).setValue(this.rpcHost);
624                 cmd.getParametersMap().get(OnapCommandConstants.RPC_PORT).setValue(this.rpcPort);
625                 cmd.getParametersMap().get(OnapCommandConstants.RPC_PRODUCT).setValue(this.product);
626                 cmd.getParametersMap().get(OnapCommandConstants.RPC_CMD).setValue(this.cmdName);
627
628                 this.handleRpcCommand(cmd);
629             } catch (Exception e) {
630                 this.print(e);
631                 this.exitFailure();
632             }
633         }
634     }
635
636     private void handleRpcCommand(OnapCommand cmd) throws OnapCommandException {
637         Map<String, List<String>> argsMap = new HashMap<>();
638         argsMap.put(OnapCommandConstants.RPC_ARGS, this.args);
639         if (this.profile != null )
640             cmd.getParametersMap().get(OnapCommandConstants.RPC_PROFILE).setValue(this.profile);
641         cmd.getParametersMap().get(OnapCommandConstants.RPC_REQID).setValue(this.requestId);
642         cmd.getParametersMap().get(OnapCommandConstants.RPC_MODE).setValue(OnapCommandConstants.RPC_MODE_RUN_CLI);
643         cmd.getParametersMap().get(OnapCommandConstants.RPC_ARGS).setValue(argsMap);
644
645         OnapCommandResult result = cmd.execute();
646         Result output = (Result) result.getOutput();
647
648         this.exitCode = output.getExitCode();
649         this.print(output.getOutput());
650     }
651     /**
652      * Handles all client input.
653      */
654     public void handle() {
655         this.handleRpc();
656
657         if (this.exitCode == -1) {
658             this.handleHelp();
659         }
660
661         if (this.exitCode == -1) {
662             this.handleVersion();
663         }
664
665         if (this.exitCode == -1) {
666             this.handleProfile();
667         }
668
669         if (this.exitCode == -1) {
670             this.handleBatchCommand();
671         }
672
673         if (this.exitCode == -1) {
674             this.handleInteractive();
675         }
676
677         if (this.exitCode == -1) {
678             this.handleCommand();
679         }
680     }
681
682     public static String getDirectiveHelp() throws OnapCommandHelpFailed {
683         OnapCommandResult help = new OnapCommandResult();
684         help.setType(OnapCommandResultType.TABLE);
685         help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
686
687         OnapCommandResultAttribute attr = new OnapCommandResultAttribute();
688         attr.setName(OnapCommandConstants.NAME.toUpperCase());
689         attr.setDescription(OnapCommandConstants.DESCRIPTION);
690         attr.setScope(OnapCommandResultAttributeScope.SHORT);
691         help.getRecords().add(attr);
692
693         OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
694         attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase());
695         attrDesc.setDescription(OnapCommandConstants.DESCRIPTION);
696         attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
697         help.getRecords().add(attrDesc);
698
699         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR);
700         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR_MSG);
701
702         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT);
703         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT_MSG);
704
705         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION);
706         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION_MSG);
707
708         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE);
709         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE_MSG);
710
711         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET);
712         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET_MSG);
713
714         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET);
715         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET_MSG);
716
717         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP);
718         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP_MSG);
719
720         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
721         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE_MSG);
722         try {
723             return "\n\nDirectives:\n" + help.print();
724         } catch (OnapCommandException e) {
725             throw new OnapCommandHelpFailed(e);
726         }
727     }
728
729     /**
730      * Creates console reader object.
731      *
732      * @return ConsoleReader
733      * @throws IOException
734      *             exception
735      */
736     private ConsoleReader createConsoleReader() throws IOException {
737         ConsoleReader console = new ConsoleReader(); // NOSONAR
738         try {
739             //ignore system commands
740             StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion());
741             strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT,
742                     OnapCliConstants.PARAM_INTERACTIVE_CLEAR,
743                     OnapCliConstants.PARAM_INTERACTIVE_USE,
744                     OnapCliConstants.PARAM_INTERACTIVE_HELP,
745                     OnapCliConstants.PARAM_INTERACTIVE_VERSION,
746                     OnapCliConstants.PARAM_INTERACTIVE_SET,
747                     OnapCliConstants.PARAM_INTERACTIVE_UNSET,
748                     OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
749             console.addCompleter(strCompleter);
750             console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">");
751         } catch (OnapCommandException e) { // NOSONAR
752             this.print("Failed to load oclip commands," + e.getMessage());
753         }
754
755         return console;
756     }
757
758
759     private void generateSmapleYaml(OnapCommand cmd) throws OnapCommandException {
760         if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED)) && this.getExitCode() == OnapCliConstants.EXIT_SUCCESS) {
761             try {
762                 SampleYamlGenerator.generateSampleYaml(cmd.getName(), args, cmd.getResult().print(),
763                         cmd.getInfo().getProduct(),
764                         OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER) + "/" + cmd.getSchemaName().replaceAll(".yaml", "") + "-sample.yaml",
765                         cmd.getResult().isDebug(),
766                         OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_NAME));
767             } catch (IOException error) {
768                 throw new OnapCommandInvalidSample(this.cmdName, error);
769             }
770         }
771     }
772
773     /**
774      * Main method.
775      *
776      * @param args
777      *            array
778      */
779     public static void main(String[] args) {
780         OnapCli cli = new OnapCli(args); //NOSONAR
781         cli.handle();
782         System.exit(cli.getExitCode());
783     }
784
785 }