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