a5113e971d7dbd819354627cfd5cade592d5734c
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-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.eventmodel.concepts.AxEvent;
28 import org.onap.policy.apex.model.modelapi.ApexApiResult;
29 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
30 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanEvent;
31 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanField;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34 import org.springframework.stereotype.Service;
35
36 /**
37  * This class handles commands on events in Apex models.
38  */
39 @Service
40 public class EventHandler implements RestCommandHandler {
41     // Get a reference to the logger
42     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventHandler.class);
43
44     // Recurring string constants
45     private static final String OK = ": OK";
46     private static final String NOT_OK = ": Not OK";
47
48     /**
49      * {@inheritDoc}.
50      */
51     @Override
52     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
53         final RestCommand command) {
54         return getUnsupportedCommandResultMessage(session, commandType, command);
55     }
56
57     /**
58      * {@inheritDoc}.
59      */
60     @Override
61     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
62         final RestCommand command, final String jsonString) {
63         if (!RestCommandType.EVENT.equals(commandType)) {
64             return getUnsupportedCommandResultMessage(session, commandType, command);
65         }
66
67         switch (command) {
68             case CREATE:
69                 return createEvent(session, jsonString);
70             case UPDATE:
71                 return updateEvent(session, jsonString);
72             default:
73                 return getUnsupportedCommandResultMessage(session, commandType, command);
74         }
75     }
76
77     /**
78      * {@inheritDoc}.
79      */
80     @Override
81     public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
82         final RestCommand command, final String name, final String version) {
83         if (!RestCommandType.EVENT.equals(commandType)) {
84             return getUnsupportedCommandResultMessage(session, commandType, command);
85         }
86
87         switch (command) {
88             case LIST:
89                 return listEvents(session, name, version);
90             case DELETE:
91                 return deleteEvent(session, name, version);
92             case VALIDATE:
93                 return validateEvent(session, name, version);
94             default:
95                 return getUnsupportedCommandResultMessage(session, commandType, command);
96         }
97     }
98
99     /**
100      * Creates an event with the information in the JSON string passed.
101      *
102      * @param session    the Apex model editing session
103      * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent}
104      * @return an ApexAPIResult object. If successful then
105      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
106      *         can be retrieved using {@link ApexApiResult#getMessages()}
107      */
108     private ApexApiResult createEvent(final RestSession session, final String jsonString) {
109         LOGGER.entry(jsonString);
110
111         final var jsonbean = RestUtils.getJsonParameters(jsonString, BeanEvent.class);
112
113         session.editModel();
114
115         ApexApiResult result = session.getApexModelEdited().createEvent(jsonbean.getName(), jsonbean.getVersion(),
116             jsonbean.getNameSpace(), jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(),
117             jsonbean.getDescription());
118
119         if (result.isOk()) {
120             result = createEventParameters(session, jsonbean);
121         }
122
123         session.finishSession(result.isOk());
124
125         LOGGER.exit("Event/Create" + (result.isOk() ? OK : NOT_OK));
126         return result;
127     }
128
129     /**
130      * Create the parameters on an event.
131      *
132      * @param session  the Apex editor session
133      * @param jsonbean the JSON bean holding the parameters
134      * @return result the result of the parameter creation operation
135      */
136     private ApexApiResult createEventParameters(final RestSession session, final BeanEvent jsonbean) {
137         var result = new ApexApiResult();
138
139         if (jsonbean.getParameters() == null || jsonbean.getParameters().isEmpty()) {
140             return result;
141         }
142
143         for (final Entry<String, BeanField> parameterEntry : jsonbean.getParameters().entrySet()) {
144             if (parameterEntry.getValue() == null) {
145                 result.setResult(Result.FAILED);
146                 result.addMessage("Null event parameter information for parameter \"" + parameterEntry.getKey()
147                     + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
148                     + ". The event was created, but there was an error adding the event parameters."
149                     + " The event has only been partially defined.");
150                 continue;
151             }
152
153             final ApexApiResult createParResult = session.getApexModelEdited().createEventPar(jsonbean.getName(),
154                 jsonbean.getVersion(), parameterEntry.getKey(), parameterEntry.getValue().getName(),
155                 parameterEntry.getValue().getVersion(), parameterEntry.getValue().isOptional());
156             if (createParResult.isNok()) {
157                 result.setResult(createParResult.getResult());
158                 result.addMessage("Failed to add event parameter information for parameter \"" + parameterEntry.getKey()
159                     + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
160                     + ". The event was created, but there was an error adding the event parameters."
161                     + " The event has only been partially defined.");
162             }
163         }
164
165         return result;
166     }
167
168     /**
169      * Update an event with the information in the JSON string passed.
170      *
171      * @param session    the Apex model editing session
172      * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent}
173      * @return an ApexAPIResult object. If successful then
174      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
175      *         can be retrieved using {@link ApexApiResult#getMessages()}
176      */
177     private ApexApiResult updateEvent(final RestSession session, final String jsonString) {
178         LOGGER.entry(jsonString);
179
180         final var jsonbean = RestUtils.getJsonParameters(jsonString, BeanEvent.class);
181
182         if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
183             LOGGER.exit("Event/Update" + NOT_OK);
184             return new ApexApiResult(Result.FAILED, "Null/Empty event name/version (\"" + jsonbean.getName() + ":"
185                 + jsonbean.getVersion() + "\" passed to UpdateEvent");
186         }
187
188         session.editModel();
189
190         ApexApiResult result = session.getApexModelEdited().deleteEvent(blank2Null(jsonbean.getName()),
191             blank2Null(jsonbean.getVersion()));
192
193         if (result.isOk()) {
194             result = session.getApexModelEdited().createEvent(jsonbean.getName(), jsonbean.getVersion(),
195                 jsonbean.getNameSpace(), jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(),
196                 jsonbean.getDescription());
197
198             if (result.isOk() && jsonbean.getParameters() != null) {
199                 result = createEventParameters(session, jsonbean);
200             }
201         }
202
203         session.finishSession(result.isOk());
204
205         LOGGER.exit("Event/Update" + (result.isOk() ? OK : NOT_OK));
206         return result;
207     }
208
209     /**
210      * List events with the given key names/versions. If successful the result(s)
211      * will be available in the result messages. The returned value(s) will be
212      * similar to {@link AxEvent}, with merged {@linkplain AxKeyInfo} for the root
213      * object.
214      *
215      * @param session the Apex model editing session
216      * @param name    the name to search for. If null or empty, then all names will
217      *                be queried
218      * @param version the version to search for. If null then all versions will be
219      *                searched for.
220      * @return an ApexAPIResult object. If successful then
221      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
222      *         can be retrieved using {@link ApexApiResult#getMessages()}
223      */
224     private ApexApiResult listEvents(final RestSession session, final String name, final String version) {
225         LOGGER.entry(name, version);
226
227         ApexApiResult result = session.getApexModel().listEvent(blank2Null(name), blank2Null(version));
228
229         LOGGER.exit("Event/Get" + (result != null && result.isOk() ? OK : NOT_OK));
230         return result;
231     }
232
233     /**
234      * Delete events with the given key names/versions.
235      *
236      * @param session the Apex model editing session
237      * @param name    the name to search for. If null or empty, then all names will
238      *                be queried
239      * @param version the version to search for. If null then all versions will be
240      *                searched for.
241      * @return an ApexAPIResult object. If successful then
242      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
243      *         can be retrieved using {@link ApexApiResult#getMessages()}
244      */
245     private ApexApiResult deleteEvent(final RestSession session, final String name, final String version) {
246         LOGGER.entry(name, version);
247
248         session.editModel();
249
250         ApexApiResult result = session.getApexModelEdited().deleteEvent(blank2Null(name), blank2Null(version));
251
252         session.finishSession(result.isOk());
253
254         LOGGER.exit("Event/Delete" + (result.isOk() ? OK : NOT_OK));
255         return result;
256     }
257
258     /**
259      * Validate events with the given key names/versions. The result(s) will be
260      * available in the result messages.
261      *
262      * @param session the Apex model editing session
263      * @param name    the name to search for. If null or empty, then all names will
264      *                be queried
265      * @param version the version to search for. If null then all versions will be
266      *                searched for.
267      * @return an ApexAPIResult object. If successful then
268      *         {@link ApexApiResult#isOk()} will return true. Any messages/errors
269      *         can be retrieved using {@link ApexApiResult#getMessages()}
270      */
271     private ApexApiResult validateEvent(final RestSession session, final String name, final String version) {
272         LOGGER.entry(name, version);
273
274         ApexApiResult result = session.getApexModel().validateEvent(blank2Null(name), blank2Null(version));
275
276         LOGGER.exit("Validate/Event" + (result != null && result.isOk() ? OK : NOT_OK));
277         return result;
278     }
279 }