X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=binding%2Fmdsal-binding-spec-util%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fmdsal%2Fbinding%2Fspec%2Freflect%2FBindingReflections.java;h=0f1dc3e9b90fc2b18ee2ec508e928fc9d4a6c2bc;hb=0ee55d1f9da11dd03ff05fc67d10cbcbfe63fd2c;hp=af800bee26fbd08ac879ff93a7cd8ded32e791a2;hpb=c77348ddc6ccebb90ef32b5e55f38e0997047f36;p=mdsal.git diff --git a/binding/mdsal-binding-spec-util/src/main/java/org/opendaylight/mdsal/binding/spec/reflect/BindingReflections.java b/binding/mdsal-binding-spec-util/src/main/java/org/opendaylight/mdsal/binding/spec/reflect/BindingReflections.java index af800bee26..0f1dc3e9b9 100644 --- a/binding/mdsal-binding-spec-util/src/main/java/org/opendaylight/mdsal/binding/spec/reflect/BindingReflections.java +++ b/binding/mdsal-binding-spec-util/src/main/java/org/opendaylight/mdsal/binding/spec/reflect/BindingReflections.java @@ -9,6 +9,7 @@ package org.opendaylight.mdsal.binding.spec.reflect; 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.cache.CacheBuilder; @@ -18,7 +19,10 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.util.concurrent.ListenableFuture; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; @@ -33,6 +37,7 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.checkerframework.checker.regex.qual.Regex; +import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.mdsal.binding.spec.naming.BindingMapping; import org.opendaylight.yangtools.util.ClassLoaderUtils; import org.opendaylight.yangtools.yang.binding.Action; @@ -67,8 +72,17 @@ public final class BindingReflections { .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) .build(new ClassToQNameLoader()); + private static final LoadingCache> MODULE_INFO_CACHE = + CacheBuilder.newBuilder().weakKeys().weakValues().build( + new CacheLoader>() { + @Override + public ImmutableSet load(final ClassLoader key) { + return loadModuleInfos(key); + } + }); + private BindingReflections() { - throw new UnsupportedOperationException("Utility class."); + // Hidden on purpose } /** @@ -179,8 +193,10 @@ public final class BindingReflections { return Optional.empty(); } - public static QName getQName(final Class context) { - return findQName(context); + public static @NonNull QName getQName(final Class bindingClass) { + final Optional qname = CLASS_TO_QNAME.getUnchecked(requireNonNull(bindingClass)); + checkState(qname.isPresent(), "Failed to resolve QName of %s", bindingClass); + return qname.get(); } /** @@ -231,37 +247,43 @@ public final class BindingReflections { return match.group(0); } - @SuppressWarnings("checkstyle:illegalCatch") public static QNameModule getQNameModule(final Class clz) { if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz) || Action.class.isAssignableFrom(clz)) { return findQName(clz).getModule(); } - try { - return BindingReflections.getModuleInfo(clz).getName().getModule(); - } catch (Exception e) { - throw new IllegalStateException("Unable to get QName of defining model.", e); - } + + return getModuleInfo(clz).getName().getModule(); } /** * Returns instance of {@link YangModuleInfo} of declaring model for specific class. * * @param cls data object class - * @return Instance of {@link YangModuleInfo} associated with model, from - * which this class was derived. + * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived. */ - public static YangModuleInfo getModuleInfo(final Class cls) throws Exception { - checkArgument(cls != null); - String packageName = getModelRootPackageName(cls.getPackage()); + public static @NonNull YangModuleInfo getModuleInfo(final Class cls) { + final String packageName = getModelRootPackageName(cls.getPackage()); final String potentialClassName = getModuleInfoClassName(packageName); - return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> { - Class moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName); - return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null); - }); + final Class moduleInfoClass; + try { + moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Failed to load " + potentialClassName, e); + } + + final Object infoInstance; + try { + infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e); + } + + checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance); + return (YangModuleInfo) infoInstance; } - public static String getModuleInfoClassName(final String packageName) { + public static @NonNull String getModuleInfoClassName(final String packageName) { return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME; } @@ -314,7 +336,7 @@ public final class BindingReflections { * * @return Set of {@link YangModuleInfo} available for current classloader. */ - public static ImmutableSet loadModuleInfos() { + public static @NonNull ImmutableSet loadModuleInfos() { return loadModuleInfos(Thread.currentThread().getContextClassLoader()); } @@ -330,12 +352,13 @@ public final class BindingReflections { * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by * collecting results of {@link YangModuleInfo#getImportedModules()}. * - * @param loader - * Classloader for which {@link YangModuleInfo} should be - * retrieved. + *

+ * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable. + * + * @param loader Classloader for which {@link YangModuleInfo} should be retrieved. * @return Set of {@link YangModuleInfo} available for supplied classloader. */ - public static ImmutableSet loadModuleInfos(final ClassLoader loader) { + public static @NonNull ImmutableSet loadModuleInfos(final ClassLoader loader) { Builder moduleInfoSet = ImmutableSet.builder(); ServiceLoader serviceLoader = ServiceLoader.load(YangModelBindingProvider.class, loader); @@ -347,6 +370,27 @@ public final class BindingReflections { return moduleInfoSet.build(); } + /** + * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available + * information does not change. Subsequent accesses may return cached values. + * + *

+ * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}. + * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance + * {@link YangModuleInfo}. + * + *

+ * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by + * collecting results of {@link YangModuleInfo#getImportedModules()}. + * + * @param loader Class loader for which {@link YangModuleInfo} should be retrieved. + * @return Set of {@link YangModuleInfo} available for supplied classloader. + */ + @Beta + public static @NonNull ImmutableSet cacheModuleInfos(final ClassLoader loader) { + return MODULE_INFO_CACHE.getUnchecked(loader); + } + private static void collectYangModuleInfo(final YangModuleInfo moduleInfo, final Builder moduleInfoSet) { moduleInfoSet.add(moduleInfo); @@ -394,19 +438,24 @@ public final class BindingReflections { /** * Scans supplied class and returns an iterable of all data children classes. * - * @param type - * YANG Modeled Entity derived from DataContainer + * @param type YANG Modeled Entity derived from DataContainer * @return Iterable of all data children, which have YANG modeled entity */ - public static Map, Method> getChildrenClassToMethod(final Class type) { - return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX); + public static Map, Method> getChildrenClassToMethod(final Class type) { + return getChildClassToMethod(type, BindingMapping.GETTER_PREFIX); + } + + @Beta + public static Map, Method> getChildrenClassToNonnullMethod(final Class type) { + return getChildClassToMethod(type, BindingMapping.NONNULL_PREFIX); } - private static Map, Method> getChildrenClassToMethod(final Class type, final String prefix) { + private static Map, Method> getChildClassToMethod(final Class type, + final String prefix) { checkArgument(type != null, "Target type must not be null"); checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer", type); - Map, Method> ret = new HashMap<>(); + Map, Method> ret = new HashMap<>(); for (Method method : type.getMethods()) { Optional> entity = getYangModeledReturnType(method, prefix); if (entity.isPresent()) { @@ -416,12 +465,6 @@ public final class BindingReflections { return ret; } - @Beta - public static Map, Method> getChildrenClassToNonnullMethod(final Class type) { - return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX); - } - - @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" }) private static Optional> getYangModeledReturnType(final Method method, final String prefix) { final String methodName = method.getName(); @@ -429,24 +472,48 @@ public final class BindingReflections { return Optional.empty(); } - Class returnType = method.getReturnType(); + final Class returnType = method.getReturnType(); if (DataContainer.class.isAssignableFrom(returnType)) { - return Optional.of(returnType); + return optionalDataContainer(returnType); + } else if (List.class.isAssignableFrom(returnType)) { + return getYangModeledReturnType(method, 0); + } else if (Map.class.isAssignableFrom(returnType)) { + return getYangModeledReturnType(method, 1); } - if (List.class.isAssignableFrom(returnType)) { - try { - return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> { - return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap( - result -> result instanceof Class && DataContainer.class.isAssignableFrom((Class) result) - ? Optional.of((Class) result) : Optional.empty()); - }); - } catch (Exception e) { - /* - * It is safe to log this this exception on debug, since this - * method should not fail. Only failures are possible if the - * runtime / backing. - */ - LOG.debug("Unable to find YANG modeled return type for {}", method, e); + return Optional.empty(); + } + + @SuppressWarnings("checkstyle:illegalCatch") + private static Optional> getYangModeledReturnType(final Method method, + final int parameterOffset) { + try { + return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), + () -> genericParameter(method.getGenericReturnType(), parameterOffset) + .flatMap(result -> result instanceof Class ? optionalCast((Class) result) : Optional.empty())); + } catch (Exception e) { + /* + * It is safe to log this this exception on debug, since this + * method should not fail. Only failures are possible if the + * runtime / backing. + */ + LOG.debug("Unable to find YANG modeled return type for {}", method, e); + } + return Optional.empty(); + } + + private static Optional> optionalCast(final Class type) { + return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty(); + } + + private static Optional> optionalDataContainer(final Class type) { + return Optional.of(type.asSubclass(DataContainer.class)); + } + + private static Optional genericParameter(final Type type, final int offset) { + if (type instanceof ParameterizedType) { + final Type[] parameters = ((ParameterizedType) type).getActualTypeArguments(); + if (parameters.length > offset) { + return Optional.of(parameters[offset]); } } return Optional.empty(); @@ -509,18 +576,11 @@ public final class BindingReflections { * @throws IllegalArgumentException If supplied class was not derived from YANG model. */ // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types. - @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" }) + @SuppressWarnings({ "rawtypes", "unchecked" }) private static QName computeQName(final Class key) { checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key); - YangModuleInfo moduleInfo; - try { - moduleInfo = getModuleInfo(key); - } catch (Exception e) { - throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.", - e); - } - final QName module = moduleInfo.getName(); + final QName module = getModuleInfo(key).getName(); if (Augmentation.class.isAssignableFrom(key)) { return module; } else if (isRpcType(key)) { @@ -539,18 +599,6 @@ public final class BindingReflections { } } - /** - * Extracts augmentation from Binding DTO field using reflection. - * - * @param input - * Instance of DataObject which is augmentable and may contain - * augmentation - * @return Map of augmentations if read was successful, otherwise empty map. - */ - public static Map>, Augmentation> getAugmentations(final Augmentable input) { - return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input); - } - /** * Determines if two augmentation classes or case classes represents same * data. @@ -579,6 +627,11 @@ public final class BindingReflections { * Class which should be used at particular subtree * @return true if and only if classes represents same data. */ + // FIXME: this really should live in BindingRuntimeTypes and should not be based on reflection. The only user is + // binding-dom-codec and the logic could easily be performed on GeneratedType instead. For a particular + // world this boils down to a matrix, which can be calculated either on-demand or when we create + // BindingRuntimeTypes. Achieving that will bring us one step closer to being able to have a pre-compiled + // Binding Runtime. @SuppressWarnings({ "rawtypes", "unchecked" }) public static boolean isSubstitutionFor(final Class potential, final Class target) { Set subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces())); @@ -592,6 +645,11 @@ public final class BindingReflections { return false; } for (Method potentialMethod : potential.getMethods()) { + if (Modifier.isStatic(potentialMethod.getModifiers())) { + // Skip any static methods, as we are not interested in those + continue; + } + try { Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes()); if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {