5495c3ccff513e7644c1a6a92f8935df55bb7127
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / CrossSourceStatementReactor.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.io.ByteSource;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.EnumMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.Set;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
27 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
28 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
29 import org.opendaylight.yangtools.yang.parser.rfc6020.repo.YangStatementStreamSource;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
33 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
34 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
35 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
36 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public final class CrossSourceStatementReactor {
41     private static final Logger LOG = LoggerFactory.getLogger(CrossSourceStatementReactor.class);
42
43     private final Map<ModelProcessingPhase, StatementSupportBundle> supportedTerminology;
44     private final Map<ValidationBundleType, Collection<?>> supportedValidation;
45
46     CrossSourceStatementReactor(final Map<ModelProcessingPhase, StatementSupportBundle> supportedTerminology,
47             final Map<ValidationBundleType, Collection<?>> supportedValidation) {
48         this.supportedTerminology = ImmutableMap.copyOf(supportedTerminology);
49         this.supportedValidation = ImmutableMap.copyOf(supportedValidation);
50     }
51
52     /**
53      * Create a new {@link Builder}.
54      *
55      * @return A new builder.
56      */
57     public static Builder builder() {
58         return new Builder();
59     }
60
61     /**
62      * Start a new reactor build using the default statement parser mode with all features and deviations enabled.
63      *
64      * @return A new {@link BuildAction}.
65      */
66     public BuildAction newBuild() {
67         return newBuild(StatementParserMode.DEFAULT_MODE);
68     }
69
70     /**
71      * Start a new reactor build using the default statement parser mode and enabling only the specified features
72      * and all deviations.
73      *
74      * @param supportedFeatures The set of supported features in the final SchemaContext
75      * @return A new {@link BuildAction}.
76      *
77      * @deprecated Use {@link #newBuild()} and then call setSupportedFeatures() on the created BuildAction instead.
78      */
79     @Deprecated
80     public BuildAction newBuild(final Set<QName> supportedFeatures) {
81         final BuildAction buildAction = newBuild();
82         if (supportedFeatures != null) {
83             buildAction.setSupportedFeatures(supportedFeatures);
84         }
85
86         return buildAction;
87     }
88
89     /**
90      * Start a new reactor build using the default statement parser mode and enabling only the specified features
91      * and all deviations.
92      *
93      * @param supportedFeatures The set of supported features in the final SchemaContext, if present.
94      * @return A new {@link BuildAction}.
95      *
96      * @deprecated Use {@link #newBuild()} and then call setSupportedFeatures() on the created BuildAction instead.
97      */
98     @Deprecated
99     public BuildAction newBuild(final Optional<Set<QName>> supportedFeatures) {
100         final BuildAction buildAction = newBuild();
101         if (supportedFeatures.isPresent()) {
102             buildAction.setSupportedFeatures(supportedFeatures.get());
103         }
104
105         return buildAction;
106     }
107
108     /**
109      * Start a new reactor build using the specified statement parser mode and enabling all features and deviations.
110      *
111      * @param statementParserMode Parser mode to use
112      * @return A new {@link BuildAction}.
113      * @throws NullPointerException if statementParserMode is null
114      */
115     public BuildAction newBuild(final StatementParserMode statementParserMode) {
116         return new BuildAction(statementParserMode);
117     }
118
119     /**
120      * Start a new reactor build using the specified statement parser mode and enabling only the specified features
121      * and all deviations.
122      *
123      * @param statementParserMode Parser mode to use
124      * @param supportedFeatures The set of supported features in the final SchemaContext
125      * @return A new {@link BuildAction}.
126      * @throws NullPointerException if statementParserMode is null
127      *
128      * @deprecated Use {@link #newBuild(StatementParserMode)} and then call setSupportedFeatures()
129      * on the created BuildAction instead.
130      */
131     @Deprecated
132     public BuildAction newBuild(final StatementParserMode statementParserMode,
133             final Set<QName> supportedFeatures) {
134         final BuildAction buildAction = new BuildAction(statementParserMode);
135         if (supportedFeatures != null) {
136             buildAction.setSupportedFeatures(supportedFeatures);
137         }
138
139         return buildAction;
140     }
141
142     /**
143      * Start a new reactor build using the specified statement parser mode and enabling only the specified features
144      * and all deviations.
145      *
146      * @param statementParserMode Parser mode to use
147      * @param supportedFeatures The set of supported features in the final SchemaContext, or absent if all features
148      *                          encountered should be supported.
149      * @return A new {@link BuildAction}.
150      * @throws NullPointerException if statementParserMode is null
151      *
152      * @deprecated Use {@link #newBuild(StatementParserMode)} and then call setSupportedFeatures()
153      * on the created BuildAction instead.
154      */
155     @Deprecated
156     public BuildAction newBuild(final StatementParserMode statementParserMode,
157             final Optional<Set<QName>> supportedFeatures) {
158         final BuildAction buildAction = new BuildAction(statementParserMode);
159         if (supportedFeatures.isPresent()) {
160             buildAction.setSupportedFeatures(supportedFeatures.get());
161         }
162
163         return buildAction;
164     }
165
166     private static <T> T warnOnNull(final T obj) {
167         if (obj == null) {
168             LOG.info("Set of supported features has not been provided, so all features are supported by default.");
169         }
170         return obj;
171     }
172
173     public static class Builder implements org.opendaylight.yangtools.concepts.Builder<CrossSourceStatementReactor> {
174         private final Map<ValidationBundleType, Collection<?>> validationBundles =
175                 new EnumMap<>(ValidationBundleType.class);
176         private final Map<ModelProcessingPhase, StatementSupportBundle> bundles =
177                 new EnumMap<>(ModelProcessingPhase.class);
178
179         public Builder setBundle(final ModelProcessingPhase phase, final StatementSupportBundle bundle) {
180             bundles.put(phase, bundle);
181             return this;
182         }
183
184         public Builder setValidationBundle(final ValidationBundleType type, final Collection<?> validationBundle) {
185             validationBundles.put(type, validationBundle);
186             return this;
187         }
188
189         @Override
190         public CrossSourceStatementReactor build() {
191             return new CrossSourceStatementReactor(bundles, validationBundles);
192         }
193     }
194
195     public class BuildAction {
196         private final BuildGlobalContext context;
197         private boolean supportedFeaturesSet = false;
198         private boolean modulesDeviatedByModulesSet = false;
199
200         BuildAction(@Nonnull final StatementParserMode statementParserMode) {
201             this.context = new BuildGlobalContext(supportedTerminology,supportedValidation,
202                     Preconditions.checkNotNull(statementParserMode));
203         }
204
205         /**
206          * Add main source. All main sources are present in resulting
207          * SchemaContext.
208          *
209          * @param source
210          *            which should be added into main sources
211          */
212         public void addSource(final StatementStreamSource source) {
213             context.addSource(source);
214         }
215
216         /**
217          * Add main sources. All main sources are present in resulting
218          * SchemaContext.
219          *
220          * @param sources
221          *            which should be added into main sources
222          */
223         public void addSources(final StatementStreamSource... sources) {
224             addSources(Arrays.asList(sources));
225         }
226
227         public void addSources(final Collection<? extends StatementStreamSource> sources) {
228             for (final StatementStreamSource source : sources) {
229                 context.addSource(source);
230             }
231         }
232
233         /**
234          * Add library sources. Only library sources required by main sources
235          * are present in resulting SchemaContext. Any other library sources are
236          * ignored and this also applies to error reporting.
237          *
238          * Library sources are not supported in openconfig version mode currently.
239          *
240          * @param libSources
241          *            yang sources which should be added into library sources
242          */
243         public void addLibSources(final StatementStreamSource... libSources) {
244             for (final StatementStreamSource libSource : libSources) {
245                 context.addLibSource(libSource);
246             }
247         }
248
249         /**
250          * Set supported features based on which all if-feature statements in the
251          * parsed YANG modules will be resolved.
252          *
253          * @param supportedFeatures
254          *            Set of supported features in the final SchemaContext.
255          *            If the set is empty, no features encountered will be supported.
256          */
257         public void setSupportedFeatures(@Nonnull final Set<QName> supportedFeatures) {
258             Preconditions.checkState(!supportedFeaturesSet, "Supported features should be set only once.");
259             context.setSupportedFeatures(Preconditions.checkNotNull(supportedFeatures));
260             supportedFeaturesSet = true;
261         }
262
263         /**
264          * Set YANG modules which can be deviated by specified modules during the parsing process.
265          * Map key (QNameModule) denotes a module which can be deviated by the modules in the Map value.
266          *
267          * @param modulesDeviatedByModules
268          *            Map of YANG modules (Map key) which can be deviated by specified modules (Map value) in the final
269          *            SchemaContext. If the map is empty, no deviations encountered will be supported.
270          */
271         public void setModulesWithSupportedDeviations(
272                 @Nonnull final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules) {
273             Preconditions.checkState(!modulesDeviatedByModulesSet,
274                     "Modules with supported deviations should be set only once.");
275             context.setModulesDeviatedByModules(Preconditions.checkNotNull(modulesDeviatedByModules));
276             modulesDeviatedByModulesSet = true;
277         }
278
279         /**
280          * @throws org.opendaylight.yangtools.yang.parser.spi.source.SourceException
281          * @throws ReactorException
282          */
283         public EffectiveModelContext build() throws ReactorException {
284             return context.build();
285         }
286
287         public EffectiveSchemaContext buildEffective() throws ReactorException {
288             return context.buildEffective();
289         }
290
291         /**
292          * @deprecated Use {@link #addSources(Collection)} and {@link #buildEffective()} instead.
293          */
294         @Deprecated
295         public SchemaContext buildEffective(final Collection<ByteSource> yangByteSources) throws ReactorException,
296                 IOException {
297             for (final ByteSource source : yangByteSources) {
298                 if (source instanceof YangTextSchemaSource) {
299                     try {
300                         addSource(YangStatementStreamSource.create((YangTextSchemaSource) source));
301                     } catch (YangSyntaxErrorException e) {
302                         throw new IOException("Source " + source + " failed to parse", e);
303                     }
304                 } else {
305                     addSource(new YangStatementSourceImpl(source.openStream()));
306                 }
307             }
308
309             return buildEffective();
310         }
311
312         /**
313          * @deprecated Use {@link #addSources(Collection)} and {@link #buildEffective()} instead.
314          */
315         @Deprecated
316         public SchemaContext buildEffective(final List<InputStream> yangInputStreams) throws ReactorException {
317             for (final InputStream yangInputStream : yangInputStreams) {
318                 addSource(new YangStatementSourceImpl(yangInputStream));
319             }
320
321             return buildEffective();
322         }
323     }
324 }