Merge "Do not test bundle activation of maven plugins"
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / util / BindingRuntimeContext.java
index c5fb378b53120de632f31cb6847d60ecda72b612..fe2510857f89911223c90a539e326c6e25f5e740 100644 (file)
@@ -1,7 +1,17 @@
+/*
+ * 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.yangtools.sal.binding.generator.util;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.HashBiMap;
@@ -32,6 +42,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@@ -39,7 +50,10 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 /**
  *
  * Runtime Context for Java YANG Binding classes
@@ -58,7 +72,7 @@ import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
  *
  */
 public class BindingRuntimeContext implements Immutable {
-
+    private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
     private final ClassLoadingStrategy strategy;
     private final SchemaContext schemaContext;
 
@@ -66,21 +80,38 @@ public class BindingRuntimeContext implements Immutable {
     private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
     private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
     private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
+    private final Map<QName, Type> identities = new HashMap<>();
+
+    private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
+        new CacheLoader<QName, Class<?>>() {
+            @Override
+            public Class<?> load(final QName key) {
+                final Type identityType = identities.get(key);
+                Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
+                try {
+                    return strategy.loadClass(identityType);
+                } catch (ClassNotFoundException e) {
+                    throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
+                }
+            }
+        });
 
     private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
         this.strategy = strategy;
         this.schemaContext = schema;
 
-        BindingGeneratorImpl generator = new BindingGeneratorImpl();
+        BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
         generator.generateTypes(schema);
         Map<Module, ModuleContext> modules = generator.getModuleContexts();
 
-        for (Entry<Module, ModuleContext> entry : modules.entrySet()) {
-            ModuleContext ctx = entry.getValue();
+        for (ModuleContext ctx : modules.values()) {
             augmentationToSchema.putAll(ctx.getTypeToAugmentation());
             typeToDefiningSchema.putAll(ctx.getTypeToSchema());
+
+            ctx.getTypedefs();
             augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
             choiceToCases.putAll(ctx.getChoiceToCases());
+            identities.putAll(ctx.getIdentities());
         }
     }
 
@@ -93,7 +124,6 @@ public class BindingRuntimeContext implements Immutable {
      * @return Instance of BindingRuntimeContext for supplied schema context.
      */
     public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
-
         return new BindingRuntimeContext(strategy, ctx);
     }
 
@@ -134,12 +164,12 @@ public class BindingRuntimeContext implements Immutable {
      *
      * @param augClass Augmentation class
      * @return Schema of augmentation
-     * @throws IllegalArgumentException If supplied class is not an augmentation or current context does not contain schema for augmenation.
+     * @throws IllegalArgumentException If supplied class is not an augmentation or current context does not contain schema for augmentation.
      */
     public AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
-        Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass),"Class {} does not represent augmentation",augClass);
+        Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
         final AugmentationSchema ret = augmentationToSchema.get(referencedType(augClass));
-        Preconditions.checkArgument(ret != null, "Supplied augmentation {} is not valid in current context",augClass);
+        Preconditions.checkArgument(ret != null, "Supplied augmentation %s is not valid in current context", augClass);
         return ret;
     }
 
@@ -158,7 +188,7 @@ public class BindingRuntimeContext implements Immutable {
      * @return Schema node, from which class was generated.
      */
     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
-        Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
+        Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
         return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
     }
 
@@ -195,59 +225,128 @@ public class BindingRuntimeContext implements Immutable {
      *
      * @param schema Resolved parent choice schema
      * @param childClass Class representing case.
-     * @return Resolved case schema.
-     * @throws IllegalArgumentException If supplied class does not represent case or supplied case class is not
-     * valid in the context of parent choice schema.
+     * @return Optionally a resolved case schema, absent if the choice is not legal in
+     *         the given context.
+     * @throws IllegalArgumentException If supplied class does not represent case.
      */
-    public ChoiceCaseNode getCaseSchemaDefinition(final ChoiceNode schema, final Class<?> childClass) throws IllegalArgumentException {
+    public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceNode schema, final Class<?> childClass) throws IllegalArgumentException {
         DataSchemaNode origSchema = getSchemaDefinition(childClass);
-        Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied {} is not case.");
+        Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "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.
          */
-        Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
+        final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
                 (ChoiceCaseNode) origSchema);
-        Preconditions.checkArgument(found.isPresent(), "Supplied {} is not valid case in schema", schema);
-        return found.get();
+        return found;
     }
 
     private static Type referencedType(final Class<?> type) {
         return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
     }
 
