Merge "Data fragment update by xpath #2 - persistence layer"
[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.regex.Matcher;
34 import java.util.regex.Pattern;
35 import java.util.stream.Collectors;
36 import lombok.NoArgsConstructor;
37 import org.onap.cps.spi.exceptions.CpsException;
38 import org.onap.cps.spi.exceptions.ModelValidationException;
39 import org.onap.cps.spi.model.ModuleReference;
40 import org.opendaylight.yangtools.yang.common.Revision;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
44 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
45 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
46 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
50
51 @NoArgsConstructor
52 public final class YangTextSchemaSourceSetBuilder {
53
54     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN =
55         Pattern.compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
56
57     private final ImmutableMap.Builder<String, String> yangModelMap = new ImmutableMap.Builder<>();
58
59     public YangTextSchemaSourceSetBuilder putAll(final Map<String, String> yangResourceNameToContent) {
60         this.yangModelMap.putAll(yangResourceNameToContent);
61         return this;
62     }
63
64     public YangTextSchemaSourceSet build() {
65         final SchemaContext schemaContext = generateSchemaContext(yangModelMap.build());
66         return new YangTextSchemaSourceSetImpl(schemaContext);
67     }
68
69     public static YangTextSchemaSourceSet of(final Map<String, String> yangResourceNameToContent) {
70         return new YangTextSchemaSourceSetBuilder().putAll(yangResourceNameToContent).build();
71     }
72
73     /**
74      * Validates if SchemaContext can be successfully built from given yang resources.
75      *
76      * @param yangResourceNameToContent the yang resources as map where key is name and value is content
77      * @throws ModelValidationException if validation fails
78      */
79     public static void validate(final Map<String, String> yangResourceNameToContent) {
80         generateSchemaContext(yangResourceNameToContent);
81     }
82
83     private static class YangTextSchemaSourceSetImpl implements YangTextSchemaSourceSet {
84
85         private final SchemaContext schemaContext;
86
87         private YangTextSchemaSourceSetImpl(final SchemaContext schemaContext) {
88             this.schemaContext = schemaContext;
89         }
90
91         @Override
92         public List<ModuleReference> getModuleReferences() {
93             return schemaContext.getModules().stream()
94                 .map(YangTextSchemaSourceSetImpl::toModuleReference)
95                 .collect(Collectors.toList());
96         }
97
98         private static ModuleReference toModuleReference(final Module module) {
99             return ModuleReference.builder()
100                 .name(module.getName())
101                 .namespace(module.getNamespace().toString())
102                 .revision(module.getRevision().map(Revision::toString).orElse(null))
103                 .build();
104         }
105
106         @Override
107         public SchemaContext getSchemaContext() {
108             return schemaContext;
109         }
110     }
111
112     /**
113      * Parse and validate a string representing a yang model to generate a SchemaContext context.
114      *
115      * @param yangResourceNameToContent is a {@link Map} collection that contains the name of the model represented
116      *                                  on yangModelContent as key and the yangModelContent as value.
117      * @return the schema context
118      */
119     private static SchemaContext generateSchemaContext(final Map<String, String> yangResourceNameToContent) {
120         final CrossSourceStatementReactor.BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild();
121         for (final YangTextSchemaSource yangTextSchemaSource : forResources(yangResourceNameToContent)) {
122             final String resourceName = yangTextSchemaSource.getIdentifier().getName();
123             try {
124                 reactor.addSource(YangStatementStreamSource.create(yangTextSchemaSource));
125             } catch (final IOException e) {
126                 throw new CpsException("Failed to read yang resource.",
127                     String.format("Exception occurred on reading resource %s.", resourceName), e);
128             } catch (final YangSyntaxErrorException e) {
129                 throw new ModelValidationException("Yang resource is invalid.",
130                     String.format("Yang syntax validation failed for resource %s.", resourceName), e);
131             }
132         }
133         try {
134             return reactor.buildEffective();
135         } catch (final ReactorException e) {
136             final List<String> resourceNames = yangResourceNameToContent.keySet().stream().collect(Collectors.toList());
137             Collections.sort(resourceNames);
138             throw new ModelValidationException("Invalid schema set.",
139                 String.format("Effective schema context build failed for resources %s.", resourceNames.toString()),
140                 e);
141         }
142     }
143
144     private static List<YangTextSchemaSource> forResources(final Map<String, String> yangResourceNameToContent) {
145         return yangResourceNameToContent.entrySet().stream()
146             .map(entry -> toYangTextSchemaSource(entry.getKey(), entry.getValue()))
147             .collect(Collectors.toList());
148     }
149
150     private static YangTextSchemaSource toYangTextSchemaSource(final String sourceName, final String source) {
151         final RevisionSourceIdentifier revisionSourceIdentifier =
152             createIdentifierFromSourceName(checkNotNull(sourceName));
153
154         return new YangTextSchemaSource(revisionSourceIdentifier) {
155             @Override
156             protected MoreObjects.ToStringHelper addToStringAttributes(
157                 final MoreObjects.ToStringHelper toStringHelper) {
158                 return toStringHelper;
159             }
160
161             @Override
162             public InputStream openStream() {
163                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
164             }
165         };
166     }
167
168     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
169         final Matcher matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
170         if (matcher.matches()) {
171             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
172         }
173         return RevisionSourceIdentifier.create(sourceName);
174     }
175 }