2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.binding.util;
10 import com.google.common.base.Preconditions;
11 import com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import java.lang.reflect.Field;
15 import java.util.Collections;
17 import org.opendaylight.yangtools.yang.binding.Augmentation;
18 import org.opendaylight.yangtools.yang.binding.BindingMapping;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 abstract class AugmentationFieldGetter {
24 private static final Logger LOG = LoggerFactory.getLogger(AugmentationFieldGetter.class);
26 private static final AugmentationFieldGetter DUMMY = new AugmentationFieldGetter() {
28 protected Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input) {
29 return Collections.emptyMap();
35 * Retrieves augmentations from supplied object
37 * @param input Input Data object, from which augmentations should be extracted
38 * @return Map of Augmentation class to augmentation
40 protected abstract Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input);
42 private static final LoadingCache<Class<?>, AugmentationFieldGetter> AUGMENTATION_GETTERS =
43 CacheBuilder.newBuilder().weakKeys().softValues().build(new AugmentationGetterLoader());
45 public static AugmentationFieldGetter getGetter(final Class<? extends Object> clz) {
46 return AUGMENTATION_GETTERS.getUnchecked(clz);
49 private static final class AugmentationGetterLoader extends CacheLoader<Class<?>, AugmentationFieldGetter> {
52 public AugmentationFieldGetter load(final Class<?> key) throws Exception {
55 field = key.getDeclaredField(BindingMapping.AUGMENTATION_FIELD);
56 } catch (NoSuchFieldException | SecurityException e) {
57 LOG.debug("Failed to acquire augmentation field", e);
60 field.setAccessible(true);
62 return new ReflectionAugmentationFieldGetter(field);
66 private static final class ReflectionAugmentationFieldGetter extends AugmentationFieldGetter {
67 private final Field augmentationField;
69 ReflectionAugmentationFieldGetter(final Field augmentationField) {
70 this.augmentationField = Preconditions.checkNotNull(augmentationField);
74 @SuppressWarnings("unchecked")
75 protected Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input) {
77 return (Map<Class<? extends Augmentation<?>>, Augmentation<?>>) augmentationField.get(input);
78 } catch (IllegalArgumentException | IllegalAccessException e) {
79 throw new IllegalStateException("Failed to access augmentation field", e);