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.Method;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Dictionary;
26 import java.util.HashMap;
27 import java.util.List;
30 import org.apache.commons.lang3.StringUtils;
31 import org.apache.commons.lang3.text.WordUtils;
32 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * Introspects on a DatastoreContext instance to set its properties via reflection.
40 * @author Thomas Pantelis
42 public class DatastoreContextIntrospector {
43 private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
45 private static final Map<String, Class<?>> DATA_STORE_PROP_TYPES = new HashMap<>();
47 private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
49 private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
51 private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
55 introspectDatastoreContextBuilder();
56 introspectDataStoreProperties();
57 introspectPrimitiveTypes();
58 } catch (IntrospectionException e) {
59 LOG.error("Error initializing DatastoreContextIntrospector", e);
64 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
65 * constructor that takes a single String argument. For primitive wrappers, this constructor
66 * converts from a String representation.
68 @SuppressWarnings("checkstyle:IllegalCatch")
69 private static void introspectPrimitiveTypes() {
71 Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
72 Primitives.allWrapperTypes()).add(String.class).build();
73 for (Class<?> primitive: primitives) {
75 processPropertyType(primitive);
76 } catch (Exception e) {
77 // Ignore primitives that can't be constructed from a String, eg Character and Void.
83 * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
84 * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
85 * follow the bean property naming convention, ie setter prefixed with "set", so look for all
86 * the methods that return Builder.
88 private static void introspectDatastoreContextBuilder() {
89 for (Method method: Builder.class.getMethods()) {
90 if (Builder.class.equals(method.getReturnType())) {
91 BUILDER_SETTERS.put(method.getName(), method);
97 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
98 * yang grouping. We use the bean Introspector to find the types of all the properties defined
99 * in the interface (this is the type returned from the getter method). For each type, we find
100 * the appropriate constructor that we will use.
102 private static void introspectDataStoreProperties() throws IntrospectionException {
103 BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
104 for (PropertyDescriptor desc: beanInfo.getPropertyDescriptors()) {
105 processDataStoreProperty(desc.getName(), desc.getPropertyType());
108 // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
109 // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
110 // "is" is only supported if it returns primitive boolean. So we'll check for these via
111 // getMethodDescriptors.
112 for (MethodDescriptor desc: beanInfo.getMethodDescriptors()) {
113 String methodName = desc.getName();
114 if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
115 String propertyName = WordUtils.uncapitalize(methodName.substring(2));
116 processDataStoreProperty(propertyName, Boolean.class);
122 * Processes a property defined on the DataStoreProperties interface.
124 @SuppressWarnings("checkstyle:IllegalCatch")
125 private static void processDataStoreProperty(String name, Class<?> propertyType) {
126 Preconditions.checkArgument(BUILDER_SETTERS.containsKey(name), String.format(
127 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
130 processPropertyType(propertyType);
131 DATA_STORE_PROP_TYPES.put(name, propertyType);
132 } catch (Exception e) {
133 LOG.error("Error finding constructor for type {}", propertyType, e);
138 * Finds the appropriate constructor for the specified type that we will use to construct
141 private static void processPropertyType(Class<?> propertyType) throws Exception {
142 Class<?> wrappedType = Primitives.wrap(propertyType);
143 if (CONSTRUCTORS.containsKey(wrappedType)) {
147 // If the type is a primitive (or String type), we look for the constructor that takes a
148 // single String argument, which, for primitives, validates and converts from a String
149 // representation which is the form we get on ingress.
150 if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
151 CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
153 // This must be a yang-defined type. We need to find the constructor that takes a
154 // primitive as the only argument. This will be used to construct instances to perform
155 // validation (eg range checking). The yang-generated types have a couple single-argument
156 // constructors but the one we want has the bean ConstructorProperties annotation.
157 for (Constructor<?> ctor: propertyType.getConstructors()) {
158 ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
159 if (ctor.getParameterTypes().length == 1 && ctorPropsAnnotation != null) {
160 findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
161 CONSTRUCTORS.put(propertyType, ctor);
169 * Finds the getter method on a yang-generated type for the specified property name.
171 private static void findYangTypeGetter(Class<?> type, String propertyName)
173 for (PropertyDescriptor desc: Introspector.getBeanInfo(type).getPropertyDescriptors()) {
174 if (desc.getName().equals(propertyName)) {
175 YANG_TYPE_GETTERS.put(type, desc.getReadMethod());
180 throw new IllegalArgumentException(String.format(
181 "Getter method for constructor property %s not found for YANG type %s",
182 propertyName, type));
185 private DatastoreContext context;
186 private Map<String, Object> currentProperties;
188 public DatastoreContextIntrospector(DatastoreContext context) {
189 this.context = context;
192 public DatastoreContext getContext() {
196 public DatastoreContextFactory newContextFactory() {
197 return new DatastoreContextFactory(this);
200 public synchronized DatastoreContext getShardDatastoreContext(String forShardName) {
201 if (currentProperties == null) {
205 Builder builder = DatastoreContext.newBuilderFrom(context);
206 String dataStoreTypePrefix = context.getDataStoreName() + '.';
207 final String shardNamePrefix = forShardName + '.';
209 List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
211 for (String key: keys) {
212 Object value = currentProperties.get(key);
213 if (key.startsWith(dataStoreTypePrefix)) {
214 key = key.replaceFirst(dataStoreTypePrefix, "");
217 if (key.startsWith(shardNamePrefix)) {
218 key = key.replaceFirst(shardNamePrefix, "");
219 convertValueAndInvokeSetter(key, value, builder);
223 return builder.build();
227 * Applies the given properties to the cached DatastoreContext and yields a new DatastoreContext
228 * instance which can be obtained via {@link #getContext()}.
230 * @param properties the properties to apply
231 * @return true if the cached DatastoreContext was updated, false otherwise.
233 public synchronized boolean update(Dictionary<String, Object> properties) {
234 currentProperties = null;
235 if (properties == null || properties.isEmpty()) {
239 LOG.debug("In update: properties: {}", properties);
241 ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
243 Builder builder = DatastoreContext.newBuilderFrom(context);
245 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
247 List<String> keys = getSortedKeysByDatastoreType(Collections.list(properties.keys()), dataStoreTypePrefix);
249 boolean updated = false;
250 for (String key: keys) {
251 Object value = properties.get(key);
252 mapBuilder.put(key, value);
254 // If the key is prefixed with the data store type, strip it off.
255 if (key.startsWith(dataStoreTypePrefix)) {
256 key = key.replaceFirst(dataStoreTypePrefix, "");
259 if (convertValueAndInvokeSetter(key, value, builder)) {
264 currentProperties = mapBuilder.build();
267 context = builder.build();
273 private static ArrayList<String> getSortedKeysByDatastoreType(Collection<String> inKeys,
274 final String dataStoreTypePrefix) {
275 // Sort the property keys by putting the names prefixed with the data store type last. This
276 // is done so data store specific settings are applied after global settings.
277 ArrayList<String> keys = new ArrayList<>(inKeys);
278 Collections.sort(keys, (key1, key2) -> key1.startsWith(dataStoreTypePrefix) ? 1 :
279 key2.startsWith(dataStoreTypePrefix) ? -1 : key1.compareTo(key2));
283 @SuppressWarnings("checkstyle:IllegalCatch")
284 private boolean convertValueAndInvokeSetter(String inKey, Object inValue, Builder builder) {
285 String key = convertToCamelCase(inKey);
288 // Convert the value to the right type.
289 Object value = convertValue(key, inValue);
294 LOG.debug("Converted value for property {}: {} ({})",
295 key, value, value.getClass().getSimpleName());
297 // Call the setter method on the Builder instance.
298 Method setter = BUILDER_SETTERS.get(key);
299 setter.invoke(builder, constructorValueRecursively(
300 Primitives.wrap(setter.getParameterTypes()[0]), value.toString()));
303 } catch (Exception e) {
304 LOG.error("Error converting value ({}) for property {}", inValue, key, e);
310 private static String convertToCamelCase(String inString) {
311 String str = inString.trim();
312 if (StringUtils.contains(str, '-') || StringUtils.contains(str, ' ')) {
313 str = inString.replace('-', ' ');
314 str = WordUtils.capitalizeFully(str);
315 str = StringUtils.deleteWhitespace(str);
318 return StringUtils.uncapitalize(str);
321 private Object convertValue(String name, Object from) throws Exception {
322 Class<?> propertyType = DATA_STORE_PROP_TYPES.get(name);
323 if (propertyType == null) {
324 LOG.debug("Property not found for {}", name);
328 LOG.debug("Type for property {}: {}, converting value {} ({})",
329 name, propertyType.getSimpleName(), from, from.getClass().getSimpleName());
331 // Recurse the chain of constructors depth-first to get the resulting value. Eg, if the
332 // property type is the yang-generated NonZeroUint32Type, it's constructor takes a Long so
333 // we have to first construct a Long instance from the input value.
334 Object converted = constructorValueRecursively(propertyType, from.toString());
336 // If the converted type is a yang-generated type, call the getter to obtain the actual value.
337 Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
338 if (getter != null) {
339 converted = getter.invoke(converted);
345 private Object constructorValueRecursively(Class<?> toType, Object fromValue) throws Exception {
346 LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
347 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
349 Constructor<?> ctor = CONSTRUCTORS.get(toType);
351 LOG.trace("Found {}", ctor);
354 throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
357 Object value = fromValue;
359 // Since the original input type is a String, once we find a constructor that takes a String
360 // argument, we're done recursing.
361 if (!ctor.getParameterTypes()[0].equals(String.class)) {
362 value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
365 return ctor.newInstance(value);