Mass-migrate to Objects.requireNonNull()
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / YangTextSchemaContextResolver.java
index 3a79452e7ad7ce67bd0b79071362c117283b360f..1955136d169564484f44575d8c78fde1f804994f 100644 (file)
@@ -8,32 +8,41 @@
 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.Optional;
-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.CheckedFuture;
-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;
 import java.net.URL;
 import java.util.Collection;
+import java.util.Optional;
 import java.util.Set;
 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.SchemaContext;
 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
 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.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;
 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
@@ -42,8 +51,8 @@ import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
-import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -54,7 +63,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 =
-            new AtomicReference<>(Optional.absent());
+            new AtomicReference<>(Optional.empty());
     private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
     private final SchemaListenerRegistration transReg;
     private final SchemaSourceRegistry registry;
@@ -63,8 +72,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);
@@ -82,16 +91,16 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * Register a {@link YangTextSchemaSource}.
      *
      * @param source YANG text source
+     * @return a YangTextSchemaSourceRegistration
      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
      * @throws IOException when the URL is not readable
      * @throws SchemaSourceException When parsing encounters general error
-     * @return a YangTextSchemaSourceRegistration
      */
-    public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
+    public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
             throws SchemaSourceException, IOException, YangSyntaxErrorException {
         checkArgument(source != null);
 
-        final ASTSchemaSource ast = TextToASTTransformer.TRANSFORMATION.apply(source).checkedGet();
+        final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
         LOG.trace("Resolved source {} to source {}", source, ast);
 
         // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
@@ -101,12 +110,12 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
         final YangTextSchemaSource text;
         if (!parsedId.equals(providedId)) {
             if (!parsedId.getName().equals(providedId.getName())) {
-                LOG.info("Provided module name {} does not match actual text {}, corrected", providedId.toYangFilename(),
-                    parsedId.toYangFilename());
+                LOG.info("Provided module name {} does not match actual text {}, corrected",
+                    providedId.toYangFilename(), parsedId.toYangFilename());
             } else {
-                final String sourceRev = providedId.getRevision();
-                final String astRev = parsedId.getRevision();
-                if (sourceRev != null) {
+                final Optional<Revision> sourceRev = providedId.getRevision();
+                final Optional<Revision> astRev = parsedId.getRevision();
+                if (sourceRev.isPresent()) {
                     if (!sourceRev.equals(astRev)) {
                         LOG.info("Provided module revision {} does not match actual text {}, corrected",
                             providedId.toYangFilename(), parsedId.toYangFilename());
@@ -151,15 +160,18 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
      * Register a URL containing a YANG text.
      *
      * @param url YANG text source URL
+     * @return a YangTextSchemaSourceRegistration for this URL
      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
      * @throws IOException when the URL is not readable
      * @throws SchemaSourceException When parsing encounters general error
-     * @return a YangTextSchemaSourceRegistration for this URL
      */
-    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 SourceIdentifier guessedId = new SourceIdentifier(url.getFile(), Optional.absent());
+        final String path = url.getPath();
+        final String fileName = path.substring(path.lastIndexOf('/') + 1);
+        final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
         return registerSource(new YangTextSchemaSource(guessedId) {
             @Override
             public InputStream openStream() throws IOException {
@@ -173,15 +185,36 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
         });
     }
 
+    private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
+        try {
+            return YangTextSchemaSource.identifierFromFilename(fileName);
+        } catch (final IllegalArgumentException e) {
+            LOG.warn("Invalid file name format in '{}'", fileName, e);
+            return RevisionSourceIdentifier.create(fileName);
+        }
+    }
+
     /**
      * 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.
      */
     public Optional<SchemaContext> getSchemaContext() {
+        return getSchemaContext(StatementParserMode.DEFAULT_MODE);
+    }
+
+    /**
+     * 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.
+     */
+    public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
         final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
         Optional<SchemaContext> sc;
-        Object v;
+        Object ver;
         do {
             // Spin get stable context version
             Object cv;
@@ -196,18 +229,22 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
             // Version has been updated
             Collection<SourceIdentifier> sources;
             do {
-                v = version;
+                ver = version;
                 sources = ImmutableSet.copyOf(requiredSources);
-            } while (v != version);
+            } while (ver != version);
 
             while (true) {
-                final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory.createSchemaContext(sources);
+                final ListenableFuture<SchemaContext> f = factory.createSchemaContext(sources, statementParserMode);
                 try {
-                    sc = Optional.of(f.checkedGet());
+                    sc = Optional.of(f.get());
                     break;
-                } catch (SchemaResolutionException 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);
-                    sources = e.getResolvedSources();
+                    final Throwable cause = e.getCause();
+                    Verify.verify(cause instanceof SchemaResolutionException);
+                    sources = ((SchemaResolutionException) cause).getResolvedSources();
                 }
             }
 
@@ -216,25 +253,26 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
             synchronized (this) {
                 if (contextVersion == cv) {
                     currentSchemaContext.set(sc);
-                    contextVersion = v;
+                    contextVersion = ver;
                 }
             }
-        } while (version == v);
+        } while (version == ver);
 
         return sc;
     }
 
     @Override
-    public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
+    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.immediateFailedCheckedFuture(
-                    new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
+            return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
+                + " not registered", sourceIdentifier));
         }
 
-        return Futures.immediateCheckedFuture(ret.iterator().next());
+        return immediateFluentFuture(ret.iterator().next());
     }
 
     /**
@@ -246,6 +284,38 @@ public final class YangTextSchemaContextResolver implements AutoCloseable, Schem
         return ImmutableSet.copyOf(texts.keySet());
     }
 
+    @Beta
+    public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
+        return ImmutableSet.copyOf(texts.get(sourceIdentifier));
+    }
+
+    @Beta
+    public SchemaContext trySchemaContext() throws SchemaResolutionException {
+        return trySchemaContext(StatementParserMode.DEFAULT_MODE);
+    }
+
+    @Beta
+    @SuppressWarnings("checkstyle:avoidHidingCauseException")
+    public SchemaContext trySchemaContext(final StatementParserMode statementParserMode)
+            throws SchemaResolutionException {
+        final ListenableFuture<SchemaContext> future = repository
+                .createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT)
+                .createSchemaContext(ImmutableSet.copyOf(requiredSources), statementParserMode);
+
+        try {
+            return future.get();
+        } 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;
+            }
+
+            throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
+        }
+    }
+
     @Override
     public void close() {
         transReg.close();