Split up BindingRuntimeContext
authorRobert Varga <robert.varga@pantheon.tech>
Thu, 20 Feb 2020 10:24:15 +0000 (11:24 +0100)
committerAnil Belur <abelur@linuxfoundation.org>
Wed, 19 Jun 2024 00:41:31 +0000 (10:41 +1000)
We need to disconnect API and implementation here, so that we can
publish BindingRuntimeTypes as a service. The split is done within
runtime-api, though the code is still subject to movement.

JIRA: MDSAL-392
Change-Id: Ied64b89018312daef61d9eb9da3e77a0314eca9d
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
binding/mdsal-binding-dom-codec-osgi/src/main/java/org/opendaylight/mdsal/binding/dom/codec/osgi/impl/SimpleBindingRuntimeContextService.java
binding/mdsal-binding-dom-codec/src/test/java/org/opendaylight/mdsal/binding/dom/codec/impl/AugmentationClassDiscoveredAfterCodecTest.java
binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/AbstractBindingRuntimeContext.java [new file with mode: 0644]
binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/BindingRuntimeContext.java
binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/DefaultBindingRuntimeContext.java [new file with mode: 0644]
binding/mdsal-binding-runtime-spi/src/main/java/org/opendaylight/binding/runtime/spi/BindingRuntimeHelpers.java
binding/mdsal-binding-runtime-spi/src/main/java/org/opendaylight/binding/runtime/spi/ModuleInfoBackedContext.java

index 708ce6817e31ca186b816eec6cd041aad3dc17b0..98203f122775af02bc98501576ec9951a687318e 100644 (file)
@@ -14,6 +14,7 @@ import com.google.common.util.concurrent.ListenableFuture;
 import org.checkerframework.checker.lock.qual.GuardedBy;
 import org.opendaylight.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.binding.runtime.api.ClassLoadingStrategy;
+import org.opendaylight.binding.runtime.api.DefaultBindingRuntimeContext;
 import org.opendaylight.mdsal.binding.dom.codec.osgi.BindingRuntimeContextListener;
 import org.opendaylight.mdsal.binding.dom.codec.osgi.BindingRuntimeContextService;
 import org.opendaylight.mdsal.binding.generator.impl.DefaultBindingRuntimeGenerator;
