ModuleInfoBackedContext cache
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / ModuleInfoBackedContext.java
index cacebb3b98ac1e369ceed58b5c0a40ab20b717f0..d12dcfe5bfe95b7ad726e378d97732e929e50b25 100644 (file)
@@ -7,23 +7,27 @@
  */
 package org.opendaylight.mdsal.binding.generator.impl;
 
-import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
-import com.google.common.io.ByteSource;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.annotations.Beta;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.util.concurrent.Futures;
-import java.io.IOException;
-import java.io.InputStream;
+import com.google.common.util.concurrent.ListenableFuture;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.lang.ref.WeakReference;
+import java.util.Optional;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
 import org.opendaylight.mdsal.binding.generator.api.ModuleInfoRegistry;
+import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
 import org.opendaylight.yangtools.concepts.ObjectRegistration;
 import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
@@ -35,15 +39,40 @@ import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
+public final class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
         implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
 
+    private static final LoadingCache<ClassLoadingStrategy,
+        LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>> CONTEXT_CACHES = CacheBuilder.newBuilder()
+            .weakKeys().build(new CacheLoader<ClassLoadingStrategy,
+                LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>>() {
+                    @Override
+                    public LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext> load(
+                            final ClassLoadingStrategy strategy) {
+                        return CacheBuilder.newBuilder().weakValues().build(
+                            new CacheLoader<Set<YangModuleInfo>, ModuleInfoBackedContext>() {
+                                @Override
+                                public ModuleInfoBackedContext load(final Set<YangModuleInfo> key) {
+                                    final ModuleInfoBackedContext context = ModuleInfoBackedContext.create(strategy);
+                                    context.addModuleInfos(key);
+                                    return context;
+                                }
+                            });
+                    }
+            });
+
     private final YangTextSchemaContextResolver ctxResolver = YangTextSchemaContextResolver.create("binding-context");
 
     private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
         this.backingLoadingStrategy = loadingStrategy;
     }
 
+    @Beta
+    public static ModuleInfoBackedContext cacheContext(final ClassLoadingStrategy loadingStrategy,
+            final ImmutableSet<YangModuleInfo> infos) {
+        return CONTEXT_CACHES.getUnchecked(loadingStrategy).getUnchecked(infos);
+    }
+
     public static ModuleInfoBackedContext create() {
         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
     }
@@ -54,8 +83,10 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
 
     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
 
-    private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader = new ConcurrentHashMap<>();
-    private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo = new ConcurrentHashMap<>();
+    private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader =
+            new ConcurrentHashMap<>();
+    private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo =
+            new ConcurrentHashMap<>();
 
     private final ClassLoadingStrategy backingLoadingStrategy;
 
@@ -90,6 +121,7 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
         return ctxResolver.getSchemaContext();
     }
 
+    @SuppressWarnings("checkstyle:illegalCatch")
     private boolean resolveModuleInfo(final Class<?> cls) {
         try {
             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
@@ -98,22 +130,22 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
         }
     }
 
+    @SuppressWarnings("checkstyle:illegalCatch")
+    @SuppressFBWarnings("REC_CATCH_EXCEPTION")
     private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
+        final SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
+        final YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
+        if (previous != null) {
+            return false;
+        }
 
-        SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
-        YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
         try {
-            if (previous == null) {
-                String modulePackageName = moduleInfo.getClass().getPackage().getName();
-                packageNameToClassLoader.putIfAbsent(modulePackageName,
-                        new WeakReference<>(moduleClassLoader));
-                ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo));
-                for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
-                    resolveModuleInfo(importedInfo);
-                }
-            } else {
-                return false;
+            String modulePackageName = moduleInfo.getClass().getPackage().getName();
+            packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<>(moduleClassLoader));
+            ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo));
+            for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
+                resolveModuleInfo(importedInfo);
             }
         } catch (Exception e) {
             LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e);
@@ -121,23 +153,14 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
         return true;
     }
 
-    private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier, final YangModuleInfo moduleInfo) {
-        return new YangTextSchemaSource(identifier) {
-
-            @Override
-            public InputStream openStream() throws IOException {
-                return moduleInfo.getModuleSourceStream();
-            }
-
-            @Override
-            protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
-                return toStringHelper;
-            }
-        };
+    private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
+            final YangModuleInfo moduleInfo) {
+        return YangTextSchemaSource.delegateForByteSource(identifier, moduleInfo.getYangTextByteSource());
     }
 
     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
-        return RevisionSourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
+        final QName name = moduleInfo.getName();
+        return RevisionSourceIdentifier.create(name.getLocalName(), name.getRevision());
     }
 
     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
@@ -153,29 +176,27 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
         return registration;
     }
 
-    @Override public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
+    @Override
+    public ListenableFuture<? extends YangTextSchemaSource> getSource(
         final SourceIdentifier sourceIdentifier) {
         final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
 
         if (yangModuleInfo == null) {
-            LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier, sourceIdentifierToModuleInfo.keySet());
-            return Futures
-                .immediateFailedCheckedFuture(new SchemaSourceException("Unknown schema source: " + sourceIdentifier));
+            LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier,
+                sourceIdentifierToModuleInfo.keySet());
+            return Futures.immediateFailedFuture(new SchemaSourceException(
+                "Unknown schema source: " + sourceIdentifier));
         }
 
-        return Futures
-            .immediateCheckedFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier, new ByteSource() {
-                @Override public InputStream openStream() throws IOException {
-                    return yangModuleInfo.getModuleSourceStream();
-                }
-            }));
+        return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
+            yangModuleInfo.getYangTextByteSource()));
     }
 
     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
 
         private final ModuleInfoBackedContext context;
 
-        public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
+        YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
             super(instance);
             this.context = context;
         }