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