67d247e8d8cdc63883d02bd6b07b5ad0c12f576f
[policy/apex-pdp.git] / auth / cli-editor / src / main / java / org / onap / policy / apex / auth / clieditor / ApexModelHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.auth.clieditor;
22
23 import java.io.PrintWriter;
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.util.Properties;
27 import java.util.SortedMap;
28
29 import org.onap.policy.apex.model.modelapi.ApexApiResult;
30 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
31 import org.onap.policy.apex.model.modelapi.ApexModel;
32 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
33
34 /**
35  * This class instantiates and holds the Apex model being manipulated by the editor.
36  *
37  * @author Liam Fallon (liam.fallon@ericsson.com)
38  */
39 public class ApexModelHandler {
40     private static final String FAILED_FOR_COMMAND = "\" failed for command \"";
41     private static final String INVOCATION_OF_SPECIFIED_METHOD = "invocation of specified method \"";
42     private ApexModel apexModel = null;
43
44     /**
45      * Create the Apex Model with the properties specified.
46      *
47      * @param properties The properties of the Apex model
48      */
49     public ApexModelHandler(final Properties properties) {
50         apexModel = new ApexModelFactory().createApexModel(properties, true);
51     }
52
53     /**
54      * Create the Apex Model with the properties specified and load it from a file.
55      *
56      * @param properties The properties of the Apex model
57      * @param modelFileName The name of the model file to edit
58      */
59     public ApexModelHandler(final Properties properties, final String modelFileName) {
60         this(properties);
61
62         if (modelFileName == null) {
63             return;
64         }
65
66         final ApexApiResult result = apexModel.loadFromFile(modelFileName);
67         if (result.isNok()) {
68             throw new CommandLineException(result.getMessages().get(0));
69         }
70     }
71
72     /**
73      * Execute a command on the Apex model.
74      *
75      * @param command The command to execute
76      * @param argumentValues Arguments of the command
77      * @param writer A writer to which to write output
78      * @return the result of the executed command
79      */
80     public Result executeCommand(final CommandLineCommand command,
81                     final SortedMap<String, CommandLineArgumentValue> argumentValues, final PrintWriter writer) {
82         // Get the method
83         final Method apiMethod = getCommandMethod(command);
84
85         // Get the method arguments
86         final Object[] parameterArray = getParameterArray(command, argumentValues, apiMethod);
87
88         try {
89             final Object returnObject = apiMethod.invoke(apexModel, parameterArray);
90
91             if (returnObject instanceof ApexApiResult) {
92                 final ApexApiResult result = (ApexApiResult) returnObject;
93                 writer.println(result);
94                 return result.getResult();
95             } else {
96                 throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod()
97                                 + FAILED_FOR_COMMAND + command.getName()
98                                 + "\" the returned object is not an instance of ApexAPIResult");
99             }
100         } catch (IllegalAccessException | IllegalArgumentException e) {
101             writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
102                             + command.getName() + "\"");
103             e.printStackTrace(writer);
104             throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
105                             + command.getName() + "\"", e);
106         } catch (final InvocationTargetException e) {
107             writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
108                             + command.getName() + "\"");
109             e.getCause().printStackTrace(writer);
110             throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
111                             + command.getName() + "\"", e);
112         }
113     }
114
115     /**
116      * Find the API method for the command.
117      *
118      * @param command The command
119      * @return the API method
120      */
121     private Method getCommandMethod(final CommandLineCommand command) {
122         final String className = command.getApiClassName();
123         final String methodName = command.getApiMethodName();
124
125         try {
126             final Class<? extends Object> apiClass = Class.forName(className);
127             for (final Method apiMethod : apiClass.getMethods()) {
128                 if (apiMethod.getName().equals(methodName)) {
129                     return apiMethod;
130                 }
131             }
132             throw new CommandLineException("specified method \"" + command.getApiMethod()
133                             + "\" not found for command \"" + command.getName() + "\"");
134         } catch (final ClassNotFoundException e) {
135             throw new CommandLineException("specified class \"" + command.getApiMethod() + "\" not found for command \""
136                             + command.getName() + "\"", e);
137         }
138     }
139
140     /**
141      * Get the arguments of the command as an ordered array of objects ready for the method.
142      *
143      * @param command the command that invoked the method
144      * @param argumentValues the argument values for the method
145      * @param apiMethod the method itself
146      * @return the argument list
147      */
148     private Object[] getParameterArray(final CommandLineCommand command,
149                     final SortedMap<String, CommandLineArgumentValue> argumentValues, final Method apiMethod) {
150         final Object[] parameterArray = new Object[argumentValues.size()];
151
152         int item = 0;
153         try {
154             for (final Class<?> parametertype : apiMethod.getParameterTypes()) {
155                 final String parameterValue = argumentValues.get(command.getArgumentList().get(item).getArgumentName())
156                                 .getValue();
157
158                 if (parametertype.equals(boolean.class)) {
159                     parameterArray[item] = Boolean.valueOf(parameterValue);
160                 } else {
161                     parameterArray[item] = parameterValue;
162                 }
163                 item++;
164             }
165         } catch (final Exception e) {
166             throw new CommandLineException("number of argument mismatch on method \"" + command.getApiMethod()
167                             + "\" for command \"" + command.getName() + "\"", e);
168         }
169
170         return parameterArray;
171     }
172
173     /**
174      * Save the model to a string.
175      *
176      * @param messageWriter the writer to write status messages to
177      * @return the string
178      */
179     public String writeModelToString(final PrintWriter messageWriter) {
180         final ApexApiResult result = apexModel.listModel();
181
182         if (result.isOk()) {
183             return result.getMessage();
184         } else {
185             return null;
186         }
187     }
188 }