c71d143501c6733c9f452fab0208d9d91f811826
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.service;
18
19 import com.google.gson.JsonArray;
20 import com.google.gson.JsonElement;
21 import com.google.gson.JsonObject;
22 import com.google.gson.JsonParser;
23
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.stream.StreamSupport;
28
29 import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapEmptyResponseException;
30 import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapNotFoundException;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.util.StringUtils;
34
35 import reactor.core.publisher.Mono;
36
37 /**
38  * Parses the fileReady event and creates an array of FileData containing the information.
39  *
40  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/8/18
41  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
42  */
43 public class DmaapConsumerJsonParser {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(DmaapConsumerJsonParser.class);
46
47     private static final String EVENT = "event";
48     private static final String NOTIFICATION_FIELDS = "notificationFields";
49     private static final String CHANGE_IDENTIFIER = "changeIdentifier";
50     private static final String CHANGE_TYPE = "changeType";
51     private static final String NOTIFICATION_FIELDS_VERSION = "notificationFieldsVersion";
52
53     private static final String ARRAY_OF_NAMED_HASH_MAP = "arrayOfNamedHashMap";
54     private static final String NAME = "name";
55     private static final String HASH_MAP = "hashMap";
56     private static final String LOCATION = "location";
57     private static final String COMPRESSION = "compression";
58     private static final String FILE_FORMAT_TYPE = "fileFormatType";
59     private static final String FILE_FORMAT_VERSION = "fileFormatVersion";
60
61     /**
62      * Extract info from string and create @see
63      * {@link org.onap.dcaegen2.collectors.datafile.service.FileData}.
64      *
65      * @param monoMessage - results from DMaaP
66      * @return reactive Mono with an array of FileData
67      */
68     public Mono<List<FileData>> getJsonObject(Mono<String> monoMessage) {
69         return monoMessage.flatMap(this::getJsonParserMessage).flatMap(this::createJsonConsumerModel);
70     }
71
72     private Mono<JsonElement> getJsonParserMessage(String message) {
73         return StringUtils.isEmpty(message) ? Mono.error(new DmaapEmptyResponseException())
74                 : Mono.fromSupplier(() -> new JsonParser().parse(message));
75     }
76
77     private Mono<List<FileData>> createJsonConsumerModel(JsonElement jsonElement) {
78         return jsonElement.isJsonObject() ? create(Mono.fromSupplier(jsonElement::getAsJsonObject))
79                 : getFileDataFromJsonArray(jsonElement);
80     }
81
82     private Mono<List<FileData>> getFileDataFromJsonArray(JsonElement jsonElement) {
83         return create(Mono.fromCallable(() -> StreamSupport.stream(jsonElement.getAsJsonArray().spliterator(), false)
84                 .findFirst().flatMap(this::getJsonObjectFromAnArray).orElseThrow(DmaapEmptyResponseException::new)));
85     }
86
87     public Optional<JsonObject> getJsonObjectFromAnArray(JsonElement element) {
88         return Optional.of(new JsonParser().parse(element.getAsString()).getAsJsonObject());
89     }
90
91     private Mono<List<FileData>> create(Mono<JsonObject> jsonObject) {
92         return jsonObject.flatMap(monoJsonP -> !containsHeader(monoJsonP)
93                 ? Mono.error(new DmaapNotFoundException("Incorrect JsonObject - missing header"))
94                 : transform(monoJsonP));
95     }
96
97     private Mono<List<FileData>> transform(JsonObject jsonObject) {
98         if (containsHeader(jsonObject, EVENT, NOTIFICATION_FIELDS)) {
99             JsonObject notificationFields = jsonObject.getAsJsonObject(EVENT).getAsJsonObject(NOTIFICATION_FIELDS);
100             String changeIdentifier = getValueFromJson(notificationFields, CHANGE_IDENTIFIER);
101             String changeType = getValueFromJson(notificationFields, CHANGE_TYPE);
102             String notificationFieldsVersion = getValueFromJson(notificationFields, NOTIFICATION_FIELDS_VERSION);
103             JsonArray arrayOfNamedHashMap = notificationFields.getAsJsonArray(ARRAY_OF_NAMED_HASH_MAP);
104
105             if (isNotificationFieldsHeaderNotEmpty(changeIdentifier, changeType, notificationFieldsVersion)
106                     && arrayOfNamedHashMap != null) {
107                 Mono<List<FileData>> res = getAllFileDataFromJson(changeIdentifier, changeType, arrayOfNamedHashMap);
108                 return res;
109             }
110
111             if (!isNotificationFieldsHeaderNotEmpty(changeIdentifier, changeType, notificationFieldsVersion)) {
112                 return Mono.error(
113                         new DmaapNotFoundException("FileReady event header is missing information. " + jsonObject));
114             } else if (arrayOfNamedHashMap != null) {
115                 return Mono.error(
116                         new DmaapNotFoundException("FileReady event arrayOfNamedHashMap is missing. " + jsonObject));
117             }
118             return Mono.error(
119                     new DmaapNotFoundException("FileReady event does not contain correct information. " + jsonObject));
120         }
121         return Mono.error(
122                 new DmaapNotFoundException("FileReady event has incorrect JsonObject - missing header. " + jsonObject));
123
124     }
125
126     private Mono<List<FileData>> getAllFileDataFromJson(String changeIdentifier, String changeType,
127             JsonArray arrayOfAdditionalFields) {
128         List<FileData> res = new ArrayList<>();
129         for (int i = 0; i < arrayOfAdditionalFields.size(); i++) {
130             if (arrayOfAdditionalFields.get(i) != null) {
131                 JsonObject fileInfo = (JsonObject) arrayOfAdditionalFields.get(i);
132                 FileData fileData = getFileDataFromJson(fileInfo, changeIdentifier, changeType);
133
134                 if (fileData != null) {
135                     res.add(fileData);
136                 } else {
137                     LOGGER.error("Unable to collect file from xNF. File information wrong. " + fileInfo);
138                 }
139             }
140         }
141         return Mono.just(res);
142     }
143
144     private FileData getFileDataFromJson(JsonObject fileInfo, String changeIdentifier, String changeType) {
145         FileData fileData = null;
146
147         String name = getValueFromJson(fileInfo, NAME);
148         JsonObject data = fileInfo.getAsJsonObject(HASH_MAP);
149         String fileFormatType = getValueFromJson(data, FILE_FORMAT_TYPE);
150         String fileFormatVersion = getValueFromJson(data, FILE_FORMAT_VERSION);
151         String location = getValueFromJson(data, LOCATION);
152         String compression = getValueFromJson(data, COMPRESSION);
153
154         if (isFileFormatFieldsNotEmpty(fileFormatVersion, fileFormatType)
155                 && isNameAndLocationAndCompressionNotEmpty(name, location, compression)) {
156             fileData = ImmutableFileData.builder().changeIdentifier(changeIdentifier).changeType(changeType)
157                     .location(location).compression(compression).fileFormatType(fileFormatType)
158                     .fileFormatVersion(fileFormatVersion).build();
159         }
160         return fileData;
161     }
162
163     private String getValueFromJson(JsonObject jsonObject, String jsonKey) {
164         return jsonObject.has(jsonKey) ? jsonObject.get(jsonKey).getAsString() : "";
165     }
166
167     private boolean isNotificationFieldsHeaderNotEmpty(String changeIdentifier, String changeType,
168             String notificationFieldsVersion) {
169         return ((changeIdentifier != null && !changeIdentifier.isEmpty())
170                 && (changeType != null && !changeType.isEmpty())
171                 && (notificationFieldsVersion != null && !notificationFieldsVersion.isEmpty()));
172     }
173
174     private boolean isFileFormatFieldsNotEmpty(String fileFormatVersion, String fileFormatType) {
175         return ((fileFormatVersion != null && !fileFormatVersion.isEmpty())
176                 && (fileFormatType != null && !fileFormatType.isEmpty()));
177     }
178
179     private boolean isNameAndLocationAndCompressionNotEmpty(String name, String location, String compression) {
180         return (name != null && !name.isEmpty()) && (location != null && !location.isEmpty())
181                 && (compression != null && !compression.isEmpty());
182     }
183
184     private boolean containsHeader(JsonObject jsonObject) {
185         return jsonObject.has(EVENT) && jsonObject.getAsJsonObject(EVENT).has(NOTIFICATION_FIELDS);
186     }
187
188     private boolean containsHeader(JsonObject jsonObject, String topHeader, String header) {
189         return jsonObject.has(topHeader) && jsonObject.getAsJsonObject(topHeader).has(header);
190     }
191 }