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