581fdd7ffab1a2bd8b06281ab85f6fcdea09aa36
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020-2022 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.gui.editors.apex.rest.handling;
24
25 import java.util.Map.Entry;
26 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
27 import org.onap.policy.apex.model.modelapi.ApexApiResult;
28 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
29 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
30 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanField;
31 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanKeyRef;
32 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanLogic;
33 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTask;
34 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTaskParameter;
35 import org.slf4j.ext.XLogger;
36 import org.slf4j.ext.XLoggerFactory;
37 import org.springframework.stereotype.Service;
38
39 /**
40  * This class handles commands on tasks in Apex models.
41  */
42 @Service
43 public class TaskHandler implements RestCommandHandler {
44     // Get a reference to the logger
45     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TaskHandler.class);
46
47     // Recurring string constants
48     private static final String OK = ": OK";
49     private static final String NOT_OK = ": Not OK";
50     private static final String IN_TASK = "\" in task ";
51     private static final String TASK_PARTIALLY_DEFINED = " The task has only been partially defined.";
52
53     /**
54      * {@inheritDoc}.
55      */
56     @Override
57     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
58         final RestCommand command) {
59         return getUnsupportedCommandResultMessage(session, commandType, command);
60     }
61
62     /**
63      * {@inheritDoc}.
64      */
65     @Override
66     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
67         final RestCommand command, final String jsonString) {
68         if (!RestCommandType.TASK.equals(commandType)) {
69             return getUnsupportedCommandResultMessage(session, commandType, command);
70         }
71
72         switch (command) {
73             case CREATE:
74                 return createTask(session, jsonString);
75             case UPDATE:
76                 return updateTask(session, jsonString);
77             default:
78                 return getUnsupportedCommandResultMessage(session, commandType, command);
79         }
80     }
81
82     /**
83      * {@inheritDoc}.
84      */
85     @Override
86     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
87         final RestCommand command, final String name, final String version) {
88         if (!RestCommandType.TASK.equals(commandType)) {
89             return getUnsupportedCommandResultMessage(session, commandType, command);
90         }
91
92         switch (command) {
93             case LIST:
94                 return listTasks(session, name, version);
95             case DELETE:
96                 return deleteTask(session, name, version);
97             case VALIDATE:
98                 return validateTask(session, name, version);
99             default:
100                 return getUnsupportedCommandResultMessage(session, commandType, command);
101         }
102     }
103
104     /**
105      * Creates a task with the information in the JSON string passed.
106      *
107      * @param session    the Apex model editing session
108      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
109      * @return an ApexAPIResult object. If successful then
110      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
111      *         can be retrieved using {@link ApexApiResult#getMessages()}
112      */
113     private ApexApiResult createTask(final RestSession session, final String jsonString) {
114         LOGGER.entry(jsonString);
115
116         final var jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class);
117
118         session.editModel();
119
120         ApexApiResult result = session.getApexModelEdited().createTask(jsonbean.getName(), jsonbean.getVersion(),
121             jsonbean.getUuid(), jsonbean.getDescription());
122
123         if (result.isOk()) {
124             result = createTaskContent(session, jsonbean);
125         }
126
127         session.finishSession(result.isOk());
128
129         LOGGER.exit("Task/Create" + (result.isOk() ? OK : NOT_OK));
130         return result;
131     }
132
133     /**
134      * Create the content of the task.
135      *
136      * @param session    the Apex model editing session
137      * @param jsonbean the JSON string to be parsed. See {@linkplain BeanTask}
138      * @return an ApexAPIResult object. If successful then
139      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
140      *         can be retrieved using {@link ApexApiResult#getMessages()}
141      */
142     private ApexApiResult createTaskContent(final RestSession session, final BeanTask jsonbean) {
143         ApexApiResult result = createInputFields(session, jsonbean);
144
145         if (result.isOk()) {
146             result = createOutputFields(session, jsonbean);
147         }
148
149         if (result.isOk()) {
150             result = createTaskLogic(session, jsonbean);
151         }
152
153         if (result.isOk()) {
154             result = createTaskParameters(session, jsonbean);
155         }
156
157         if (result.isOk()) {
158             result = createContextReferences(session, jsonbean);
159         }
160         return result;
161     }
162
163     /**
164      * Create the input fields for the task.
165      *
166      * @param session  the Apex model editing session
167      * @param jsonbean the ban containing the fields
168      * @return the result of the operation
169      */
170     private ApexApiResult createInputFields(final RestSession session, final BeanTask jsonbean) {
171         var result = new ApexApiResult();
172
173         if (jsonbean.getInputFields() == null || jsonbean.getInputFields().isEmpty()) {
174             return result;
175         }
176
177         for (final Entry<String, BeanField> fieldEntry : jsonbean.getInputFields().entrySet()) {
178             if (fieldEntry.getValue() == null) {
179                 result.setResult(Result.FAILED);
180                 result.addMessage("Null task input field information for field \"" + fieldEntry.getKey() + IN_TASK
181                     + jsonbean.getName() + ":" + jsonbean.getVersion()
182                     + ". The task was created, but there was an error adding the input fields."
183                     + TASK_PARTIALLY_DEFINED);
184                 continue;
185             }
186
187             if (fieldEntry.getKey() == null || !fieldEntry.getKey().equals(fieldEntry.getValue().getLocalName())) {
188                 result.setResult(Result.FAILED);
189                 result.addMessage("Invalid task input field information for field \"" + fieldEntry.getKey() + IN_TASK
190                     + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The localName of the field (\""
191                     + fieldEntry.getValue().getLocalName() + "\") is not the same as the field name. "
192                     + "The task was created, but there was an error adding the input fields." + TASK_PARTIALLY_DEFINED);
193             } else {
194                 ApexApiResult fieldCreationResult = session.getApexModelEdited().createTaskInputField(
195                     jsonbean.getName(), jsonbean.getVersion(), fieldEntry.getKey(), fieldEntry.getValue().getName(),
196                     fieldEntry.getValue().getVersion(), fieldEntry.getValue().isOptional());
197
198                 if (fieldCreationResult.isNok()) {
199                     result.setResult(fieldCreationResult.getResult());
200                     result.addMessage("Failed to add task input field information for field \"" + fieldEntry.getKey()
201                         + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion()
202                         + ". The task was created, but there was an error adding the input fields."
203                         + TASK_PARTIALLY_DEFINED);
204                 }
205             }
206         }
207
208         return result;
209     }
210
211     /**
212      * Create the output fields for the task.
213      *
214      * @param session  the Apex model editing session
215      * @param jsonbean the ban containing the fields
216      * @return the result of the operation
217      */
218     private ApexApiResult createOutputFields(final RestSession session, final BeanTask jsonbean) {
219         var result = new ApexApiResult();
220
221         if (jsonbean.getOutputFields() == null || jsonbean.getOutputFields().isEmpty()) {
222             return result;
223         }
224
225         for (final Entry<String, BeanField> fieldEntry : jsonbean.getOutputFields().entrySet()) {
226             if (fieldEntry.getValue() == null) {
227                 result.setResult(Result.FAILED);
228                 result.addMessage("Null task output field information for field \"" + fieldEntry.getKey() + IN_TASK
229                     + jsonbean.getName() + ":" + jsonbean.getVersion()
230                     + ". The task was created, but there was an error adding the output fields."
231                     + TASK_PARTIALLY_DEFINED);
232                 continue;
233             }
234
235             if (fieldEntry.getKey() == null || !fieldEntry.getKey().equals(fieldEntry.getValue().getLocalName())) {
236                 result.setResult(Result.FAILED);
237                 result.addMessage("Invalid task output field information for field \"" + fieldEntry.getKey() + IN_TASK
238                     + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The localName of the field (\""
239                     + fieldEntry.getValue().getLocalName() + "\") is not the same as the field name. "
240                     + "The task was created, but there was an error adding the output fields."
241                     + TASK_PARTIALLY_DEFINED);
242             } else {
243                 ApexApiResult fieldCreationResult = session.getApexModelEdited().createTaskOutputField(
244                     jsonbean.getName(), jsonbean.getVersion(), fieldEntry.getKey(), fieldEntry.getValue().getName(),
245                     fieldEntry.getValue().getVersion(), fieldEntry.getValue().isOptional());
246                 if (fieldCreationResult.isNok()) {
247                     result.setResult(fieldCreationResult.getResult());
248                     result.addMessage("Failed to add task output field information for field \"" + fieldEntry.getKey()
249                         + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion()
250                         + ". The task was created, but there was an error adding the output fields."
251                         + TASK_PARTIALLY_DEFINED);
252                 }
253             }
254         }
255
256         return result;
257     }
258
259     /**
260      * Create the task logic for the task.
261      *
262      * @param session  the Apex model editing session
263      * @param jsonbean the bean containing the logic
264      * @return the result of the operation
265      */
266     private ApexApiResult createTaskLogic(final RestSession session, final BeanTask jsonbean) {
267         var result = new ApexApiResult();
268
269         if (jsonbean.getTaskLogic() == null) {
270             return result;
271         }
272
273         final BeanLogic logic = jsonbean.getTaskLogic();
274         result = session.getApexModelEdited().createTaskLogic(jsonbean.getName(), jsonbean.getVersion(),
275             logic.getLogicFlavour(), logic.getLogic());
276
277         if (result.isNok()) {
278             result.addMessage("Failed to add task logic in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
279                 + ". The task was created, but there was an error adding the logic." + TASK_PARTIALLY_DEFINED);
280         }
281
282         return result;
283     }
284
285     /**
286      * Create the task parameters for the task.
287      *
288      * @param session  the Apex model editing session
289      * @param jsonbean the bean containing the parameters
290      * @return the result of the operation
291      */
292     private ApexApiResult createTaskParameters(final RestSession session, final BeanTask jsonbean) {
293         var result = new ApexApiResult();
294
295         if (jsonbean.getParameters() == null || jsonbean.getParameters().isEmpty()) {
296             return result;
297         }
298
299         for (final Entry<String, BeanTaskParameter> parameterEntry : jsonbean.getParameters().entrySet()) {
300             if (parameterEntry.getKey() == null || parameterEntry.getValue() == null
301                 || !parameterEntry.getKey().equals(parameterEntry.getValue().getParameterName())) {
302                 result.setResult(Result.FAILED);
303                 result
304                     .addMessage("Null or invalid task parameter information for parameter \"" + parameterEntry.getKey()
305                         + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The task was created, "
306                         + "but there was an error adding the parameters." + TASK_PARTIALLY_DEFINED);
307                 continue;
308             }
309             ApexApiResult createParResult = session.getApexModelEdited().createTaskParameter(jsonbean.getName(),
310                 jsonbean.getVersion(), parameterEntry.getValue().getParameterName(),
311                 parameterEntry.getValue().getDefaultValue());
312             if (createParResult.isNok()) {
313                 result.setResult(createParResult.getResult());
314                 result.addMessage("Failed to add task parameter \"" + parameterEntry.getKey() + IN_TASK
315                     + jsonbean.getName() + ":" + jsonbean.getVersion()
316                     + ". The task was created, but there was an error adding the parameters." + 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         var 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() + ". 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() + ". The task was created, but there was an error adding the"
351                     + " context album reference. " + "The task has only been partially defined.");
352             }
353         }
354
355         return result;
356     }
357
358     /**
359      * Update a task with the information in the JSON string passed.
360      *
361      * @param session    the Apex model editing session
362      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
363      * @return an ApexAPIResult object. If successful then
364      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
365      *         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 var 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.isOk() ? OK : NOT_OK));
394         return result;
395     }
396
397     /**
398      * List tasks with the given key names/versions. If successful the result(s)
399      * will be available in the result messages. The returned value(s) will be
400      * similar to {@link AxTask}, with merged {@linkplain AxKeyInfo} for the root
401      * 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
405      *                be queried
406      * @param version the version to search for. If null then all versions will be
407      *                searched for.
408      * @return an ApexAPIResult object. If successful then
409      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
410      *         can be retrieved using {@link ApexApiResult#getMessages()}
411      */
412     private ApexApiResult listTasks(final RestSession session, final String name, final String version) {
413         LOGGER.entry(name, version);
414
415         ApexApiResult result = session.getApexModel().listTask(blank2Null(name), blank2Null(version));
416
417         LOGGER.exit("Task/Get" + (result != null && result.isOk() ? OK : NOT_OK));
418         return result;
419     }
420
421     /**
422      * Delete tasks with the given key names/versions.
423      *
424      * @param session the Apex model editing session
425      * @param name    the name to search for. If null or empty, then all names will
426      *                be queried
427      * @param version the version to search for. If null then all versions will be
428      *                searched for.
429      * @return an ApexAPIResult object. If successful then
430      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
431      *         can be retrieved using {@link ApexApiResult#getMessages()}
432      */
433     private ApexApiResult deleteTask(final RestSession session, final String name, final String version) {
434         LOGGER.entry(name, version);
435
436         session.editModel();
437
438         // all input/output fields, parameters, logic, context references is
439         // "owned"/contained
440         // in the task, so
441         // deleting the task removes all of these
442         ApexApiResult result = session.getApexModelEdited().deleteTask(blank2Null(name), blank2Null(version));
443
444         session.finishSession(result.isOk());
445
446         LOGGER.exit("Task/Delete" + (result.isOk() ? OK : NOT_OK));
447         return result;
448     }
449
450     /**
451      * Validate tasks with the given key names/versions. The result(s) will be
452      * available in the result messages.
453      *
454      * @param session the Apex model editing session
455      * @param name    the name to search for. If null or empty, then all names will
456      *                be queried
457      * @param version the version to search for. If null then all versions will be
458      *                searched for.
459      * @return an ApexAPIResult object. If successful then
460      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
461      *         can be retrieved using {@link ApexApiResult#getMessages()}
462      */
463     private ApexApiResult validateTask(final RestSession session, final String name, final String version) {
464         LOGGER.entry(name, version);
465
466         ApexApiResult result = session.getApexModel().validateTask(blank2Null(name), blank2Null(version));
467
468         LOGGER.exit("Validate/Task" + (result != null && result.isOk() ? OK : NOT_OK));
469         return result;
470     }
471 }