@@ -57,7 +58,7 @@ final class SimpleBindingRuntimeContextService extends
     }
 
     void updateBindingRuntimeContext(final SchemaContext schemaContext) {
-        final BindingRuntimeContext next = BindingRuntimeContext.create(
+        final BindingRuntimeContext next = DefaultBindingRuntimeContext.create(
             new DefaultBindingRuntimeGenerator().generateTypeMapping(schemaContext), strategy);
 
         final BindingRuntimeContextListener[] listeners;
index 2c916b7e71357cb898828225779c1e924ae7ca4d..090b9c179e11a33f1fb7e3d8fce54442e971a3df 100644 (file)
@@ -17,6 +17,7 @@ import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.binding.runtime.api.ClassLoadingStrategy;
+import org.opendaylight.binding.runtime.api.DefaultBindingRuntimeContext;
 import org.opendaylight.binding.runtime.spi.BindingRuntimeHelpers;
 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
 import org.opendaylight.mdsal.binding.generator.impl.DefaultBindingRuntimeGenerator;
@@ -50,7 +51,8 @@ public class AugmentationClassDiscoveredAfterCodecTest {
 
         // Class loading filter, manipulated by tests
         filter = new FilteringClassLoadingStrategy(delegate.getStrategy());
-        registry = new BindingNormalizedNodeCodecRegistry(BindingRuntimeContext.create(delegate.getTypes(), filter));
+        registry = new BindingNormalizedNodeCodecRegistry(DefaultBindingRuntimeContext.create(delegate.getTypes(),
+            filter));
     }
 
     private static final TopLevelListKey TOP_FOO_KEY = new TopLevelListKey("foo");
diff --git a/binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/AbstractBindingRuntimeContext.java b/binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/AbstractBindingRuntimeContext.java
new file mode 100644 (file)
index 0000000..cf36fad
--- /dev/null
@@ -0,0 +1,388 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.binding.runtime.api;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.MoreObjects;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import java.util.AbstractMap.SimpleEntry;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.mdsal.binding.model.api.DefaultType;
+import org.opendaylight.mdsal.binding.model.api.GeneratedType;
+import org.opendaylight.mdsal.binding.model.api.MethodSignature;
+import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
+import org.opendaylight.mdsal.binding.model.api.Type;
+import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
+import org.opendaylight.yangtools.yang.binding.Action;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
+import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
+ * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
+ *
+ * <p>Some of this information are for example list of all available children for cases
+ * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
+ * by additional models. Same goes for all possible augmentations.
+ */
+@Beta
+public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
+
+    private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
+        new CacheLoader<QName, Class<?>>() {
+            @Override
+            public Class<?> load(final QName key) {
+                final Optional<Type> identityType = getTypes().findIdentity(key);
+                checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
+                try {
+                    return getStrategy().loadClass(identityType.get());
+                } catch (final ClassNotFoundException e) {
+                    throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
+                }
+            }
+        });
+
+    /**
+     * Returns schema of augmentation.
+     *
+     * <p>Returned schema is schema definition from which augmentation class was generated.
+     * This schema is isolated from other augmentations. This means it contains
+     * augmentation definition as was present in original YANG module.
+     *
+     * <p>Children of returned schema does not contain any additional augmentations,
+     * which may be present in runtime for them, thus returned schema is unsuitable
+     * for use for validation of data.
+     *
+     * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
+     * full model for child nodes, you should use method
+     * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
+     * which will return augmentation schema derived from supplied augmentation target
+     * schema.
+     *
+     * @param augClass Augmentation class
+     * @return Schema of augmentation or null if augmentaiton is not known in this context
+     * @throws IllegalArgumentException If supplied class is not an augmentation
+     */
+    @Override
+    public final @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
+        checkArgument(Augmentation.class.isAssignableFrom(augClass),
+            "Class %s does not represent augmentation", augClass);
+        return getTypes().findAugmentation(DefaultType.of(augClass)).orElse(null);
+    }
+
+    /**
+     * Returns defining {@link DataSchemaNode} for supplied class.
+     *
+     * <p>Returned schema is schema definition from which class was generated.
+     * This schema may be isolated from augmentations, if supplied class
+     * represent node, which was child of grouping or augmentation.
+     *
+     * <p>For getting augmentation schema from augmentation class use
+     * {@link #getAugmentationDefinition(Class)} instead.
+     *
+     * @param cls Class which represents list, container, choice or case.
+     * @return Schema node, from which class was generated.
+     */
+    @Override
+    public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
+        checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
+            cls);
+        checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
+        return (DataSchemaNode) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
+    }
+
+    @Override
+    public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
+        return (ActionDefinition) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
+    }
+
+    @Override
+    public final Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
+            final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
+        final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
+        checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
+        /*
+         * FIXME: Validate augmentation schema lookup
+         *
+         * Currently this algorithm, does not verify if instantiated child nodes
+         * are real one derived from augmentation schema. The problem with
+         * full validation is, if user used copy builders, he may use
+         * augmentation which was generated for different place.
+         *
+         * If this augmentations have same definition, we emit same identifier
+         * with data and it is up to underlying user to validate data.
+         *
+         */
+        final Set<QName> childNames = new HashSet<>();
+        final Set<DataSchemaNode> realChilds = new HashSet<>();
+        for (final DataSchemaNode child : origSchema.getChildNodes()) {
+            final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
+            final String childLocalName = child.getQName().getLocalName();
+            if (dataChildQNname == null) {
+                for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
+                    if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
+                        realChilds.add(dataSchemaNode);
+                        childNames.add(dataSchemaNode.getQName());
+                    }
+                }
+            } else {
+                realChilds.add(dataChildQNname);
+                childNames.add(child.getQName());
+            }
+        }
+
+        final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
+        final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
+        return new SimpleEntry<>(identifier, proxy);
+    }
+
+    /**
+     * Returns resolved case schema for supplied class.
+     *
+     * @param schema Resolved parent choice schema
+     * @param childClass Class representing case.
+     * @return Optionally a resolved case schema,.empty if the choice is not legal in
+     *         the given context.
+     * @throws IllegalArgumentException If supplied class does not represent case.
+     */
+    @Override
+    public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
+            final Class<?> childClass) {
+        final DataSchemaNode origSchema = getSchemaDefinition(childClass);
+        checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
+
+        /* FIXME: Make sure that if there are multiple augmentations of same
+         * named case, with same structure we treat it as equals
+         * this is due property of Binding specification and copy builders
+         * that user may be unaware that he is using incorrect case
+         * which was generated for choice inside grouping.
+         */
+        return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
+    }
+
+    /**
+     * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
+     * from which supplied class was generated. Returned schema may be augmented with
+     * additional information, which was not available at compile type
+     * (e.g. third party augmentations).
+     *
+     * @param type Binding Class for which schema should be retrieved.
+     * @return Instance of generated type (definition of Java API), along with
+     *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
+     *     which was used to generate supplied class.
+     */
+    @Override
+    public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
+        return getTypeWithSchema(getTypes(), DefaultType.of(type));
+    }
+
+    private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
+            final Type referencedType) {
+        final WithStatus schema = types.findSchema(referencedType).orElseThrow(
+            () -> new NullPointerException("Failed to find schema for type " + referencedType));
+        final Type definedType = types.findType(schema).orElseThrow(
+            () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
+
+        if (definedType instanceof GeneratedTypeBuilder) {
+            return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
+        }
+        checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
+        return new SimpleEntry<>((GeneratedType) definedType, schema);
+    }
+
+    @Override
+    public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
+        return getChoiceCaseChildren(getTypes(), schema);
+    }
+
+    private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
+            final DataNodeContainer schema) {
+        final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
+
+        for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
+            final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
+            final Optional<Type> optType = types.findType(originalChoice);
+            checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
+            final Type choiceType = optType.get();
+
+            for (Type caze : types.findCases(choiceType)) {
+                final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
+                final HashSet<Type> caseChildren = new HashSet<>();
+                if (caze instanceof GeneratedTypeBuilder) {
+                    caze = ((GeneratedTypeBuilder) caze).build();
+                }
+                collectAllContainerTypes((GeneratedType) caze, caseChildren);
+                for (final Type caseChild : caseChildren) {
+                    childToCase.put(caseChild, caseIdentifier);
+                }
+            }
+        }
+        return ImmutableMap.copyOf(childToCase);
+    }
+
+    @Override
+    public final Set<Class<?>> getCases(final Class<?> choice) {
+        final Collection<Type> cazes = getTypes().findCases(DefaultType.of(choice));
+        final Set<Class<?>> ret = new HashSet<>(cazes.size());
+        for (final Type caze : cazes) {
+            try {
+                ret.add(getStrategy().loadClass(caze));
+            } catch (final ClassNotFoundException e) {
+                LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
+            }
+        }
+        return ret;
+    }
+
+    @Override
+    public final Class<?> getClassForSchema(final SchemaNode childSchema) {
+        final SchemaNode origSchema = getOriginalSchema(childSchema);
+        final Optional<Type> clazzType = getTypes().findType(origSchema);
+        checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
+            childSchema, origSchema);
+
+        try {
+            return getStrategy().loadClass(clazzType.get());
+        } catch (final ClassNotFoundException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    @Override
+    public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
+            final DataNodeContainer container) {
+        final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
+        if (container instanceof AugmentationTarget) {
+            final BindingRuntimeTypes types = getTypes();
+            for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
+                // Augmentation must have child nodes if is to be used with Binding classes
+                AugmentationSchemaNode augOrig = augment;
+                while (augOrig.getOriginalDefinition().isPresent()) {
+                    augOrig = augOrig.getOriginalDefinition().get();
+                }
+
+                if (!augment.getChildNodes().isEmpty()) {
+                    final Optional<Type> augType = types.findType(augOrig);
+                    if (augType.isPresent()) {
+                        identifierToType.put(getAugmentationIdentifier(augment), augType.get());
+                    }
+                }
+            }
+        }
+
+        return ImmutableMap.copyOf(identifierToType);
+    }
+
+    @Override
+    public final Class<?> getIdentityClass(final QName input) {
+        return identityClasses.getUnchecked(input);
+    }
+
+    @Override
+    public final String toString() {
+        return MoreObjects.toStringHelper(this)
+                .add("ClassLoadingStrategy", getStrategy())
+                .add("runtimeTypes", getTypes())
+                .toString();
+    }
+
+    private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
+        // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
+        return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
+            .collect(ImmutableSet.toImmutableSet()));
+    }
+
+    private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
+        for (final MethodSignature definition : type.getMethodDefinitions()) {
+            Type childType = definition.getReturnType();
+            if (childType instanceof ParameterizedType) {
+                childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
+            }
+            if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
+                collection.add(childType);
+            }
+        }
+        for (final Type parent : type.getImplements()) {
+            if (parent instanceof GeneratedType) {
+                collectAllContainerTypes((GeneratedType) parent, collection);
+            }
+        }
+        return collection;
+    }
+
+    private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
+        @SuppressWarnings("unchecked")
+        final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
+        if (original != null) {
+            return original;
+        }
+        return choice;
+    }
+
+    private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
+            final CaseSchemaNode originalDefinition) {
+        CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
+        if (originalDefinition.equals(potential)) {
+            return Optional.of(potential);
+        }
+        if (potential != null) {
+            SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
+            if (originalDefinition.equals(potentialRoot)) {
+                return Optional.of(potential);
+            }
+        }
+
+        // We try to find case by name, then lookup its root definition
+        // and compare it with original definition
+        // This solves case, if choice was inside grouping
+        // which was used in different module and thus namespaces are
+        // different, but local names are still same.
+        //
+        // Still we need to check equality of definition, because local name is not
+        // sufficient to uniquelly determine equality of cases
+        //
+        for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
+            if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
+                return Optional.of(caze);
+            }
+        }
+        return Optional.empty();
+    }
+}
index a46a4ced6e9e6fcc9a8b5130cdce443865299fe5..886fb6376fe54ca2c33a52eae834ccf15f800adc 100644 (file)
@@ -7,34 +7,16 @@
  */
 package org.opendaylight.binding.runtime.api;
 
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
 import com.google.common.annotations.Beta;
