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