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.lang.reflect.Constructor;
16 import java.lang.reflect.InvocationTargetException;
17 import java.lang.reflect.Method;
18 import java.util.AbstractMap.SimpleImmutableEntry;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Locale;
25 import java.util.Map.Entry;
27 import java.util.function.Function;
28 import javax.management.ConstructorParameters;
29 import org.apache.commons.lang3.StringUtils;
30 import org.apache.commons.text.WordUtils;
31 import org.checkerframework.checker.lock.qual.GuardedBy;
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.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
35 import org.opendaylight.yangtools.yang.common.Uint16;
36 import org.opendaylight.yangtools.yang.common.Uint32;
37 import org.opendaylight.yangtools.yang.common.Uint64;
38 import org.opendaylight.yangtools.yang.common.Uint8;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * Introspects on a DatastoreContext instance to set its properties via reflection.
45 * @author Thomas Pantelis
47 public class DatastoreContextIntrospector {
48 private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
50 private static final Map<String, Entry<Class<?>, Method>> DATA_STORE_PROP_INFO = new HashMap<>();
52 private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
54 private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
56 private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
58 private static final ImmutableMap<Class<?>, Function<String, Object>> UINT_FACTORIES =
59 ImmutableMap.<Class<?>, Function<String, Object>>builder()
60 .put(Uint8.class, Uint8::valueOf)
61 .put(Uint16.class, Uint16::valueOf)
62 .put(Uint32.class, Uint32::valueOf)
63 .put(Uint64.class, Uint64::valueOf)
68 introspectDatastoreContextBuilder();
69 introspectDataStoreProperties();
70 introspectPrimitiveTypes();
71 } catch (final IllegalArgumentException e) {
72 LOG.error("Error initializing DatastoreContextIntrospector", e);
77 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
78 * constructor that takes a single String argument. For primitive wrappers, this constructor
79 * converts from a String representation.
81 // Disables "Either log or rethrow this exception" sonar warning
82 @SuppressWarnings("squid:S1166")
83 private static void introspectPrimitiveTypes() {
84 final Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
85 Primitives.allWrapperTypes()).add(String.class).build();
86 for (final Class<?> primitive : primitives) {
88 processPropertyType(primitive);
89 } catch (final NoSuchMethodException e) {
90 // Ignore primitives that can't be constructed from a String, eg Character and Void.
91 } catch (SecurityException | IllegalArgumentException e) {
92 LOG.error("Error introspect primitive type {}", primitive, e);
98 * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
99 * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
100 * follow the bean property naming convention, ie setter prefixed with "set", so look for all
101 * the methods that return Builder.
103 private static void introspectDatastoreContextBuilder() {
104 for (final Method method: Builder.class.getMethods()) {
105 if (Builder.class.equals(method.getReturnType())) {
106 BUILDER_SETTERS.put(method.getName(), method);
112 * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
113 * yang grouping. We use the bean Introspector to find the types of all the properties defined
114 * in the interface (this is the type returned from the getter method). For each type, we find
115 * the appropriate constructor that we will use.
117 * @throws IllegalArgumentException if failed to process yang-defined property
119 private static void introspectDataStoreProperties() {
120 for (final Method method : DataStoreProperties.class.getDeclaredMethods()) {
121 final String propertyName = getPropertyName(method);
122 if (propertyName != null) {
123 processDataStoreProperty(propertyName, method.getReturnType(), method);
128 private static String getPropertyName(final Method method) {
129 final String methodName = method.getName();
130 if (Boolean.class.equals(method.getReturnType()) && methodName.startsWith("is")) {
131 return WordUtils.uncapitalize(methodName.substring(2));
132 } else if (methodName.startsWith("get")) {
133 return WordUtils.uncapitalize(methodName.substring(3));
139 * Processes a property defined on the DataStoreProperties interface.
141 @SuppressWarnings("checkstyle:IllegalCatch")
142 private static void processDataStoreProperty(final String name, final Class<?> propertyType,
143 final Method readMethod) {
144 checkArgument(BUILDER_SETTERS.containsKey(name),
145 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
148 processPropertyType(propertyType);
149 DATA_STORE_PROP_INFO.put(name, new SimpleImmutableEntry<>(propertyType, readMethod));
150 } catch (final Exception e) {
151 LOG.error("Error finding constructor for type {}", propertyType, e);
156 * Finds the appropriate constructor for the specified type that we will use to construct
159 * @throws IllegalArgumentException if yang-defined type has no property, annotated by ConstructorParameters
161 private static void processPropertyType(final Class<?> propertyType)
162 throws NoSuchMethodException, SecurityException {
163 final Class<?> wrappedType = Primitives.wrap(propertyType);
164 if (CONSTRUCTORS.containsKey(wrappedType)) {
168 // If the type is a primitive (or String type), we look for the constructor that takes a
169 // single String argument, which, for primitives, validates and converts from a String
170 // representation which is the form we get on ingress.
171 if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
172 CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
174 // This must be a yang-defined type. We need to find the constructor that takes a
175 // primitive as the only argument. This will be used to construct instances to perform
176 // validation (eg range checking). The yang-generated types have a couple single-argument
177 // constructors but the one we want has the ConstructorParameters annotation.
178 for (final Constructor<?> ctor: propertyType.getConstructors()) {
179 final ConstructorParameters ctorParAnnotation = ctor.getAnnotation(ConstructorParameters.class);
180 if (ctor.getParameterCount() == 1 && ctorParAnnotation != null) {
181 findYangTypeGetter(propertyType, ctorParAnnotation.value()[0]);
182 CONSTRUCTORS.put(propertyType, ctor);
190 * Finds the getter method on a yang-generated type for the specified property name.
192 * @throws IllegalArgumentException if passed type has no passed property
194 private static void findYangTypeGetter(final Class<?> type, final String propertyName) {
195 for (Method method : type.getDeclaredMethods()) {
196 final String property = getPropertyName(method);
197 if (property != null && property.equals(propertyName)) {
198 YANG_TYPE_GETTERS.put(type, method);
203 throw new IllegalArgumentException(String.format(
204 "Getter method for constructor property %s not found for YANG type %s",
205 propertyName, type));
208 @GuardedBy(value = "this")
209 private DatastoreContext context;
210 @GuardedBy(value = "this")
211 private Map<String, Object> currentProperties;
213 public DatastoreContextIntrospector(final DatastoreContext context,
214 final DataStorePropertiesContainer defaultPropsContainer) {
216 final Builder builder = DatastoreContext.newBuilderFrom(context);
217 for (Entry<String, Entry<Class<?>, Method>> entry: DATA_STORE_PROP_INFO.entrySet()) {
220 value = entry.getValue().getValue().invoke(defaultPropsContainer);
221 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
222 LOG.error("Error obtaining default value for property {}", entry.getKey(), e);
227 convertValueAndInvokeSetter(entry.getKey(), value, builder);
231 this.context = builder.build();
234 public synchronized DatastoreContext getContext() {
238 public DatastoreContextFactory newContextFactory() {
239 return new DatastoreContextFactory(this);
242 public synchronized DatastoreContext getShardDatastoreContext(final String forShardName) {
243 if (currentProperties == null) {
247 final Builder builder = DatastoreContext.newBuilderFrom(context);
248 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
249 final String shardNamePrefix = forShardName + '.';
251 final List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
253 for (String key: keys) {
254 final Object value = currentProperties.get(key);
255 if (key.startsWith(dataStoreTypePrefix)) {
256 key = key.replaceFirst(dataStoreTypePrefix, "");
259 if (key.startsWith(shardNamePrefix)) {
260 key = key.replaceFirst(shardNamePrefix, "");
261 convertValueAndInvokeSetter(key, value.toString(), builder);
265 return builder.build();
269 * Applies the given properties to the cached DatastoreContext and yields a new DatastoreContext
270 * instance which can be obtained via {@link #getContext()}.
272 * @param properties the properties to apply
273 * @return true if the cached DatastoreContext was updated, false otherwise.
275 public synchronized boolean update(final Map<String, Object> properties) {
276 currentProperties = null;
277 if (properties == null || properties.isEmpty()) {
281 LOG.debug("In update: properties: {}", properties);
283 final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
285 final Builder builder = DatastoreContext.newBuilderFrom(context);
287 final String dataStoreTypePrefix = context.getDataStoreName() + '.';
289 final List<String> keys = getSortedKeysByDatastoreType(properties.keySet(), dataStoreTypePrefix);
291 boolean updated = false;
292 for (String key: keys) {
293 final Object value = properties.get(key);
294 mapBuilder.put(key, value);
296 // If the key is prefixed with the data store type, strip it off.
297 if (key.startsWith(dataStoreTypePrefix)) {
298 key = key.replaceFirst(dataStoreTypePrefix, "");
301 if (convertValueAndInvokeSetter(key, value.toString(), builder)) {
306 currentProperties = mapBuilder.build();
309 context = builder.build();
315 private static ArrayList<String> getSortedKeysByDatastoreType(final Collection<String> inKeys,
316 final String dataStoreTypePrefix) {
317 // Sort the property keys by putting the names prefixed with the data store type last. This
318 // is done so data store specific settings are applied after global settings.
319 final ArrayList<String> keys = new ArrayList<>(inKeys);
320 keys.sort((key1, key2) -> key1.startsWith(dataStoreTypePrefix) ? 1 :
321 key2.startsWith(dataStoreTypePrefix) ? -1 : key1.compareTo(key2));
325 @SuppressWarnings("checkstyle:IllegalCatch")
326 private boolean convertValueAndInvokeSetter(final String inKey, final Object inValue, final Builder builder) {
327 final String key = convertToCamelCase(inKey);
330 // Convert the value to the right type.
331 final Object value = convertValue(key, inValue);
336 LOG.debug("Converted value for property {}: {} ({})",
337 key, value, value.getClass().getSimpleName());
339 // Call the setter method on the Builder instance.
340 final Method setter = BUILDER_SETTERS.get(key);
341 if (value.getClass().isEnum()) {
342 setter.invoke(builder, value);
344 setter.invoke(builder, constructorValueRecursively(
345 Primitives.wrap(setter.getParameterTypes()[0]), value.toString()));
349 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
350 | InstantiationException e) {
351 LOG.error("Error converting value ({}) for property {}", inValue, key, e);
357 private static String convertToCamelCase(final String inString) {
358 String str = inString.trim();
359 if (StringUtils.contains(str, '-') || StringUtils.contains(str, ' ')) {
360 str = inString.replace('-', ' ');
361 str = WordUtils.capitalizeFully(str);
362 str = StringUtils.deleteWhitespace(str);
365 return StringUtils.uncapitalize(str);
368 private Object convertValue(final String name, final Object from)
369 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
370 final Entry<Class<?>, Method> propertyInfo = DATA_STORE_PROP_INFO.get(name);
371 if (propertyInfo == null) {
372 LOG.debug("Property not found for {}", name);
376 final Class<?> propertyType = propertyInfo.getKey();
378 LOG.debug("Type for property {}: {}, converting value {} ({})",
379 name, propertyType.getSimpleName(), from, from.getClass().getSimpleName());
381 if (propertyType.isEnum()) {
383 final Method enumConstructor = propertyType.getDeclaredMethod("forName", String.class);
384 if (enumConstructor.getReturnType().equals(propertyType)) {
385 return enumConstructor.invoke(null, from.toString().toLowerCase(Locale.ROOT));
387 } catch (NoSuchMethodException e) {
388 LOG.error("Error constructing value ({}) for enum {}", from, propertyType);
392 // Recurse the chain of constructors depth-first to get the resulting value. Eg, if the
393 // property type is the yang-generated NonZeroUint32Type, it's constructor takes a Long so
394 // we have to first construct a Long instance from the input value.
395 Object converted = constructorValueRecursively(propertyType, from);
397 // If the converted type is a yang-generated type, call the getter to obtain the actual value.
398 final Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
399 if (getter != null) {
400 converted = getter.invoke(converted);
406 private Object constructorValueRecursively(final Class<?> toType, final Object fromValue)
407 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
408 LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
409 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
411 if (toType.equals(fromValue.getClass())) {
415 final Constructor<?> ctor = CONSTRUCTORS.get(toType);
417 if (fromValue instanceof String) {
418 final Function<String, Object> factory = UINT_FACTORIES.get(toType);
419 if (factory != null) {
420 return factory.apply((String) fromValue);
424 throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
427 LOG.trace("Found {}", ctor);
428 Object value = fromValue;
430 // Once we find a constructor that takes the original type as an argument, we're done recursing.
431 if (!ctor.getParameterTypes()[0].equals(fromValue.getClass())) {
432 value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
435 return ctor.newInstance(value);