Merge changes I20ff8508,I00e014fd
[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                 handleBatchCommandUtil();
245             }
246         } catch (Exception e) {
247             this.print(e);
248             this.exitFailure();
249         }
250     }
251
252     private void handleBatchCommandUtil() {
253         //Read YAML and loop thru it
254         // one
255         // - param-long-option-1: value
256         // - param-long-option-1: value
257         // - positional-arg1
258         // - positional-arg2
259         // two
260         // - param-long-option-1: value
261         // - param-long-option-1: value
262         // - positional-arg1
263         // - positional-arg2
264         try {
265             Map<String, Object> values = OnapCommandDiscoveryUtils.loadYaml(this.paramFile);
266
267             for (Entry<String, Object> cmdsParam: values.entrySet()) {
268                 for (Object param: (List)cmdsParam.getValue()) {
269                     if (param instanceof Map) { //optional args
270                         Map <String, String> paramMap = (Map<String, String>) param;
271                         String paramName = paramMap.keySet().iterator().next();
272                         Object paramValue = paramMap.get(paramName);
273                         argsParamFile.add(this.getLongOption(paramName));
274                         argsParamFile.add(paramValue.toString());
275                     } else { //positional args
276                         argsParamFile.add(param.toString());
277                     }
278                 }
279             }
280
281         } catch (Exception e) { // NOSONAR
282             this.print("Failed to read param file " + this.paramFile);
283             this.print(e);
284         }
285     }
286
287     public void verifyCommand(OnapCommand cmd) throws OnapCommandException {
288
289         OnapCliArgsParser.populateParams(cmd.getParameters(), args);
290
291         Optional<OnapCommandParameter> contextOptArg = cmd.getParameters().stream()
292                 .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
293                 .findFirst();
294
295         List<Map<String, Object>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(
296                 cmd.getName(),
297                 cmd.getInfo().getProduct());
298
299         OnapCommandResult testSuiteResult = new OnapCommandResult();
300         testSuiteResult.setType(OnapCommandResultType.TABLE);
301         testSuiteResult.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
302         testSuiteResult.setIncludeTitle(true);
303
304         OnapCommandResultAttribute sampleFileAtt = new OnapCommandResultAttribute();
305         OnapCommandResultAttribute sampleIdAtt = new OnapCommandResultAttribute();
306         OnapCommandResultAttribute resultAtt = new OnapCommandResultAttribute();
307
308         sampleFileAtt.setName("Test");
309         sampleIdAtt.setName("SampleId");
310         resultAtt.setName("Result");
311
312         testSuiteResult.setRecords(Arrays.asList(sampleFileAtt,
313                 sampleIdAtt,
314                 resultAtt));
315
316         for (Map<String, ?> sampleTest : testSuite) {
317
318             sampleFileAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID));
319             sampleIdAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_ID));
320
321             cmd = OnapCommandRegistrar.getRegistrar().get(cmd.getName(),
322                     cmd.getInfo().getProduct());
323             List<String> arguments = (List<String>) sampleTest.get(OnapCommandConstants.VERIFY_INPUT);
324
325             OnapCliArgsParser.populateParams(cmd.getParameters(), arguments);
326             this.print("\n***************Test Command: \n" + sampleTest.get(OnapCommandConstants.VERIFY_INPUT).toString());
327
328             cmd.getParametersMap().get(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG).setValue(Boolean.TRUE);
329
330             Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream()
331                     .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
332                     .findFirst();
333
334             if (contextOpt.isPresent()) {
335                 HashMap<String, Object> map = new HashMap<>();
336
337                 Object moco = sampleTest.get(OnapCommandConstants.VERIFY_MOCO);
338                 if (moco == null) {
339                     continue;
340                 }
341                 map.put(OnapCommandConstants.VERIFY_MOCO, moco);
342
343                 if (contextOptArg.isPresent()) {
344                     OnapCommandParameter contextArg = contextOptArg.get();
345                     map.putAll((Map) contextArg.getValue());
346                 }
347
348                 contextOpt.get().setValue(map);
349             }
350
351             OnapCommandResult testResult = cmd.execute();
352             String actualOutput = testResult.print().trim();
353             String expectedOutput = (String) sampleTest.get(OnapCommandConstants.VERIFY_OUPUT);
354             expectedOutput = expectedOutput == null ? "" : expectedOutput.trim();
355
356             if (actualOutput.equals(expectedOutput)) {
357                 resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_PASS);
358             } else {
359                 resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_FAIL);
360             }
361             this.printerr(testResult.getDebugInfo());
362             this.print("\n***************Expected Output: \n" + expectedOutput);
363             this.print("\n***************Actual Output: \n" + actualOutput);
364         }
365
366         this.print(testSuiteResult.print());
367     }
368
369     /**
370      * Handles Interactive Mode.
371      */
372     public void handleInteractive() { // NOSONAR
373         if (this.cmdName == null) {
374             ConsoleReader console = null;
375             try {
376                 OnapCommandRegistrar.getRegistrar().setInteractiveMode(true);
377                 console = createConsoleReader();
378                 String line = null;
379
380                 while ((line = console.readLine()) != null) {
381                     line = line.trim();
382                     if (OnapCliConstants.PARAM_INTERACTIVE_EXIT.equalsIgnoreCase(line)) {
383                         break;
384                     } else if (OnapCliConstants.PARAM_INTERACTIVE_CLEAR.equalsIgnoreCase(line)) {
385                         console.clearScreen();
386                     } else {
387                         this.args = new ArrayList<>();
388                         this.args.addAll(Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)));
389
390                         if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
391                             if (args.size() == 1) {
392                                 this.print("Please use it in the form of use <product-version>.\nSupported versions: " +
393                                         OnapCommandRegistrar.getRegistrar().getAvailableProductVersions());
394                             } else {
395                                 OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(args.get(1));
396                                 console = createConsoleReader();
397                             }
398
399                         } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
400                             this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
401                             this.print(OnapCli.getDirectiveHelp());
402                         } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
403                             this.printVersion = true;
404                             handleVersion();
405
406                         } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) {
407                             if (args.size() == 1) {
408                                 this.print("Please use it in the form of 'profile <profile-name>'\n");
409                                 this.print("Available profiles: ");
410                                 this.print(OnapCommandRegistrar.getRegistrar().getUserProfiles().toString());
411                             } else {
412                                 this.profile = args.get(1);
413                                 handleProfile();
414                             }
415
416                         } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) {
417                             if (args.size() > 1) {
418                                 String[] paramEntry = args.get(1).trim().split("=", 2);
419                                 if (paramEntry.length == 2) {
420                                     OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim());
421                                 } else {
422                                     this.print("Please use it in the form of 'set <param-name>=<param-value>'");
423                                 }
424                             } else {
425                                 this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString());
426                             }
427
428                         } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) {
429                             if (args.size() > 1) {
430                                 for (int i = 1; i < args.size(); i++) {
431                                     OnapCommandRegistrar.getRegistrar().removeParamCache(args.get(i));
432                                 }
433                             }
434                         } else {
435                             if (!(args.size() == 1 && args.get(0).trim().isEmpty())) {
436                                 this.setArgs(this.args.toArray(new String[]{}));
437                                 handleCommand();
438                             }
439                         }
440                     }
441                 }
442             } catch (IOException e) { // NOSONAR
443                 this.print("Failed to read console, " + e.getMessage());
444             } catch (OnapCommandException e) {
445                 this.print(e);
446                 this.exitFailure();
447             } finally {
448                 try {
449                     TerminalFactory.get().restore();
450                 } catch (Exception e) { // NOSONAR
451                 }
452                 this.exitSuccessfully();
453             }
454         }
455     }
456
457     /**
458      * Handles command.
459      */
460     public void handleCommand() {
461         OnapCommand cmd = null;
462         if (this.cmdName != null) {
463             try {
464                 if (this.product != null) {
465                     cmd = OnapCommandRegistrar.getRegistrar().get(this.cmdName, this.product);
466                 } else {
467                     cmd = OnapCommandRegistrar.getRegistrar().get(this.cmdName);
468                 }
469             } catch (Exception e) {
470                 this.print(e);
471                 this.exitFailure();
472                 return;
473             }
474
475             ExecutionStoreContext executionStoreContext = null;
476
477             try {
478                 //Registrar identified this command marked with rpc as true and it will make direct RPC command call...
479                 if (cmd.isRpc() && !this.cmdName.equals("schema-rpc")) {
480                     this.handleRpcCommand(cmd);
481                     return;
482                 }
483
484                 // verify
485                 if(args.contains(OnapCommandConstants.VERIFY_LONG_OPTION)
486                         || args.contains(OnapCommandConstants.VERIFY_SHORT_OPTION)) {
487                     verifyCommand(cmd);
488                     this.exitSuccessfully();
489                     return;
490                 }
491                 // check for help or version
492                 if (args.size() == 2) {
493                     if (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(1))
494                             || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(1))) {
495                         String help = cmd.printHelp();
496                         this.print(help);
497                         this.exitSuccessfully();
498                         return;
499                     } else if (this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG).equals(args.get(1))
500                             || this.getShortOption(OnapCliConstants.PARAM_VERSION_SHORT).equals(args.get(1))) {
501                         String version = cmd.printVersion();
502                         this.print(version);
503                         this.exitSuccessfully();
504                         return;
505                     }
506                 }
507
508                 //refer params from profile
509                 if (this.profile != null) {
510
511                     Map<String, String> paramCache = new HashMap<>(); //NOSONAR
512                     if (this.product == null)
513                         paramCache = OnapCommandRegistrar.getRegistrar().getParamCache();
514                     else
515                         paramCache = OnapCommandRegistrar.getRegistrar().getParamCache(this.product);
516
517                     for (OnapCommandParameter param: cmd.getParameters()) {
518                         if (paramCache.containsKey(
519                                 cmd.getInfo().getService() + ":" + cmd.getName() + ":" + param.getLongOption())) {
520                             param.setValue(paramCache.get(
521                                     cmd.getInfo().getService() + ":" + cmd.getName() + ":" + param.getLongOption()));
522                         } else if (paramCache.containsKey(
523                                 cmd.getInfo().getService() + ":" + param.getLongOption())) {
524                             param.setValue(paramCache.get(
525                                     cmd.getInfo().getService() + ":" + param.getLongOption()));
526                         } else if (paramCache.containsKey(param.getLongOption())) {
527                             param.setValue(paramCache.get(param.getLongOption()));
528                         }
529                     }
530                 }
531
532                 //load the parameters value from the map read from param-file
533                 if (!this.argsParamFile.isEmpty()) {
534                     OnapCliArgsParser.populateParams(cmd.getParameters(), this.argsParamFile);
535                 }
536
537                 OnapCliArgsParser.populateParams(cmd.getParameters(), this.args);
538
539                 //start the execution
540                     if (this.requestId != null && this.product != null && !this.requestId.isEmpty()&& !(this.product.equalsIgnoreCase("open-cli") &&
541                             this.cmdName.equalsIgnoreCase("execution-list"))) {
542                         String input = cmd.getArgsJson(true);
543                         executionStoreContext = OnapCommandExecutionStore.getStore().storeExectutionStart(
544                                 this.requestId,
545                                 cmd.getInfo().getProduct(),
546                                 cmd.getInfo().getService(),
547                                 this.cmdName,
548                                 this.profile,
549                                 input);
550                     }
551
552                 cmd.setExecutionContext(executionStoreContext);
553                 OnapCommandResult result = cmd.execute();
554
555                 this.handleTracking(cmd);
556
557                 if (result.isPassed()) {
558                     this.exitSuccessfully();
559                     generateSmapleYaml(cmd);
560                 } else {
561                     this.exitFailure();
562                 }
563             } catch (OnapCommandWarning w) {
564                 if (cmd.getExecutionContext() != null) {
565                     OnapCommandExecutionStore.getStore().storeExectutionEnd(
566                             cmd.getExecutionContext(),
567                             w.getMessage(),
568                             null,
569                             cmd.getResult().getDebugInfo(),
570                             cmd.getResult().isPassed());
571                 }
572
573                 this.print(w);
574                 this.printerr(cmd.getResult().getDebugInfo());
575                 this.exitSuccessfully();
576             } catch (Exception e) {
577                 if (executionStoreContext != null) {
578                     OnapCommandExecutionStore.getStore().storeExectutionEnd(
579                             executionStoreContext,
580                             null,
581                             e.getMessage(),
582                             cmd.getResult().getDebugInfo(),
583                             false);
584                 }
585
586                 this.print(e);
587                 this.printerr(cmd.getResult().getDebugInfo());
588                 this.exitFailure();
589             }
590         }
591     }
592
593     public void handleTracking(OnapCommand cmd) throws OnapCommandException {
594         if (cmd.getResult().isDebug())
595             this.printerr(cmd.getResult().getDebugInfo());
596
597         String printOut = cmd.getResult().print();
598         this.print(printOut);
599
600         if (cmd.getExecutionContext() != null) {
601             OnapCommandExecutionStore.getStore().storeExectutionEnd(
602                     cmd.getExecutionContext(),
603                     printOut,
604                     null,
605                     cmd.getResult().getDebugInfo(),
606                     cmd.getResult().isPassed());
607         }
608     }
609     /**
610      * When user invokes cli with RPC arguments...
611      */
612     public void handleRpc() {
613         if (this.rpcHost != null && this.rpcPort != null && this.product != null) {
614             try {
615                 OnapCommand cmd = OnapCommandRegistrar.getRegistrar().get("schema-rpc", "open-cli");
616                 cmd.getParametersMap().get(OnapCommandConstants.RPC_HOST).setValue(this.rpcHost);
617                 cmd.getParametersMap().get(OnapCommandConstants.RPC_PORT).setValue(this.rpcPort);
618                 cmd.getParametersMap().get(OnapCommandConstants.RPC_PRODUCT).setValue(this.product);
619                 cmd.getParametersMap().get(OnapCommandConstants.RPC_CMD).setValue(this.cmdName);
620
621                 this.handleRpcCommand(cmd);
622             } catch (Exception e) {
623                 this.print(e);
624                 this.exitFailure();
625             }
626         }
627     }
628
629     private void handleRpcCommand(OnapCommand cmd) throws OnapCommandException {
630         Map<String, List<String>> argsMap = new HashMap<>();
631         argsMap.put(OnapCommandConstants.RPC_ARGS, this.args);
632         if (this.profile != null )
633             cmd.getParametersMap().get(OnapCommandConstants.RPC_PROFILE).setValue(this.profile);
634         cmd.getParametersMap().get(OnapCommandConstants.RPC_REQID).setValue(this.requestId);
635         cmd.getParametersMap().get(OnapCommandConstants.RPC_MODE).setValue(OnapCommandConstants.RPC_MODE_RUN_CLI);
636         cmd.getParametersMap().get(OnapCommandConstants.RPC_ARGS).setValue(argsMap);
637
638         OnapCommandResult result = cmd.execute();
639         Result output = (Result) result.getOutput();
640
641         this.exitCode = output.getExitCode();
642         this.print(output.getOutput());
643     }
644     /**
645      * Handles all client input.
646      */
647     public void handle() {
648         this.handleRpc();
649
650         if (this.exitCode == -1) {
651             this.handleHelp();
652         }
653
654         if (this.exitCode == -1) {
655             this.handleVersion();
656         }
657
658         if (this.exitCode == -1) {
659             this.handleProfile();
660         }
661
662         if (this.exitCode == -1) {
663             this.handleBatchCommand();
664         }
665
666         if (this.exitCode == -1) {
667             this.handleInteractive();
668         }
669
670         if (this.exitCode == -1) {
671             this.handleCommand();
672         }
673     }
674
675     public static String getDirectiveHelp() throws OnapCommandHelpFailed {
676         OnapCommandResult help = new OnapCommandResult();
677         help.setType(OnapCommandResultType.TABLE);
678         help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
679
680         OnapCommandResultAttribute attr = new OnapCommandResultAttribute();
681         attr.setName(OnapCommandConstants.NAME.toUpperCase());
682         attr.setDescription(OnapCommandConstants.DESCRIPTION);
683         attr.setScope(OnapCommandResultAttributeScope.SHORT);
684         help.getRecords().add(attr);
685
686         OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
687         attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase());
688         attrDesc.setDescription(OnapCommandConstants.DESCRIPTION);
689         attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
690         help.getRecords().add(attrDesc);
691
692         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR);
693         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR_MSG);
694
695         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT);
696         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT_MSG);
697
698         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION);
699         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION_MSG);
700
701         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE);
702         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE_MSG);
703
704         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET);
705         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET_MSG);
706
707         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET);
708         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET_MSG);
709
710         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP);
711         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP_MSG);
712
713         attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
714         attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE_MSG);
715         try {
716             return "\n\nDirectives:\n" + help.print();
717         } catch (OnapCommandException e) {
718             throw new OnapCommandHelpFailed(e);
719         }
720     }
721
722     /**
723      * Creates console reader object.
724      *
725      * @return ConsoleReader
726      * @throws IOException
727      *             exception
728      */
729     private ConsoleReader createConsoleReader() throws IOException {
730         ConsoleReader console = new ConsoleReader(); // NOSONAR
731         try {
732             //ignore system commands
733             StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion());
734             strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT,
735                     OnapCliConstants.PARAM_INTERACTIVE_CLEAR,
736                     OnapCliConstants.PARAM_INTERACTIVE_USE,
737                     OnapCliConstants.PARAM_INTERACTIVE_HELP,
738                     OnapCliConstants.PARAM_INTERACTIVE_VERSION,
739                     OnapCliConstants.PARAM_INTERACTIVE_SET,
740                     OnapCliConstants.PARAM_INTERACTIVE_UNSET,
741                     OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
742             console.addCompleter(strCompleter);
743             console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">");
744         } catch (OnapCommandException e) { // NOSONAR
745             this.print("Failed to load oclip commands," + e.getMessage());
746         }
747
748         return console;
749     }
750
751
752     private void generateSmapleYaml(OnapCommand cmd) throws OnapCommandException {
753         if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED)) && this.getExitCode() == OnapCliConstants.EXIT_SUCCESS) {
754             try {
755                 SampleYamlGenerator.generateSampleYaml(cmd.getName(), args, cmd.getResult().print(),
756                         cmd.getInfo().getProduct(),
757                         OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER) + "/" + cmd.getSchemaName().replaceAll(".yaml", "") + "-sample.yaml",
758                         cmd.getResult().isDebug(),
759                         OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_NAME));
760             } catch (IOException error) {
761                 throw new OnapCommandInvalidSample(this.cmdName, error);
762             }
763         }
764     }
765
766     /**
767      * Main method.
768      *
769      * @param args
770      *            array
771      */
772     public static void main(String[] args) {
773         OnapCli cli = new OnapCli(args); //NOSONAR
774         cli.handle();
775         System.exit(cli.getExitCode());
776     }
777
778 }