aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/main/java/org/onap/cli/main/OnapCli.java
blob: 4cc2132df97c3294cc87efa2c222e88c6aba84d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
 * Copyright 2017 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.cli.main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.onap.cli.fw.OnapCommand;
import org.onap.cli.fw.OnapCommandRegistrar;
import org.onap.cli.fw.conf.Constants;
import org.onap.cli.fw.conf.OnapCommandConfg;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.error.OnapCommandHelpFailed;
import org.onap.cli.fw.error.OnapCommandInvalidSample;
import org.onap.cli.fw.error.OnapCommandWarning;
import org.onap.cli.fw.input.OnapCommandParameter;
import org.onap.cli.fw.output.OnapCommandResult;
import org.onap.cli.fw.output.OnapCommandResultAttribute;
import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
import org.onap.cli.fw.output.PrintDirection;
import org.onap.cli.fw.output.ResultType;
import org.onap.cli.main.conf.OnapCliConstants;
import org.onap.cli.main.interactive.StringCompleter;
import org.onap.cli.main.utils.OnapCliUtils;
import org.onap.cli.sample.yaml.SampleYamlGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jline.TerminalFactory;
import jline.console.ConsoleReader;

/**
 * Onap Command Line Interface (CLI).
 *
 */
public class OnapCli {

    private static Logger LOG = LoggerFactory.getLogger(OnapCli.class);

    private List<String> args = new ArrayList<>();

    private int exitCode = -1;

    public OnapCli(String[] args) {
        this.args = Arrays.asList(args);
    }

    private void exitSuccessfully() {
        this.exitCode = OnapCliConstants.EXIT_SUCCESS;
    }

    private void exitFailure() {
        this.exitCode = OnapCliConstants.EXIT_FAILURE;
    }

    private void print(String msg) {
        System.out.println(msg);
    }

    private void print(Throwable throwable) {
        this.print(throwable.getMessage());
        LOG.error(throwable.getMessage(), throwable);
    }

    private String getShortOption(String opt) {
        return OnapCommandParameter.printShortOption(opt);
    }

    private String getLongOption(String opt) {
        return OnapCommandParameter.printLongOption(opt);
    }

    public int getExitCode() {
        return this.exitCode;
    }

