Fix Java Code Conventions non-compliance issues
[sdc.git] / common / onap-generic-artifact-browser / onap-generic-artifact-browser-service / src / main / java / org / onap / sdc / gab / yaml / YamlParser.java
1 /*
2  * ============LICENSE_START=======================================================
3  * GAB
4  * ================================================================================
5  * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved.
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.sdc.gab.yaml;
22
23 import com.google.gson.Gson;
24 import com.google.gson.JsonElement;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.AbstractMap.SimpleEntry;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Objects;
33 import java.util.Set;
34 import java.util.function.Function;
35 import java.util.function.Predicate;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import java.util.stream.Collectors;
39 import java.util.stream.Stream;
40 import java.util.stream.StreamSupport;
41 import org.antlr.v4.runtime.misc.ParseCancellationException;
42 import org.apache.commons.io.IOUtils;
43 import org.jsfr.json.JsonSurfer;
44 import org.jsfr.json.JsonSurferGson;
45 import org.yaml.snakeyaml.Yaml;
46
47 /**
48  * Yaml parser and searcher which requires 3 steps:
49  *
50  * <br>1. Load content of Yaml file using {@link #parseContent(String)} or {@link #parseFile(String)}
51  * <br>2. Provide keywords to search using {@link #filter(String)} or {@link #filter(Set)}
52  * <br>3. Collect the results using {@link #collect()}
53  */
54 public class YamlParser implements AutoCloseable {
55
56     private static final Logger LOGGER = Logger.getLogger(YamlParser.class.getName());
57
58     private Stream<Object> parsedYamlContent;
59     private InputStream inputStream;
60     private Set<String> filters;
61     private Function<Object, List<SimpleEntry<String, ? extends Collection<Object>>>> containsKeys = parsedYamlSingleDocument -> {
62         JsonElement jsonElement = new Gson().toJsonTree(parsedYamlSingleDocument);
63         return findInJson(filters, jsonElement);
64     };
65
66     public YamlParser() {
67         this.parsedYamlContent = Stream.empty();
68         filters = new HashSet<>();
69     }
70
71     /**
72      * Provides yaml path for processing.
73      *
74      * @param path Yaml file path.
75      * @return Same parser with loaded source.
76      */
77     YamlParser parseFile(String path) {
78         filters = new HashSet<>();
79         InputStream newInputStream = this.getClass().getClassLoader().getResourceAsStream(path);
80         parse(path, newInputStream);
81         return this;
82     }
83
84     /**
85      * Provides yaml content for processing.
86      *
87      * @param content Yaml file content.
88      * @return Same parser with loaded source.
89      */
90     YamlParser parseContent(String content) {
91         filters = new HashSet<>();
92         InputStream newInputStream = IOUtils.toInputStream(content);
93         parse(content, newInputStream);
94         return this;
95     }
96
97     /**
98      * Adds set of filters for processing.
99      *
100      * @param filters correct json paths for searching resources.
101      * @return Same parser with loaded filters.
102      */
103     YamlParser filter(Set<String> filters) {
104         this.filters.addAll(filters);
105         return this;
106     }
107
108     /**
109      * Adds single filter for processing.
110      *
111      * @param filter correct json path for searching resource.
112      * @return Same parser with loaded filter.
113      */
114     YamlParser filter(String filter) {
115         filters.add(filter);
116         return this;
117     }
118
119     /**
120      * Collects the results from parsed yaml file and applied filters.
121      *
122      * @exception IOException Means that yaml file has invalid content.
123      * @return List of List of simple entry 'key: collection of data'
124      */
125     List<List<SimpleEntry<String, ? extends Collection<Object>>>> collect() throws IOException {
126         try {
127             return parsedYamlContent.map(containsKeys).filter(notEmptyListPredicate()).collect(Collectors.toList());
128         } catch (Exception e) {
129             LOGGER.log(Level.WARNING, "Unexpected document content. Please check body of the yaml file.", e);
130             throw new IOException("Unexpected document content");
131         }
132     }
133
134     private void parse(String yaml, InputStream newInputStream) {
135         try {
136             closeStream(inputStream);
137             inputStream = newInputStream;
138             if (Objects.isNull(inputStream) || inputStream.available() <= 0) {
139                 throw new IOException("Empty input stream of yaml content.");
140             }
141             parsedYamlContent = StreamSupport.stream(new Yaml().loadAll(inputStream).spliterator(), false);
142         } catch (IOException e) {
143             LOGGER.log(Level.WARNING, "Cannot parse yaml: " + yaml, e);
144             parsedYamlContent = Stream.empty();
145         }
146     }
147
148     private List<SimpleEntry<String, ? extends Collection<Object>>> findInJson(Set<String> keys,
149         JsonElement document) {
150         return keys.stream()
151             .map(getEntryForKeyFunction(document))
152             .filter(notEmptyEntryPredicate())
153             .collect(Collectors.toList());
154     }
155
156     private Predicate<? super List<SimpleEntry<String, ? extends Collection<Object>>>> notEmptyListPredicate() {
157         return list -> !list.isEmpty();
158     }
159
160     private Predicate<SimpleEntry<String, ? extends Collection<Object>>> notEmptyEntryPredicate() {
161         return entry -> !entry.getValue().isEmpty();
162     }
163
164     private Function<String, SimpleEntry<String, ? extends Collection<Object>>> getEntryForKeyFunction(
165         JsonElement document) {
166         return key -> {
167             JsonSurfer surfer = JsonSurferGson.INSTANCE;
168             try {
169                 return new SimpleEntry<>(key, surfer.collectAll(document.toString(), "$." + key));
170             } catch (ParseCancellationException e) {
171                 LOGGER.log(Level.WARNING, "Invalid filter key: " + key, e);
172                 return new SimpleEntry<>(key, Collections.emptyList());
173             }
174         };
175     }
176
177     private void closeStream(InputStream stream) throws IOException {
178         if (!Objects.isNull(stream) && !(stream.available() > 0)) {
179             stream.close();
180         }
181     }
182
183     @Override
184     public void close() throws IOException {
185         closeStream(inputStream);
186     }
187 }