List all modules references in a given dataspace and schemas set name
[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 com.google.common.base.MoreObjects;
23 import com.google.common.collect.ImmutableMap;
24 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.stream.Collectors;
30 import org.onap.cps.spi.exceptions.CpsException;
31 import org.onap.cps.spi.model.ModuleReference;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.common.YangNames;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
37 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
38 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
39 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors;
40 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
42 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
43
44 public final class YangTextSchemaSourceSetBuilder {
45
46     private final ImmutableMap.Builder<String, String> yangModelMap = new ImmutableMap.Builder<>();
47
48     public YangTextSchemaSourceSetBuilder() {
49     }
50
51     public YangTextSchemaSourceSetBuilder put(final String fileName, final String content) {
52         this.yangModelMap.put(fileName, content);
53         return this;
54     }
55
56     public YangTextSchemaSourceSetBuilder putAll(final Map<String, String> yangResourceNameToContent) {
57         this.yangModelMap.putAll(yangResourceNameToContent);
58         return this;
59     }
60
61     public YangTextSchemaSourceSet build() throws ReactorException, YangSyntaxErrorException {
62         final SchemaContext schemaContext = generateSchemaContext(yangModelMap.build());
63         return new YangTextSchemaSourceSetImpl(schemaContext);
64     }
65
66     public static YangTextSchemaSourceSet of(final Map<String, String> yangResourceNameToContent)
67             throws ReactorException, YangSyntaxErrorException {
68         return new YangTextSchemaSourceSetBuilder().putAll(yangResourceNameToContent).build();
69     }
70
71     private static class YangTextSchemaSourceSetImpl implements YangTextSchemaSourceSet {
72
73         private final SchemaContext schemaContext;
74
75         public YangTextSchemaSourceSetImpl(final SchemaContext schemaContext) {
76             this.schemaContext = schemaContext;
77         }
78
79         @Override
80         public List<ModuleReference> getModuleReferences() {
81             return schemaContext.getModules().stream()
82                            .map(YangTextSchemaSourceSetImpl::toModuleReference)
83                            .collect(Collectors.toList());
84         }
85
86         private static ModuleReference toModuleReference(final Module module) {
87             return ModuleReference.builder()
88                            .namespace(module.getName())
89                            .revision(module.getRevision().map(Revision::toString).orElse(null))
90                            .build();
91         }
92
93         @Override
94         public SchemaContext getSchemaContext() {
95             return schemaContext;
96         }
97     }
98
99     /**
100      * Parse and validate a string representing a yang model to generate a SchemaContext context.
101      *
102      * @param yangResourceNameToContent is a {@link Map} collection that contains the name of the model represented
103      *                     on yangModelContent as key and the yangModelContent as value.
104      * @return the schema context
105      */
106     private SchemaContext generateSchemaContext(final Map<String, String> yangResourceNameToContent)
107             throws ReactorException, YangSyntaxErrorException {
108         final CrossSourceStatementReactor.BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild();
109         final List<YangTextSchemaSource> yangTextSchemaSources = forResources(yangResourceNameToContent);
110         for (final YangTextSchemaSource yangTextSchemaSource : yangTextSchemaSources) {
111             try {
112                 reactor.addSource(YangStatementStreamSource.create(yangTextSchemaSource));
113             } catch (final IOException e) {
114                 throw new CpsException("Failed to read yangTextSchemaSource %s.",
115                         yangTextSchemaSource.getIdentifier().getName(), e);
116             }
117         }
118         return reactor.buildEffective();
119     }
120
121     private List<YangTextSchemaSource> forResources(final Map<String, String> yangResourceNameToContent) {
122         return yangResourceNameToContent.entrySet().stream()
123                        .map(entry -> toYangTextSchemaSource(entry.getKey(), entry.getValue()))
124                        .collect(Collectors.toList());
125     }
126
127     private YangTextSchemaSource toYangTextSchemaSource(final String sourceName, final String source) {
128         final Map.Entry<String, String> sourceNameParsed = YangNames.parseFilename(sourceName);
129         final RevisionSourceIdentifier revisionSourceIdentifier = RevisionSourceIdentifier
130             .create(sourceNameParsed.getKey(), Revision.ofNullable(sourceNameParsed.getValue()));
131         return new YangTextSchemaSource(revisionSourceIdentifier) {
132             @Override
133             protected MoreObjects.ToStringHelper addToStringAttributes(
134                     final MoreObjects.ToStringHelper toStringHelper) {
135                 return toStringHelper;
136             }
137
138             @Override
139             public InputStream openStream() {
140                 return new ByteArrayInputStream(source.getBytes());
141             }
142         };
143     }
144 }