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.Dictionary;
27 import java.util.HashMap;
28 import java.util.List;
31 import javax.annotation.concurrent.GuardedBy;
32 import org.apache.commons.lang3.StringUtils;
33 import org.apache.commons.lang3.text.WordUtils;
34 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * Introspects on a DatastoreContext instance to set its properties via reflection.
42 * @author Thomas Pantelis
44 public class DatastoreContextIntrospector {
45 private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
47 private static final Map<String, Class<?>> DATA_STORE_PROP_TYPES = new HashMap<>();
49 private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
51 private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
53 private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
57 introspectDatastoreContextBuilder();
58 introspectDataStoreProperties();
59 introspectPrimitiveTypes();
60 } catch (IntrospectionException e) {
61 LOG.error("Error initializing DatastoreContextIntrospector", e);
66 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
67 * constructor that takes a single String argument. For primitive wrappers, this constructor
68 * converts from a String representation.
70 // Disables "Either log or rethrow this exception" sonar warning
71 @SuppressWarnings("squid:S1166")
72 private static void introspectPrimitiveTypes() {
73 Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
74 Primitives.allWrapperTypes()).add(String.class).build();
75 for (Class<?> primitive: primitives) {
77 processPropertyType(primitive);
78 } catch (NoSuchMethodException e) {
79 // Ignore primitives that can't be constructed from a String, eg Character and Void.
80 } catch (SecurityException | IntrospectionException e) {
81 LOG.error("Error introspect primitive type {}", primitive, e);
87 * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
88 * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
89 * follow the bean property naming convention, ie setter prefixed with "set", so look for all
90 * the methods that return Builder.
92 private static void introspectDatastoreContextBuilder() {
93 for (Method method: Builder.class.getMethods()) {
94 if (Builder.class.equals(method.getReturnType())) {
95 BUILDER_SETTERS.put(method.getName(), method);
101 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
102 * yang grouping. We use the bean Introspector to find the types of all the properties defined
103 * in the interface (this is the type returned from the getter method). For each type, we find
104 * the appropriate constructor that we will use.
106 private static void introspectDataStoreProperties() throws IntrospectionException {
107 BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
108 for (PropertyDescriptor desc: beanInfo.getPropertyDescriptors()) {
109 processDataStoreProperty(desc.getName(), desc.getPropertyType());
112 // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
113 // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
114 // "is" is only supported if it returns primitive boolean. So we'll check for these via
115 // getMethodDescriptors.
116 for (MethodDescriptor desc: beanInfo.getMethodDescriptors()) {
117 String methodName = desc.getName();
118 if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
119 String propertyName = WordUtils.uncapitalize(methodName.substring(2));
120 processDataStoreProperty(propertyName, Boolean.class);
126 * Processes a property defined on the DataStoreProperties interface.
128 @SuppressWarnings("checkstyle:IllegalCatch")
129 private static void processDataStoreProperty(String name, Class<?> propertyType) {
130 Preconditions.checkArgument(BUILDER_SETTERS.containsKey(name), String.format(
131 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
134 processPropertyType(propertyType);
135 DATA_STORE_PROP_TYPES.put(name, propertyType);
136 } catch (Exception e) {
137 LOG.error("Error finding constructor for type {}", propertyType, e);
142 * Finds the appropriate constructor for the specified type that we will use to construct
145 private static void processPropertyType(Class<?> propertyType) throws NoSuchMethodException, SecurityException,
146 IntrospectionException {
147 Class<?> wrappedType = Primitives.wrap(propertyType);
148 if (CONSTRUCTORS.containsKey(wrappedType)) {
152 // If the type is a primitive (or String type), we look for the constructor that takes a
153 // single String argument, which, for primitives, validates and converts from a String
154 // representation which is the form we get on ingress.
155 if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
156 CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
158 // This must be a yang-defined type. We need to find the constructor that takes a
159 // primitive as the only argument. This will be used to construct instances to perform
160 // validation (eg range checking). The yang-generated types have a couple single-argument
161 // constructors but the one we want has the bean ConstructorProperties annotation.
162 for (Constructor<?> ctor: propertyType.getConstructors()) {
163 ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
164 if (ctor.getParameterTypes().length == 1 && ctorPropsAnnotation != null) {
165 findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
166 CONSTRUCTORS.put(propertyType, ctor);
174 * Finds the getter method on a yang-generated type for the specified property name.
176 private static void findYangTypeGetter(Class<?> type, String propertyName) throws IntrospectionException {
177 for (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(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(String forShardName) {
207 if (currentProperties == null) {
211 Builder builder = DatastoreContext.newBuilderFrom(context);
212 String dataStoreTypePrefix = context.getDataStoreName() + '.';
213 final String shardNamePrefix = forShardName + '.';
215 List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
217 for (String key: keys) {
218 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(Dictionary<String, Object> properties) {
240 currentProperties = null;
241 if (properties == null || properties.isEmpty()) {
245 LOG.debug("In update: properties: {}", properties);
247 ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
249 Builder builder = DatastoreContext.newBuilderFrom(context);
251 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
253 List<String> keys = getSortedKeysByDatastoreType(Collections.list(properties.keys()), dataStoreTypePrefix);
255 boolean updated = false;
256 for (String key: keys) {
257 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(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 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(String inKey, Object inValue, Builder builder) {
291 String key = convertToCamelCase(inKey);
294 // Convert the value to the right type.
295 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 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(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(String name, Object from)
329 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
330 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 Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
346 if (getter != null) {
347 converted = getter.invoke(converted);
353 private Object constructorValueRecursively(Class<?> toType, Object fromValue)
354 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
355 LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
356 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
358 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);