eed0f0bd410b8ffc1dded48006a7f4328f56eedd
[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     public static final String ERROR_MSG_VES_EVENT_PARSING = "VES event parsing. ";
55
56     private static final String COMMON_EVENT_HEADER = "commonEventHeader";
57     private static final String EVENT_NAME = "eventName";
58     private static final String LAST_EPOCH_MICROSEC = "lastEpochMicrosec";
59     private static final String SOURCE_NAME = "sourceName";
60     private static final String START_EPOCH_MICROSEC = "startEpochMicrosec";
61     private static final String TIME_ZONE_OFFSET = "timeZoneOffset";
62
63     private static final String EVENT = "event";
64     private static final String NOTIFICATION_FIELDS = "notificationFields";
65     private static final String CHANGE_IDENTIFIER = "changeIdentifier";
66     private static final String CHANGE_TYPE = "changeType";
67     private static final String NOTIFICATION_FIELDS_VERSION = "notificationFieldsVersion";
68
69     private static final String ARRAY_OF_NAMED_HASH_MAP = "arrayOfNamedHashMap";
70     private static final String NAME = "name";
71     private static final String HASH_MAP = "hashMap";
72     private static final String LOCATION = "location";
73     private static final String COMPRESSION = "compression";
74     private static final String FILE_FORMAT_TYPE = "fileFormatType";
75     private static final String FILE_FORMAT_VERSION = "fileFormatVersion";
76
77     private static final String FILE_READY_CHANGE_TYPE = "FileReady";
78
79     /**
80      * The data types available in the event name.
81      */
82     private enum EventNameDataType {
83         PRODUCT_NAME(1), VENDOR_NAME(2);
84
85         private int index;
86
87         EventNameDataType(int index) {
88             this.index = index;
89         }
90     }
91
92     /**
93      * Parses the Json message and returns a stream of messages.
94      *
95      * @param rawMessage the Json message to parse.
96      * @return a <code>Flux</code> containing messages.
97      */
98
99     public Flux<FileReadyMessage> getMessagesFromJson(Mono<JsonElement> rawMessage) {
100         return rawMessage.flatMapMany(this::createMessageData);
101     }
102
103     Optional<JsonObject> getJsonObjectFromAnArray(JsonElement element) {
104         JsonParser jsonParser = new JsonParser();
105         if (element.isJsonPrimitive()) {
106             return Optional.of(jsonParser.parse(element.getAsString()).getAsJsonObject());
107         } else if (element.isJsonObject()) {
108             return Optional.of((JsonObject) element);
109         } else {
110             return Optional.of(jsonParser.parse(element.toString()).getAsJsonObject());
111         }
112     }
113
114     private Flux<FileReadyMessage> getMessagesFromJsonArray(JsonElement jsonElement) {
115         return createMessages(Flux.fromStream(StreamSupport.stream(jsonElement.getAsJsonArray().spliterator(), false)
116             .map(jsonElementFromArray -> getJsonObjectFromAnArray(jsonElementFromArray).orElseGet(JsonObject::new))));
117     }
118
119     /**
120      * Extract info from string and create a Flux of {@link FileReadyMessage}.
121      *
122      * @param rawMessage - results from DMaaP
123      * @return reactive Flux of FileReadyMessages
124      */
125     private Flux<FileReadyMessage> createMessageData(JsonElement jsonElement) {
126         return jsonElement.isJsonObject() ? createMessages(Flux.just(jsonElement.getAsJsonObject()))
127             : getMessagesFromJsonArray(jsonElement);
128     }
129
130     private static Flux<FileReadyMessage> createMessages(Flux<JsonObject> jsonObject) {
131         return jsonObject.flatMap(monoJsonP -> containsNotificationFields(monoJsonP) ? transformMessages(monoJsonP)
132             : logErrorAndReturnEmptyMessageFlux("Incorrect JsonObject - missing header. " + jsonObject));
133     }
134
135     private static Mono<FileReadyMessage> transformMessages(JsonObject message) {
136         Optional<MessageMetaData> optionalMessageMetaData = getMessageMetaData(message);
137         if (optionalMessageMetaData.isPresent()) {
138             MessageMetaData messageMetaData = optionalMessageMetaData.get();
139             JsonObject notificationFields = message.getAsJsonObject(EVENT).getAsJsonObject(NOTIFICATION_FIELDS);
140             JsonArray arrayOfNamedHashMap = notificationFields.getAsJsonArray(ARRAY_OF_NAMED_HASH_MAP);
141             if (arrayOfNamedHashMap != null) {
142                 List<FileData> allFileDataFromJson = getAllFileDataFromJson(arrayOfNamedHashMap, messageMetaData);
143                 if (!allFileDataFromJson.isEmpty()) {
144                     return Mono.just(ImmutableFileReadyMessage.builder() //
145                         .files(allFileDataFromJson) //
146                         .build());
147                 } else {
148                     return Mono.empty();
149                 }
150             }
151
152             logger.error(ERROR_MSG_VES_EVENT_PARSING + "Missing arrayOfNamedHashMap in message. {}", message);
153             return Mono.empty();
154         }
155         logger.error(ERROR_MSG_VES_EVENT_PARSING + "FileReady event has incorrect JsonObject. {}", message);
156         return Mono.empty();
157     }
158
159     private static Optional<MessageMetaData> getMessageMetaData(JsonObject message) {
160         List<String> missingValues = new ArrayList<>();
161         JsonObject commonEventHeader = message.getAsJsonObject(EVENT).getAsJsonObject(COMMON_EVENT_HEADER);
162         String eventName = getValueFromJson(commonEventHeader, EVENT_NAME, missingValues);
163
164         JsonObject notificationFields = message.getAsJsonObject(EVENT).getAsJsonObject(NOTIFICATION_FIELDS);
165         String changeIdentifier = getValueFromJson(notificationFields, CHANGE_IDENTIFIER, missingValues);
166         String changeType = getValueFromJson(notificationFields, CHANGE_TYPE, missingValues);
167
168         // Just to check that it is in the message. Might be needed in the future if there is a new
169         // version.
170         getValueFromJson(notificationFields, NOTIFICATION_FIELDS_VERSION, missingValues);
171
172         MessageMetaData messageMetaData = ImmutableMessageMetaData.builder() //
173             .productName(getDataFromEventName(EventNameDataType.PRODUCT_NAME, eventName, missingValues)) //
174             .vendorName(getDataFromEventName(EventNameDataType.VENDOR_NAME, eventName, missingValues)) //
175             .lastEpochMicrosec(getValueFromJson(commonEventHeader, LAST_EPOCH_MICROSEC, missingValues)) //
176             .sourceName(getValueFromJson(commonEventHeader, SOURCE_NAME, missingValues)) //
177             .startEpochMicrosec(getValueFromJson(commonEventHeader, START_EPOCH_MICROSEC, missingValues)) //
178             .timeZoneOffset(getValueFromJson(commonEventHeader, TIME_ZONE_OFFSET, missingValues)) //
179             .changeIdentifier(changeIdentifier) //
180             .changeType(changeType) //
181             .build();
182         if (missingValues.isEmpty() && isChangeTypeCorrect(changeType)) {
183             return Optional.of(messageMetaData);
184         } else {
185             String errorMessage = ERROR_MSG_VES_EVENT_PARSING;
186             if (!missingValues.isEmpty()) {
187                 errorMessage += "Missing data: " + missingValues + ".";
188             }
189             if (!isChangeTypeCorrect(changeType)) {
190                 errorMessage += " Change type is wrong: " + changeType + " Expected: " + FILE_READY_CHANGE_TYPE;
191             }
192             errorMessage += " Message: {}";
193             logger.error(errorMessage, message);
194             return Optional.empty();
195         }
196     }
197
198     private static boolean isChangeTypeCorrect(String changeType) {
199         return FILE_READY_CHANGE_TYPE.equals(changeType);
200     }
201
202     private static List<FileData> getAllFileDataFromJson(JsonArray arrayOfAdditionalFields,
203         MessageMetaData messageMetaData) {
204         List<FileData> res = new ArrayList<>();
205         for (int i = 0; i < arrayOfAdditionalFields.size(); i++) {
206             JsonObject fileInfo = (JsonObject) arrayOfAdditionalFields.get(i);
207             Optional<FileData> fileData = getFileDataFromJson(fileInfo, messageMetaData);
208
209             if (fileData.isPresent()) {
210                 res.add(fileData.get());
211             }
212         }
213         return res;
214     }
215
216     private static Optional<FileData> getFileDataFromJson(JsonObject fileInfo, MessageMetaData messageMetaData) {
217         logger.trace("starting to getFileDataFromJson!");
218
219         List<String> missingValues = new ArrayList<>();
220         JsonObject data = fileInfo.getAsJsonObject(HASH_MAP);
221
222         String location = getValueFromJson(data, LOCATION, missingValues);
223         if (StringUtils.isEmpty(location)) {
224             logger.error(ERROR_MSG_VES_EVENT_PARSING + "File information wrong. Missing location. Data: {} {}",
225                 messageMetaData, fileInfo);
226             return Optional.empty();
227         }
228         Scheme scheme;
229         try {
230             scheme = Scheme.getSchemeFromString(URI.create(location).getScheme());
231         } catch (Exception e) {
232             logger.error(ERROR_MSG_VES_EVENT_PARSING + "{}. Location: {} Data: {}", e.getMessage(), location,
233                 messageMetaData, e);
234             return Optional.empty();
235         }
236         FileData fileData = ImmutableFileData.builder() //
237             .name(getValueFromJson(fileInfo, NAME, missingValues)) //
238             .fileFormatType(getValueFromJson(data, FILE_FORMAT_TYPE, missingValues)) //
239             .fileFormatVersion(getValueFromJson(data, FILE_FORMAT_VERSION, missingValues)) //
240             .location(location) //
241             .scheme(scheme) //
242             .compression(getValueFromJson(data, COMPRESSION, missingValues)) //
243             .messageMetaData(messageMetaData) //
244             .build();
245         if (missingValues.isEmpty()) {
246             return Optional.of(fileData);
247         }
248         logger.error(ERROR_MSG_VES_EVENT_PARSING + "File information wrong. Missing data: {} Data: {}", missingValues,
249             fileInfo);
250         return Optional.empty();
251     }
252
253     /**
254      * Gets data from the event name. Defined as: {DomainAbbreviation}_{productName}-{vendorName}_{Description},
255      * example: Noti_RnNode-Ericsson_FileReady
256      *
257      * @param dataType The type of data to get, {@link DmaapConsumerJsonParser.EventNameDataType}.
258      * @param eventName The event name to get the data from.
259      * @param missingValues List of missing values. The dataType will be added if missing.
260      * @return String of data from event name
261      */
262     private static String getDataFromEventName(EventNameDataType dataType, String eventName,
263         List<String> missingValues) {
264         String[] eventArray = eventName.split("_|-");
265         if (eventArray.length >= 4) {
266             return eventArray[dataType.index];
267         } else {
268             missingValues.add(dataType.toString());
269             logger.error(
270                 ERROR_MSG_VES_EVENT_PARSING + "Can not get {} from eventName, eventName is not in correct format: {}",
271                 dataType, eventName);
272         }
273         return "";
274     }
275
276     private static String getValueFromJson(JsonObject jsonObject, String jsonKey, List<String> missingValues) {
277         if (jsonObject.has(jsonKey)) {
278             return jsonObject.get(jsonKey).getAsString();
279         } else {
280             missingValues.add(jsonKey);
281             return "";
282         }
283     }
284
285     private static boolean containsNotificationFields(JsonObject jsonObject) {
286         return jsonObject.has(EVENT) && jsonObject.getAsJsonObject(EVENT).has(NOTIFICATION_FIELDS);
287     }
288
289     private static Flux<FileReadyMessage> logErrorAndReturnEmptyMessageFlux(String errorMessage) {
290         logger.error(errorMessage);
291         return Flux.empty();
292     }
293 }