-import com.google.common.base.MoreObjects;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.Set;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.mdsal.binding.model.api.DefaultType;
 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
-import org.opendaylight.mdsal.binding.model.api.MethodSignature;
-import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
 import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.binding.Action;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
@@ -42,7 +24,6 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@@ -52,10 +33,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 /**
  * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
@@ -66,65 +43,20 @@ import org.slf4j.LoggerFactory;
  * by additional models. Same goes for all possible augmentations.
  */
 @Beta
-public final class BindingRuntimeContext implements SchemaContextProvider, Immutable {
-    private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
-
-    private final @NonNull BindingRuntimeTypes runtimeTypes;
-    private final @NonNull ClassLoadingStrategy strategy;
-
-    private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
-        new CacheLoader<QName, Class<?>>() {
-            @Override
-            public Class<?> load(final QName key) {
-                final Optional<Type> identityType = runtimeTypes.findIdentity(key);
-                checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
-                try {
-                    return strategy.loadClass(identityType.get());
-                } catch (final ClassNotFoundException e) {
-                    throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
-                }
-            }
-        });
-
-    private BindingRuntimeContext(final BindingRuntimeTypes runtimeTypes, final ClassLoadingStrategy strategy) {
-        this.runtimeTypes = requireNonNull(runtimeTypes);
-        this.strategy = requireNonNull(strategy);
-    }
-
-    /**
-     * Creates Binding Runtime Context from supplied class loading strategy and schema context.
-     *
-     * @param strategy Class loading strategy to retrieve generated Binding classes
-     * @param runtimeTypes Binding classes to YANG schema mapping
-     * @return A new instance
-     */
-    public static @NonNull BindingRuntimeContext create(final BindingRuntimeTypes runtimeTypes,
-            final ClassLoadingStrategy strategy) {
-        return new BindingRuntimeContext(runtimeTypes, strategy);
-    }
-
+public interface BindingRuntimeContext extends SchemaContextProvider, Immutable {
     /**
      * Returns a class loading strategy associated with this binding runtime context
      * which is used to load classes.
      *
      * @return Class loading strategy.
      */
-    public @NonNull ClassLoadingStrategy getStrategy() {
-        return strategy;
-    }
+    @NonNull ClassLoadingStrategy getStrategy();
 
-    public @NonNull BindingRuntimeTypes getTypes() {
-        return runtimeTypes;
-    }
+    @NonNull BindingRuntimeTypes getTypes();
 
-    /**
-     * Returns an stable immutable view of schema context associated with this Binding runtime context.
-     *
-     * @return stable view of schema context
-     */
     @Override
-    public SchemaContext getSchemaContext() {
-        return runtimeTypes.getSchemaContext();
+    default SchemaContext getSchemaContext() {
+        return getTypes().getSchemaContext();
     }
 
     /**
@@ -148,11 +80,7 @@ public final class BindingRuntimeContext implements SchemaContextProvider, Immut
      * @return Schema of augmentation or null if augmentaiton is not known in this context
      * @throws IllegalArgumentException If supplied class is not an augmentation
      */
-    public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
-        checkArgument(Augmentation.class.isAssignableFrom(augClass),
-            "Class %s does not represent augmentation", augClass);
-        return runtimeTypes.findAugmentation(DefaultType.of(augClass)).orElse(null);
-    }
+    @Nullable AugmentationSchemaNode getAugmentationDefinition(Class<?> augClass);
 
     /**
      * Returns defining {@link DataSchemaNode} for supplied class.
@@ -167,55 +95,12 @@ public final class BindingRuntimeContext implements SchemaContextProvider, Immut
      * @param cls Class which represents list, container, choice or case.
      * @return Schema node, from which class was generated.
      */
-    public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
-        checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
-            cls);
-        checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
-        return (DataSchemaNode) runtimeTypes.findSchema(DefaultType.of(cls)).orElse(null);
-    }
-
-    public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
-        return (ActionDefinition) runtimeTypes.findSchema(DefaultType.of(cls)).orElse(null);
-    }
+    @Nullable DataSchemaNode getSchemaDefinition(Class<?> cls);
 
