aboutsummaryrefslogtreecommitdiffstats
path: root/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCommandLineEditorMain.java
blob: 9258b45b8e4a88d54263d8c2e695fadb59345f3d (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2019 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.auth.clieditor;

import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import org.onap.policy.apex.auth.clieditor.utils.CliUtils;
import org.onap.policy.apex.model.utilities.json.JsonHandler;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * This class initiates an Apex CLI editor from a java main method.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class ApexCommandLineEditorMain {
    // Get a reference to the logger
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexCommandLineEditorMain.class);

    // The editor parameters
    private CommandLineParameters parameters;

    // The CLI commands read in from JSON
    private CommandLineCommands commands;

    // The Apex model properties read in from JSON
    private ApexModelProperties apexModelProperties;

    // The number of errors encountered in command processing
    private int errorCount = 0;

    /**
     * Instantiates the Apex CLI editor.
     *
     * @param args the command line arguments
     */
    public ApexCommandLineEditorMain(final String[] args) {
        String startMessage = "Starting Apex CLI editor " + Arrays.toString(args) + " . . .";
        LOGGER.info(startMessage);

        try {
            final CommandLineParameterParser parser = new CommandLineParameterParser();
            parameters = parser.parse(args);

            if (parameters.isHelpSet()) {
                CliUtils.help(ApexCommandLineEditorMain.class.getName(), parser.getOptions());
                return;
            }
            parameters.validate();
        } catch (final Exception e) {
            LOGGER.error("start of Apex command line editor failed, ", e);
            errorCount++;
            return;
        }

        String message = "parameters are: " + parameters.toString();
        LOGGER.debug(message);

        // Read the command definitions
        try {
            commands = new JsonHandler<CommandLineCommands>().read(CommandLineCommands.class,
                            parameters.getMetadataStream());
        } catch (final Exception e) {
            LOGGER.error("start of Apex command line editor failed, error reading command metadata from {}",
                            parameters.getMetadataLocation(), e);
            errorCount++;
            return;
        }

        // The JSON processing returns null if there is an empty file
        if (commands == null || commands.getCommandSet().isEmpty()) {
            LOGGER.error("start of Apex command line editor failed, no commands found in {}",
                            parameters.getApexPropertiesLocation());
            errorCount++;
            return;
        }

        LOGGER.debug("found {} commands", commands.getCommandSet().size());

        // Read the Apex properties
        try {
            apexModelProperties = new JsonHandler<ApexModelProperties>().read(ApexModelProperties.class,
                            parameters.getApexPropertiesStream());
        } catch (final Exception e) {
            LOGGER.error("start of Apex command line editor failed, error reading Apex model properties from "
                            + parameters.getApexPropertiesLocation(), e);
            errorCount++;
            return;
        }

        // The JSON processing returns null if there is an empty file
        if (apexModelProperties == null) {
            LOGGER.error("start of Apex command line editor failed, no Apex model properties found in {}",
                            parameters.getApexPropertiesLocation());
            errorCount++;
            return;
        }

        String modelPropertiesString = "model properties are: " + apexModelProperties.toString();
        LOGGER.debug(modelPropertiesString);

        // Find the system commands
        final Set<KeywordNode> systemCommandNodes = new TreeSet<>();
        for (final CommandLineCommand command : commands.getCommandSet()) {
            if (command.isSystemCommand()) {
                systemCommandNodes.add(new KeywordNode(command.getName(), command));
            }
        }

        // Read in the command hierarchy, this builds a tree of commands
        final KeywordNode rootKeywordNode = new KeywordNode("root");
        for (final CommandLineCommand command : commands.getCommandSet()) {
            rootKeywordNode.processKeywords(command.getKeywordlist(), command);
        }
        rootKeywordNode.addSystemCommandNodes(systemCommandNodes);

        // Create the model we will work towards
        ApexModelHandler modelHandler = null;
        try {
            modelHandler = new ApexModelHandler(apexModelProperties.getProperties(),
                            parameters.getInputModelFileName());
        } catch (final Exception e) {
            LOGGER.error("execution of Apex command line editor failed: ", e);
            errorCount++;
            return;
        }

        final CommandLineEditorLoop cliEditorLoop = new CommandLineEditorLoop(apexModelProperties.getProperties(),
                        modelHandler, rootKeywordNode);
        try {
            errorCount = cliEditorLoop.runLoop(parameters.getCommandInputStream(), parameters.getOutputStream(),
                            parameters);

            if (errorCount == 0) {
                LOGGER.info("Apex CLI editor completed execution");
            } else {
                LOGGER.error("execution of Apex command line editor failed: {} command execution failure(s) occurred",
                                errorCount);
            }
        } catch (final IOException e) {
            LOGGER.error("execution of Apex command line editor failed: " + e.getMessage(), e);
        }
    }

    /**
     * Get the number of errors encountered in command processing.
     *
     * @return the number of errors
     */
    public int getErrorCount() {
        return errorCount;
    }

    /**
     * Sets the number of errors encountered in command processing.
     *
     * @param errorCount the number of errors
     */
    public void setErrorCount(final int errorCount) {
        this.errorCount = errorCount;
    }

    /**
     * The main method, kicks off the editor.
     *
     * @param args the arguments
     */
    public static void main(final String[] args) {
        final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(args);

        // Only call system.exit on errors as it brings the JVM down
        if (cliEditor.getErrorCount() > 0) {
            System.exit(cliEditor.getErrorCount());
        }
    }
}