Changes for checkstyle 8.32
[policy/apex-pdp.git] / client / client-editor / src / main / java / org / onap / policy / apex / client / editor / rest / handling / TaskHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 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.client.editor.rest.handling;
22
23 import java.util.Map.Entry;
24 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanField;
25 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanKeyRef;
26 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanLogic;
27 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanTask;
28 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanTaskParameter;
29 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
30 import org.onap.policy.apex.model.modelapi.ApexApiResult;
31 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
32 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
33 import org.slf4j.ext.XLogger;
34 import org.slf4j.ext.XLoggerFactory;
35
36 /**
37  * This class handles commands on tasks in Apex models.
38  */
39 public class TaskHandler implements RestCommandHandler {
40     // Get a reference to the logger
41     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TaskHandler.class);
42
43     // Recurring string constants
44     private static final String OK = ": OK";
45     private static final String NOT_OK = ": Not OK";
46     private static final String IN_TASK = "\" in task ";
47     private static final String TASK_PARTIALLY_DEFINED = " The task has only been partially defined.";
48
49     /**
50      * {@inheritDoc}.
51      */
52     @Override
53     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
54                     final RestCommand command) {
55         return getUnsupportedCommandResultMessage(session, commandType, command);
56     }
57
58     /**
59      * {@inheritDoc}.
60      */
61     @Override
62     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
63                     final RestCommand command, final String jsonString) {
64         if (!RestCommandType.TASK.equals(commandType)) {
65             return getUnsupportedCommandResultMessage(session, commandType, command);
66         }
67
68         switch (command) {
69             case CREATE:
70                 return createTask(session, jsonString);
71             case UPDATE:
72                 return updateTask(session, jsonString);
73             default:
74                 return getUnsupportedCommandResultMessage(session, commandType, command);
75         }
76     }
77
78     /**
79      * {@inheritDoc}.
80      */
81     @Override
82     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
83                     final RestCommand command, final String name, final String version) {
84         if (!RestCommandType.TASK.equals(commandType)) {
85             return getUnsupportedCommandResultMessage(session, commandType, command);
86         }
87
88         switch (command) {
89             case LIST:
90                 return listTasks(session, name, version);
91             case DELETE:
92                 return deleteTask(session, name, version);
93             case VALIDATE:
94                 return validateTask(session, name, version);
95             default:
96                 return getUnsupportedCommandResultMessage(session, commandType, command);
97         }
98     }
99
100     /**
101      * Creates a task with the information in the JSON string passed.
102      *
103      * @param session the Apex model editing session
104      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
105      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
106      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
107      */
108     private ApexApiResult createTask(final RestSession session, final String jsonString) {
109         LOGGER.entry(jsonString);
110
111         final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class);
112
113         session.editModel();
114
115         ApexApiResult result = session.getApexModelEdited().createTask(jsonbean.getName(), jsonbean.getVersion(),
116                         jsonbean.getUuid(), jsonbean.getDescription());
117
118         if (result.isOk()) {
119             result = createTaskContent(session, jsonbean);
120         }
121
122         session.finishSession(result.isOk());
123
124         LOGGER.exit("Task/Create" + (result != null && result.isOk() ? OK : NOT_OK));
125         return result;
126     }
127
128     /**
129      * Create the content of the task.
130      * 
131      * @param session the Apex model editing session
132      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
133      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
134      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
135      */
136     private ApexApiResult createTaskContent(final RestSession session, final BeanTask jsonbean) {
137         ApexApiResult result = createInputFields(session, jsonbean);
138
139         if (result.isOk()) {
140             result = createOutputFields(session, jsonbean);
141         }
142
143         if (result.isOk()) {
144             result = createTaskLogic(session, jsonbean);
145         }
146
147         if (result.isOk()) {
148             result = createTaskParameters(session, jsonbean);
149         }
150
151         if (result.isOk()) {
152             result = createContextReferences(session, jsonbean);
153         }
154         return result;
155     }
156
157     /**
158      * Create the input fields for the task.
159      * 
160      * @param session the Apex model editing session
161      * @param jsonbean the ban containing the fields
162      * @return the result of the operation
163      */
164     private ApexApiResult createInputFields(final RestSession session, final BeanTask jsonbean) {
165         ApexApiResult result = new ApexApiResult();
166
167         if (jsonbean.getInputFields() == null || jsonbean.getInputFields().isEmpty()) {
168             return result;
169         }
170
171         for (final Entry<String, BeanField> fieldEntry : jsonbean.getInputFields().entrySet()) {
172             if (fieldEntry.getValue() == null) {
173                 result.setResult(Result.FAILED);
174                 result.addMessage("Null task input field information for field \"" + fieldEntry.getKey() + IN_TASK
175                                 + jsonbean.getName() + ":" + jsonbean.getVersion()
176                                 + ". The task was created, but there was an error adding the input fields."
177                                 + TASK_PARTIALLY_DEFINED);
178                 continue;
179             }
180
181             if (fieldEntry.getKey() == null || !fieldEntry.getKey().equals(fieldEntry.getValue().getLocalName())) {
182                 result.setResult(Result.FAILED);
183                 result.addMessage("Invalid task input field information for field \"" + fieldEntry.getKey() + IN_TASK
184                                 + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The localName of the field (\""
185                                 + fieldEntry.getValue().getLocalName() + "\") is not the same as the field name. "
186                                 + "The task was created, but there was an error adding the input fields."
187                                 + TASK_PARTIALLY_DEFINED);
188             } else {
189                 ApexApiResult fieldCreationResult = session.getApexModelEdited().createTaskInputField(
190                                 jsonbean.getName(), jsonbean.getVersion(), fieldEntry.getKey(),
191                                 fieldEntry.getValue().getName(), fieldEntry.getValue().getVersion(),
192                                 fieldEntry.getValue().getOptional());
193
194                 if (fieldCreationResult.isNok()) {
195                     result.setResult(fieldCreationResult.getResult());
196                     result.addMessage("Failed to add task input field information for field \"" + fieldEntry.getKey()
197                                     + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion()
198                                     + ". The task was created, but there was an error adding the input fields."
199                                     + TASK_PARTIALLY_DEFINED);
200                 }
201             }
202         }
203
204         return result;
205     }
206
207     /**
208      * Create the output fields for the task.
209      * 
210      * @param session the Apex model editing session
211      * @param jsonbean the ban containing the fields
212      * @return the result of the operation
213      */
214     private ApexApiResult createOutputFields(final RestSession session, final BeanTask jsonbean) {
215         ApexApiResult result = new ApexApiResult();
216
217         if (jsonbean.getOutputFields() == null || jsonbean.getOutputFields().isEmpty()) {
218             return result;
219         }
220
221         for (final Entry<String, BeanField> fieldEntry : jsonbean.getOutputFields().entrySet()) {
222             if (fieldEntry.getValue() == null) {
223                 result.setResult(Result.FAILED);
224                 result.addMessage("Null task output field information for field \"" + fieldEntry.getKey() + IN_TASK
225                                 + jsonbean.getName() + ":" + jsonbean.getVersion()
226                                 + ". The task was created, but there was an error adding the output fields."
227                                 + TASK_PARTIALLY_DEFINED);
228                 continue;
229             }
230
231             if (fieldEntry.getKey() == null || !fieldEntry.getKey().equals(fieldEntry.getValue().getLocalName())) {
232                 result.setResult(Result.FAILED);
233                 result.addMessage("Invalid task output field information for field \"" + fieldEntry.getKey() + IN_TASK
234                                 + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The localName of the field (\""
235                                 + fieldEntry.getValue().getLocalName() + "\") is not the same as the field name. "
236                                 + "The task was created, but there was an error adding the output fields."
237                                 + TASK_PARTIALLY_DEFINED);
238             } else {
239                 ApexApiResult fieldCreationResult = session.getApexModelEdited().createTaskOutputField(
240                                 jsonbean.getName(), jsonbean.getVersion(), fieldEntry.getKey(),
241                                 fieldEntry.getValue().getName(), fieldEntry.getValue().getVersion(),
242                                 fieldEntry.getValue().getOptional());
243                 if (fieldCreationResult.isNok()) {
244                     result.setResult(fieldCreationResult.getResult());
245                     result.addMessage("Failed to add task output field information for field \"" + fieldEntry.getKey()
246                                     + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion()
247                                     + ". The task was created, but there was an error adding the output fields."
248                                     + TASK_PARTIALLY_DEFINED);
249                 }
250             }
251         }
252
253         return result;
254     }
255
256     /**
257      * Create the task logic for the task.
258      * 
259      * @param session the Apex model editing session
260      * @param jsonbean the bean containing the logic
261      * @return the result of the operation
262      */
263     private ApexApiResult createTaskLogic(final RestSession session, final BeanTask jsonbean) {
264         ApexApiResult result = new ApexApiResult();
265
266         if (jsonbean.getTaskLogic() == null) {
267             return result;
268         }
269
270         final BeanLogic logic = jsonbean.getTaskLogic();
271         result = session.getApexModelEdited().createTaskLogic(jsonbean.getName(), jsonbean.getVersion(),
272                         logic.getLogicFlavour(), logic.getLogic());
273
274         if (result.isNok()) {
275             result.addMessage("Failed to add task logic in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
276                             + ". The task was created, but there was an error adding the logic."
277                             + TASK_PARTIALLY_DEFINED);
278         }
279
280         return result;
281     }
282
283     /**
284      * Create the task parameters for the task.
285      * 
286      * @param session the Apex model editing session
287      * @param jsonbean the bean containing the parameters
288      * @return the result of the operation
289      */
290     private ApexApiResult createTaskParameters(final RestSession session, final BeanTask jsonbean) {
291         ApexApiResult result = new ApexApiResult();
292
293         if (jsonbean.getParameters() == null || jsonbean.getParameters().isEmpty()) {
294             return result;
295         }
296
297         for (final Entry<String, BeanTaskParameter> parameterEntry : jsonbean.getParameters().entrySet()) {
298             if (parameterEntry.getKey() == null || parameterEntry.getValue() == null
299                             || !parameterEntry.getKey().equals(parameterEntry.getValue().getParameterName())) {
300                 result.setResult(Result.FAILED);
301                 result.addMessage("Null or invalid task parameter information for parameter \""
302                                 + parameterEntry.getKey() + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion()
303                                 + ". The task was created, " + "but there was an error adding the parameters."
304                                 + TASK_PARTIALLY_DEFINED);
305                 continue;
306             }
307             ApexApiResult createParResult = session.getApexModelEdited().createTaskParameter(jsonbean.getName(),
308                             jsonbean.getVersion(), parameterEntry.getValue().getParameterName(),
309                             parameterEntry.getValue().getDefaultValue());
310             if (createParResult.isNok()) {
311                 result.setResult(createParResult.getResult());
312                 result.addMessage("Failed to add task parameter \"" + parameterEntry.getKey() + IN_TASK
313                                 + jsonbean.getName() + ":" + jsonbean.getVersion()
314                                 + ". The task was created, but there was an error adding the parameters."
315                                 + TASK_PARTIALLY_DEFINED);
316             }
317         }
318
319         return result;
320     }
321
322     /**
323      * Create the context references for the task.
324      * 
325      * @param session the Apex model editing session
326      * @param jsonbean the bean containing the context references
327      * @return the result of the operation
328      */
329     private ApexApiResult createContextReferences(final RestSession session, final BeanTask jsonbean) {
330         ApexApiResult result = new ApexApiResult();
331
332         if (jsonbean.getContexts() == null || jsonbean.getContexts().length == 0) {
333             return result;
334         }
335
336         for (final BeanKeyRef contextalbum : jsonbean.getContexts()) {
337             if (contextalbum.getName() == null || contextalbum.getVersion() == null) {
338                 result.setResult(Result.FAILED);
339                 result.addMessage("Null or invalid context album reference information in task " + jsonbean.getName()
340                                 + ":" + jsonbean.getVersion()
341                                 + ". The task was created, but there was an error adding the"
342                                 + " context album reference. " + "The task has only been partially defined.");
343                 continue;
344             }
345             ApexApiResult createRefResult = session.getApexModelEdited().createTaskContextRef(jsonbean.getName(),
346                             jsonbean.getVersion(), contextalbum.getName(), contextalbum.getVersion());
347             if (createRefResult.isNok()) {
348                 result.setResult(createRefResult.getResult());
349                 result.addMessage("Failed to add context album reference information in task " + jsonbean.getName()
350                                 + ":" + jsonbean.getVersion()
351                                 + ". The task was created, but there was an error adding the"
352                                 + " context album reference. " + "The task has only been partially defined.");
353             }
354         }
355
356         return result;
357     }
358
359     /**
360      * Update a task with the information in the JSON string passed.
361      *
362      * @param session the Apex model editing session
363      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
364      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
365      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
366      */
367     private ApexApiResult updateTask(final RestSession session, final String jsonString) {
368         LOGGER.entry(jsonString);
369
370         final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class);
371
372         if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
373             LOGGER.exit("Task/Update" + NOT_OK);
374             return new ApexApiResult(Result.FAILED, "Null/Empty task name/version (\"" + jsonbean.getName() + ":"
375                             + jsonbean.getVersion() + "\" passed to UpdateTask");
376         }
377
378         session.editModel();
379
380         ApexApiResult result = session.getApexModelEdited().deleteTask(jsonbean.getName(), jsonbean.getVersion());
381
382         if (result.isOk()) {
383             result = session.getApexModelEdited().createTask(jsonbean.getName(), jsonbean.getVersion(),
384                             jsonbean.getUuid(), jsonbean.getDescription());
385
386             if (result.isOk()) {
387                 result = createTaskContent(session, jsonbean);
388             }
389         }
390
391         session.finishSession(result.isOk());
392
393         LOGGER.exit("Task/Update" + (result != null && result.isOk() ? OK : NOT_OK));
394         return result;
395     }
396
397     /**
398      * List tasks with the given key names/versions. If successful the result(s) will be available in the result
399      * messages. The returned value(s) will be similar to {@link AxTask}, with merged {@linkplain AxKeyInfo} for the
400      * root object.
401      *
402      * @param session the Apex model editing session
403      * @param name the name to search for. If null or empty, then all names will be queried
404      * @param version the version to search for. If null then all versions will be searched for.
405      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
406      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
407      */
408     private ApexApiResult listTasks(final RestSession session, final String name, final String version) {
409         LOGGER.entry(name, version);
410
411         ApexApiResult result = session.getApexModel().listTask(blank2Null(name), blank2Null(version));
412
413         LOGGER.exit("Task/Get" + (result != null && result.isOk() ? OK : NOT_OK));
414         return result;
415     }
416
417     /**
418      * Delete tasks with the given key names/versions.
419      *
420      * @param session the Apex model editing session
421      * @param name the name to search for. If null or empty, then all names will be queried
422      * @param version the version to search for. If null then all versions will be searched for.
423      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
424      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
425      */
426     private ApexApiResult deleteTask(final RestSession session, final String name, final String version) {
427         LOGGER.entry(name, version);
428
429         session.editModel();
430
431         // all input/output fields, parameters, logic, context references is "owned"/contained
432         // in the task, so
433         // deleting the task removes all of these
434         ApexApiResult result = session.getApexModelEdited().deleteTask(blank2Null(name), blank2Null(version));
435
436         session.finishSession(result.isOk());
437
438         LOGGER.exit("Task/Delete" + (result != null && result.isOk() ? OK : NOT_OK));
439         return result;
440     }
441
442     /**
443      * Validate tasks with the given key names/versions. The result(s) will be available in the result messages.
444      *
445      * @param session the Apex model editing session
446      * @param name the name to search for. If null or empty, then all names will be queried
447      * @param version the version to search for. If null then all versions will be searched for.
448      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
449      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
450      */
451     private ApexApiResult validateTask(final RestSession session, final String name, final String version) {
452         LOGGER.entry(name, version);
453
454         ApexApiResult result = session.getApexModel().validateTask(blank2Null(name), blank2Null(version));
455
456         LOGGER.exit("Validate/Task" + (result != null && result.isOk() ? OK : NOT_OK));
457         return result;
458     }
459 }