2 * Copyright (c) 2015 Brocade Communications 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.controller.cluster.datastore;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.primitives.Primitives;
15 import java.beans.BeanInfo;
16 import java.beans.ConstructorProperties;
17 import java.beans.IntrospectionException;
18 import java.beans.Introspector;
19 import java.beans.MethodDescriptor;
20 import java.beans.PropertyDescriptor;
21 import java.lang.reflect.Constructor;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.AbstractMap.SimpleImmutableEntry;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import org.apache.commons.lang3.StringUtils;
33 import org.apache.commons.text.WordUtils;
34 import org.checkerframework.checker.lock.qual.GuardedBy;
35 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
36 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
37 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Introspects on a DatastoreContext instance to set its properties via reflection.
49 * @author Thomas Pantelis
51 public class DatastoreContextIntrospector {
52 private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
54 private static final Map<String, Entry<Class<?>, Method>> DATA_STORE_PROP_INFO = new HashMap<>();
56 private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
58 private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
60 private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
64 introspectDatastoreContextBuilder();
65 introspectDataStoreProperties();
66 introspectPrimitiveTypes();
67 } catch (final IntrospectionException e) {
68 LOG.error("Error initializing DatastoreContextIntrospector", e);
73 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
74 * constructor that takes a single String argument. For primitive wrappers, this constructor
75 * converts from a String representation.
77 // Disables "Either log or rethrow this exception" sonar warning
78 @SuppressWarnings("squid:S1166")
79 private static void introspectPrimitiveTypes() {
80 final Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
81 Primitives.allWrapperTypes()).add(String.class).build();
82 for (final Class<?> primitive: primitives) {
84 processPropertyType(primitive);
85 } catch (final NoSuchMethodException e) {
86 // Ignore primitives that can't be constructed from a String, eg Character and Void.
87 } catch (SecurityException | IntrospectionException e) {
88 LOG.error("Error introspect primitive type {}", primitive, e);
94 * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
95 * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
96 * follow the bean property naming convention, ie setter prefixed with "set", so look for all
97 * the methods that return Builder.
99 private static void introspectDatastoreContextBuilder() {
100 for (final Method method: Builder.class.getMethods()) {
101 if (Builder.class.equals(method.getReturnType())) {
102 BUILDER_SETTERS.put(method.getName(), method);
108 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
109 * yang grouping. We use the bean Introspector to find the types of all the properties defined
110 * in the interface (this is the type returned from the getter method). For each type, we find
111 * the appropriate constructor that we will use.
113 private static void introspectDataStoreProperties() throws IntrospectionException {
114 final BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
115 for (final PropertyDescriptor desc: beanInfo.getPropertyDescriptors()) {
116 processDataStoreProperty(desc.getName(), desc.getPropertyType(), desc.getReadMethod());
119 // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
120 // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
121 // "is" is only supported if it returns primitive boolean. So we'll check for these via
122 // getMethodDescriptors.
123 for (final MethodDescriptor desc: beanInfo.getMethodDescriptors()) {
124 final String methodName = desc.getName();
125 if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
126 final String propertyName = WordUtils.uncapitalize(methodName.substring(2));
127 processDataStoreProperty(propertyName, Boolean.class, desc.getMethod());
133 * Processes a property defined on the DataStoreProperties interface.
135 @SuppressWarnings("checkstyle:IllegalCatch")
136 private static void processDataStoreProperty(final String name, final Class<?> propertyType,
137 final Method readMethod) {
138 checkArgument(BUILDER_SETTERS.containsKey(name),
139 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
142 processPropertyType(propertyType);
143 DATA_STORE_PROP_INFO.put(name, new SimpleImmutableEntry<>(propertyType, readMethod));
144 } catch (final Exception e) {
145 LOG.error("Error finding constructor for type {}", propertyType, e);
150 * Finds the appropriate constructor for the specified type that we will use to construct
153 private static void processPropertyType(final Class<?> propertyType)
154 throws NoSuchMethodException, SecurityException, IntrospectionException {
155 final Class<?> wrappedType = Primitives.wrap(propertyType);
156 if (CONSTRUCTORS.containsKey(wrappedType)) {
160 // If the type is a primitive (or String type), we look for the constructor that takes a
161 // single String argument, which, for primitives, validates and converts from a String
162 // representation which is the form we get on ingress.
163 if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
164 CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
166 // This must be a yang-defined type. We need to find the constructor that takes a
167 // primitive as the only argument. This will be used to construct instances to perform
168 // validation (eg range checking). The yang-generated types have a couple single-argument
169 // constructors but the one we want has the bean ConstructorProperties annotation.
170 for (final Constructor<?> ctor: propertyType.getConstructors()) {
171 final ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
172 if (ctor.getParameterCount() == 1 && ctorPropsAnnotation != null) {
173 findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
174 CONSTRUCTORS.put(propertyType, ctor);
182 * Finds the getter method on a yang-generated type for the specified property name.
184 private static void findYangTypeGetter(final Class<?> type, final String propertyName)
185 throws IntrospectionException {
186 for (final PropertyDescriptor desc: Introspector.getBeanInfo(type).getPropertyDescriptors()) {
187 if (desc.getName().equals(propertyName)) {
188 YANG_TYPE_GETTERS.put(type, desc.getReadMethod());
193 throw new IntrospectionException(String.format(
194 "Getter method for constructor property %s not found for YANG type %s",
195 propertyName, type));
198 @GuardedBy(value = "this")
199 private DatastoreContext context;
200 @GuardedBy(value = "this")
201 private Map<String, Object> currentProperties;
203 public DatastoreContextIntrospector(final DatastoreContext context,
204 final BindingNormalizedNodeSerializer bindingSerializer) {
205 final QName qname = BindingReflections.findQName(DataStorePropertiesContainer.class);
206 final DataStorePropertiesContainer defaultPropsContainer = (DataStorePropertiesContainer)
207 bindingSerializer.fromNormalizedNode(bindingSerializer.toYangInstanceIdentifier(
208 InstanceIdentifier.builder(DataStorePropertiesContainer.class).build()),
209 ImmutableNodes.containerNode(qname)).getValue();
211 final Builder builder = DatastoreContext.newBuilderFrom(context);
212 for (Entry<String, Entry<Class<?>, Method>> entry: DATA_STORE_PROP_INFO.entrySet()) {
215 value = entry.getValue().getValue().invoke(defaultPropsContainer);
216 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
217 LOG.error("Error obtaining default value for property {}", entry.getKey(), e);
222 convertValueAndInvokeSetter(entry.getKey(), value, builder);
226 this.context = builder.build();
229 public synchronized DatastoreContext getContext() {
233 public DatastoreContextFactory newContextFactory() {
234 return new DatastoreContextFactory(this);
237 public synchronized DatastoreContext getShardDatastoreContext(final String forShardName) {
238 if (currentProperties == null) {
242 final Builder builder = DatastoreContext.newBuilderFrom(context);
243 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
244 final String shardNamePrefix = forShardName + '.';
246 final List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
248 for (String key: keys) {
249 final Object value = currentProperties.get(key);
250 if (key.startsWith(dataStoreTypePrefix)) {
251 key = key.replaceFirst(dataStoreTypePrefix, "");
254 if (key.startsWith(shardNamePrefix)) {
255 key = key.replaceFirst(shardNamePrefix, "");
256 convertValueAndInvokeSetter(key, value.toString(), builder);
260 return builder.build();
264 * Applies the given properties to the cached DatastoreContext and yields a new DatastoreContext
265 * instance which can be obtained via {@link #getContext()}.
267 * @param properties the properties to apply
268 * @return true if the cached DatastoreContext was updated, false otherwise.
270 public synchronized boolean update(final Map<String, Object> properties) {
271 currentProperties = null;
272 if (properties == null || properties.isEmpty()) {
276 LOG.debug("In update: properties: {}", properties);
278 final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
280 final Builder builder = DatastoreContext.newBuilderFrom(context);
282 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
284 final List<String> keys = getSortedKeysByDatastoreType(properties.keySet(), dataStoreTypePrefix);
286 boolean updated = false;
287 for (String key: keys) {
288 final Object value = properties.get(key);
289 mapBuilder.put(key, value);
291 // If the key is prefixed with the data store type, strip it off.
292 if (key.startsWith(dataStoreTypePrefix)) {
293 key = key.replaceFirst(dataStoreTypePrefix, "");
296 if (convertValueAndInvokeSetter(key, value.toString(), builder)) {
301 currentProperties = mapBuilder.build();
304 context = builder.build();
310 private static ArrayList<String> getSortedKeysByDatastoreType(final Collection<String> inKeys,
311 final String dataStoreTypePrefix) {
312 // Sort the property keys by putting the names prefixed with the data store type last. This
313 // is done so data store specific settings are applied after global settings.
314 final ArrayList<String> keys = new ArrayList<>(inKeys);
315 keys.sort((key1, key2) -> key1.startsWith(dataStoreTypePrefix) ? 1 :
316 key2.startsWith(dataStoreTypePrefix) ? -1 : key1.compareTo(key2));
320 @SuppressWarnings("checkstyle:IllegalCatch")
321 private boolean convertValueAndInvokeSetter(final String inKey, final Object inValue, final Builder builder) {
322 final String key = convertToCamelCase(inKey);
325 // Convert the value to the right type.
326 final Object value = convertValue(key, inValue);
331 LOG.debug("Converted value for property {}: {} ({})",
332 key, value, value.getClass().getSimpleName());
334 // Call the setter method on the Builder instance.
335 final Method setter = BUILDER_SETTERS.get(key);
336 setter.invoke(builder, constructorValueRecursively(
337 Primitives.wrap(setter.getParameterTypes()[0]), value.toString()));
340 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
341 | InstantiationException e) {
342 LOG.error("Error converting value ({}) for property {}", inValue, key, e);
348 private static String convertToCamelCase(final String inString) {
349 String str = inString.trim();
350 if (StringUtils.contains(str, '-') || StringUtils.contains(str, ' ')) {
351 str = inString.replace('-', ' ');
352 str = WordUtils.capitalizeFully(str);
353 str = StringUtils.deleteWhitespace(str);
356 return StringUtils.uncapitalize(str);
359 private Object convertValue(final String name, final Object from)
360 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
361 final Entry<Class<?>, Method> propertyInfo = DATA_STORE_PROP_INFO.get(name);
362 if (propertyInfo == null) {
363 LOG.debug("Property not found for {}", name);
367 final Class<?> propertyType = propertyInfo.getKey();
369 LOG.debug("Type for property {}: {}, converting value {} ({})",
370 name, propertyType.getSimpleName(), from, from.getClass().getSimpleName());
372 // Recurse the chain of constructors depth-first to get the resulting value. Eg, if the
373 // property type is the yang-generated NonZeroUint32Type, it's constructor takes a Long so
374 // we have to first construct a Long instance from the input value.
375 Object converted = constructorValueRecursively(propertyType, from);
377 // If the converted type is a yang-generated type, call the getter to obtain the actual value.
378 final Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
379 if (getter != null) {
380 converted = getter.invoke(converted);
386 private Object constructorValueRecursively(final Class<?> toType, final Object fromValue)
387 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
388 LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
389 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
391 if (toType.equals(fromValue.getClass())) {
395 final Constructor<?> ctor = CONSTRUCTORS.get(toType);
397 LOG.trace("Found {}", ctor);
400 throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
403 Object value = fromValue;
405 // Once we find a constructor that takes the original type as an argument, we're done recursing.
406 if (!ctor.getParameterTypes()[0].equals(fromValue.getClass())) {
407 value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
410 return ctor.newInstance(value);