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