Changes for checkstyle 8.32
[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 import org.onap.policy.apex.model.modelapi.ApexApiResult;
29 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
30 import org.onap.policy.apex.model.modelapi.ApexModel;
31 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
32
33 /**
34  * This class instantiates and holds the Apex model being manipulated by the editor.
35  *
36  * @author Liam Fallon (liam.fallon@ericsson.com)
37  */
38 public class ApexModelHandler {
39     private static final String FAILED_FOR_COMMAND = "\" failed for command \"";
40     private static final String INVOCATION_OF_SPECIFIED_METHOD = "invocation of specified method \"";
41     private ApexModel apexModel = null;
42
43     /**
44      * Create the Apex Model with the properties specified.
45      *
46      * @param properties The properties of the Apex model
47      */
48     public ApexModelHandler(final Properties properties) {
49         apexModel = new ApexModelFactory().createApexModel(properties, true);
50     }
51
52     /**
53      * Create the Apex Model with the properties specified and load it from a file.
54      *
55      * @param properties The properties of the Apex model
56      * @param modelFileName The name of the model file to edit
57      */
58     public ApexModelHandler(final Properties properties, final String modelFileName) {
59         this(properties);
60
61         if (modelFileName == null) {
62             return;
63         }
64
65         final ApexApiResult result = apexModel.loadFromFile(modelFileName);
66         if (result.isNok()) {
67             throw new CommandLineException(result.getMessages().get(0));
68         }
69     }
70
71     /**
72      * Execute a command on the Apex model.
73      *
74      * @param command The command to execute
75      * @param argumentValues Arguments of the command
76      * @param writer A writer to which to write output
77      * @return the result of the executed command
78      */
79     public Result executeCommand(final CommandLineCommand command,
80                     final SortedMap<String, CommandLineArgumentValue> argumentValues, final PrintWriter writer) {
81         // Get the method
82         final Method apiMethod = getCommandMethod(command);
83
84         // Get the method arguments
85         final Object[] parameterArray = getParameterArray(command, argumentValues, apiMethod);
86
87         try {
88             final Object returnObject = apiMethod.invoke(apexModel, parameterArray);
89
90             if (returnObject instanceof ApexApiResult) {
91                 final ApexApiResult result = (ApexApiResult) returnObject;
92                 writer.println(result);
93                 return result.getResult();
94             } else {
95                 throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod()
96                                 + FAILED_FOR_COMMAND + command.getName()
97                                 + "\" the returned object is not an instance of ApexAPIResult");
98             }
99         } catch (IllegalAccessException | IllegalArgumentException e) {
100             writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
101                             + command.getName() + "\"");
102             e.printStackTrace(writer);
103             throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
104                             + command.getName() + "\"", e);
105         } catch (final InvocationTargetException e) {
106             writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
107                             + command.getName() + "\"");
108             e.getCause().printStackTrace(writer);
109             throw new CommandLineException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
110                             + command.getName() + "\"", e);
111         }
112     }
113
114     /**
115      * Find the API method for the command.
116      *
117      * @param command The command
118      * @return the API method
119      */
120     private Method getCommandMethod(final CommandLineCommand command) {
121         final String className = command.getApiClassName();
122         final String methodName = command.getApiMethodName();
123
124         try {
125             final Class<? extends Object> apiClass = Class.forName(className);
126             for (final Method apiMethod : apiClass.getMethods()) {
127                 if (apiMethod.getName().equals(methodName)) {
128                     return apiMethod;
129                 }
130             }
131             throw new CommandLineException("specified method \"" + command.getApiMethod()
132                             + "\" not found for command \"" + command.getName() + "\"");
133         } catch (final ClassNotFoundException e) {
134             throw new CommandLineException("specified class \"" + command.getApiMethod() + "\" not found for command \""
135                             + command.getName() + "\"", e);
136         }
137     }
138
139     /**
140      * Get the arguments of the command as an ordered array of objects ready for the method.
141      *
142      * @param command the command that invoked the method
143      * @param argumentValues the argument values for the method
144      * @param apiMethod the method itself
145      * @return the argument list
146      */
147     private Object[] getParameterArray(final CommandLineCommand command,
148                     final SortedMap<String, CommandLineArgumentValue> argumentValues, final Method apiMethod) {
149         final Object[] parameterArray = new Object[argumentValues.size()];
150
151         int item = 0;
152         try {
153             for (final Class<?> parametertype : apiMethod.getParameterTypes()) {
154                 final String parameterValue = argumentValues.get(command.getArgumentList().get(item).getArgumentName())
155                                 .getValue();
156
157                 if (parametertype.equals(boolean.class)) {
158                     parameterArray[item] = Boolean.valueOf(parameterValue);
159                 } else {
160                     parameterArray[item] = parameterValue;
161                 }
162                 item++;
163             }
164         } catch (final Exception e) {
165             throw new CommandLineException("number of argument mismatch on method \"" + command.getApiMethod()
166                             + "\" for command \"" + command.getName() + "\"", e);
167         }
168
169         return parameterArray;
170     }
171
172     /**
173      * Save the model to a string.
174      *
175      * @param messageWriter the writer to write status messages to
176      * @return the string
177      */
178     public String writeModelToString(final PrintWriter messageWriter) {
179         final ApexApiResult result = apexModel.listModel();
180
181         if (result.isOk()) {
182             return result.getMessage();
183         } else {
184             return null;
185         }
186     }
187 }