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