8a52a03e3bcace6c1da9a1bffbc9044887e7b5e6
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.gui.editors.apex.rest.handling;
23
24 import java.util.Map.Entry;
25 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
26 import org.onap.policy.apex.model.modelapi.ApexApiResult;
27 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
28 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
29 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanField;
30 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanKeyRef;
31 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanLogic;
32 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTask;
33 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTaskParameter;
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
107      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
108      *         can be retrieved using {@link ApexApiResult#getMessages()}
109      */
110     private ApexApiResult createTask(final RestSession session, final String jsonString) {
111         LOGGER.entry(jsonString);
112
113         final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class);
114
115         session.editModel();
116
117         ApexApiResult result = session.getApexModelEdited().createTask(jsonbean.getName(), jsonbean.getVersion(),
118             jsonbean.getUuid(), jsonbean.getDescription());
119
120         if (result.isOk()) {
121             result = createTaskContent(session, jsonbean);
122         }
123
124         session.finishSession(result.isOk());
125
126         LOGGER.exit("Task/Create" + (result != null && result.isOk() ? OK : NOT_OK));
127         return result;
128     }
129
130     /**
131      * Create the content of the task.
132      *
133      * @param session    the Apex model editing session
134      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
135      * @return an ApexAPIResult object. If successful then
136      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
137      *         can be retrieved using {@link ApexApiResult#getMessages()}
138      */
139     private ApexApiResult createTaskContent(final RestSession session, final BeanTask jsonbean) {
140         ApexApiResult result = createInputFields(session, jsonbean);
141
142         if (result.isOk()) {
143             result = createOutputFields(session, jsonbean);
144         }
145
146         if (result.isOk()) {
147             result = createTaskLogic(session, jsonbean);
148         }
149
150         if (result.isOk()) {
151             result = createTaskParameters(session, jsonbean);
152         }
153
154         if (result.isOk()) {
155             result = createContextReferences(session, jsonbean);
156         }
157         return result;
158     }
159
160     /**
161      * Create the input fields for the task.
162      *
163      * @param session  the Apex model editing session
164      * @param jsonbean the ban containing the fields
165      * @return the result of the operation
166      */
167     private ApexApiResult createInputFields(final RestSession session, final BeanTask jsonbean) {
168         ApexApiResult result = new ApexApiResult();
169
170         if (jsonbean.getInputFields() == null || jsonbean.getInputFields().isEmpty()) {
171             return result;
172         }
173
174         for (final Entry<String, BeanField> fieldEntry : jsonbean.getInputFields().entrySet()) {
175             if (fieldEntry.getValue() == null) {
176                 result.setResult(Result.FAILED);
177                 result.addMessage("Null task input field information for field \"" + fieldEntry.getKey() + IN_TASK
178                     + jsonbean.getName() + ":" + jsonbean.getVersion()
179                     + ". The task was created, but there was an error adding the input fields."
180                     + TASK_PARTIALLY_DEFINED);
181                 continue;
182             }
183
184             if (fieldEntry.getKey() == null || !fieldEntry.getKey().equals(fieldEntry.getValue().getLocalName())) {
185                 result.setResult(Result.FAILED);
186                 result.addMessage("Invalid task input field information for field \"" + fieldEntry.getKey() + IN_TASK
187                     + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The localName of the field (\""
188                     + fieldEntry.getValue().getLocalName() + "\") is not the same as the field name. "
189                     + "The task was created, but there was an error adding the input fields." + TASK_PARTIALLY_DEFINED);
190             } else {
191                 ApexApiResult fieldCreationResult = session.getApexModelEdited().createTaskInputField(
192                     jsonbean.getName(), jsonbean.getVersion(), fieldEntry.getKey(), fieldEntry.getValue().getName(),
193                     fieldEntry.getValue().getVersion(), 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(), fieldEntry.getValue().getName(),
242                     fieldEntry.getValue().getVersion(), 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." + TASK_PARTIALLY_DEFINED);
277         }
278
279         return result;
280     }
281
282     /**
283      * Create the task parameters for the task.
284      *
285      * @param session  the Apex model editing session
286      * @param jsonbean the bean containing the parameters
287      * @return the result of the operation
288      */
289     private ApexApiResult createTaskParameters(final RestSession session, final BeanTask jsonbean) {
290         ApexApiResult result = new ApexApiResult();
291
292         if (jsonbean.getParameters() == null || jsonbean.getParameters().isEmpty()) {
293             return result;
294         }
295
296         for (final Entry<String, BeanTaskParameter> parameterEntry : jsonbean.getParameters().entrySet()) {
297             if (parameterEntry.getKey() == null || parameterEntry.getValue() == null
298                 || !parameterEntry.getKey().equals(parameterEntry.getValue().getParameterName())) {
299                 result.setResult(Result.FAILED);
300                 result
301                     .addMessage("Null or invalid task parameter information for parameter \"" + parameterEntry.getKey()
302                         + IN_TASK + jsonbean.getName() + ":" + jsonbean.getVersion() + ". The task was created, "
303                         + "but there was an error adding the parameters." + TASK_PARTIALLY_DEFINED);
304                 continue;
305             }
306             ApexApiResult createParResult = session.getApexModelEdited().createTaskParameter(jsonbean.getName(),
307                 jsonbean.getVersion(), parameterEntry.getValue().getParameterName(),
308                 parameterEntry.getValue().getDefaultValue());
309             if (createParResult.isNok()) {
310                 result.setResult(createParResult.getResult());
311                 result.addMessage("Failed to add task parameter \"" + parameterEntry.getKey() + IN_TASK
312                     + jsonbean.getName() + ":" + jsonbean.getVersion()
313                     + ". The task was created, but there was an error adding the parameters." + TASK_PARTIALLY_DEFINED);
314             }
315         }
316
317         return result;
318     }
319
320     /**
321      * Create the context references for the task.
322      *
323      * @param session  the Apex model editing session
324      * @param jsonbean the bean containing the context references
325      * @return the result of the operation
326      */
327     private ApexApiResult createContextReferences(final RestSession session, final BeanTask jsonbean) {
328         ApexApiResult result = new ApexApiResult();
329
330         if (jsonbean.getContexts() == null || jsonbean.getContexts().length == 0) {
331             return result;
332         }
333
334         for (final BeanKeyRef contextalbum : jsonbean.getContexts()) {
335             if (contextalbum.getName() == null || contextalbum.getVersion() == null) {
336                 result.setResult(Result.FAILED);
337                 result.addMessage("Null or invalid context album reference information in task " + jsonbean.getName()
338                     + ":" + jsonbean.getVersion() + ". The task was created, but there was an error adding the"
339                     + " context album reference. " + "The task has only been partially defined.");
340                 continue;
341             }
342             ApexApiResult createRefResult = session.getApexModelEdited().createTaskContextRef(jsonbean.getName(),
343                 jsonbean.getVersion(), contextalbum.getName(), contextalbum.getVersion());
344             if (createRefResult.isNok()) {
345                 result.setResult(createRefResult.getResult());
346                 result.addMessage("Failed to add context album reference information in task " + jsonbean.getName()
347                     + ":" + jsonbean.getVersion() + ". The task was created, but there was an error adding the"
348                     + " context album reference. " + "The task has only been partially defined.");
349             }
350         }
351
352         return result;
353     }
354
355     /**
356      * Update a task with the information in the JSON string passed.
357      *
358      * @param session    the Apex model editing session
359      * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
360      * @return an ApexAPIResult object. If successful then
361      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
362      *         can be retrieved using {@link ApexApiResult#getMessages()}
363      */
364     private ApexApiResult updateTask(final RestSession session, final String jsonString) {
365         LOGGER.entry(jsonString);
366
367         final BeanTask jsonbean = RestUtils.getJsonParameters(jsonString, BeanTask.class);
368
369         if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
370             LOGGER.exit("Task/Update" + NOT_OK);
371             return new ApexApiResult(Result.FAILED, "Null/Empty task name/version (\"" + jsonbean.getName() + ":"
372                 + jsonbean.getVersion() + "\" passed to UpdateTask");
373         }
374
375         session.editModel();
376
377         ApexApiResult result = session.getApexModelEdited().deleteTask(jsonbean.getName(), jsonbean.getVersion());
378
379         if (result.isOk()) {
380             result = session.getApexModelEdited().createTask(jsonbean.getName(), jsonbean.getVersion(),
381                 jsonbean.getUuid(), jsonbean.getDescription());
382
383             if (result.isOk()) {
384                 result = createTaskContent(session, jsonbean);
385             }
386         }
387
388         session.finishSession(result.isOk());
389
390         LOGGER.exit("Task/Update" + (result != null && result.isOk() ? OK : NOT_OK));
391         return result;
392     }
393
394     /**
395      * List tasks with the given key names/versions. If successful the result(s)
396      * will be available in the result messages. The returned value(s) will be
397      * similar to {@link AxTask}, with merged {@linkplain AxKeyInfo} for the root
398      * object.
399      *
400      * @param session the Apex model editing session
401      * @param name    the name to search for. If null or empty, then all names will
402      *                be queried
403      * @param version the version to search for. If null then all versions will be
404      *                searched for.
405      * @return an ApexAPIResult object. If successful then
406      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
407      *         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
423      *                be queried
424      * @param version the version to search for. If null then all versions will be
425      *                searched for.
426      * @return an ApexAPIResult object. If successful then
427      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
428      *         can be retrieved using {@link ApexApiResult#getMessages()}
429      */
430     private ApexApiResult deleteTask(final RestSession session, final String name, final String version) {
431         LOGGER.entry(name, version);
432
433         session.editModel();
434
435         // all input/output fields, parameters, logic, context references is
436         // "owned"/contained
437         // in the task, so
438         // deleting the task removes all of these
439         ApexApiResult result = session.getApexModelEdited().deleteTask(blank2Null(name), blank2Null(version));
440
441         session.finishSession(result.isOk());
442
443         LOGGER.exit("Task/Delete" + (result != null && result.isOk() ? OK : NOT_OK));
444         return result;
445     }
446
447     /**
448      * Validate tasks with the given key names/versions. The result(s) will be
449      * available in the result messages.
450      *
451      * @param session the Apex model editing session
452      * @param name    the name to search for. If null or empty, then all names will
453      *                be queried
454      * @param version the version to search for. If null then all versions will be
455      *                searched for.
456      * @return an ApexAPIResult object. If successful then
457      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
458      *         can be retrieved using {@link ApexApiResult#getMessages()}
459      */
460     private ApexApiResult validateTask(final RestSession session, final String name, final String version) {
461         LOGGER.entry(name, version);
462
463         ApexApiResult result = session.getApexModel().validateTask(blank2Null(name), blank2Null(version));
464
465         LOGGER.exit("Validate/Task" + (result != null && result.isOk() ? OK : NOT_OK));
466         return result;
467     }
468 }