Reduce the number of problems in aai-common by removing unused imports
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / rest / ueb / UEBNotification.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.rest.ueb;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.URI;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.ws.rs.core.Response.Status;
32
33 import org.onap.aai.exceptions.AAIException;
34 import org.onap.aai.introspection.Introspector;
35 import org.onap.aai.introspection.Loader;
36 import org.onap.aai.introspection.LoaderFactory;
37 import org.onap.aai.introspection.ModelType;
38 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
39 import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
40 import org.onap.aai.logging.LogFormatTools;
41 import org.onap.aai.parsers.uri.URIToObject;
42 import org.onap.aai.setup.SchemaVersion;
43 import org.onap.aai.setup.SchemaVersions;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * The Class UEBNotification.
49  */
50 public class UEBNotification {
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(UEBNotification.class);
53
54     private Loader currentVersionLoader = null;
55     protected Map<String, NotificationEvent> events = null;
56     private SchemaVersion notificationVersion = null;
57
58     /**
59      * Instantiates a new UEB notification.
60      *
61      * @param loader the loader
62      */
63     public UEBNotification(Loader loader, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
64         events = new LinkedHashMap<>();
65         SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
66         currentVersionLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), defaultVersion);
67         notificationVersion = defaultVersion;
68     }
69
70     /**
71      * Instantiates a new UEB notification.
72      *
73      * @param modelType - Model type
74      * @param loaderFactory - the loader factory
75      * @param schemaVersions the schema versions bean
76      */
77     public UEBNotification(ModelType modelType, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
78         events = new LinkedHashMap<>();
79         SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
80         currentVersionLoader = loaderFactory.createLoaderForVersion(modelType, defaultVersion);
81         notificationVersion = defaultVersion;
82     }
83
84     /**
85      * Creates the notification event.
86      *
87      * @param transactionId the X-TransactionId
88      * @param sourceOfTruth
89      * @param status the status
90      * @param uri the uri
91      * @param obj the obj
92      * @param basePath base URI path
93      * @throws AAIException the AAI exception
94      * @throws IllegalArgumentException the illegal argument exception
95      * @throws UnsupportedEncodingException the unsupported encoding exception
96      */
97     public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri,
98             Introspector obj, HashMap<String, Introspector> relatedObjects, String basePath)
99             throws AAIException, UnsupportedEncodingException {
100
101         String action = "UPDATE";
102
103         if (status.equals(Status.CREATED)) {
104             action = "CREATE";
105         } else if (status.equals(Status.OK)) {
106             action = "UPDATE";
107         } else if (status.equals(Status.NO_CONTENT)) {
108             action = "DELETE";
109         }
110
111         try {
112             Introspector eventHeader = currentVersionLoader.introspectorFromName("notification-event-header");
113             URIToObject parser = new URIToObject(currentVersionLoader, uri, relatedObjects);
114
115             if ((basePath != null) && (!basePath.isEmpty())) {
116                 if (!(basePath.startsWith("/"))) {
117                     basePath = "/" + basePath;
118                 }
119                 if (!(basePath.endsWith("/"))) {
120                     basePath = basePath + "/";
121                 }
122             } else {
123                 // default
124                 basePath = "/aai/";
125                 if (LOGGER.isDebugEnabled()) {
126                     LOGGER.debug("Please check the schema.uri.base.path as it didn't seem to be set");
127                 }
128             }
129
130             String uriStr = getUri(uri.toString(), basePath);
131             String entityLink;
132             if (uriStr.startsWith("/")) {
133                 entityLink = basePath + notificationVersion + uriStr;
134             } else {
135                 entityLink = basePath + notificationVersion + "/" + uriStr;
136             }
137
138             eventHeader.setValue("entity-link", entityLink);
139             eventHeader.setValue("action", action);
140             eventHeader.setValue("entity-type", obj.getDbName());
141             eventHeader.setValue("top-entity-type", parser.getTopEntityName());
142             eventHeader.setValue("source-name", sourceOfTruth);
143             eventHeader.setValue("version", notificationVersion.toString());
144             eventHeader.setValue("id", transactionId);
145
146             List<Object> parentList = parser.getParentList();
147             parentList.clear();
148
149             if (!parser.getTopEntity().equals(parser.getEntity())) {
150                 Introspector child = obj;
151                 if (!parser.getLoader().getVersion().equals(obj.getVersion())) {
152                     String json = obj.marshal(false);
153                     child = parser.getLoader().unmarshal(parser.getEntity().getName(), json);
154                 }
155
156                 // wrap the child object in its parents
157                 parentList.add(child.getUnderlyingObject());
158             }
159
160             final Introspector eventObject;
161
162             // convert to most resent version
163             if (!parser.getLoader().getVersion().equals(currentVersionLoader.getVersion())) {
164                 String json = "";
165                 if (parser.getTopEntity().equals(parser.getEntity())) {
166                     // convert the parent object passed in
167                     json = obj.marshal(false);
168                     eventObject = currentVersionLoader.unmarshal(obj.getName(), json);
169                 } else {
170                     // convert the object created in the parser
171                     json = parser.getTopEntity().marshal(false);
172                     eventObject = currentVersionLoader.unmarshal(parser.getTopEntity().getName(), json);
173                 }
174             } else {
175                 if (parser.getTopEntity().equals(parser.getEntity())) {
176                     // take the top level parent object passed in
177                     eventObject = obj;
178                 } else {
179                     // take the wrapped child objects (ogres are like onions)
180                     eventObject = parser.getTopEntity();
181                 }
182             }
183             final NotificationEvent event =
184                     new NotificationEvent(currentVersionLoader, eventHeader, eventObject, transactionId, sourceOfTruth);
185             events.put(uri.toString(), event);
186         } catch (AAIUnknownObjectException e) {
187             throw new RuntimeException("Fatal error - notification-event-header object not found!");
188         } catch (AAIUnmarshallingException e) {
189             LOGGER.error(
190                     "Unmarshalling error occurred while generating UEBNotification " + LogFormatTools.getStackTop(e));
191         }
192     }
193
194     /**
195      * Trigger events.
196      *
197      * @throws AAIException the AAI exception
198      */
199     public void triggerEvents() throws AAIException {
200         for (NotificationEvent event : events.values()) {
201             event.trigger();
202         }
203         clearEvents();
204     }
205
206     public List<NotificationEvent> getEvents() {
207         return new ArrayList<>(this.events.values());
208     }
209
210     public Map<String, NotificationEvent> getEventsMap() {
211         return this.events;
212     }
213
214     private String getUri(String uri, String basePath) {
215         if (uri == null || uri.isEmpty()) {
216             return "";
217         } else if (uri.charAt(0) != '/') {
218             uri = '/' + uri;
219         }
220
221         if ((basePath != null) && (!basePath.isEmpty())) {
222             if (!(basePath.startsWith("/"))) {
223                 basePath = "/" + basePath;
224             }
225             if (!(basePath.endsWith("/"))) {
226                 basePath = basePath + "/";
227             }
228         }
229
230         LOGGER.trace("Notification header uri base path:'{}', uri:'{}'", basePath, uri);
231
232         return uri.replaceAll("^" + basePath + "v\\d+", "");
233     }
234
235     public void clearEvents() {
236         events.clear();
237     }
238 }