+    /**
+     * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} 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 AugmentationSchema} or {@link TypeDefinition}
+     *     which was used to generate supplied class.
+     */
     public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
         Object schema = typeToDefiningSchema.get(referencedType(type));
         Type definedType = typeToDefiningSchema.inverse().get(schema);
         Preconditions.checkNotNull(schema);
         Preconditions.checkNotNull(definedType);
+        if(definedType instanceof GeneratedTypeBuilder) {
+            return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
+        }
+        Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType",type);
+        return new SimpleEntry<>((GeneratedType) definedType,schema);
 
-        return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
     }
 
     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
         Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
-        for(ChoiceNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceNode.class)) {
+        for (ChoiceNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceNode.class)) {
             ChoiceNode originalChoice = getOriginalSchema(choice);
             Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
             Collection<Type> cases = choiceToCases.get(choiceType);
 
-            for(Type caze : cases) {
+            for (Type caze : cases) {
                 Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
                 HashSet<Type> caseChildren = new HashSet<>();
-                if(caze instanceof GeneratedTypeBuilder) {
+                if (caze instanceof GeneratedTypeBuilder) {
                     caze = ((GeneratedTypeBuilder) caze).toInstance();
                 }
                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
-                for(Type caseChild : caseChildren) {
+                for (Type caseChild : caseChildren) {
                     childToCase.put(caseChild, caseIdentifier);
                 }
             }
         }
         return ImmutableMap.copyOf(childToCase);
+    }
+
+    public Set<Class<?>> getCases(final Class<?> choice) {
+        Collection<Type> cazes = choiceToCases.get(referencedType(choice));
+        Set<Class<?>> ret = new HashSet<>(cazes.size());
+        for(Type caze : cazes) {
+            try {
+                final Class<?> c = strategy.loadClass(caze);
+                ret.add(c);
+            } catch (ClassNotFoundException e) {
+                LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
+            }
+        }
+        return ret;
+    }
 
+    public Class<?> getClassForSchema(final DataSchemaNode childSchema) {
+        DataSchemaNode origSchema = getOriginalSchema(childSchema);
+        Type clazzType = typeToDefiningSchema.inverse().get(origSchema);
+        try {
+            return strategy.loadClass(clazzType);
+        } catch (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) {
+            Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
+            for (AugmentationSchema augment : augments) {
+                // Augmentation must have child nodes if is to be used with Binding classes
+                AugmentationSchema augOrig = augment;
+                while (augOrig.getOriginalDefinition().isPresent()) {
+                    augOrig = augOrig.getOriginalDefinition().get();
+                }
+
+                if (!augment.getChildNodes().isEmpty()) {
+                    Type augType = typeToDefiningSchema.inverse().get(augOrig);
+                    if (augType != null) {
+                        identifierToType.put(getAugmentationIdentifier(augment),augType);
+                    }
+                }
+            }
+        }
+
+        return ImmutableMap.copyOf(identifierToType);
+    }
+
+    private AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
+        Set<QName> childNames = new HashSet<>();
+        for (DataSchemaNode child : augment.getChildNodes()) {
+            childNames.add(child.getQName());
+        }
+        return new AugmentationIdentifier(childNames);
     }
 
     private static Type referencedType(final Type type) {
@@ -278,10 +377,13 @@ public class BindingRuntimeContext implements Immutable {
     private static final <T extends SchemaNode> T getOriginalSchema(final T choice) {
         @SuppressWarnings("unchecked")
         T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
-        if(original != null) {
+        if (original != null) {
             return original;
         }
         return choice;
     }
 
+    public Class<?> getIdentityClass(final QName input) {
+        return identityClasses.getUnchecked(input);
+    }
 }