-    public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
-            final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
-        final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
-        checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
-        /*
-         * FIXME: Validate augmentation schema lookup
-         *
-         * Currently this algorithm, does not verify if instantiated child nodes
-         * are real one derived from augmentation schema. The problem with
-         * full validation is, if user used copy builders, he may use
-         * augmentation which was generated for different place.
-         *
-         * If this augmentations have same definition, we emit same identifier
-         * with data and it is up to underlying user to validate data.
-         *
-         */
-        final Set<QName> childNames = new HashSet<>();
-        final Set<DataSchemaNode> realChilds = new HashSet<>();
-        for (final DataSchemaNode child : origSchema.getChildNodes()) {
-            final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
-            final String childLocalName = child.getQName().getLocalName();
-            if (dataChildQNname == null) {
-                for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
-                    if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
-                        realChilds.add(dataSchemaNode);
-                        childNames.add(dataSchemaNode.getQName());
-                    }
-                }
-            } else {
-                realChilds.add(dataChildQNname);
-                childNames.add(child.getQName());
-            }
-        }
+    @Nullable ActionDefinition getActionDefinition(Class<? extends Action<?, ?, ?>> cls);
 
-        final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
-        final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
-        return new SimpleEntry<>(identifier, proxy);
-    }
+    @NonNull Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
+            DataNodeContainer target, Class<? extends Augmentation<?>> aug);
 
     /**
      * Returns resolved case schema for supplied class.
@@ -226,19 +111,7 @@ public final class BindingRuntimeContext implements SchemaContextProvider, Immut
      *         the given context.
      * @throws IllegalArgumentException If supplied class does not represent case.
      */
