Upgraded to Support VES 7.0
[dcaegen2/services/mapper.git] / UniversalVesAdapter / src / main / java / org / onap / universalvesadapter / adapter / UniversalEventAdapter.java
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DCAE
4 * ================================================================================
5 * Copyright 2018 TechMahindra
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.universalvesadapter.adapter;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.IOException;
24 import java.nio.charset.StandardCharsets;
25 import java.util.Iterator;
26 import java.util.Map;
27 import java.util.concurrent.ConcurrentHashMap;
28
29 import javax.annotation.PreDestroy;
30
31 import org.milyn.Smooks;
32 import org.onap.dcaegen2.ves.domain.ves7_0.VesEvent;
33 import org.onap.universalvesadapter.exception.ConfigFileSmooksConversionException;
34 import org.onap.universalvesadapter.exception.VesException;
35 import org.onap.universalvesadapter.service.VESAdapterInitializer;
36 import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrival;
37 import org.onap.universalvesadapter.utils.SmooksUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Value;
41 import org.springframework.stereotype.Component;
42 import org.xml.sax.SAXException;
43
44 import com.fasterxml.jackson.core.JsonProcessingException;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import com.google.gson.Gson;
47 import com.google.gson.JsonElement;
48 import com.google.gson.JsonObject;
49 import com.google.gson.JsonParseException;
50 import com.google.gson.JsonSyntaxException;
51
52 /**
53  * Default implementation of the Generic Adapter
54  * 
55  * @author kmalbari
56  *
57  */
58
59 @Component
60 public class UniversalEventAdapter implements GenericAdapter {
61          private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
62          private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
63          
64         @Value("${defaultConfigFilelocation}")
65         private String defaultConfigFilelocation;
66         private String collectorIdentifierValue;
67         private String collectorIdentifierKey;
68         private Map<String, Smooks> eventToSmooksMapping = new ConcurrentHashMap<>();
69
70         public UniversalEventAdapter() {
71
72         }
73
74         /**
75          * transforms JSON to VES format and and returns the ves Event
76          * 
77          * @param IncomingJason,eventType
78          * @return ves Event
79          */
80         @Override
81         public String transform(String incomingJsonString)
82                         throws  ConfigFileSmooksConversionException, VesException {
83                 String result = "";
84                 String configFileData;
85                 
86                 String identifier[]= CollectorConfigPropertyRetrival.getProperyArray("identifier",defaultConfigFilelocation );
87                 String defaultMappingFile="defaultMappingFile-"+Thread.currentThread().getName();
88                 try {
89
90                                 Gson gson = new Gson();
91                                 JsonObject body = gson.fromJson(incomingJsonString, JsonObject.class);
92                                 
93                                 JsonElement results;
94                                 for(int i=0;i<identifier.length;i++)
95                                 {
96                                 JsonObject obj;
97                                 if((obj=keyObject(body,identifier[i])).has(identifier[i]))
98                                 {
99                                         collectorIdentifierKey=identifier[i];
100                                          results=obj.get(identifier[i]);
101                                          collectorIdentifierValue=results.getAsString();
102                                         
103                                 }
104                                 
105                                 }
106                                 //collectorIdentifierValue = collectorIdentifierValue.substring(0, collectorIdentifierValue.length() - 4);
107                                 if(collectorIdentifierKey.equals("notify OID"))
108                                 {
109                                         collectorIdentifierValue = collectorIdentifierValue.substring(0, collectorIdentifierValue.length() - 4);
110                                 }
111                                 
112
113                                 if (VESAdapterInitializer.getMappingFiles().containsKey(collectorIdentifierValue)) {
114                                         configFileData = VESAdapterInitializer.getMappingFiles().get(collectorIdentifierValue);
115                                         debugLogger.debug("Using Mapping file as Mapping file is available for collector identifier:{}",collectorIdentifierValue);
116                                 
117                                 } else {
118
119                                         configFileData = VESAdapterInitializer.getMappingFiles().get(defaultMappingFile);
120                                         
121                                         debugLogger.debug("Using Default Mapping file as Mapping file is not available for Enterprise Id:{}",collectorIdentifierValue);
122                                 }
123
124                                 Smooks smooksTemp = new Smooks(new ByteArrayInputStream(configFileData.getBytes(StandardCharsets.UTF_8)));
125                                 eventToSmooksMapping.put(collectorIdentifierKey, smooksTemp);
126
127                         VesEvent vesEvent = SmooksUtils.getTransformedObjectForInput(smooksTemp,incomingJsonString);
128                         debugLogger.info("Incoming json transformed to VES format successfully:"+Thread.currentThread().getName());
129                         ObjectMapper objectMapper = new ObjectMapper();
130                         result = objectMapper.writeValueAsString(vesEvent);
131                         debugLogger.info("Serialized VES json");
132                 } catch (JsonProcessingException exception) {
133                         throw new VesException("Unable to convert pojo to VES format, Reason :{}", exception);
134                 } catch (SAXException | IOException exception) {
135                         //Invalid Mapping file
136                         exception.printStackTrace();
137                         errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString, exception.getMessage()); 
138
139                 } catch (JsonSyntaxException exception) {
140                         // Invalid Trap
141                         errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}", incomingJsonString, exception);
142                 }catch (JsonParseException exception) {
143                         // Invalid Trap
144                         errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}", incomingJsonString, exception);
145                 } 
146                 catch (RuntimeException exception) {
147
148                         exception.printStackTrace();
149                         errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString, exception.getMessage());
150
151                 }
152                 return result;
153         }
154
155         /**
156          * Closes all open smooks' instances before bean is destroyed
157          */
158         @PreDestroy
159         public void destroy() {
160                 for (Smooks smooks : eventToSmooksMapping.values())
161                         smooks.close();
162                 debugLogger.warn("All Smooks objects closed");
163         }
164         
165         public JsonObject keyObject(JsonObject  object, String searchedKey) {
166             boolean exists = object.has(searchedKey);
167             JsonObject jsonObject = object;
168            
169             if(!exists) {      
170                 Iterator<?> keys = object.keySet().iterator();
171                 while( keys.hasNext() ) {
172                     String key = (String)keys.next();
173                     if ( object.get(key) instanceof JsonObject ) {
174                          
175                         jsonObject=(JsonObject) object.get(key);
176                         JsonObject   obj = keyObject(jsonObject, searchedKey);
177                         exists = obj.has(searchedKey);
178                     }
179                 }
180             }
181             
182             return jsonObject;
183         }
184
185 }