    /**
     * Handles help. --help or -h
     */
    public void handleHelp() {
        try {
            if ((args.size() == 1) && (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(0))
                        || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(0)))) {
                this.print(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("onap-readme.txt")));
                String help = OnapCommandRegistrar.getRegistrar().getHelp();
                this.print(help);
                this.exitSuccessfully();
            }
        } catch (Exception e) {
            this.print(e);
            this.exitFailure();
        }
    }

    /**
     * Handles version. --version or -v
     */
    public void handleVersion() {
        try {
            if ((args.size() == 1) && (this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG).equals(args.get(0))
                    || this.getShortOption(OnapCliConstants.PARAM_VERSION_SHORT).equals(args.get(0)))) {
                String version = OnapCommandRegistrar.getRegistrar().getVersion();
                this.print(version);
                this.exitSuccessfully();
            }
        } catch (Exception e) {
            this.print(e);
            this.exitFailure();
        }
    }


    /**
     * Handles profile. --profile or -c
     */
    public void handleProfile() {
        try {
            if ((args.size() == 2) && (this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG).equals(args.get(0))
                        || this.getShortOption(OnapCliConstants.PARAM_PROFILE_SHORT).equals(args.get(0)))) {

                OnapCommandRegistrar.getRegistrar().setProfile(args.get(1));
                //Make space of interactive mode
                this.args = new ArrayList<>();
            }
        } catch (Exception e) {
            this.print(e);
            this.exitFailure();
        }
    }

    public static String getDirectiveHelp() throws OnapCommandHelpFailed {
        OnapCommandResult help = new OnapCommandResult();
        help.setType(ResultType.TABLE);
        help.setPrintDirection(PrintDirection.LANDSCAPE);

        OnapCommandResultAttribute attr = new OnapCommandResultAttribute();
        attr.setName(Constants.NAME.toUpperCase());
        attr.setDescription(Constants.DESCRIPTION);
        attr.setScope(OnapCommandResultAttributeScope.SHORT);
        help.getRecords().add(attr);

        OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
        attrDesc.setName(Constants.DESCRIPTION.toUpperCase());
        attrDesc.setDescription(Constants.DESCRIPTION);
        attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
        help.getRecords().add(attrDesc);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP_MSG);

        attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
        attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE_MSG);
        try {
            return "\n\nDirectives:\n" + help.print();
        } catch (OnapCommandException e) {
            throw new OnapCommandHelpFailed(e);
        }
    }
    /**
     * Handles Interactive Mode.
     */
    public void handleInteractive() { // NOSONAR
        if (args.isEmpty()) {
            ConsoleReader console = null;
            try {
                OnapCommandRegistrar.getRegistrar().setInteractiveMode(true);
                console = createConsoleReader();
                String line = null;

                while ((line = console.readLine()) != null) {
                    if (OnapCliConstants.PARAM_INTERACTIVE_EXIT.equalsIgnoreCase(line)) {
                        break;
                    } else if (OnapCliConstants.PARAM_INTERACTIVE_CLEAR.equalsIgnoreCase(line)) {
                        console.clearScreen();
                        continue;
                    }
                    this.args = Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN));

                    if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
                        if (args.size() == 1) {
                            this.print("Please input the product version to use, supported versions: " +
                                    OnapCommandRegistrar.getRegistrar().getAvailableProductVersions());
                        } else {
                            try {
                                OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(args.get(1));
                                console.close();
                                console = createConsoleReader();
                            } catch (OnapCommandException e) {
                                this.print(e);
                            }
                        }
                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
                        try {
                            this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
                            this.print(this.getDirectiveHelp());
                        } catch (OnapCommandException e) {
                            this.print(e);
                        }
                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
                        this.args = Arrays.asList(new String [] {this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG)});
                        handleVersion();
                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) {
                        if (args.size() == 1) {
                            this.print("Please use it in the form of 'profile <profile-name>'");
                        } else {
                            this.args = Arrays.asList(new String [] {
                                    this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG),
                                    this.args.get(1)});
                            handleProfile();
                        }
                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) {
                        if (args.size() > 1) {
                            String [] paramEntry = args.get(1).trim().split("=");
                            if (paramEntry.length >= 2) {
                                OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim());
                            } else {
                                this.print("Please use it in the form of 'set param-name=param-value'");
                            }
                        } else {
                            this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString());
                        }
                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) {
                        if (args.size() > 1) {
                            for (int i = 1; i <args.size(); i++) {
                                OnapCommandRegistrar.getRegistrar().removeParamCache(args.get(i));
                            }
                        }
                    } else {
                        if (args.size() == 1 && args.get(0).trim().isEmpty()) {
                            //Ignore blanks // NOSONAR
                            continue;
                        }

                        handleCommand();
                    }
                }
            } catch (IOException e) { // NOSONAR
                this.print("Failed to read console, " + e.getMessage());
            } catch (OnapCommandException e) {
                this.print(e);
                this.exitFailure();
            } finally {
                try {
                    TerminalFactory.get().restore();
                } catch (Exception e) { // NOSONAR
                }
                if (console != null) {
                    console.close();
                }
                this.exitSuccessfully();
            }
        }
    }

    /**
     * Creates console reader object.
     *
     * @return ConsoleReader
     * @throws IOException
     *             exception
     */
    private ConsoleReader createConsoleReader() throws IOException {
        ConsoleReader console = new ConsoleReader();
        try {
            StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion());
            strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT,
                    OnapCliConstants.PARAM_INTERACTIVE_CLEAR,
                    OnapCliConstants.PARAM_INTERACTIVE_USE,
                    OnapCliConstants.PARAM_INTERACTIVE_HELP,
                    OnapCliConstants.PARAM_INTERACTIVE_VERSION,
                    OnapCliConstants.PARAM_INTERACTIVE_SET,
                    OnapCliConstants.PARAM_INTERACTIVE_UNSET,
                    OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
            console.addCompleter(strCompleter);
            console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT);
        } catch (OnapCommandException e) { // NOSONAR
            this.print("Failed to load onap commands," + e.getMessage());
        }

        return console;
    }

    /**
     * Handles command.
     */
    public void handleCommand() {
        OnapCommand cmd;
        if (!args.isEmpty()) {
            try {
                cmd = OnapCommandRegistrar.getRegistrar().get(args.get(0));
            } catch (Exception e) {
                this.print(e);
                this.exitFailure();
                return;
            }
            try {
                // check for help or version
                if (args.size() == 2) {
                    if (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(1))
                            || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(1))) {
                        String help = cmd.printHelp();
                        this.print(help);
                        this.exitSuccessfully();
                        return;
                    } else if (this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG).equals(args.get(1))
                            || this.getShortOption(OnapCliConstants.PARAM_VERSION_SHORT).equals(args.get(1))) {
                        String version = cmd.printVersion();
                        this.print(version);
                        this.exitSuccessfully();
                        return;
                    }
                }

                for (OnapCommandParameter param: cmd.getParameters()) {
                    if (OnapCommandRegistrar.getRegistrar().getParamCache().containsKey(
                            cmd.getService().getName() + ":" + param.getLongOption())) {
                        param.setValue(OnapCommandRegistrar.getRegistrar().getParamCache().get(
                                cmd.getService().getName() + ":" + param.getLongOption()));
                    } else if (OnapCommandRegistrar.getRegistrar().getParamCache().containsKey(param.getLongOption())) {
                        param.setValue(OnapCommandRegistrar.getRegistrar().getParamCache().get(param.getLongOption()));
                    }
                }

                OnapCliUtils.populateParams(cmd.getParameters(), args);
                OnapCommandResult result = cmd.execute();

                this.print(result.getDebugInfo());
                this.print(result.print());
                this.exitSuccessfully();

                generateSmapleYaml(cmd);
            } catch (Exception e) {
                this.print(cmd.getResult().getDebugInfo());
                if (e instanceof OnapCommandWarning) {
                    this.exitSuccessfully();
                } else {
                    this.print(e);
                    this.exitFailure();
                }
            }
        }
    }

    private void generateSmapleYaml(OnapCommand cmd) throws OnapCommandException {
        if (OnapCommandConfg.isSampleGenerateEnabled() && this.getExitCode() == OnapCliConstants.EXIT_SUCCESS) {
            try {
                SampleYamlGenerator.generateSampleYaml(args, cmd.getResult().print(),
                        OnapCommandRegistrar.getRegistrar().getEnabledProductVersion(),
                        OnapCommandConfg.getSampleGenerateTargetFolder() + "/" + cmd.getSchemaName().replaceAll(".yaml", "") + "-sample.yaml",
                        cmd.getResult().isDebug());
            } catch (IOException error) {
                throw new OnapCommandInvalidSample(args.get(0), error);
            }
        }
    }

    /**
     * Handles all client input.
     */
    public void handle() {
        this.handleHelp();

        if (this.exitCode == -1) {
            this.handleVersion();
        }

        if (this.exitCode == -1) {
            this.handleProfile();
        }

        if (this.exitCode == -1) {
            this.handleInteractive();
        }

        if (this.exitCode == -1) {
            this.handleCommand();
        }
    }

    /**
     * Main method.
     *
     * @param args
     *            array
     */
    public static void main(String[] args) {
        OnapCli cli = new OnapCli(args);
        cli.handle();
        System.exit(cli.getExitCode());
    }

}