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