Update the license for 2017-2018 license
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / StoreNotificationEvent.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 package org.onap.aai.util;
21
22 import java.io.StringWriter;
23 import java.util.Iterator;
24 import java.util.UUID;
25
26 import javax.xml.bind.Marshaller;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import org.eclipse.persistence.dynamic.DynamicEntity;
31 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
32 import org.json.JSONException;
33 import org.json.JSONObject;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.dmaap.AAIDmaapEventJMSProducer;
36 import org.onap.aai.dmaap.JMSProducer;
37 import org.onap.aai.dmaap.MessageProducer;
38 import org.onap.aai.domain.notificationEvent.NotificationEvent;
39 import org.onap.aai.exceptions.AAIException;
40 import org.onap.aai.introspection.Introspector;
41 import org.onap.aai.introspection.Loader;
42 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
43 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
44 import org.springframework.context.ApplicationContext;
45 import org.springframework.core.env.Environment;
46
47 public class StoreNotificationEvent {
48
49     private static final EELFLogger logger = EELFManager.getInstance().getLogger(StoreNotificationEvent.class);
50         private MessageProducer messageProducer;
51         private String fromAppId = "";
52         private String transId = "";
53         private final String transactionId;
54         private final String sourceOfTruth;
55
56         private ApplicationContext context;
57         private Environment env;
58
59         /**
60          * Instantiates a new store notification event.
61          */
62         public StoreNotificationEvent(String transactionId, String sourceOfTruth) {
63                 this.context         = SpringContextAware.getApplicationContext();
64                 // If the context is null then this is being invoked from
65                 // non spring context so creating the jms producer each time
66                 // Otherwise, get the jms producer from the spring context so
67                 // no need to create a instance of this each time
68         // Also check if the environment has the dmaap profile
69                 // TODO - Add the constants for profile so do this when adding the https two-way ssl and one way with basic auth
70                 if(this.context == null){
71                         this.messageProducer = new AAIDmaapEventJMSProducer();
72                 } else {
73                     env = context.getEnvironment();
74                         if(env.acceptsProfiles("dmaap")){
75                                 try {
76                                         this.messageProducer = (JMSProducer)context.getBean("jmsProducer");
77                                 } catch(NoSuchBeanDefinitionException ex){
78                                         logger.error("Currently using the dmaap profile but still not able to find bean so check DmaapConfig", ex);
79                                 }
80                         } else {
81                                 this.messageProducer = new AAIDmaapEventJMSProducer();
82                         }
83                 }
84         this.transactionId   = transactionId;
85         this.sourceOfTruth   = sourceOfTruth;
86         }
87
88         public StoreNotificationEvent(AAIDmaapEventJMSProducer producer, String transactionId, String sourceOfTruth) {
89             this.messageProducer = producer;
90                 this.transactionId   = transactionId;
91                 this.sourceOfTruth   = sourceOfTruth;
92         }
93
94         /**
95          * Store event.
96          *
97          * @param eh
98          *            the eh
99          * @param obj
100          *            the obj
101          * @throws AAIException
102          *             the AAI exception
103          */
104         public String storeEvent(NotificationEvent.EventHeader eh, Object obj) throws AAIException {
105
106                 if (obj == null) {
107                         throw new AAIException("AAI_7350");
108                 }
109
110                 org.onap.aai.domain.notificationEvent.ObjectFactory factory = new org.onap.aai.domain.notificationEvent.ObjectFactory();
111
112                 org.onap.aai.domain.notificationEvent.NotificationEvent ne = factory.createNotificationEvent();
113
114                 if (eh.getId() == null) {
115                         eh.setId(genDate2() + "-" + UUID.randomUUID().toString());
116                 }
117                 if (eh.getTimestamp() == null) {
118                         eh.setTimestamp(genDate());
119                 }
120
121                 // there's no default, but i think we want to put this in hbase?
122
123                 if (eh.getEntityLink() == null) {
124                         eh.setEntityLink("UNK");
125                 }
126
127                 if (eh.getAction() == null) {
128                         eh.setAction("UNK");
129                 }
130
131                 if (eh.getEventType() == null) {
132                         eh.setEventType(AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
133                 }
134
135                 if (eh.getDomain() == null) {
136                         eh.setDomain(AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
137                 }
138
139                 if (eh.getSourceName() == null) {
140                         eh.setSourceName(AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
141                 }
142
143                 if (eh.getSequenceNumber() == null) {
144                         eh.setSequenceNumber(AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
145                 }
146
147                 if (eh.getSeverity() == null) {
148                         eh.setSeverity(AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
149                 }
150
151                 if (eh.getVersion() == null) {
152                         eh.setVersion(AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
153                 }
154
155                 ne.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI);
156                 ne.setEventHeader(eh);
157                 ne.setEntity(obj);
158
159                 try {
160                         PojoUtils pu = new PojoUtils();
161                         String entityJson = pu.getJsonFromObject(ne);
162                         sendToDmaapJmsQueue(entityJson);
163                         return entityJson;
164                 } catch (Exception e) {
165                         throw new AAIException("AAI_7350", e);
166                 }
167         }
168
169         /**
170          * Store dynamic event.
171          *
172          * @param notificationJaxbContext
173          *            the notification jaxb context
174          * @param notificationVersion
175          *            the notification version
176          * @param eventHeader
177          *            the event header
178          * @param obj
179          *            the obj
180          * @throws AAIException
181          *             the AAI exception
182          */
183         public void storeDynamicEvent(DynamicJAXBContext notificationJaxbContext, String notificationVersion, DynamicEntity eventHeader, DynamicEntity obj) throws AAIException {
184
185                 if (obj == null) {
186                         throw new AAIException("AAI_7350");
187                 }
188
189                 DynamicEntity notificationEvent = notificationJaxbContext.getDynamicType("inventory.aai.onap.org." + notificationVersion + ".NotificationEvent").newDynamicEntity();
190
191                 if (eventHeader.get("id") == null) {
192                         eventHeader.set("id", genDate2() + "-" + UUID.randomUUID().toString());
193                 }
194                 
195                 if (eventHeader.get("timestamp") == null) {
196                         eventHeader.set("timestamp", genDate());
197                 }
198
199                 if (eventHeader.get("entityLink") == null) {
200                         eventHeader.set("entityLink", "UNK");
201                 }
202
203                 if (eventHeader.get("action") == null) {
204                         eventHeader.set("action", "UNK");
205                 }
206
207                 if (eventHeader.get("eventType") == null) {
208                         eventHeader.set("eventType", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
209                 }
210
211                 if (eventHeader.get("domain") == null) {
212                         eventHeader.set("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
213                 }
214
215                 if (eventHeader.get("sourceName") == null) {
216                         eventHeader.set("sourceName", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
217                 }
218
219                 if (eventHeader.get("sequenceNumber") == null) {
220                         eventHeader.set("sequenceNumber", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
221                 }
222
223                 if (eventHeader.get("severity") == null) {
224                         eventHeader.set("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
225                 }
226
227                 if (eventHeader.get("version") == null) {
228                         eventHeader.set("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
229                 }
230
231                 if (notificationEvent.get("cambriaPartition") == null) {
232                         notificationEvent.set("cambriaPartition", AAIConstants.UEB_PUB_PARTITION_AAI);
233                 }
234
235                 notificationEvent.set("eventHeader", eventHeader);
236                 notificationEvent.set("entity", obj);
237
238                 try {
239                         StringWriter result = new StringWriter();
240                         
241                         Marshaller marshaller = notificationJaxbContext.createMarshaller();
242                         marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
243                         marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, false);
244                         marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
245                         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
246                         marshaller.marshal(notificationEvent, result);
247                         
248                         this.sendToDmaapJmsQueue(result.toString());
249
250                 } catch (Exception e) {
251                         throw new AAIException("AAI_7350", e);
252                 }
253         }
254
255         public String storeEvent(Loader loader, Introspector eventHeader, Introspector obj) throws AAIException {
256                 if (obj == null) {
257                         throw new AAIException("AAI_7350");
258                 }
259
260                 try {
261                         final Introspector notificationEvent = loader.introspectorFromName("notification-event");
262
263                         if (eventHeader.getValue("id") == null) {
264                                 eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString());
265                         }
266
267                         if (eventHeader.getValue("timestamp") == null) {
268                                 eventHeader.setValue("timestamp", genDate());
269                         }
270
271                         if (eventHeader.getValue("entity-link") == null) {
272                                 eventHeader.setValue("entity-link", "UNK");
273                         }
274
275                         if (eventHeader.getValue("action") == null) {
276                                 eventHeader.setValue("action", "UNK");
277                         }
278
279                         if (eventHeader.getValue("event-type") == null) {
280                                 eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
281                         }
282
283                         if (eventHeader.getValue("domain") == null) {
284                                 eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
285                         }
286
287                         if (eventHeader.getValue("source-name") == null) {
288                                 eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
289                         }
290
291                         if (eventHeader.getValue("sequence-number") == null) {
292                                 eventHeader.setValue("sequence-number", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
293                         }
294
295                         if (eventHeader.getValue("severity") == null) {
296                                 eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
297                         }
298
299                         if (eventHeader.getValue("version") == null) {
300                                 eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
301                         }
302
303                         if (notificationEvent.getValue("cambria-partition") == null) {
304                                 notificationEvent.setValue("cambria-partition", AAIConstants.UEB_PUB_PARTITION_AAI);
305                         }
306
307                         notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject());
308                         notificationEvent.setValue("entity", obj.getUnderlyingObject());
309
310                         String entityJson = notificationEvent.marshal(false);
311                         sendToDmaapJmsQueue(entityJson);
312                         return entityJson;
313                 } catch (JSONException e) {
314                         throw new AAIException("AAI_7350", e);
315                 } catch (AAIUnknownObjectException e) {
316                         throw new AAIException("AAI_7350", e);
317                 }
318         }
319
320         private void sendToDmaapJmsQueue(String entityString) throws JSONException {
321                 
322                 JSONObject entityJsonObject = new JSONObject(entityString);
323                 
324                 JSONObject entityJsonObjectUpdated = new JSONObject();
325                 JSONObject finalJson = new JSONObject();
326
327                 JSONObject entityHeader = entityJsonObject.getJSONObject("event-header");
328                 String cambriaPartition = entityJsonObject.getString("cambria.partition");
329
330                 entityJsonObject.remove("event-header");
331                 entityJsonObject.remove("cambria.partition");
332
333                 entityJsonObjectUpdated.put("event-header", entityHeader);
334                 entityJsonObjectUpdated.put("cambria.partition", cambriaPartition);
335                 
336                 String transId = entityHeader.getString("id");
337                 String fromAppId = entityHeader.getString("source-name");
338                 
339                 Iterator<String> iter = entityJsonObject.keys();
340                 JSONObject entity = new JSONObject();
341                 if (iter.hasNext()) {
342                         entity = entityJsonObject.getJSONObject(iter.next());
343                 }
344                 
345                 entityJsonObjectUpdated.put("entity", entity);
346
347                 finalJson.put("event-topic", "AAI-EVENT");
348                 finalJson.put("transId", transId);
349                 finalJson.put("fromAppId", fromAppId);
350                 finalJson.put("fullId", "");
351                 finalJson.put("aaiEventPayload", entityJsonObjectUpdated);
352
353                 messageProducer.sendMessageToDefaultDestination(finalJson);
354         }
355
356         /**
357          * Gen date.
358          *
359          * @return the string
360          */
361         public static String genDate() {
362                 FormatDate fd = new FormatDate("YYYYMMdd-HH:mm:ss:SSS");
363                 return fd.getDateTime();
364         }
365
366         /**
367          * Gen date 2.
368          *
369          * @return the string
370          */
371         public static String genDate2() {
372                 FormatDate fd = new FormatDate("YYYYMMddHHmmss");
373                 return fd.getDateTime();
374         }
375
376 }