-    public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
-        final DataSchemaNode origSchema = getSchemaDefinition(childClass);
-        checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
-
-        /* FIXME: Make sure that if there are multiple augmentations of same
-         * named case, with same structure we treat it as equals
-         * this is due property of Binding specification and copy builders
-         * that user may be unaware that he is using incorrect case
-         * which was generated for choice inside grouping.
-         */
-        final Optional<CaseSchemaNode> found = findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
-        return found;
-    }
+    @NonNull Optional<CaseSchemaNode> getCaseSchemaDefinition(ChoiceSchemaNode schema, Class<?> childClass);
 
     /**
      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
@@ -251,168 +124,15 @@ public final class BindingRuntimeContext implements SchemaContextProvider, Immut
      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
      *     which was used to generate supplied class.
      */
-    public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
-        return getTypeWithSchema(DefaultType.of(type));
-    }
+    @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(Class<?> type);
 
-    private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
-        final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
-            () -> new NullPointerException("Failed to find schema for type " + referencedType));
-        final Type definedType = runtimeTypes.findType(schema).orElseThrow(
-            () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
+    @NonNull Map<Type, Entry<Type, Type>> getChoiceCaseChildren(DataNodeContainer schema);
 
-        if (definedType instanceof GeneratedTypeBuilder) {
-            return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
-        }
-        checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
-        return new SimpleEntry<>((GeneratedType) definedType, schema);
-    }
+    @NonNull Set<Class<?>> getCases(Class<?> choice);
 
