import static java.util.Objects.requireNonNull;
import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
-import com.google.common.collect.ImmutableSortedMap;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
-import java.util.Collection;
+import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
-import java.util.SortedMap;
-import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-import java.util.function.Function;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
import org.opendaylight.mdsal.binding.model.api.Type;
+import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
private static final Augmentations EMPTY_AUGMENTATIONS = new Augmentations(ImmutableMap.of(), ImmutableMap.of());
+ private static final Method[] EMPTY_METHODS = new Method[0];
private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
- private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
- private final ImmutableMap<Method, NodeContextSupplier> nonnullMethods;
+ private final ImmutableMap<String, NodeContextSupplier> byMethod;
+ private final ImmutableMap<String, String> nonnullToGetter;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
private final MethodHandle proxyConstructor;
+ private final Method[] propertyMethods;
@SuppressWarnings("rawtypes")
private static final AtomicReferenceFieldUpdater<DataObjectCodecContext, Augmentations>
final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
- final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
+ final Map<Method, NodeContextSupplier> tmpMethodToSupplier = new HashMap<>();
final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
// Adds leaves to mapping
for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
- byMethodBuilder.put(leaf.getGetter(), leaf);
+ tmpMethodToSupplier.put(leaf.getGetter(), leaf);
byYangBuilder.put(leaf.getDomPathArgument(), leaf);
}
final Method method = childDataObj.getValue();
verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
- byMethodBuilder.put(method, childProto);
+ tmpMethodToSupplier.put(method, childProto);
byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
byYangBuilder.put(childProto.getYangArg(), childProto);
if (childProto.isChoice()) {
}
}
}
- this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
+
+ final int methodCount = tmpMethodToSupplier.size();
+ final Builder<String, NodeContextSupplier> byMethodBuilder = ImmutableMap.builderWithExpectedSize(methodCount);
+ this.propertyMethods = methodCount == 0 ? EMPTY_METHODS : new Method[methodCount];
+
+ int offset = 0;
+ for (Entry<Method, NodeContextSupplier> entry : tmpMethodToSupplier.entrySet()) {
+ final Method method = entry.getKey();
+ propertyMethods[offset++] = method;
+ byMethodBuilder.put(method.getName(), entry.getValue());
+ }
+
+ // Make sure properties are alpha-sorted
+ Arrays.sort(propertyMethods, METHOD_BY_ALPHABET);
+
+ this.byMethod = byMethodBuilder.build();
this.byYang = ImmutableMap.copyOf(byYangBuilder);
this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
byBindingArgClassBuilder.putAll(byStreamClass);
this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
final Map<Class<?>, Method> clsToNonnull = BindingReflections.getChildrenClassToNonnullMethod(bindingClass);
- final Map<Method, NodeContextSupplier> nonnullMethodsBuilder = new HashMap<>();
+ final Map<String, String> nonnullToGetterBuilder = new HashMap<>();
for (final Entry<Class<?>, Method> entry : clsToNonnull.entrySet()) {
final Method method = entry.getValue();
if (!method.isDefault()) {
LOG.warn("Ignoring non-default method {} in {}", method, bindingClass);
continue;
}
- final DataContainerCodecPrototype<?> supplier = byStreamClass.get(entry.getKey());
- if (supplier != null) {
- nonnullMethodsBuilder.put(method, supplier);
- } else {
- LOG.warn("Failed to look up data handler for method {}", method);
- }
- }
- nonnullMethods = ImmutableMap.copyOf(nonnullMethodsBuilder);
+ // Derive getter name from the nonnull method and verify we have the corresponding getter. Note that
+ // the intern() call is important, as it makes sure we use the same instance to bridge to byMethod map.
+ final String methodName = method.getName();
+ final String getterName = BindingMapping.getGetterMethodForNonnull(methodName).intern();
+ verify(byMethod.containsKey(getterName), "Cannot find getter %s for %s", getterName, methodName);
+ nonnullToGetterBuilder.put(methodName, getterName);
+ }
+ nonnullToGetter = ImmutableMap.copyOf(nonnullToGetterBuilder);
if (Augmentable.class.isAssignableFrom(bindingClass)) {
this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
}
- Object getBindingChildValue(final Method method, final NormalizedNodeContainer<?, ?, ?> domData) {
- return method.isDefault() ? getBindingChildValue(nonnullMethods, method, domData, dummy -> ImmutableList.of())
- : getBindingChildValue(byMethod, method, domData, NodeCodecContext::defaultObject);
+ // Unlike BindingMapping.getGetterMethodForNonnull() this returns an interned String
+ @NonNull String getterNameForNonnullName(final String nonnullMethod) {
+ return verifyNotNull(nonnullToGetter.get(nonnullMethod), "Failed to look up getter method for %s",
+ nonnullMethod);
}
@SuppressWarnings("rawtypes")
- private static Object getBindingChildValue(final ImmutableMap<Method, NodeContextSupplier> map, final Method method,
- final NormalizedNodeContainer domData, final Function<NodeCodecContext<?>, Object> getDefaultObject) {
- final NodeCodecContext<?> childContext = verifyNotNull(map.get(method),
+ @Nullable Object getBindingChildValue(final String method, final NormalizedNodeContainer domData) {
+ final NodeCodecContext<?> childContext = verifyNotNull(byMethod.get(method),
"Cannot find data handler for method %s", method).get();
@SuppressWarnings("unchecked")
// We do not want to use Optional.map() here because we do not want to invoke defaultObject() when we have
// normal value because defaultObject() may end up throwing an exception intentionally.
- return domChild.isPresent() ? childContext.deserializeObject(domChild.get())
- : getDefaultObject.apply(childContext);
+ return domChild.isPresent() ? childContext.deserializeObject(domChild.get()) : childContext.defaultObject();
}
@SuppressWarnings("checkstyle:illegalCatch")
return map;
}
- Collection<Method> getHashCodeAndEqualsMethods() {
- return byMethod.keySet();
+ final Method[] propertyMethods() {
+ return propertyMethods;
}
@Override
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
import org.opendaylight.yangtools.yang.binding.Augmentable;
private static final String EQUALS = "equals";
private static final String HASHCODE = "hashCode";
private static final String AUGMENTATIONS = "augmentations";
- private static final Object NULL_VALUE = new Object();
+ private static final @NonNull Object NULL_VALUE = new Object();
+ // Method.getName() is guaranteed to be interned and all getter methods have zero arguments, name is sufficient to
+ // identify the data, skipping Method.hashCode() computation.
private final ConcurrentHashMap<String, Object> cachedData = new ConcurrentHashMap<>();
private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
private final DataObjectCodecContext<D,?> context;
public Object invoke(final Object proxy, final Method method, final Object[] args) {
switch (method.getParameterCount()) {
case 0:
- switch (method.getName()) {
+ final String methodName = method.getName();
+ switch (methodName) {
case DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME:
return context.getBindingClass();
case TO_STRING:
case AUGMENTATIONS:
return getAugmentationsImpl();
default:
- return getBindingData(method);
+ return method.isDefault() ? nonnullBindingData(methodName) : getBindingData(methodName);
}
case 1:
switch (method.getName()) {
return false;
}
try {
- for (final Method m : context.getHashCodeAndEqualsMethods()) {
- final Object thisValue = getBindingData(m);
+ for (final Method m : context.propertyMethods()) {
+ final Object thisValue = getBindingData(m.getName());
final Object otherValue = m.invoke(other);
/*
- * added for valid byte array comparison, when list key type is binary
- * deepEquals is not used since it does excessive amount of instanceof calls.
- */
+ * added for valid byte array comparison, when list key type is binary
+ * deepEquals is not used since it does excessive amount of instanceof calls.
+ */
if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
return false;
final int prime = 31;
int result = 1;
- for (final Method m : context.getHashCodeAndEqualsMethods()) {
- final Object value = getBindingData(m);
+ for (final Method m : context.propertyMethods()) {
+ final Object value = getBindingData(m.getName());
result = prime * result + Objects.hashCode(value);
}
if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
return ret;
}
- private Object getBindingData(final Method method) {
- // Guaranteed to be interned and since method has zero arguments, name is sufficient to identify the data,
- // skipping Method.hashCode() computation.
- final String methodName = method.getName();
- Object cached = cachedData.get(methodName);
- if (cached == null) {
- final Object readedValue = context.getBindingChildValue(method, data);
- cached = readedValue == null ? NULL_VALUE : readedValue;
+ private Object nonnullBindingData(final String methodName) {
+ final Object value = getBindingData(context.getterNameForNonnullName(methodName));
+ return value != null ? value : ImmutableList.of();
+ }
- final Object raced = cachedData.putIfAbsent(methodName, cached);
- if (raced != null) {
- // Load/store raced, we should return the stored value
- cached = raced;
- }
+ // Internal invocation, can only target getFoo() methods
+ private Object getBindingData(final String methodName) {
+ final Object cached = cachedData.get(methodName);
+ if (cached != null) {
+ return unmaskNull(cached);
}
- return cached == NULL_VALUE ? null : cached;
+ final Object value = context.getBindingChildValue(methodName, data);
+ final Object raced = cachedData.putIfAbsent(methodName, value == null ? NULL_VALUE : value);
+ // If we raced we need to return previously-stored value
+ return raced != null ? unmaskNull(raced) : value;
+ }
+
+ private static Object unmaskNull(final @NonNull Object masked) {
+ return masked == NULL_VALUE ? null : masked;
}
private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
final Class<D> bindingClass = context.getBindingClass();
final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
- for (final Method m : context.getHashCodeAndEqualsMethods()) {
- helper.add(m.getName(), getBindingData(m));
+ for (final Method m : context.propertyMethods()) {
+ final String methodName = m.getName();
+ helper.add(methodName, getBindingData(methodName));
}
if (Augmentable.class.isAssignableFrom(bindingClass)) {
helper.add("augmentations", getAugmentationsImpl());