2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Pantheon.tech
4 * Modifications Copyright (C) 2022-2023 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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.yang;
24 import static com.google.common.base.Preconditions.checkNotNull;
26 import com.google.common.base.MoreObjects;
27 import com.google.common.collect.ImmutableMap;
28 import io.micrometer.core.annotation.Timed;
29 import java.io.ByteArrayInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.nio.charset.StandardCharsets;
33 import java.util.Collections;
34 import java.util.List;
36 import java.util.Optional;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import lombok.NoArgsConstructor;
40 import org.onap.cps.spi.exceptions.CpsException;
41 import org.onap.cps.spi.exceptions.ModelValidationException;
42 import org.onap.cps.spi.model.ModuleReference;
43 import org.opendaylight.yangtools.yang.common.Revision;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
47 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
48 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
49 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors;
50 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
55 public final class YangTextSchemaSourceSetBuilder {
57 private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN =
58 Pattern.compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
60 private final ImmutableMap.Builder<String, String> yangModelMap = new ImmutableMap.Builder<>();
63 * Add Yang resource context.
65 * @param yangResourceNameToContent the resource content
66 * @return this builder
68 public YangTextSchemaSourceSetBuilder putAll(final Map<String, String> yangResourceNameToContent) {
69 this.yangModelMap.putAll(yangResourceNameToContent);
74 * Build a YangTextSchemaSourceSet.
76 * @return the YangTextSchemaSourceSet
78 public YangTextSchemaSourceSet build() {
79 final var schemaContext = generateSchemaContext(yangModelMap.build());
80 return new YangTextSchemaSourceSetImpl(schemaContext);
84 * Add yangResourceNameToContent and build a YangTextSchemaSourceSet.
86 * @param yangResourceNameToContent the resource content
87 * @return the YangTextSchemaSourceSet
90 @Timed(value = "cps.yang.schemasourceset.build", description = "Time taken to build a ODL yang Model")
91 public static YangTextSchemaSourceSet of(final Map<String, String> yangResourceNameToContent) {
92 return new YangTextSchemaSourceSetBuilder().putAll(yangResourceNameToContent).build();
96 * Validates if SchemaContext can be successfully built from given yang resources.
98 * @param yangResourceNameToContent the yang resources as map where key is name and value is content
99 * @throws ModelValidationException if validation fails
101 public static void validate(final Map<String, String> yangResourceNameToContent) {
102 generateSchemaContext(yangResourceNameToContent);
105 private static class YangTextSchemaSourceSetImpl implements YangTextSchemaSourceSet {
107 private final SchemaContext schemaContext;
109 private YangTextSchemaSourceSetImpl(final SchemaContext schemaContext) {
110 this.schemaContext = schemaContext;
114 public List<ModuleReference> getModuleReferences() {
115 return schemaContext.getModules().stream()
116 .map(YangTextSchemaSourceSetImpl::toModuleReference)
117 .collect(Collectors.toList());
120 private static ModuleReference toModuleReference(final Module module) {
121 return ModuleReference.builder()
122 .moduleName(module.getName())
123 .namespace(module.getQNameModule().getNamespace().toString())
124 .revision(module.getRevision().map(Revision::toString).orElse(null))
129 public SchemaContext getSchemaContext() {
130 return schemaContext;
135 * Parse and validate a string representing a yang model to generate a SchemaContext context.
137 * @param yangResourceNameToContent is a {@link Map} collection that contains the name of the model represented
138 * on yangModelContent as key and the yangModelContent as value.
139 * @return the schema context
141 private static SchemaContext generateSchemaContext(final Map<String, String> yangResourceNameToContent) {
142 final CrossSourceStatementReactor.BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild();
143 for (final YangTextSchemaSource yangTextSchemaSource : forResources(yangResourceNameToContent)) {
144 final String resourceName = yangTextSchemaSource.getIdentifier().getName();
146 reactor.addSource(YangStatementStreamSource.create(yangTextSchemaSource));
147 } catch (final IOException e) {
148 throw new CpsException("Failed to read yang resource.",
149 String.format("Exception occurred on reading resource %s.", resourceName), e);
150 } catch (final YangSyntaxErrorException e) {
151 throw new ModelValidationException("Yang resource is invalid.",
153 "Yang syntax validation failed for resource %s:%n%s", resourceName, e.getMessage()), e);
157 return reactor.buildEffective();
158 } catch (final ReactorException e) {
159 final List<String> resourceNames = yangResourceNameToContent.keySet().stream().collect(Collectors.toList());
160 Collections.sort(resourceNames);
161 throw new ModelValidationException("Invalid schema set.",
162 String.format("Effective schema context build failed for resources %s.", resourceNames.toString()),
167 private static List<YangTextSchemaSource> forResources(final Map<String, String> yangResourceNameToContent) {
168 return yangResourceNameToContent.entrySet().stream()
169 .map(entry -> toYangTextSchemaSource(entry.getKey(), entry.getValue()))
170 .collect(Collectors.toList());
173 private static YangTextSchemaSource toYangTextSchemaSource(final String sourceName, final String source) {
174 final var revisionSourceIdentifier =
175 createIdentifierFromSourceName(checkNotNull(sourceName));
177 return new YangTextSchemaSource(revisionSourceIdentifier) {
179 public Optional<String> getSymbolicName() {
180 return Optional.empty();
184 protected MoreObjects.ToStringHelper addToStringAttributes(
185 final MoreObjects.ToStringHelper toStringHelper) {
186 return toStringHelper;
190 public InputStream openStream() {
191 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
196 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
197 final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
198 if (matcher.matches()) {
199 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
201 return RevisionSourceIdentifier.create(sourceName);