-    public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
-        final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
+    @NonNull Class<?> getClassForSchema(SchemaNode childSchema);
 
-        for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
-            final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
-            final Optional<Type> optType = runtimeTypes.findType(originalChoice);
-            checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
-            final Type choiceType = optType.get();
+    @NonNull ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(DataNodeContainer container);
 
-            for (Type caze : runtimeTypes.findCases(choiceType)) {
-                final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
-                final HashSet<Type> caseChildren = new HashSet<>();
-                if (caze instanceof GeneratedTypeBuilder) {
-                    caze = ((GeneratedTypeBuilder) caze).build();
-                }
-                collectAllContainerTypes((GeneratedType) caze, caseChildren);
-                for (final Type caseChild : caseChildren) {
-                    childToCase.put(caseChild, caseIdentifier);
-                }
-            }
-        }
-        return ImmutableMap.copyOf(childToCase);
-    }
-
-    public Set<Class<?>> getCases(final Class<?> choice) {
-        final Collection<Type> cazes = runtimeTypes.findCases(DefaultType.of(choice));
-        final Set<Class<?>> ret = new HashSet<>(cazes.size());
-        for (final Type caze : cazes) {
-            try {
-                final Class<?> c = strategy.loadClass(caze);
-                ret.add(c);
-            } catch (final ClassNotFoundException e) {
-                LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
-            }
-        }
-        return ret;
-    }
-
-    public Class<?> getClassForSchema(final SchemaNode childSchema) {
-        final SchemaNode origSchema = getOriginalSchema(childSchema);
-        final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
-        checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
-            childSchema, origSchema);
-
-        try {
-            return strategy.loadClass(clazzType.get());
-        } catch (final ClassNotFoundException e) {
-            throw new IllegalStateException(e);
-        }
-    }
-
-    public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
-        final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
-        if (container instanceof AugmentationTarget) {
-            for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
-                // Augmentation must have child nodes if is to be used with Binding classes
-                AugmentationSchemaNode augOrig = augment;
-                while (augOrig.getOriginalDefinition().isPresent()) {
-                    augOrig = augOrig.getOriginalDefinition().get();
-                }
-
-                if (!augment.getChildNodes().isEmpty()) {
-                    final Optional<Type> augType = runtimeTypes.findType(augOrig);
-                    if (augType.isPresent()) {
-                        identifierToType.put(getAugmentationIdentifier(augment), augType.get());
-                    }
-                }
-            }
-        }
-
-        return ImmutableMap.copyOf(identifierToType);
-    }
-
-    public Class<?> getIdentityClass(final QName input) {
-        return identityClasses.getUnchecked(input);
-    }
-
-    @Override
-    public String toString() {
-        return MoreObjects.toStringHelper(this)
-                .add("ClassLoadingStrategy", strategy)
-                .add("runtimeTypes", runtimeTypes)
-                .toString();
-    }
-
-    private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
-        // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
-        return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
-            .collect(ImmutableSet.toImmutableSet()));
-    }
-
-    private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
-        for (final MethodSignature definition : type.getMethodDefinitions()) {
-            Type childType = definition.getReturnType();
-            if (childType instanceof ParameterizedType) {
-                childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
-            }
-            if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
-                collection.add(childType);
-            }
-        }
-        for (final Type parent : type.getImplements()) {
-            if (parent instanceof GeneratedType) {
-                collectAllContainerTypes((GeneratedType) parent, collection);
-            }
-        }
-        return collection;
-    }
-
-    private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
-        @SuppressWarnings("unchecked")
-        final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
-        if (original != null) {
-            return original;
-        }
-        return choice;
-    }
-
-    private static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
-            final CaseSchemaNode originalDefinition) {
-        CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
-        if (originalDefinition.equals(potential)) {
-            return Optional.of(potential);
-        }
-        if (potential != null) {
-            SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
-            if (originalDefinition.equals(potentialRoot)) {
-                return Optional.of(potential);
-            }
-        }
-
-        // We try to find case by name, then lookup its root definition
-        // and compare it with original definition
-        // This solves case, if choice was inside grouping
-        // which was used in different module and thus namespaces are
-        // different, but local names are still same.
-        //
-        // Still we need to check equality of definition, because local name is not
-        // sufficient to uniquelly determine equality of cases
-        //
-        for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
-            if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
-                return Optional.of(caze);
-            }
-        }
-        return Optional.empty();
-    }
+    @NonNull Class<?> getIdentityClass(QName input);
 }
