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