Add an explicit intermediate YANG representation
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / YangTextSchemaContextResolver.java
index 8a6968ad152fdf7a90a0a1751faaad9e9250bb2e..bb6b4b5c54b85b60bd96129d9a326417d8f97bb9 100644 (file)
@@ -8,15 +8,17 @@
 package org.opendaylight.yangtools.yang.parser.repo;
 
 import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
+import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
 
 import com.google.common.annotations.Beta;
 import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Preconditions;
 import com.google.common.base.Verify;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Multimap;
-import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.ListenableFuture;
 import java.io.IOException;
 import java.io.InputStream;
@@ -28,17 +30,19 @@ import java.util.concurrent.ConcurrentLinkedDeque;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
-import javax.annotation.Nonnull;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
@@ -60,7 +64,7 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
 
     private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
     private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
-    private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
+    private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
             new AtomicReference<>(Optional.empty());
     private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
     private final SchemaListenerRegistration transReg;
@@ -70,8 +74,8 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
     private volatile Object contextVersion = version;
 
     private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
-        this.repository = Preconditions.checkNotNull(repository);
-        this.registry = Preconditions.checkNotNull(registry);
+        this.repository = requireNonNull(repository);
+        this.registry = requireNonNull(registry);
 
         final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
         transReg = registry.registerSchemaSourceListener(t);
@@ -80,11 +84,16 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
             TimeUnit.SECONDS);
     }
 
-    public static YangTextSchemaContextResolver create(final String name) {
+    public static @NonNull YangTextSchemaContextResolver create(final String name) {
         final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
     }
 
+    public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
+        final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
+        return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
+    }
+
     /**
      * Register a {@link YangTextSchemaSource}.
      *
@@ -94,7 +103,7 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * @throws IOException when the URL is not readable
      * @throws SchemaSourceException When parsing encounters general error
      */
-    public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
+    public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
             throws SchemaSourceException, IOException, YangSyntaxErrorException {
         checkArgument(source != null);
 
@@ -163,8 +172,8 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * @throws IOException when the URL is not readable
      * @throws SchemaSourceException When parsing encounters general error
      */
-    public YangTextSchemaSourceRegistration registerSource(@Nonnull final URL url) throws SchemaSourceException,
-            IOException, YangSyntaxErrorException {
+    public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
+            throws SchemaSourceException, IOException, YangSyntaxErrorException {
         checkArgument(url != null, "Supplied URL must not be null");
 
         final String path = url.getPath();
@@ -183,10 +192,10 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
         });
     }
 
-    private static SourceIdentifier guessSourceIdentifier(final String fileName) {
+    private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
         try {
             return YangTextSchemaSource.identifierFromFilename(fileName);
-        } catch (IllegalArgumentException e) {
+        } catch (final IllegalArgumentException e) {
             LOG.warn("Invalid file name format in '{}'", fileName, e);
             return RevisionSourceIdentifier.create(fileName);
         }
@@ -198,8 +207,8 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * @return new schema context iif there is at least 1 yang file registered and
      *         new schema context was successfully built.
      */
-    public Optional<SchemaContext> getSchemaContext() {
-        return getSchemaContext(StatementParserMode.DEFAULT_MODE);
+    public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
+        return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
     }
 
     /**
@@ -209,9 +218,11 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * @return new schema context iif there is at least 1 yang file registered and
      *         new schema context was successfully built.
      */
-    public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
-        final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
-        Optional<SchemaContext> sc;
+    public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
+            final StatementParserMode statementParserMode) {
+        final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
+            config(statementParserMode));
+        Optional<EffectiveModelContext> sc;
         Object ver;
         do {
             // Spin get stable context version
@@ -232,13 +243,13 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
             } while (ver != version);
 
             while (true) {
-                final ListenableFuture<SchemaContext> f = factory.createSchemaContext(sources, statementParserMode);
+                final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
                 try {
                     sc = Optional.of(f.get());
                     break;
-                } catch (InterruptedException e) {
-                    throw new RuntimeException("Interrupted while assembling schema context", e);
-                } catch (ExecutionException e) {
+                } catch (final InterruptedException e) {
+                    throw new IllegalStateException("Interrupted while assembling schema context", e);
+                } catch (final ExecutionException e) {
                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
                     final Throwable cause = e.getCause();
                     Verify.verify(cause instanceof SchemaResolutionException);
@@ -259,18 +270,43 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
         return sc;
     }
 
+    /**
+     * Try to parse all currently available yang files and build new schema context.
+     *
+     * @return new schema context iif there is at least 1 yang file registered and new schema context was successfully
+     *         built.
+     * @deprecated Use {@link #getEffectiveModelContext()} instead.
+     */
+    @Deprecated(forRemoval = true)
+    public Optional<? extends SchemaContext> getSchemaContext() {
+        return getEffectiveModelContext();
+    }
+
+    /**
+     * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
+     *
+     * @param statementParserMode mode of statement parser
+     * @return new schema context iif there is at least 1 yang file registered and
+     *         new schema context was successfully built.
+     * @deprecated Use {@link #getEffectiveModelContext(StatementParserMode)} instead.
+     */
+    @Deprecated(forRemoval = true)
+    public Optional<? extends SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
+        return getEffectiveModelContext(statementParserMode);
+    }
+
     @Override
-    public synchronized ListenableFuture<YangTextSchemaSource> getSource(
+    public synchronized FluentFuture<YangTextSchemaSource> getSource(
             final SourceIdentifier sourceIdentifier) {
         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
 
         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
         if (ret.isEmpty()) {
-            return Futures.immediateFailedFuture(new MissingSchemaSourceException(
-                "URL for " + sourceIdentifier + " not registered", sourceIdentifier));
+            return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
+                + " not registered", sourceIdentifier));
         }
 
-        return Futures.immediateFuture(ret.iterator().next());
+        return immediateFluentFuture(ret.iterator().next());
     }
 
     /**
@@ -288,22 +324,23 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
     }
 
     @Beta
-    public SchemaContext trySchemaContext() throws SchemaResolutionException {
+    public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
         return trySchemaContext(StatementParserMode.DEFAULT_MODE);
     }
 
     @Beta
-    public SchemaContext trySchemaContext(final StatementParserMode statementParserMode)
+    @SuppressWarnings("checkstyle:avoidHidingCauseException")
+    public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
             throws SchemaResolutionException {
-        final ListenableFuture<SchemaContext> future = repository
-                .createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT)
-                .createSchemaContext(ImmutableSet.copyOf(requiredSources), statementParserMode);
+        final ListenableFuture<EffectiveModelContext> future = repository
+                .createEffectiveModelContextFactory(config(statementParserMode))
+                .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
 
         try {
             return future.get();
-        } catch (InterruptedException e) {
-            throw new RuntimeException("Interrupted while waiting for SchemaContext assembly", e);
-        } catch (ExecutionException e) {
+        } catch (final InterruptedException e) {
+            throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
+        } catch (final ExecutionException e) {
             final Throwable cause = e.getCause();
             if (cause instanceof SchemaResolutionException) {
                 throw (SchemaResolutionException) cause;
@@ -317,4 +354,8 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
     public void close() {
         transReg.close();
     }
+
+    private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
+        return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();
+    }
 }