diff --git a/binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/DefaultBindingRuntimeContext.java b/binding/mdsal-binding-runtime-api/src/main/java/org/opendaylight/binding/runtime/api/DefaultBindingRuntimeContext.java
new file mode 100644 (file)
index 0000000..d06157e
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.binding.runtime.api;
+
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.annotations.Beta;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+
+/**
+ * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
+ * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
+ *
+ * <p>Some of this information are for example list of all available children for cases
+ * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
+ * by additional models. Same goes for all possible augmentations.
+ */
+@Beta
+public final class DefaultBindingRuntimeContext extends AbstractBindingRuntimeContext {
+    private final @NonNull BindingRuntimeTypes runtimeTypes;
+    private final @NonNull ClassLoadingStrategy strategy;
+
+    private DefaultBindingRuntimeContext(final BindingRuntimeTypes runtimeTypes, final ClassLoadingStrategy strategy) {
+        this.runtimeTypes = requireNonNull(runtimeTypes);
+        this.strategy = requireNonNull(strategy);
+    }
+
+    /**
+     * Creates Binding Runtime Context from supplied class loading strategy and schema context.
+     *
+     * @param strategy Class loading strategy to retrieve generated Binding classes
+     * @param runtimeTypes Binding classes to YANG schema mapping
+     * @return A new instance
+     */
+    public static @NonNull DefaultBindingRuntimeContext create(final BindingRuntimeTypes runtimeTypes,
+            final ClassLoadingStrategy strategy) {
+        return new DefaultBindingRuntimeContext(runtimeTypes, strategy);
+    }
+
+    /**
+     * Returns a class loading strategy associated with this binding runtime context
+     * which is used to load classes.
+     *
+     * @return Class loading strategy.
+     */
+    @Override
+    public @NonNull ClassLoadingStrategy getStrategy() {
+        return strategy;
+    }
+
+    @Override
+    public @NonNull BindingRuntimeTypes getTypes() {
+        return runtimeTypes;
+    }
+}
index 154c7d53852ef431032fa47794ffe652760d56d6..b252b2e5cfd4dc52566b0942d387badd608caefc 100644 (file)
@@ -13,6 +13,7 @@ import java.util.stream.Collectors;
 import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.binding.runtime.api.BindingRuntimeGenerator;
