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