Fix wait for schema in BindingToNormalizedNodeCodec
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / BindingToNormalizedNodeCodec.java
index 5768bd09dee138501ad43a7be4db411d1c1ee19e..5e5905ec47238d8db2403929d4555911775728bd 100644 (file)
@@ -14,6 +14,8 @@ import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
 import com.google.common.collect.ImmutableBiMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterators;
 import java.lang.reflect.Method;
 import java.net.URI;
 import java.util.AbstractMap.SimpleEntry;
@@ -24,21 +26,23 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
 import javax.annotation.Nonnull;
 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
-import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy;
+import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
+import org.opendaylight.mdsal.binding.dom.codec.impl.MissingSchemaException;
+import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
-import org.opendaylight.yangtools.binding.data.codec.impl.MissingSchemaException;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
@@ -68,33 +72,27 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
     private static final long WAIT_DURATION_SEC = 5;
     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
 
-    private final BindingNormalizedNodeCodecRegistry codecRegistry;
-
-    private final GeneratedClassLoadingStrategy classLoadingStrategy;
-    private final FutureSchema futureSchema;
     private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
             .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
-
                 @Override
-                public YangInstanceIdentifier load(@Nonnull final InstanceIdentifier<?> key) throws Exception {
+                public YangInstanceIdentifier load(@Nonnull final InstanceIdentifier<?> key) {
                     return toYangInstanceIdentifierBlocking(key);
                 }
-
             });
+    private final BindingNormalizedNodeCodecRegistry codecRegistry;
+    private final ClassLoadingStrategy classLoadingStrategy;
+    private final FutureSchema futureSchema;
 
-    private volatile BindingRuntimeContext runtimeContext;
-
-    public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
+    public BindingToNormalizedNodeCodec(final ClassLoadingStrategy classLoadingStrategy,
             final BindingNormalizedNodeCodecRegistry codecRegistry) {
-        this(classLoadingStrategy,codecRegistry,false);
-
+        this(classLoadingStrategy, codecRegistry, false);
     }
 
-    public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
-            final BindingNormalizedNodeCodecRegistry codecRegistry,final boolean waitForSchema) {
-        this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy,"classLoadingStrategy");
-        this.codecRegistry = Preconditions.checkNotNull(codecRegistry,"codecRegistry");
-        this.futureSchema = waitForSchema ? new FutureSchema(WAIT_DURATION_SEC, TimeUnit.SECONDS) : null;
+    public BindingToNormalizedNodeCodec(final ClassLoadingStrategy classLoadingStrategy,
+            final BindingNormalizedNodeCodecRegistry codecRegistry, final boolean waitForSchema) {
+        this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy, "classLoadingStrategy");
+        this.codecRegistry = Preconditions.checkNotNull(codecRegistry, "codecRegistry");
+        this.futureSchema = FutureSchema.create(WAIT_DURATION_SEC, TimeUnit.SECONDS, waitForSchema);
     }
 
     YangInstanceIdentifier toYangInstanceIdentifierBlocking(final InstanceIdentifier<? extends DataObject> binding) {
@@ -154,7 +152,7 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
     @SuppressWarnings({"unchecked", "rawtypes"})
     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
-        return toNormalizedNode((InstanceIdentifier) binding.getKey(),binding.getValue());
+        return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue());
     }
 
     @Override
@@ -196,7 +194,6 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
      * <p>
      * Returns Optional.absent for cases where target is mixin node except
      * augmentation.
-     *
      */
     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(final YangInstanceIdentifier normalized)
                     throws DeserializationException {
@@ -218,13 +215,12 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
              * InstanceIdentifier has definition InstanceIdentifier<T extends DataObject>,
              * this means '?' is always  <? extends DataObject>. Eclipse compiler
              * is able to determine this relationship and treats
-             * Entry<InstanceIdentifier<?>,DataObject> and Entry<InstanceIdentifier<? extends DataObject,DataObject>
+             * Entry<InstanceIdentifier<?>, DataObject> and Entry<InstanceIdentifier<? extends DataObject, DataObject>
              * as assignable. However openjdk / oracle javac treats this two types
              * as incompatible and issues a compile error.
              *
              * <p>
-             * It is safe to  loose generic information and cast it to other generic signature.
-             *
+             * It is safe to lose generic information and cast it to other generic signature.
              */
             @SuppressWarnings("unchecked")
             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding = Entry.class.cast(
@@ -236,12 +232,10 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
     }
 
     @Override
-    public void onGlobalContextUpdated(final SchemaContext arg0) {
-        runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, arg0);
+    public void onGlobalContextUpdated(final SchemaContext context) {
+        final BindingRuntimeContext runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, context);
         codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
-        if (futureSchema != null) {
-            futureSchema.onRuntimeContextUpdated(runtimeContext);
-        }
+        futureSchema.onRuntimeContextUpdated(runtimeContext);
     }
 
     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>
