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 com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.primitives.Primitives;
14 import java.beans.BeanInfo;
15 import java.beans.ConstructorProperties;
16 import java.beans.IntrospectionException;
17 import java.beans.Introspector;
18 import java.beans.MethodDescriptor;
19 import java.beans.PropertyDescriptor;
20 import java.lang.reflect.Constructor;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
30 import javax.annotation.concurrent.GuardedBy;
31 import org.apache.commons.lang3.StringUtils;
32 import org.apache.commons.text.WordUtils;
33 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * Introspects on a DatastoreContext instance to set its properties via reflection.
41 * @author Thomas Pantelis
43 public class DatastoreContextIntrospector {
44 private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
46 private static final Map<String, Class<?>> DATA_STORE_PROP_TYPES = new HashMap<>();
48 private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
50 private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
52 private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
56 introspectDatastoreContextBuilder();
57 introspectDataStoreProperties();
58 introspectPrimitiveTypes();
59 } catch (final IntrospectionException e) {
60 LOG.error("Error initializing DatastoreContextIntrospector", e);
65 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
66 * constructor that takes a single String argument. For primitive wrappers, this constructor
67 * converts from a String representation.
69 // Disables "Either log or rethrow this exception" sonar warning
70 @SuppressWarnings("squid:S1166")
71 private static void introspectPrimitiveTypes() {
72 final Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
73 Primitives.allWrapperTypes()).add(String.class).build();
74 for (final Class<?> primitive: primitives) {
76 processPropertyType(primitive);
77 } catch (final NoSuchMethodException e) {
78 // Ignore primitives that can't be constructed from a String, eg Character and Void.
79 } catch (SecurityException | IntrospectionException e) {
80 LOG.error("Error introspect primitive type {}", primitive, e);
86 * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
87 * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
88 * follow the bean property naming convention, ie setter prefixed with "set", so look for all
89 * the methods that return Builder.
91 private static void introspectDatastoreContextBuilder() {
92 for (final Method method: Builder.class.getMethods()) {
93 if (Builder.class.equals(method.getReturnType())) {
94 BUILDER_SETTERS.put(method.getName(), method);
100 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
101 * yang grouping. We use the bean Introspector to find the types of all the properties defined
102 * in the interface (this is the type returned from the getter method). For each type, we find
103 * the appropriate constructor that we will use.
105 private static void introspectDataStoreProperties() throws IntrospectionException {
106 final BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
107 for (final PropertyDescriptor desc: beanInfo.getPropertyDescriptors()) {
108 processDataStoreProperty(desc.getName(), desc.getPropertyType());
111 // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
112 // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
113 // "is" is only supported if it returns primitive boolean. So we'll check for these via
114 // getMethodDescriptors.
115 for (final MethodDescriptor desc: beanInfo.getMethodDescriptors()) {
116 final String methodName = desc.getName();
117 if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
118 final String propertyName = WordUtils.uncapitalize(methodName.substring(2));
119 processDataStoreProperty(propertyName, Boolean.class);
125 * Processes a property defined on the DataStoreProperties interface.
127 @SuppressWarnings("checkstyle:IllegalCatch")
128 private static void processDataStoreProperty(final String name, final Class<?> propertyType) {
129 Preconditions.checkArgument(BUILDER_SETTERS.containsKey(name), String.format(
130 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
133 processPropertyType(propertyType);
134 DATA_STORE_PROP_TYPES.put(name, propertyType);
135 } catch (final Exception e) {
136 LOG.error("Error finding constructor for type {}", propertyType, e);
141 * Finds the appropriate constructor for the specified type that we will use to construct
144 private static void processPropertyType(final Class<?> propertyType)
145 throws NoSuchMethodException, SecurityException, IntrospectionException {
146 final Class<?> wrappedType = Primitives.wrap(propertyType);
147 if (CONSTRUCTORS.containsKey(wrappedType)) {
151 // If the type is a primitive (or String type), we look for the constructor that takes a
152 // single String argument, which, for primitives, validates and converts from a String
153 // representation which is the form we get on ingress.
154 if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
155 CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
157 // This must be a yang-defined type. We need to find the constructor that takes a
158 // primitive as the only argument. This will be used to construct instances to perform
159 // validation (eg range checking). The yang-generated types have a couple single-argument
160 // constructors but the one we want has the bean ConstructorProperties annotation.
161 for (final Constructor<?> ctor: propertyType.getConstructors()) {
162 final ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
163 if (ctor.getParameterTypes().length == 1 && ctorPropsAnnotation != null) {
164 findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
165 CONSTRUCTORS.put(propertyType, ctor);
173 * Finds the getter method on a yang-generated type for the specified property name.
175 private static void findYangTypeGetter(final Class<?> type, final String propertyName)
176 throws IntrospectionException {
177 for (final PropertyDescriptor desc: Introspector.getBeanInfo(type).getPropertyDescriptors()) {
178 if (desc.getName().equals(propertyName)) {
179 YANG_TYPE_GETTERS.put(type, desc.getReadMethod());
184 throw new IntrospectionException(String.format(
185 "Getter method for constructor property %s not found for YANG type %s",
186 propertyName, type));
189 @GuardedBy(value = "this")
190 private DatastoreContext context;
191 @GuardedBy(value = "this")
192 private Map<String, Object> currentProperties;
194 public DatastoreContextIntrospector(final DatastoreContext context) {
195 this.context = context;
198 public synchronized DatastoreContext getContext() {
202 public DatastoreContextFactory newContextFactory() {
203 return new DatastoreContextFactory(this);
206 public synchronized DatastoreContext getShardDatastoreContext(final String forShardName) {
207 if (currentProperties == null) {
211 final Builder builder = DatastoreContext.newBuilderFrom(context);
212 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
213 final String shardNamePrefix = forShardName + '.';
215 final List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
217 for (String key: keys) {
218 final Object value = currentProperties.get(key);
219 if (key.startsWith(dataStoreTypePrefix)) {
220 key = key.replaceFirst(dataStoreTypePrefix, "");
223 if (key.startsWith(shardNamePrefix)) {
224 key = key.replaceFirst(shardNamePrefix, "");
225 convertValueAndInvokeSetter(key, value, builder);
229 return builder.build();
233 * Applies the given properties to the cached DatastoreContext and yields a new DatastoreContext
234 * instance which can be obtained via {@link #getContext()}.
236 * @param properties the properties to apply
237 * @return true if the cached DatastoreContext was updated, false otherwise.
239 public synchronized boolean update(final Map<String, Object> properties) {
240 currentProperties = null;
241 if (properties == null || properties.isEmpty()) {
245 LOG.debug("In update: properties: {}", properties);
247 final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
249 final Builder builder = DatastoreContext.newBuilderFrom(context);
251 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
253 final List<String> keys = getSortedKeysByDatastoreType(properties.keySet(), dataStoreTypePrefix);
255 boolean updated = false;
256 for (String key: keys) {
257 final Object value = properties.get(key);
258 mapBuilder.put(key, value);
260 // If the key is prefixed with the data store type, strip it off.
261 if (key.startsWith(dataStoreTypePrefix)) {
262 key = key.replaceFirst(dataStoreTypePrefix, "");
265 if (convertValueAndInvokeSetter(key, value, builder)) {
270 currentProperties = mapBuilder.build();
273 context = builder.build();
279 private static ArrayList<String> getSortedKeysByDatastoreType(final Collection<String> inKeys,
280 final String dataStoreTypePrefix) {
281 // Sort the property keys by putting the names prefixed with the data store type last. This
282 // is done so data store specific settings are applied after global settings.
283 final ArrayList<String> keys = new ArrayList<>(inKeys);
284 Collections.sort(keys, (key1, key2) -> key1.startsWith(dataStoreTypePrefix) ? 1 :
285 key2.startsWith(dataStoreTypePrefix) ? -1 : key1.compareTo(key2));
289 @SuppressWarnings("checkstyle:IllegalCatch")
290 private boolean convertValueAndInvokeSetter(final String inKey, final Object inValue, final Builder builder) {
291 final String key = convertToCamelCase(inKey);
294 // Convert the value to the right type.
295 final Object value = convertValue(key, inValue);
300 LOG.debug("Converted value for property {}: {} ({})",
301 key, value, value.getClass().getSimpleName());
303 // Call the setter method on the Builder instance.
304 final Method setter = BUILDER_SETTERS.get(key);
305 setter.invoke(builder, constructorValueRecursively(
306 Primitives.wrap(setter.getParameterTypes()[0]), value.toString()));
309 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
310 | InstantiationException e) {
311 LOG.error("Error converting value ({}) for property {}", inValue, key, e);
317 private static String convertToCamelCase(final String inString) {
318 String str = inString.trim();
319 if (StringUtils.contains(str, '-') || StringUtils.contains(str, ' ')) {
320 str = inString.replace('-', ' ');
321 str = WordUtils.capitalizeFully(str);
322 str = StringUtils.deleteWhitespace(str);
325 return StringUtils.uncapitalize(str);
328 private Object convertValue(final String name, final Object from)
329 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
330 final Class<?> propertyType = DATA_STORE_PROP_TYPES.get(name);
331 if (propertyType == null) {
332 LOG.debug("Property not found for {}", name);
336 LOG.debug("Type for property {}: {}, converting value {} ({})",
337 name, propertyType.getSimpleName(), from, from.getClass().getSimpleName());
339 // Recurse the chain of constructors depth-first to get the resulting value. Eg, if the
340 // property type is the yang-generated NonZeroUint32Type, it's constructor takes a Long so
341 // we have to first construct a Long instance from the input value.
342 Object converted = constructorValueRecursively(propertyType, from.toString());
344 // If the converted type is a yang-generated type, call the getter to obtain the actual value.
345 final Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
346 if (getter != null) {
347 converted = getter.invoke(converted);
353 private Object constructorValueRecursively(final Class<?> toType, final Object fromValue)
354 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
355 LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
356 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
358 final Constructor<?> ctor = CONSTRUCTORS.get(toType);
360 LOG.trace("Found {}", ctor);
363 throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
366 Object value = fromValue;
368 // Since the original input type is a String, once we find a constructor that takes a String
369 // argument, we're done recursing.
370 if (!ctor.getParameterTypes()[0].equals(String.class)) {
371 value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
374 return ctor.newInstance(value);