Enable spotbugs and fix spotbugs warns
[cps.git] / cps-service / src / main / java / org / onap / cps / yang / YangTextSchemaSourceSetBuilder.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Pantheon.tech
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  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.yang;
21
22 import static com.google.common.base.Preconditions.checkNotNull;
23
24 import com.google.common.base.MoreObjects;
25 import com.google.common.collect.ImmutableMap;
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.nio.charset.StandardCharsets;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.stream.Collectors;
34 import lombok.NoArgsConstructor;
35 import org.onap.cps.spi.exceptions.CpsException;
36 import org.onap.cps.spi.exceptions.ModelValidationException;
37 import org.onap.cps.spi.model.ModuleReference;
38 import org.opendaylight.yangtools.yang.common.Revision;
39 import org.opendaylight.yangtools.yang.common.YangNames;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
43 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
44 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
45 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors;
46 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
48 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
49
50 @NoArgsConstructor
51 public final class YangTextSchemaSourceSetBuilder {
52
53     private final ImmutableMap.Builder<String, String> yangModelMap = new ImmutableMap.Builder<>();
54
55     public YangTextSchemaSourceSetBuilder putAll(final Map<String, String> yangResourceNameToContent) {
56         this.yangModelMap.putAll(yangResourceNameToContent);
57         return this;
58     }
59
60     public YangTextSchemaSourceSet build() {
61         final SchemaContext schemaContext = generateSchemaContext(yangModelMap.build());
62         return new YangTextSchemaSourceSetImpl(schemaContext);
63     }
64
65     public static YangTextSchemaSourceSet of(final Map<String, String> yangResourceNameToContent) {
66         return new YangTextSchemaSourceSetBuilder().putAll(yangResourceNameToContent).build();
67     }
68
69     /**
70      * Validates if SchemaContext can be successfully built from given yang resources.
71      *
72      * @param yangResourceNameToContent the yang resources as map where key is name and value is content
73      * @throws ModelValidationException if validation fails
74      */
75     public static void validate(final Map<String, String> yangResourceNameToContent) {
76         generateSchemaContext(yangResourceNameToContent);
77     }
78
79     private static class YangTextSchemaSourceSetImpl implements YangTextSchemaSourceSet {
80
81         private final SchemaContext schemaContext;
82
83         private YangTextSchemaSourceSetImpl(final SchemaContext schemaContext) {
84             this.schemaContext = schemaContext;
85         }
86
87         @Override
88         public List<ModuleReference> getModuleReferences() {
89             return schemaContext.getModules().stream()
90                 .map(YangTextSchemaSourceSetImpl::toModuleReference)
91                 .collect(Collectors.toList());
92         }
93
94         private static ModuleReference toModuleReference(final Module module) {
95             return ModuleReference.builder()
96                 .name(module.getName())
97                 .namespace(module.getNamespace().toString())
98                 .revision(module.getRevision().map(Revision::toString).orElse(null))
99                 .build();
100         }
101
102         @Override
103         public SchemaContext getSchemaContext() {
104             return schemaContext;
105         }
106     }
107
108     /**
109      * Parse and validate a string representing a yang model to generate a SchemaContext context.
110      *
111      * @param yangResourceNameToContent is a {@link Map} collection that contains the name of the model represented
112      *                                  on yangModelContent as key and the yangModelContent as value.
113      * @return the schema context
114      */
115     private static SchemaContext generateSchemaContext(final Map<String, String> yangResourceNameToContent) {
116         final CrossSourceStatementReactor.BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild();
117         for (final YangTextSchemaSource yangTextSchemaSource : forResources(yangResourceNameToContent)) {
118             final String resourceName = yangTextSchemaSource.getIdentifier().getName();
119             try {
120                 reactor.addSource(YangStatementStreamSource.create(yangTextSchemaSource));
121             } catch (final IOException e) {
122                 throw new CpsException("Failed to read yang resource.",
123                     String.format("Exception occurred on reading resource %s.", resourceName), e);
124             } catch (final YangSyntaxErrorException e) {
125                 throw new ModelValidationException("Yang resource is invalid.",
126                     String.format("Yang syntax validation failed for resource %s.", resourceName), e);
127             }
128         }
129         try {
130             return reactor.buildEffective();
131         } catch (final ReactorException e) {
132             final List<String> resourceNames = yangResourceNameToContent.keySet().stream().collect(Collectors.toList());
133             Collections.sort(resourceNames);
134             throw new ModelValidationException("Invalid schema set.",
135                 String.format("Effective schema context build failed for resources %s.", resourceNames.toString()),
136                 e);
137         }
138     }
139
140     private static List<YangTextSchemaSource> forResources(final Map<String, String> yangResourceNameToContent) {
141         return yangResourceNameToContent.entrySet().stream()
142             .map(entry -> toYangTextSchemaSource(entry.getKey(), entry.getValue()))
143             .collect(Collectors.toList());
144     }
145
146     private static YangTextSchemaSource toYangTextSchemaSource(final String sourceName,
147             final String source) {
148         final Map.Entry<String, String> sourceNameParsed = checkNotNull(YangNames.parseFilename(sourceName));
149         final RevisionSourceIdentifier revisionSourceIdentifier = RevisionSourceIdentifier
150             .create(sourceNameParsed.getKey(), Revision.ofNullable(sourceNameParsed.getValue()));
151
152         return new YangTextSchemaSource(revisionSourceIdentifier) {
153             @Override
154             protected MoreObjects.ToStringHelper addToStringAttributes(
155                 final MoreObjects.ToStringHelper toStringHelper) {
156                 return toStringHelper;
157             }
158
159             @Override
160             public InputStream openStream() {
161                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
162             }
163         };
164     }
165 }