@@ -295,11 +289,11 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
         final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
         final URI namespace = moduleName.getNamespace();
         final Date revision = moduleName.getRevision();
-        BindingRuntimeContext localRuntimeContext = runtimeContext;
+        BindingRuntimeContext localRuntimeContext = runtimeContext();
         Module module = localRuntimeContext == null ? null :
             localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
-        if (module == null && futureSchema != null && futureSchema.waitForSchema(namespace,revision)) {
-            localRuntimeContext = runtimeContext;
+        if (module == null && futureSchema.waitForSchema(namespace,revision)) {
+            localRuntimeContext = runtimeContext();
             Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
             module = localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
         }
@@ -308,21 +302,18 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
     }
 
     private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException exception) {
-        if (futureSchema != null) {
-            LOG.warn("Blocking thread to wait for schema convergence updates for {} {}",
-                    futureSchema.getDuration(), futureSchema.getUnit());
-            if (!futureSchema.waitForSchema(binding)) {
-                return;
-            }
+        LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(),
+            futureSchema.getUnit());
+        if (!futureSchema.waitForSchema(binding)) {
+            throw exception;
         }
-        throw exception;
     }
 
     private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef)
             throws NoSuchMethodException {
         final String methodName = BindingMapping.getMethodName(rpcDef.getQName());
         if (rpcDef.getInput() != null && isExplicitStatement(rpcDef.getInput())) {
-            final Class<?> inputClz = runtimeContext.getClassForSchema(rpcDef.getInput());
+            final Class<?> inputClz = runtimeContext().getClassForSchema(rpcDef.getInput());
             return key.getMethod(methodName, inputClz);
         }
         return key.getMethod(methodName);
@@ -330,7 +321,7 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
 
     private static boolean isExplicitStatement(final ContainerSchemaNode node) {
         return node instanceof EffectiveStatement
-                && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
+                && ((EffectiveStatement<?, ?>) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
     }
 
     @Override
@@ -361,30 +352,30 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
     @SuppressWarnings("unchecked")
     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
         final Set<Class<? extends Notification>> result = new HashSet<>();
-        final Set<NotificationDefinition> knownNotifications = runtimeContext.getSchemaContext().getNotifications();
-        for (final NotificationDefinition notification : knownNotifications) {
+        final BindingRuntimeContext runtimeContext = runtimeContext();
+        for (final NotificationDefinition notification : runtimeContext.getSchemaContext().getNotifications()) {
             if (interested.contains(notification.getPath())) {
                 try {
                     result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
                 } catch (final IllegalStateException e) {
                     // Ignore
-                    LOG.warn("Class for {} is currently not known.",notification.getPath(),e);
+                    LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
                 }
             }
         }
         return result;
     }
 
+    private BindingRuntimeContext runtimeContext() {
+        return futureSchema.runtimeContext();
+    }
+
     private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
-        final Set<Class<?>> clazzes = new HashSet<>();
-        for (final InstanceIdentifier.PathArgument arg : path.getPathArguments()) {
-            clazzes.add(arg.getType());
-        }
-        return clazzes;
+        return ImmutableSet.copyOf(Iterators.transform(path.getPathArguments().iterator(), PathArgument::getType));
     }
 
     protected NormalizedNode<?, ?> instanceIdentifierToNode(final YangInstanceIdentifier parentPath) {
-        return ImmutableNodes.fromInstanceId(runtimeContext.getSchemaContext(), parentPath);
+        return ImmutableNodes.fromInstanceId(runtimeContext().getSchemaContext(), parentPath);
     }
 
     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier parentMapPath) {
@@ -392,28 +383,19 @@ public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFacto
         final Object schema = mapCodec.getSchema();
         if (schema instanceof ListSchemaNode) {
             final ListSchemaNode castedSchema = (ListSchemaNode) schema;
-            if (castedSchema.isUserOrdered()) {
-                return Builders.orderedMapBuilder(castedSchema).build();
-            } else {
-                return Builders.mapBuilder(castedSchema).build();
-            }
+            return castedSchema.isUserOrdered() ? Builders.orderedMapBuilder(castedSchema).build()
+                    : Builders.mapBuilder(castedSchema).build();
         }
         throw new IllegalArgumentException("Path does not point to list schema node");
     }
 
     protected Collection<DOMDataTreeIdentifier> toDOMDataTreeIdentifiers(
             final Collection<DataTreeIdentifier<?>> subtrees) {
-        final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
-
-        for (final DataTreeIdentifier<?> subtree : subtrees) {
-            ret.add(toDOMDataTreeIdentifier(subtree));
-        }
-        return ret;
+        return subtrees.stream().map(this::toDOMDataTreeIdentifier).collect(Collectors.toSet());
     }
 
     protected DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier<?> path) {
         final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier());
         return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath);
     }
-
 }