470c4e730b53119286979ea845f2d087cd064f99
[dcaegen2/collectors/datafile.git] /
1 /*-
2  * ============LICENSE_START========================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
4  * ==================================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.dcaegen2.collectors.datafile.service;
20
21 import com.google.gson.JsonArray;
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonObject;
24 import com.google.gson.JsonParser;
25
26 import java.net.URI;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.stream.StreamSupport;
31
32 import org.onap.dcaegen2.collectors.datafile.ftp.Scheme;
33 import org.onap.dcaegen2.collectors.datafile.model.FileData;
34 import org.onap.dcaegen2.collectors.datafile.model.FileReadyMessage;
35 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFileData;
36 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFileReadyMessage;
37 import org.onap.dcaegen2.collectors.datafile.model.ImmutableMessageMetaData;
38 import org.onap.dcaegen2.collectors.datafile.model.MessageMetaData;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.util.StringUtils;
42
43 import reactor.core.publisher.Flux;
44 import reactor.core.publisher.Mono;
45
46 /**
47  * Parses the fileReady event and creates a Flux of FileReadyMessage containing the information.
48  *
49  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
50  */
51 public class JsonMessageParser {
52     private static final Logger logger = LoggerFactory.getLogger(JsonMessageParser.class);
53
54     private static final String COMMON_EVENT_HEADER = "commonEventHeader";
55     private static final String EVENT_NAME = "eventName";
56     private static final String LAST_EPOCH_MICROSEC = "lastEpochMicrosec";
57     private static final String SOURCE_NAME = "sourceName";
58     private static final String START_EPOCH_MICROSEC = "startEpochMicrosec";
59     private static final String TIME_ZONE_OFFSET = "timeZoneOffset";
60
61     private static final String EVENT = "event";
62     private static final String NOTIFICATION_FIELDS = "notificationFields";
63     private static final String CHANGE_IDENTIFIER = "changeIdentifier";
64     private static final String CHANGE_TYPE = "changeType";
65     private static final String NOTIFICATION_FIELDS_VERSION = "notificationFieldsVersion";
66
67     private static final String ARRAY_OF_NAMED_HASH_MAP = "arrayOfNamedHashMap";
68     private static final String NAME = "name";
69     private static final String HASH_MAP = "hashMap";
70     private static final String LOCATION = "location";
71     private static final String COMPRESSION = "compression";
72     private static final String FILE_FORMAT_TYPE = "fileFormatType";
73     private static final String FILE_FORMAT_VERSION = "fileFormatVersion";
74
75     private static final String FILE_READY_CHANGE_TYPE = "FileReady";
76
77     /**
78      * The data types available in the event name.
79      */
80     private enum EventNameDataType {
81         PRODUCT_NAME(1), VENDOR_NAME(2);
82
83         private int index;
84
85         EventNameDataType(int index) {
86             this.index = index;
87         }
88     }
89
90     /**
91      * Parses the Json message and returns a stream of messages.
92      *
93      * @param rawMessage the Json message to parse.
94      * @return a <code>Flux</code> containing messages.
95      */
96     public Flux<FileReadyMessage> getMessagesFromJson(Mono<String> rawMessage) {
97         return rawMessage.flatMapMany(JsonMessageParser::getJsonParserMessage).flatMap(this::createMessageData);
98     }
99
100     Optional<JsonObject> getJsonObjectFromAnArray(JsonElement element) {
101         JsonParser jsonParser = new JsonParser();
102         if (element.isJsonPrimitive()) {
103             return Optional.of(jsonParser.parse(element.getAsString()).getAsJsonObject());
104         } else if (element.isJsonObject()) {
105             return Optional.of((JsonObject) element);
106         } else {
107             return Optional.of(jsonParser.parse(element.toString()).getAsJsonObject());
108         }
109     }
110
111     private Flux<FileReadyMessage> getMessagesFromJsonArray(JsonElement jsonElement) {
112         return createMessages(Flux.fromStream(StreamSupport.stream(jsonElement.getAsJsonArray().spliterator(), false)
113                 .map(jsonElementFromArray -> getJsonObjectFromAnArray(jsonElementFromArray)
114                         .orElseGet(JsonObject::new))));
115     }
116
117     /**
118      * Extract info from string and create a Flux of {@link FileReadyMessage}.
119      *
120      * @param rawMessage - results from DMaaP
121      * @return reactive Flux of FileReadyMessages
122      */
123     private Flux<FileReadyMessage> createMessageData(JsonElement jsonElement) {
124         return jsonElement.isJsonObject() ? createMessages(Flux.just(jsonElement.getAsJsonObject()))
125                 : getMessagesFromJsonArray(jsonElement);
126     }
127
128     private static Mono<JsonElement> getJsonParserMessage(String message) {
129         return StringUtils.isEmpty(message) ? Mono.empty() : Mono.fromSupplier(() -> new JsonParser().parse(message));
130     }
131
132     private static Flux<FileReadyMessage> createMessages(Flux<JsonObject> jsonObject) {
133         return jsonObject.flatMap(monoJsonP -> containsNotificationFields(monoJsonP) ? transformMessages(monoJsonP)
134                 : logErrorAndReturnEmptyMessageFlux("Incorrect JsonObject - missing header. " + jsonObject));
135     }
136
137
138     private static Mono<FileReadyMessage> transformMessages(JsonObject message) {
139         Optional<MessageMetaData> optionalMessageMetaData = getMessageMetaData(message);
140         if (optionalMessageMetaData.isPresent()) {
141             MessageMetaData messageMetaData = optionalMessageMetaData.get();
142             JsonObject notificationFields = message.getAsJsonObject(EVENT).getAsJsonObject(NOTIFICATION_FIELDS);
143             JsonArray arrayOfNamedHashMap = notificationFields.getAsJsonArray(ARRAY_OF_NAMED_HASH_MAP);
144             if (arrayOfNamedHashMap != null) {
145                 List<FileData> allFileDataFromJson = getAllFileDataFromJson(arrayOfNamedHashMap, messageMetaData);
146                 if (!allFileDataFromJson.isEmpty()) {
147                     return Mono.just(ImmutableFileReadyMessage.builder() //
148                             .files(allFileDataFromJson) //
149                             .build());
150                 } else {
151                     return Mono.empty();
152                 }
153             }
154
155             logger.error("VES event parsing. Missing arrayOfNamedHashMap in message. {}", message);
156             return Mono.empty();
157         }
158         logger.error("VES event parsing. FileReady event has incorrect JsonObject. {}", message);
159         return Mono.empty();
160     }
161
162
163     private static Optional<MessageMetaData> getMessageMetaData(JsonObject message) {
164         List<String> missingValues = new ArrayList<>();
165         JsonObject commonEventHeader = message.getAsJsonObject(EVENT).getAsJsonObject(COMMON_EVENT_HEADER);
166         String eventName = getValueFromJson(commonEventHeader, EVENT_NAME, missingValues);
167
168         JsonObject notificationFields = message.getAsJsonObject(EVENT).getAsJsonObject(NOTIFICATION_FIELDS);
169         String changeIdentifier = getValueFromJson(notificationFields, CHANGE_IDENTIFIER, missingValues);
170         String changeType = getValueFromJson(notificationFields, CHANGE_TYPE, missingValues);
171
172         // Just to check that it is in the message. Might be needed in the future if there is a new
173         // version.
174         getValueFromJson(notificationFields, NOTIFICATION_FIELDS_VERSION, missingValues);
175
176         MessageMetaData messageMetaData = ImmutableMessageMetaData.builder() //
177                 .productName(getDataFromEventName(EventNameDataType.PRODUCT_NAME, eventName, missingValues)) //
178                 .vendorName(getDataFromEventName(EventNameDataType.VENDOR_NAME, eventName, missingValues)) //
179                 .lastEpochMicrosec(getValueFromJson(commonEventHeader, LAST_EPOCH_MICROSEC, missingValues)) //
180                 .sourceName(getValueFromJson(commonEventHeader, SOURCE_NAME, missingValues)) //
181                 .startEpochMicrosec(getValueFromJson(commonEventHeader, START_EPOCH_MICROSEC, missingValues)) //
182                 .timeZoneOffset(getValueFromJson(commonEventHeader, TIME_ZONE_OFFSET, missingValues)) //
183                 .changeIdentifier(changeIdentifier) //
184                 .changeType(changeType) //
185                 .build();
186         if (missingValues.isEmpty() && isChangeTypeCorrect(changeType)) {
187             return Optional.of(messageMetaData);
188         } else {
189             String errorMessage = "VES event parsing.";
190             if (!missingValues.isEmpty()) {
191                 errorMessage += " Missing data: " + missingValues;
192             }
193             if (!isChangeTypeCorrect(changeType)) {
194                 errorMessage += " Change type is wrong: " + changeType + " expected: " + FILE_READY_CHANGE_TYPE;
195             }
196             errorMessage += " Message: {}";
197             logger.error(errorMessage, message);
198             return Optional.empty();
199         }
200     }
201
202     private static boolean isChangeTypeCorrect(String changeType) {
203         return FILE_READY_CHANGE_TYPE.equals(changeType);
204     }
205
206     private static List<FileData> getAllFileDataFromJson(JsonArray arrayOfAdditionalFields,
207             MessageMetaData messageMetaData) {
208         List<FileData> res = new ArrayList<>();
209         for (int i = 0; i < arrayOfAdditionalFields.size(); i++) {
210             JsonObject fileInfo = (JsonObject) arrayOfAdditionalFields.get(i);
211             Optional<FileData> fileData = getFileDataFromJson(fileInfo, messageMetaData);
212
213             if (fileData.isPresent()) {
214                 res.add(fileData.get());
215             }
216         }
217         return res;
218     }
219
220     private static Optional<FileData> getFileDataFromJson(JsonObject fileInfo, MessageMetaData messageMetaData) {
221         logger.trace("starting to getFileDataFromJson!");
222
223         List<String> missingValues = new ArrayList<>();
224         JsonObject data = fileInfo.getAsJsonObject(HASH_MAP);
225
226         String location = getValueFromJson(data, LOCATION, missingValues);
227         Scheme scheme;
228         try {
229             scheme = Scheme.getSchemeFromString(URI.create(location).getScheme());
230         } catch (Exception e) {
231             logger.error("VES event parsing.", e);
232             return Optional.empty();
233         }
234         FileData fileData = ImmutableFileData.builder() //
235                 .name(getValueFromJson(fileInfo, NAME, missingValues)) //
236                 .fileFormatType(getValueFromJson(data, FILE_FORMAT_TYPE, missingValues)) //
237                 .fileFormatVersion(getValueFromJson(data, FILE_FORMAT_VERSION, missingValues)) //
238                 .location(location) //
239                 .scheme(scheme) //
240                 .compression(getValueFromJson(data, COMPRESSION, missingValues)) //
241                 .messageMetaData(messageMetaData) //
242                 .build();
243         if (missingValues.isEmpty()) {
244             return Optional.of(fileData);
245         }
246         logger.error("VES event parsing. File information wrong. Missing data: {} Data: {}", missingValues, fileInfo);
247         return Optional.empty();
248     }
249
250     /**
251      * Gets data from the event name. Defined as:
252      * {DomainAbbreviation}_{productName}-{vendorName}_{Description}, example:
253      * Noti_RnNode-Ericsson_FileReady
254      *
255      * @param dataType The type of data to get, {@link DmaapConsumerJsonParser.EventNameDataType}.
256      * @param eventName The event name to get the data from.
257      * @param missingValues List of missing values. The dataType will be added if missing.
258      * @return String of data from event name
259      */
260     private static String getDataFromEventName(EventNameDataType dataType, String eventName,
261             List<String> missingValues) {
262         String[] eventArray = eventName.split("_|-");
263         if (eventArray.length >= 4) {
264             return eventArray[dataType.index];
265         } else {
266             missingValues.add(dataType.toString());
267             logger.error("Can not get {} from eventName, eventName is not in correct format: {}", dataType, eventName);
268         }
269         return "";
270     }
271
272     private static String getValueFromJson(JsonObject jsonObject, String jsonKey, List<String> missingValues) {
273         if (jsonObject.has(jsonKey)) {
274             return jsonObject.get(jsonKey).getAsString();
275         } else {
276             missingValues.add(jsonKey);
277             return "";
278         }
279     }
280
281     private static boolean containsNotificationFields(JsonObject jsonObject) {
282         return jsonObject.has(EVENT) && jsonObject.getAsJsonObject(EVENT).has(NOTIFICATION_FIELDS);
283     }
284
285     private static Flux<FileReadyMessage> logErrorAndReturnEmptyMessageFlux(String errorMessage) {
286         logger.error(errorMessage);
287         return Flux.empty();
288     }
289 }