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