08b487321434fd4166a30edbd913178036608d7f
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.client.editor.rest.handling;
22
23 import java.util.Map.Entry;
24
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 != null && 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      * @param result the result of the parameter creation operation
131      * @return
132      */
133     private ApexApiResult createEventParameters(final RestSession session, final BeanEvent jsonbean) {
134         ApexApiResult result = new ApexApiResult();
135
136         if (jsonbean.getParameters() == null || jsonbean.getParameters().isEmpty()) {
137             return result;
138         }
139
140         for (final Entry<String, BeanField> parameterEntry : jsonbean.getParameters().entrySet()) {
141             if (parameterEntry.getValue() == null) {
142                 result.setResult(Result.FAILED);
143                 result.addMessage("Null event parameter information for parameter \"" + parameterEntry.getKey()
144                                 + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
145                                 + ". The event was created, but there was an error adding the event parameters."
146                                 + " The event has only been partially defined.");
147                 continue;
148             }
149
150             final ApexApiResult createParResult = session.getApexModelEdited().createEventPar(jsonbean.getName(),
151                             jsonbean.getVersion(), parameterEntry.getKey(), parameterEntry.getValue().getName(),
152                             parameterEntry.getValue().getVersion(), parameterEntry.getValue().getOptional());
153             if (createParResult.isNok()) {
154                 result.setResult(createParResult.getResult());
155                 result.addMessage("Failed to add event parameter information for parameter \"" + parameterEntry.getKey()
156                                 + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
157                                 + ". The event was created, but there was an error adding the event parameters."
158                                 + " The event has only been partially defined.");
159             }
160         }
161
162         return result;
163     }
164
165     /**
166      * Update an event with the information in the JSON string passed.
167      *
168      * @param session the Apex model editing session
169      * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent}
170      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
171      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
172      */
173     private ApexApiResult updateEvent(final RestSession session, final String jsonString) {
174         LOGGER.entry(jsonString);
175
176         final BeanEvent jsonbean = RestUtils.getJsonParameters(jsonString, BeanEvent.class);
177
178         if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
179             LOGGER.exit("Event/Update" + NOT_OK);
180             return new ApexApiResult(Result.FAILED, "Null/Empty event name/version (\"" + jsonbean.getName() + ":"
181                             + jsonbean.getVersion() + "\" passed to UpdateEvent");
182         }
183
184         session.editModel();
185
186         ApexApiResult result = session.getApexModelEdited().deleteEvent(blank2Null(jsonbean.getName()),
187                         blank2Null(jsonbean.getVersion()));
188
189         if (result.isOk()) {
190             result = session.getApexModelEdited().createEvent(jsonbean.getName(), jsonbean.getVersion(),
191                             jsonbean.getNameSpace(), jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(),
192                             jsonbean.getDescription());
193
194             if (result.isOk() && jsonbean.getParameters() != null) {
195                 result = createEventParameters(session, jsonbean);
196             }
197         }
198
199         session.finishSession(result.isOk());
200
201         LOGGER.exit("Event/Update" + (result != null && result.isOk() ? OK : NOT_OK));
202         return result;
203     }
204
205     /**
206      * List events with the given key names/versions. If successful the result(s) will be available in the result
207      * messages. The returned value(s) will be similar to {@link AxEvent}, with merged {@linkplain AxKeyInfo} for the
208      * root object.
209      *
210      * @param session the Apex model editing session
211      * @param name the name to search for. If null or empty, then all names will be queried
212      * @param version the version to search for. If null then all versions will be searched for.
213      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
214      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
215      */
216     private ApexApiResult listEvents(final RestSession session, final String name, final String version) {
217         LOGGER.entry(name, version);
218
219         ApexApiResult result = session.getApexModel().listEvent(blank2Null(name), blank2Null(version));
220
221         LOGGER.exit("Event/Get" + (result != null && result.isOk() ? OK : NOT_OK));
222         return result;
223     }
224
225     /**
226      * Delete events with the given key names/versions.
227      *
228      * @param session the Apex model editing session
229      * @param name the name to search for. If null or empty, then all names will be queried
230      * @param version the version to search for. If null then all versions will be searched for.
231      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
232      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
233      */
234     private ApexApiResult deleteEvent(final RestSession session, final String name, final String version) {
235         LOGGER.entry(name, version);
236
237         session.editModel();
238
239         ApexApiResult result = session.getApexModelEdited().deleteEvent(blank2Null(name), blank2Null(version));
240
241         session.finishSession(result.isOk());
242
243         LOGGER.exit("Event/Delete" + (result != null && result.isOk() ? OK : NOT_OK));
244         return result;
245     }
246
247     /**
248      * Validate events with the given key names/versions. The result(s) will be available in the result messages.
249      *
250      * @param session the Apex model editing session
251      * @param name the name to search for. If null or empty, then all names will be queried
252      * @param version the version to search for. If null then all versions will be searched for.
253      * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
254      *         messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
255      */
256     private ApexApiResult validateEvent(final RestSession session, final String name, final String version) {
257         LOGGER.entry(name, version);
258
259         ApexApiResult result = session.getApexModel().validateEvent(blank2Null(name), blank2Null(version));
260
261         LOGGER.exit("Validate/Event" + (result != null && result.isOk() ? OK : NOT_OK));
262         return result;
263     }
264 }