2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.sdc.gab.yaml;
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;
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;
48 * Yaml parser and searcher which requires 3 steps:
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()}
54 public class YamlParser implements AutoCloseable {
56 private static final Logger LOGGER = Logger.getLogger(YamlParser.class.getName());
58 private Stream<Object> parsedYamlContent;
59 private InputStream inputStream;
60 private Set<String> filters;
63 this.parsedYamlContent = Stream.empty();
64 filters = new HashSet<>();
68 * Provides yaml path for processing.
70 * @param path Yaml file path.
71 * @return Same parser with loaded source.
73 YamlParser parseFile(String path) {
74 filters = new HashSet<>();
75 InputStream newInputStream = this.getClass().getClassLoader().getResourceAsStream(path);
76 parse(path, newInputStream);
81 * Provides yaml content for processing.
83 * @param content Yaml file content.
84 * @return Same parser with loaded source.
86 YamlParser parseContent(String content) {
87 filters = new HashSet<>();
88 InputStream newInputStream = IOUtils.toInputStream(content);
89 parse(content, newInputStream);
94 * Adds set of filters for processing.
96 * @param filters correct json paths for searching resources.
97 * @return Same parser with loaded filters.
99 YamlParser filter(Set<String> filters) {
100 this.filters.addAll(filters);
105 * Adds single filter for processing.
107 * @param filter correct json path for searching resource.
108 * @return Same parser with loaded filter.
110 YamlParser filter(String filter) {
116 * Collects the results from parsed yaml file and applied filters.
118 * @exception IOException Means that yaml file has invalid content.
119 * @return List of List of simple entry 'key: collection of data'
121 List<List<SimpleEntry<String, ? extends Collection<Object>>>> collect() throws IOException {
123 return parsedYamlContent.map(containsKeys).filter(notEmptyListPredicate()).collect(Collectors.toList());
124 } catch (Exception e) {
125 LOGGER.log(Level.WARNING, "Unexpected document content. Please check body of the yaml file.", e);
126 throw new IOException("Unexpected document content");
130 private void parse(String yaml, InputStream newInputStream) {
132 closeStream(inputStream);
133 inputStream = newInputStream;
134 if (Objects.isNull(inputStream) || inputStream.available() <= 0) {
135 throw new IOException("Empty input stream of yaml content.");
137 parsedYamlContent = StreamSupport.stream(new Yaml().loadAll(inputStream).spliterator(), false);
138 } catch (IOException e) {
139 LOGGER.log(Level.WARNING, "Cannot parse yaml: " + yaml, e);
140 parsedYamlContent = Stream.empty();
144 private Function<Object, List<SimpleEntry<String, ? extends Collection<Object>>>> containsKeys = parsedYamlSingleDocument -> {
145 JsonElement jsonElement = new Gson().toJsonTree(parsedYamlSingleDocument);
146 return findInJson(filters, jsonElement);
149 private List<SimpleEntry<String, ? extends Collection<Object>>> findInJson(Set<String> keys,
150 JsonElement document) {
152 .map(getEntryForKeyFunction(document))
153 .filter(notEmptyEntryPredicate())
154 .collect(Collectors.toList());
157 private Predicate<? super List<SimpleEntry<String, ? extends Collection<Object>>>> notEmptyListPredicate() {
158 return list -> !list.isEmpty();
161 private Predicate<SimpleEntry<String, ? extends Collection<Object>>> notEmptyEntryPredicate() {
162 return entry -> !entry.getValue().isEmpty();
165 private Function<String, SimpleEntry<String, ? extends Collection<Object>>> getEntryForKeyFunction(
166 JsonElement document) {
168 JsonSurfer surfer = JsonSurferGson.INSTANCE;
170 return new SimpleEntry<>(key, surfer.collectAll(document.toString(), "$." + key));
171 } catch (ParseCancellationException e) {
172 LOGGER.log(Level.WARNING, "Invalid filter key: " + key, e);
173 return new SimpleEntry<>(key, Collections.emptyList());
178 private void closeStream(InputStream stream) throws IOException {
179 if (!Objects.isNull(stream) && !(stream.available() > 0)) {
185 public void close() throws IOException {
186 closeStream(inputStream);