+import org.opendaylight.binding.runtime.api.DefaultBindingRuntimeContext;
 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
@@ -41,8 +42,8 @@ public final class BindingRuntimeHelpers {
 
     public static @NonNull BindingRuntimeContext createRuntimeContext(final BindingRuntimeGenerator generator) {
         final ModuleInfoBackedContext ctx = prepareContext(BindingReflections.loadModuleInfos());
-        return BindingRuntimeContext.create(generator.generateTypeMapping(ctx.tryToCreateModelContext().orElseThrow()),
-            ctx);
+        return DefaultBindingRuntimeContext.create(generator.generateTypeMapping(
+            ctx.tryToCreateModelContext().orElseThrow()), ctx);
     }
 
     public static @NonNull BindingRuntimeContext createRuntimeContext(final BindingRuntimeGenerator generator,
@@ -50,8 +51,8 @@ public final class BindingRuntimeHelpers {
         final ModuleInfoBackedContext ctx = prepareContext(Arrays.stream(classes)
             .map(BindingRuntimeHelpers::extractYangModuleInfo)
             .collect(Collectors.toList()));
-        return BindingRuntimeContext.create(generator.generateTypeMapping(ctx.tryToCreateModelContext().orElseThrow()),
-            ctx);
+        return DefaultBindingRuntimeContext.create(
+            generator.generateTypeMapping(ctx.tryToCreateModelContext().orElseThrow()), ctx);
     }
 
     @SuppressWarnings("checkstyle:IllegalCatch")
index efe11652ae99f84dbf11010247883c7041a4b9cc..02666536acbe180c781be73ebeabb95d0608b34e 100644 (file)
@@ -35,6 +35,7 @@ import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.binding.runtime.api.BindingRuntimeGenerator;
 import org.opendaylight.binding.runtime.api.ClassLoadingStrategy;
+import org.opendaylight.binding.runtime.api.DefaultBindingRuntimeContext;
 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
 import org.opendaylight.yangtools.concepts.ObjectRegistration;
@@ -220,8 +221,8 @@ public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
 
     @Beta
     public final @NonNull BindingRuntimeContext createRuntimeContext(final BindingRuntimeGenerator generator) {
-        return BindingRuntimeContext.create(generator.generateTypeMapping(tryToCreateModelContext().orElseThrow()),
-            this);
+        return DefaultBindingRuntimeContext.create(
+            generator.generateTypeMapping(tryToCreateModelContext().orElseThrow()), this);
     }
 
     // TODO finish schema parsing and expose as SchemaService