Deprecate BindingRuntimeContext.getEnumMapping()
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / util / BindingRuntimeContext.java
index 3a3f2d92abadd706b66ce514283fa205861dd8f9..a5eb055255edddb3a498e263f8c7f136f3d12250 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.mdsal.binding.generator.util;
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
 
-import com.google.common.base.Optional;
+import com.google.common.base.MoreObjects;
 import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
@@ -18,30 +18,39 @@ import com.google.common.cache.LoadingCache;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
 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.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Optional;
 import java.util.Set;
-import javax.annotation.Nullable;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeTypes;
 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
 import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
 import org.opendaylight.mdsal.binding.generator.impl.BindingSchemaContextUtils;
 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
+import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
 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.mdsal.binding.model.util.ReferencedTypeImpl;
+import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.binding.Action;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.yangtools.yang.binding.Enumeration;
 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;
@@ -59,23 +68,21 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- *
  * Runtime Context for Java YANG Binding classes
  *
- *<p>
- * Runtime Context provides additional insight in Java YANG Binding,
+ * <p>Runtime Context provides additional insight in Java YANG Binding,
  * binding classes and underlying YANG schema, it contains
  * runtime information, which could not be derived from generated
- * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
- * <p>
- * Some of this information are for example list of all available
+ * classes alone using {@link org.opendaylight.mdsal.binding.spec.reflect.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.
- * <p>
- * Same goes for all possible augmentations.
  *
+ * <p>Same goes for all possible augmentations.
  */
-public class BindingRuntimeContext implements Immutable {
+public final class BindingRuntimeContext implements Immutable {
+
     private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
     private static final char DOT = '.';
 
@@ -87,7 +94,7 @@ public class BindingRuntimeContext implements Immutable {
         new CacheLoader<QName, Class<?>>() {
             @Override
             public Class<?> load(final QName key) {
-                final java.util.Optional<Type> identityType = runtimeTypes.findIdentity(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());
@@ -104,14 +111,13 @@ public class BindingRuntimeContext implements Immutable {
     }
 
     /**
-     *
      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
      *
      * @param strategy Class loading strategy to retrieve generated Binding classes
      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
      * @return Instance of BindingRuntimeContext for supplied schema context.
      */
-    public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
+    public static BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
         return new BindingRuntimeContext(strategy, ctx);
     }
 
@@ -135,18 +141,19 @@ public class BindingRuntimeContext implements Immutable {
     }
 
     /**
-     * Returns schema of augmentation
-     * <p>
-     * Returned schema is schema definition from which augmentation class was generated.
+     * 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,
+     *
+     * <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)}
+     *
+     * <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.
      *
@@ -163,23 +170,27 @@ public class BindingRuntimeContext implements Immutable {
     /**
      * Returns defining {@link DataSchemaNode} for supplied class.
      *
-     * <p>
-     * Returned schema is schema definition from which class was generated.
+     * <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
+     *
+     * <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.
      */
     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
-        checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be augmentation (%s is)",
+        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(referencedType(cls)).orElse(null);
     }
 
+    public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
+        return (ActionDefinition) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
+    }
+
     public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
@@ -214,18 +225,17 @@ public class BindingRuntimeContext implements Immutable {
             }
         }
 
-        final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
+        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
+     * Returns resolved case schema for supplied class.
      *
      * @param schema Resolved parent choice schema
      * @param childClass Class representing case.
-     * @return Optionally a resolved case schema, absent if the choice is not legal in
+     * @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.
      */
@@ -244,15 +254,6 @@ public class BindingRuntimeContext implements Immutable {
         return found;
     }
 
-    private static Type referencedType(final Class<?> type) {
-        return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
-    }
-
-    static Type referencedType(final String type) {
-        final int packageClassSeparator = type.lastIndexOf(DOT);
-        return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
-    }
-
     /**
      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
      * from which supplied class was generated. Returned schema may be augmented with
@@ -268,10 +269,6 @@ public class BindingRuntimeContext implements Immutable {
         return getTypeWithSchema(referencedType(type));
     }
 
-    public Entry<GeneratedType, WithStatus> getTypeWithSchema(final String type) {
-        return getTypeWithSchema(referencedType(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));
@@ -290,7 +287,7 @@ public class BindingRuntimeContext implements Immutable {
 
         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
-            final java.util.Optional<Type> optType = runtimeTypes.findType(originalChoice);
+            final Optional<Type> optType = runtimeTypes.findType(originalChoice);
             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
             final Type choiceType = optType.get();
 
@@ -310,22 +307,28 @@ public class BindingRuntimeContext implements Immutable {
     }
 
     /**
-     * Map enum constants: yang - java
+     * Map enum constants: yang - java.
      *
      * @param enumClass enum generated class
      * @return mapped enum constants from yang with their corresponding values in generated binding classes
+     * @deprecated This method is not guaranteed to be accurate. Use {@link Enumeration#getName()} instead.
      */
+    @Deprecated(forRemoval = true)
     public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
         final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
         return getEnumMapping(typeWithSchema);
     }
 
     /**
-     * See {@link #getEnumMapping(Class)}}
+     * Map enum constants: yang - java.
+     *
+     * @param enumClassName enum generated class name
+     * @return mapped enum constants from yang with their corresponding values in generated binding classes
+     * @deprecated This method is not guaranteed to be accurate. Use {@link Enumeration#getName()} instead.
      */
-    public BiMap<String, String> getEnumMapping(final String enumClass) {
-        final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
-        return getEnumMapping(typeWithSchema);
+    @Deprecated(forRemoval = true)
+    public BiMap<String, String> getEnumMapping(final String enumClassName) {
+        return getEnumMapping(findTypeWithSchema(enumClassName));
     }
 
     private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
@@ -344,10 +347,56 @@ public class BindingRuntimeContext implements Immutable {
         return mappedEnums;
     }
 
+    private Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
+        // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
+        // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
+        // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
+        // "foo.bar.baz.Foo.Bar" + "Baz"
+        // "foo.bar.baz.Foo" + Bar" + "Baz"
+        // "foo.bar.baz" + Foo" + Bar" + "Baz"
+        //
+        // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
+        // Nested classes are not common, so we should be arriving at the result pretty quickly.
+        final List<String> components = new ArrayList<>();
+        String packageName = className;
+
+        for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
+            components.add(packageName.substring(lastDot + 1));
+            packageName = packageName.substring(0, lastDot);
+
+            final Iterator<String> it = components.iterator();
+            JavaTypeName name = JavaTypeName.create(packageName, it.next());
+            while (it.hasNext()) {
+                name = name.createEnclosed(it.next());
+            }
+
+            final Type type = new ReferencedTypeImpl(name);
+            final Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
+            if (!optSchema.isPresent()) {
+                continue;
+            }
+
+            final WithStatus schema = optSchema.get();
+            final Optional<Type> optDefinedType =  runtimeTypes.findType(schema);
+            if (!optDefinedType.isPresent()) {
+                continue;
+            }
+
+            final Type definedType = optDefinedType.get();
+            if (definedType instanceof GeneratedTypeBuilder) {
+                return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
+            }
+            checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
+            return new SimpleEntry<>((GeneratedType) definedType, schema);
+        }
+
+        throw new IllegalArgumentException("Failed to find type for " + className);
+    }
+
     public Set<Class<?>> getCases(final Class<?> choice) {
         final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
         final Set<Class<?>> ret = new HashSet<>(cazes.size());
-        for(final Type caze : cazes) {
+        for (final Type caze : cazes) {
             try {
                 final Class<?> c = strategy.loadClass(caze);
                 ret.add(c);
@@ -360,7 +409,7 @@ public class BindingRuntimeContext implements Immutable {
 
     public Class<?> getClassForSchema(final SchemaNode childSchema) {
         final SchemaNode origSchema = getOriginalSchema(childSchema);
-        final java.util.Optional<Type> clazzType = runtimeTypes.findType(origSchema);
+        final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
             childSchema, origSchema);
 
@@ -383,7 +432,7 @@ public class BindingRuntimeContext implements Immutable {
                 }
 
                 if (!augment.getChildNodes().isEmpty()) {
-                    final java.util.Optional<Type> augType = runtimeTypes.findType(augOrig);
+                    final Optional<Type> augType = runtimeTypes.findType(augOrig);
                     if (augType.isPresent()) {
                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
                     }
@@ -395,18 +444,20 @@ public class BindingRuntimeContext implements Immutable {
     }
 
     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
-        final Set<QName> childNames = new HashSet<>();
-        for (final DataSchemaNode child : augment.getChildNodes()) {
-            childNames.add(child.getQName());
-        }
-        return new AugmentationIdentifier(childNames);
+        // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
+        return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
+            .collect(ImmutableSet.toImmutableSet()));
+    }
+
+    private static Type referencedType(final Class<?> type) {
+        return new ReferencedTypeImpl(JavaTypeName.create(type));
     }
 
     private static Type referencedType(final Type type) {
         if (type instanceof ReferencedTypeImpl) {
             return type;
         }
-        return new ReferencedTypeImpl(type.getPackageName(), type.getName());
+        return new ReferencedTypeImpl(type.getIdentifier());
     }
 
     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
@@ -439,4 +490,12 @@ public class BindingRuntimeContext implements Immutable {
     public Class<?> getIdentityClass(final QName input) {
         return identityClasses.getUnchecked(input);
     }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(this)
+                .add("ClassLoadingStrategy", strategy)
+                .add("runtimeTypes", runtimeTypes)
+                .add("schemaContext", schemaContext).toString();
+    }
 }