http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java index e39b070..699208e 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java @@ -18,18 +18,18 @@ */ package org.apache.tamaya.inject.internal; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.TypeLiteral; import org.apache.tamaya.inject.api.DynamicValue; -import org.apache.tamaya.inject.spi.InjectionUtils; +import org.apache.tamaya.inject.spi.InjectionEvaluator; import org.apache.tamaya.inject.spi.ConfiguredField; +import javax.config.Config; +import javax.config.ConfigProvider; import java.lang.reflect.Field; +import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.Collection; +import java.util.NoSuchElementException; import java.util.Objects; /** @@ -58,9 +58,9 @@ public class ConfiguredFieldImpl implements ConfiguredField{ * Evaluate the initial keys from the configuration and apply changes to the field. * * @param target the target instance. - * @throws ConfigException if evaluation or conversion failed. + * @throws java.util.NoSuchElementException if evaluation or conversion failed. */ - public void configure(Object target, Configuration config) throws ConfigException { + public void configure(Object target, Config config) { if (this.annotatedField.getType() == DynamicValue.class) { applyDynamicValue(target); } else { @@ -73,9 +73,9 @@ public class ConfiguredFieldImpl implements ConfiguredField{ * This method instantiates and assigns a dynamic value. * * @param target the target instance, not null. - * @throws ConfigException if the configuration required could not be resolved or converted. + * @throws NoSuchElementException if the configuration required could not be resolved or converted. */ - private void applyDynamicValue(Object target) throws ConfigException { + private void applyDynamicValue(Object target) { Objects.requireNonNull(target); try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @@ -83,13 +83,13 @@ public class ConfiguredFieldImpl implements ConfiguredField{ public Object run() throws Exception { annotatedField.setAccessible(true); annotatedField.set(target, - DefaultDynamicValue.of(target, annotatedField, ConfigurationProvider.getConfiguration())); + DefaultDynamicValue.of(target, annotatedField, ConfigProvider.getConfig())); return annotatedField; } }); } catch (Exception e) { - throw new ConfigException("Failed to annotation configured field: " + this.annotatedField.getDeclaringClass() - .getName() + '.' + annotatedField.getName(), e); + throw new NoSuchElementException("Failed to annotation configured field: " + this.annotatedField.getDeclaringClass() + .getName() + '.' + annotatedField.getName()+": " + e); } } @@ -99,34 +99,28 @@ public class ConfiguredFieldImpl implements ConfiguredField{ * @param target the target instance, not null. * @param config The configuration to be used. * @param resolve set to true, if expression resolution should be applied on the keys passed. - * @throws ConfigException if the configuration required could not be resolved or converted. + * @throws NoSuchElementException if the configuration required could not be resolved or converted. */ - private void applyValue(Object target, Configuration config, boolean resolve) throws ConfigException { + private void applyValue(Object target, Config config, boolean resolve) { Objects.requireNonNull(target); try { - String[] retKey = new String[1]; - String configValue = InjectionHelper.getConfigValue(this.annotatedField, retKey, config); - // Next step perform expression resolution, if any - String evaluatedValue = resolve && configValue != null - ? InjectionHelper.evaluateValue(configValue) - : configValue; - - // Check for adapter/filter - Object value = InjectionHelper.adaptValue(this.annotatedField, - TypeLiteral.of(this.annotatedField.getType()), retKey[0], evaluatedValue); + Class targetType = this.annotatedField.getType(); + Object configValue = InjectionHelper.getConfigValue(this.annotatedField, targetType, config); + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { annotatedField.setAccessible(true); - if(value!=null) { - annotatedField.set(target, value); + if(configValue!=null) { + annotatedField.set(target, configValue); } return annotatedField; } }); } catch (Exception e) { - throw new ConfigException("Failed to evaluate annotated field: " + this.annotatedField.getDeclaringClass() - .getName() + '.' + annotatedField.getName(), e); + e.printStackTrace(); + throw new NoSuchElementException("Failed to evaluate annotated field: " + this.annotatedField.getDeclaringClass() + .getName() + '.' + annotatedField.getName()+": "+ e); } } @@ -145,7 +139,7 @@ public class ConfiguredFieldImpl implements ConfiguredField{ */ @Override public Collection<String> getConfiguredKeys(){ - return InjectionUtils.getKeys(this.annotatedField); + return InjectionEvaluator.getKeys(this.annotatedField); } @Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java index b10300e..7ea94d0 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java @@ -18,16 +18,16 @@ */ package org.apache.tamaya.inject.internal; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.TypeLiteral; -import org.apache.tamaya.inject.spi.InjectionUtils; +import org.apache.tamaya.inject.spi.InjectionEvaluator; import org.apache.tamaya.inject.spi.ConfiguredMethod; +import javax.config.Config; import java.lang.reflect.Method; +import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.Collection; +import java.util.NoSuchElementException; import java.util.Objects; /** @@ -55,20 +55,11 @@ public class ConfiguredSetterMethod implements ConfiguredMethod { } @Override - public void configure(Object target, Configuration config) throws ConfigException { - String[] retKey = new String[1]; - String configValue = InjectionHelper.getConfigValue(this.setterMethod, retKey, config); + public void configure(Object target, Config config) { + Class targetType = this.setterMethod.getParameterTypes()[0]; + Object configValue = InjectionHelper.getConfigValue(this.setterMethod, targetType, config); Objects.requireNonNull(target); try { - String evaluatedString = configValue != null - ? InjectionHelper.evaluateValue(configValue) - : configValue; - - // Check for adapter/filter - Object value = InjectionHelper.adaptValue( - this.setterMethod, TypeLiteral.of(this.setterMethod.getParameterTypes()[0]), - retKey[0], evaluatedString); - AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { @@ -76,11 +67,10 @@ public class ConfiguredSetterMethod implements ConfiguredMethod { return setterMethod; } }); - - setterMethod.invoke(target, value); + setterMethod.invoke(target, configValue); } catch (Exception e) { - throw new ConfigException("Failed to annotation configured method: " + this.setterMethod.getDeclaringClass() - .getName() + '.' + setterMethod.getName(), e); + throw new NoSuchElementException("Failed to annotation configured method: " + this.setterMethod.getDeclaringClass() + .getName() + '.' + setterMethod.getName()+": "+ e); } } @@ -92,7 +82,7 @@ public class ConfiguredSetterMethod implements ConfiguredMethod { */ @Override public Collection<String> getConfiguredKeys() { - return InjectionUtils.getKeys(this.setterMethod); + return InjectionEvaluator.getKeys(this.setterMethod); } /** http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java index 85f1f4a..25bd051 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java @@ -24,17 +24,17 @@ import java.lang.reflect.Modifier; import java.util.*; import java.util.logging.Logger; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.inject.api.ConfigAutoInject; +import org.apache.tamaya.inject.api.ConfigAutoDetect; +import org.apache.tamaya.inject.api.ConfigFallbackKeys; import org.apache.tamaya.inject.api.NoConfig; -import org.apache.tamaya.inject.api.Config; import org.apache.tamaya.inject.api.ConfigDefaultSections; import org.apache.tamaya.inject.spi.ConfiguredField; import org.apache.tamaya.inject.spi.ConfiguredMethod; import org.apache.tamaya.inject.spi.ConfiguredType; +import javax.config.ConfigProvider; +import javax.config.inject.ConfigProperty; + /** * Structure that contains and manages configuration related things for a configured type registered. * Created by Anatole on 03.10.2014. @@ -69,7 +69,7 @@ public class ConfiguredTypeImpl implements ConfiguredType{ initFields(type, true); initMethods(type, true); }else { - ConfigAutoInject autoInject = (ConfigAutoInject) type.getAnnotation(ConfigAutoInject.class); + ConfigAutoDetect autoInject = (ConfigAutoDetect) type.getAnnotation(ConfigAutoDetect.class); if (autoInject != null) { initFields(type, autoInject != null); initMethods(type, autoInject != null); @@ -108,8 +108,8 @@ public class ConfiguredTypeImpl implements ConfiguredType{ f.toGenericString()); } } catch (Exception e) { - throw new ConfigException("Failed to initialized configured field: " + - f.getDeclaringClass().getName() + '.' + f.getName(), e); + throw new NoSuchElementException("Failed to initialized configured field: " + + f.getDeclaringClass().getName() + '.' + f.getName()+": "+ e); } } } @@ -131,8 +131,10 @@ public class ConfiguredTypeImpl implements ConfiguredType{ continue; } if(isConfiguredMethod(m) || autoConfigure) { - Config propAnnot = m.getAnnotation(Config.class); - if (addPropertySetter(m, propAnnot)) { + if (addPropertySetter( + m, + m.getAnnotation(ConfigProperty.class), + m.getAnnotation(ConfigFallbackKeys.class))) { LOG.finer("Added configured setter: " + m.getClass().getName() + "#" + m.toGenericString()); } @@ -140,7 +142,7 @@ public class ConfiguredTypeImpl implements ConfiguredType{ } } - private boolean addPropertySetter(Method m, Config prop) { + private boolean addPropertySetter(Method m, ConfigProperty prop, ConfigFallbackKeys fallbackKeys) { if (prop!=null) { if (m.getParameterTypes().length == 1) { // getter method @@ -150,8 +152,8 @@ public class ConfiguredTypeImpl implements ConfiguredType{ configuredSetterMethods.add(new ConfiguredSetterMethod(m)); return true; } catch (Exception e) { - throw new ConfigException("Failed to initialize configured setter method: " + - m.getDeclaringClass().getName() + '.' + m.getName(), e); + throw new NoSuchElementException("Failed to initialize configured setter method: " + + m.getDeclaringClass().getName() + '.' + m.getName()+": "+ e); } } } @@ -166,11 +168,11 @@ public class ConfiguredTypeImpl implements ConfiguredType{ * @param instance The instance to be configured. */ public void configure(Object instance) { - configure(instance, ConfigurationProvider.getConfiguration()); + configure(instance, ConfigProvider.getConfig()); } @Override - public void configure(Object instance, Configuration config) { + public void configure(Object instance, javax.config.Config config) { for (ConfiguredField field : configuredFields) { field.configure(instance, config); } @@ -204,11 +206,11 @@ public class ConfiguredTypeImpl implements ConfiguredType{ } public static boolean isConfiguredField(Field field) { - return field.isAnnotationPresent(Config.class); + return field.isAnnotationPresent(ConfigProperty.class); } public static boolean isConfiguredMethod(Method method) { - return method.isAnnotationPresent(Config.class); + return method.isAnnotationPresent(ConfigProperty.class); } @Override http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java index 7b3fb61..b3fa28a 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java @@ -18,11 +18,11 @@ */ package org.apache.tamaya.inject.internal; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; import org.apache.tamaya.inject.ConfigurationInjector; import javax.annotation.Priority; +import javax.config.ConfigProvider; +import javax.config.inject.ConfigProperty; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -33,7 +33,6 @@ import java.util.function.Supplier; import java.util.logging.Logger; import org.apache.tamaya.inject.api.NoConfig; -import org.apache.tamaya.inject.api.Config; import org.apache.tamaya.inject.api.ConfigDefaultSections; import org.apache.tamaya.inject.spi.ConfiguredType; import org.osgi.service.component.annotations.Component; @@ -57,13 +56,26 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { * @param type the type to be configured. * @return the configured type registered. */ - public ConfiguredType registerType(Class<?> type) { + public ConfiguredType getConfiguredType(Class<?> type) { ConfiguredType confType = configuredTypes.get(type); if (confType == null) { if(!isConfigAnnotated(type) && !autoConfigureEnabled){ return null; } confType = new ConfiguredTypeImpl(type); + } + return confType; + } + + /** + * Extract the configuration annotation config and registers it per class, for later reuse. + * + * @param type the type to be configured. + * @return the configured type registered. + */ + public ConfiguredType registerType(Class<?> type) { + ConfiguredType confType = getConfiguredType(type); + if (confType != null) { configuredTypes.put(type, confType); InjectionHelper.sendConfigurationEvent(confType); } @@ -97,12 +109,12 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { return true; } for (Field f : type.getDeclaredFields()) { - if (f.isAnnotationPresent(NoConfig.class) || f.isAnnotationPresent(Config.class)) { + if (f.isAnnotationPresent(NoConfig.class) || f.isAnnotationPresent(ConfigProperty.class)) { return true; } } for (Method m : type.getDeclaredMethods()) { - if (m.isAnnotationPresent(NoConfig.class) || m.isAnnotationPresent(Config.class)) { + if (m.isAnnotationPresent(NoConfig.class) || m.isAnnotationPresent(ConfigProperty.class)) { return true; } } @@ -117,7 +129,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { */ @Override public <T> T configure(T instance) { - return configure(instance, ConfigurationProvider.getConfiguration()); + return configure(instance, ConfigProvider.getConfig()); } /** @@ -128,7 +140,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { * @param config the target configuration, not null. */ @Override - public <T> T configure(T instance, Configuration config) { + public <T> T configure(T instance, javax.config.Config config) { Class<?> type = Objects.requireNonNull(instance).getClass(); ConfiguredType configuredType = registerType(type); if(configuredType!=null){ @@ -146,7 +158,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { */ @Override public <T> T createTemplate(Class<T> templateType) { - return createTemplate(templateType, ConfigurationProvider.getConfiguration()); + return createTemplate(templateType, ConfigProvider.getConfig()); } /** @@ -156,7 +168,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { * @param config the target configuration, not null. */ @Override - public <T> T createTemplate(Class<T> templateType, Configuration config) { + public <T> T createTemplate(Class<T> templateType, javax.config.Config config) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if(cl==null){ cl = this.getClass().getClassLoader(); @@ -167,15 +179,16 @@ public class DefaultConfigurationInjector implements ConfigurationInjector { @Override public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier) { - return getConfiguredSupplier(supplier, ConfigurationProvider.getConfiguration()); + return getConfiguredSupplier(supplier, ConfigProvider.getConfig()); } @Override - public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier, final Configuration config) { - return new Supplier<T>() { - public T get() { - return configure(supplier.get(), config); - } - }; + public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier, final javax.config.Config config) { + return () -> configure(supplier.get(), config); + } + + @Override + public boolean isConfigured(Object o) { + return getConfiguredType(o.getClass())!=null; } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java index ac7e977..f0763a8 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java @@ -18,34 +18,26 @@ */ package org.apache.tamaya.inject.internal; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.TypeLiteral; import org.apache.tamaya.inject.api.DynamicValue; -import org.apache.tamaya.inject.spi.InjectionUtils; +import org.apache.tamaya.inject.spi.InjectionEvaluator; import org.apache.tamaya.inject.api.LoadPolicy; import org.apache.tamaya.inject.api.UpdatePolicy; -import org.apache.tamaya.inject.api.WithPropertyConverter; +import org.apache.tamaya.inject.api.WithConverter; import org.apache.tamaya.inject.spi.BaseDynamicValue; -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; +import javax.config.Config; +import javax.config.spi.Converter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; import java.util.List; +import java.util.NoSuchElementException; import java.util.Objects; -import java.util.function.Supplier; +import java.util.Optional; import java.util.logging.Logger; /** @@ -70,11 +62,11 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { * Back reference to the base configuration instance. This reference is used reevaluate the given property and * compare the result with the previous value after a configuration change was triggered. */ - private final Configuration configuration; + private final Config configuration; /** * The property converter to be applied, may be null. In the ladder case targetType is not null. */ - private final PropertyConverter<T> propertyConverter; + private final Converter<T> propertyConverter; /** * Load policy. @@ -90,8 +82,8 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { * @param targetType the target type, not null. * @param propertyConverter the optional converter to be used. */ - private DefaultDynamicValue(Object owner, String propertyName, Configuration configuration, TypeLiteral<T> targetType, - PropertyConverter<T> propertyConverter, List<String> keys, LoadPolicy loadPolicy, + private DefaultDynamicValue(Object owner, String propertyName, Config configuration, Type targetType, + Converter<T> propertyConverter, List<String> keys, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) { super(owner, propertyName, targetType, keys); this.configuration = Objects.requireNonNull(configuration); @@ -103,102 +95,102 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { } } - public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration) { + public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration) { return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE); } - public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy) { + public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy) { return of(owner, annotatedField, configuration, loadPolicy, UpdatePolicy.IMMEDIATE); } - public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, UpdatePolicy updatePolicy) { + public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, UpdatePolicy updatePolicy) { return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, updatePolicy); } @SuppressWarnings({ "rawtypes", "unchecked" }) - public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) { + public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) { // Check for adapter/filter Type targetType = annotatedField.getGenericType(); if (targetType == null) { - throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName() + throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName() + '.' + annotatedField.getName()); } if (targetType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) targetType; Type[] types = pt.getActualTypeArguments(); if (types.length != 1) { - throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName() + throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName() + '.' + annotatedField.getName()); } targetType = types[0]; } - PropertyConverter<?> propertyConverter = null; - WithPropertyConverter annot = annotatedField.getAnnotation(WithPropertyConverter.class); + Converter<?> propertyConverter = null; + WithConverter annot = annotatedField.getAnnotation(WithConverter.class); if (annot != null) { try { propertyConverter = annot.value().newInstance(); } catch (Exception e) { - throw new ConfigException("Failed to instantiate annotated PropertyConverter on " + + throw new IllegalArgumentException("Failed to instantiate annotated PropertyConverter on " + annotatedField.getDeclaringClass().getName() + '.' + annotatedField.getName(), e); } } - List<String> keys = InjectionUtils.getKeys(annotatedField); + List<String> keys = InjectionEvaluator.getKeys(annotatedField); return new DefaultDynamicValue(owner, annotatedField.getName(), configuration, - TypeLiteral.of(targetType), propertyConverter, keys, loadPolicy, updatePolicy); + targetType, propertyConverter, keys, loadPolicy, updatePolicy); } - public static DynamicValue<?> of(Object owner, Method method, Configuration configuration) { + public static DynamicValue<?> of(Object owner, Method method, Config configuration) { return of(owner, method, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE); } - public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, UpdatePolicy updatePolicy) { + public static DynamicValue<?> of(Object owner, Method method, Config configuration, UpdatePolicy updatePolicy) { return of(owner, method, configuration, LoadPolicy.ALWAYS, updatePolicy); } - public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy) { + public static DynamicValue<?> of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy) { return of(owner, method, configuration, loadPolicy, UpdatePolicy.IMMEDIATE); } @SuppressWarnings("unchecked") - public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) { + public static DynamicValue<?> of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) { // Check for adapter/filter Type targetType = method.getGenericReturnType(); if (targetType == null) { - throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass() + throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass() .getName() + '.' + method.getName()); } if (targetType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) targetType; Type[] types = pt.getActualTypeArguments(); if (types.length != 1) { - throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass() + throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass() .getName() + '.' + method.getName()); } targetType = types[0]; } - PropertyConverter<Object> propertyConverter = null; - WithPropertyConverter annot = method.getAnnotation(WithPropertyConverter.class); + Converter<Object> propertyConverter = null; + WithConverter annot = method.getAnnotation(WithConverter.class); if (annot != null) { try { - propertyConverter = (PropertyConverter<Object>) annot.value().newInstance(); + propertyConverter = (Converter<Object>) annot.value().newInstance(); } catch (Exception e) { - throw new ConfigException("Failed to instantiate annotated PropertyConverter on " + + throw new IllegalArgumentException("Failed to instantiate annotated PropertyConverter on " + method.getDeclaringClass().getName() + '.' + method.getName(), e); } } - return new DefaultDynamicValue<>(owner, method.getName(), - configuration, TypeLiteral.of(targetType), propertyConverter, InjectionUtils.getKeys(method), + return new DefaultDynamicValue(owner, method.getName(), + configuration, targetType, propertyConverter, InjectionEvaluator.getKeys(method), loadPolicy, updatePolicy); } - protected PropertyConverter getCustomConverter(){ + protected Converter getCustomConverter(){ return this.propertyConverter; } @Override - protected Configuration getConfiguration() { + protected Config getConfiguration() { return configuration; } @@ -207,10 +199,23 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { * otherwise throws {@code ConfigException}. * * @return the non-null value held by this {@code Optional} - * @throws ConfigException if there is no value present + * @throws java.util.NoSuchElementException if there is no value present * @see DefaultDynamicValue#isPresent() */ - public T get() { + public T getValue() { + return getOptionalValue() + .orElseThrow(() -> new NoSuchElementException("No config value for: " + getKeys())); + } + + /** + * If a value is present in this {@code DynamicValue}, returns the value, + * otherwise throws {@code ConfigException}. + * + * @return the non-null value held by this {@code Optional} + * @throws java.util.NoSuchElementException if there is no value present + * @see DefaultDynamicValue#isPresent() + */ + public Optional<T> getOptionalValue() { T newLocalValue; if(loadPolicy!=LoadPolicy.INITIAL) { newLocalValue = evaluateValue(); @@ -219,11 +224,9 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { } if(!Objects.equals(this.value, newLocalValue)){ switch (getUpdatePolicy()){ - case IMMEDEATE: case IMMEDIATE: commit(); break; - case EXPLCIT: case EXPLICIT: this.newValue = newLocalValue; break; @@ -240,7 +243,7 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { } } } - return value; + return Optional.ofNullable(value); } /** @@ -268,8 +271,9 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> { case NEVER: this.newValue = null; break; - case EXPLCIT: - case IMMEDEATE: + case EXPLICIT: + this.newValue = newValue; + break; default: this.newValue = newValue; commit(); http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java index 06f3556..d404b3e 100644 --- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java +++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java @@ -18,31 +18,28 @@ */ package org.apache.tamaya.inject.internal; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; +import java.lang.reflect.*; import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.TypeLiteral; +import org.apache.tamaya.base.convert.ConversionContext; import org.apache.tamaya.events.ConfigEventManager; import org.apache.tamaya.events.spi.BaseConfigEvent; -import org.apache.tamaya.inject.api.Config; -import org.apache.tamaya.inject.api.ConfigDefaultSections; -import org.apache.tamaya.inject.spi.InjectionUtils; -import org.apache.tamaya.inject.api.WithPropertyConverter; +import org.apache.tamaya.inject.spi.InjectionEvaluator; +import org.apache.tamaya.inject.api.WithConverter; import org.apache.tamaya.inject.spi.ConfiguredType; import org.apache.tamaya.resolver.spi.ExpressionEvaluator; -import org.apache.tamaya.spi.ConfigurationContext; -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; +import org.apache.tamaya.spi.ConfigContext; +import org.apache.tamaya.spi.ConfigContextSupplier; import org.apache.tamaya.spi.ServiceContextManager; +import javax.config.Config; +import javax.config.inject.ConfigProperty; +import javax.config.spi.Converter; + /** * Utility class containing several aspects used in this module. @@ -58,7 +55,7 @@ final class InjectionHelper { private static boolean checkForEvents() { try{ - Class.forName("org.apache.tamaya.events.FrozenConfiguration"); + Class.forName("org.apache.tamaya.events.FrozenConfig"); LOG.info("Detected tamaya-events is loaded, will trigger ConfigEvents..."); return true; } catch(Exception e){ @@ -81,123 +78,134 @@ final class InjectionHelper { /** * Internally evaluated the current valid configuration keys based on the given annotations present. - * @param method the method + * @param method the method, not null. + * @param config the config, not null. * @return the keys to be returned, or null. */ - public static String getConfigValue(Method method, Configuration config) { - return getConfigValue(method, null, config); + public static <T> T getConfigValue(Method method, Class<T> type, javax.config.Config config) { + return getConfigValue(method, type, null, config); } /** * Internally evaluated the current valid configuration keys based on the given annotations present. - * @param method the method - * @param retKey the array to return the key found, or null. + * @param field the field, not null. + * @param config the config, not null. * @return the keys to be returned, or null. */ - public static String getConfigValue(Method method, String[] retKey, Configuration config) { - ConfigDefaultSections areasAnnot = method.getDeclaringClass().getAnnotation(ConfigDefaultSections.class); - return getConfigValueInternal(method, areasAnnot, retKey, config); + public static <T> T getConfigValue(Field field, Class<T> type, javax.config.Config config) { + return getConfigValue(field, type, null, config); } - /** - * Internally evaluated the current valid configuration keys based on the given annotations present. - * @param field the field - * @return the keys to be returned, or null. - */ - public static String getConfigValue(Field field, Configuration config) { - return getConfigValue(field, null, config); - } /** * Internally evaluated the current valid configuration keys based on the given annotations present. - * @param field the field + * @param member the member, not null. * @param retKey the array to return the key found, or null. * @return the keys to be returned, or null. */ - public static String getConfigValue(Field field, String[] retKey, Configuration config) { - ConfigDefaultSections areasAnnot = field.getDeclaringClass().getAnnotation(ConfigDefaultSections.class); - return getConfigValueInternal(field, areasAnnot, retKey, config); - } + private static <T> T getConfigValue(AccessibleObject member, Class<T> targetType, + String[] retKey, + javax.config.Config config) { + Objects.requireNonNull(targetType); + targetType = unboxType(targetType); + List<String> keys = InjectionEvaluator.getKeys(member); + + WithConverter converterAnnot = member.getAnnotation(WithConverter.class); + if(converterAnnot!=null && !converterAnnot.value().getName().equals(WithConverter.class.getName())){ + return getCustomConvertedConfigValue(member, converterAnnot, targetType, keys, config); + } - /** - * Internally evaluated the current valid configuration keys based on the given annotations present. - * - * @return the keys to be returned, or null. - */ - private static String getConfigValueInternal(AnnotatedElement element, ConfigDefaultSections areasAnnot, String[] retKey, Configuration config) { - Config prop = element.getAnnotation(Config.class); - List<String> keys; - if (prop == null) { - keys = InjectionUtils.evaluateKeys((Member) element, areasAnnot); - } else { - keys = InjectionUtils.evaluateKeys((Member) element, areasAnnot, prop); + Optional<T> result = null; + for(String key:keys) { + result = config.getOptionalValue(key, targetType); + if (result.isPresent()) { + if (retKey != null) { + retKey[0] = key; + } + return result.get(); + } } - String configValue = evaluteConfigValue(keys, retKey, config); - if (configValue == null) { - if(prop!=null && !prop.defaultValue().equals(Config.UNCONFIGURED_VALUE)){ - return prop.defaultValue(); + ConfigProperty prop = member.getAnnotation(ConfigProperty.class); + if(prop!=null && !prop.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE)){ + String textValue = prop.defaultValue(); + // How tp convert the default value in a portable way? + if(config instanceof ConfigContextSupplier){ + ConfigContext ctx = ((ConfigContextSupplier)config).getConfigContext(); + for(Converter converter:ctx.getConverters(targetType)){ + try{ + Object o = converter.convert(textValue); + if(o!=null){ + return (T)o; + } + }catch(Exception e){ + LOG.log(Level.SEVERE, "Failed to convert using Converter on " + + converter.getClass().getName(), e); + } + } + if(String.class.equals(targetType) || CharSequence.class.equals(targetType)){ + return (T)textValue; + } + throw new IllegalArgumentException("Non convertible value: " + textValue + ", target: " + targetType.getName()); } } - return configValue; + return null; } - private static String evaluteConfigValue(List<String> keys, String[] retKey, Configuration config) { - String configValue = null; - for (String key : keys) { - configValue = config.get(key); - if (configValue != null) { - if(retKey!=null && retKey.length>0){ - retKey[0] = key; - } - break; - } + private static Class unboxType(Class targetType) { + switch(targetType.getName()){ + case "byte": + return Byte.class; + case "char": + return Character.class; + case "boolean": + return Boolean.class; + case "int": + return Integer.class; + case "short": + return Short.class; + case "long": + return Long.class; + case "float": + return Float.class; + case "double": + return Double.class; + default: + return targetType; + } - return configValue; } - public static <T> T adaptValue(AnnotatedElement element, TypeLiteral<T> targetType, String key, String configValue) { + public static <T> T getCustomConvertedConfigValue(AccessibleObject element, WithConverter converterAnnot, + Class<T> targetType, List<String> keys, Config config) { // Check for adapter/filter - T adaptedValue = null; - WithPropertyConverter converterAnnot = element.getAnnotation(WithPropertyConverter.class); - Class<? extends PropertyConverter<T>> converterType; - if (converterAnnot != null) { - converterType = (Class<? extends PropertyConverter<T>>) converterAnnot.value(); - if (!converterType.getName().equals(WithPropertyConverter.class.getName())) { + Class<? extends Converter<T>> converterType = (Class<? extends Converter<T>>) converterAnnot.value(); + if (!converterType.getName().equals(WithConverter.class.getName())) { + Converter<T> converter = null; + try { + converter = Converter.class.cast(converterType.newInstance()); + } catch (Exception e) { + throw new IllegalArgumentException("Failed to instantiate converter: " + converterType.getName(), e); + } + for (String key : keys) { try { - // TODO cache here... - ConversionContext ctx = new ConversionContext.Builder(key,targetType) + ConversionContext ctx = new ConversionContext.Builder(key, targetType) .setAnnotatedElement(element).build(); - - PropertyConverter<T> converter = PropertyConverter.class.cast(converterType.newInstance()); - adaptedValue = converter.convert(configValue, ctx); + ConversionContext.setContext(ctx); + Optional<String> textValue = config.getOptionalValue(key, String.class); + if (textValue.isPresent()) { + T adaptedValue = converter.convert(textValue.get()); + if (adaptedValue != null) { + return adaptedValue; + } + } } catch (Exception e) { - LOG.log(Level.SEVERE, "Failed to convert using explicit PropertyConverter on " + element + - ", trying default conversion.", e); - } - } - } - if (adaptedValue != null) { - return adaptedValue; - } - if (String.class == targetType.getType()) { - return (T) configValue; - } else{ - if(configValue==null) { - return null; - } - ConfigurationContext configContext = ConfigurationProvider.getConfiguration().getContext(); - List<PropertyConverter<T>> converters = configContext - .getPropertyConverters(targetType); - ConversionContext ctx = new ConversionContext.Builder(ConfigurationProvider.getConfiguration(), - configContext, key, targetType).setAnnotatedElement(element).build(); - for (PropertyConverter<T> converter : converters) { - adaptedValue = converter.convert(configValue, ctx); - if (adaptedValue != null) { - return adaptedValue; + LOG.log(Level.SEVERE, "Failed to convert using explicit PropertyConverter on " + element, e); + } finally { + ConversionContext.reset(); } } } - throw new ConfigException("Non convertible property type: " + element); + return null; } /** http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java index 3420977..5c0fe98 100644 --- a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java +++ b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java @@ -18,10 +18,11 @@ */ package annottext; +import org.apache.tamaya.inject.api.ConfigFallbackKeys; import org.apache.tamaya.inject.api.DynamicValue; import org.apache.tamaya.inject.api.NoConfig; -import org.apache.tamaya.inject.api.Config; +import javax.config.inject.ConfigProperty; import java.util.ArrayList; import java.util.List; @@ -32,20 +33,20 @@ import java.util.List; */ public class AnnotatedConfigBean { - @Config(value = {"foo.bar.myprop", "mp", "common.testdata.myProperty"}, defaultValue = "ET") - // @ConfigLoadPolicy(listener = MyListener.class) + @ConfigProperty(name="foo.bar.myprop", defaultValue = "ET") + @ConfigFallbackKeys({"mp", "common.testdata.myProperty"}) public String myParameter; - @Config("simple_value") + @ConfigProperty(name="simple_value") public String simpleValue; - @Config + @ConfigProperty String anotherValue; - @Config("host.name") + @ConfigProperty(name="host.name") private String hostName; - @Config("host.name") + @ConfigProperty(name="host.name") private DynamicValue<String> dynamicHostname; @NoConfig @@ -70,7 +71,7 @@ public class AnnotatedConfigBean { public static final String CONSTANT = "a constant"; - @Config("java.version") + @ConfigProperty(name="java.version") void setJavaVersion(String version){ this.javaVersion = version; } http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java index 8c6d692..6dbcde7 100644 --- a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java +++ b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java @@ -18,8 +18,10 @@ */ package annottext; +import org.apache.tamaya.inject.api.ConfigFallbackKeys; import org.apache.tamaya.inject.api.DynamicValue; -import org.apache.tamaya.inject.api.Config; + +import javax.config.inject.ConfigProperty; /** * An example showing some basic annotations, using an interface to be proxied by the @@ -28,20 +30,20 @@ import org.apache.tamaya.inject.api.Config; */ public interface AnnotatedConfigTemplate { - @Config(value = {"foo.bar.myprop", "mp","common.testdata.myProperty"}, defaultValue = "ET") - // @ConfigLoadPolicy(listener = MyListener.class) + @ConfigProperty(name = "foo.bar.myprop", defaultValue = "ET") + @ConfigFallbackKeys({"mp","common.testdata.myProperty"}) String myParameter(); - @Config("simple_value") + @ConfigProperty(name="simple_value") String simpleValue(); - @Config + @ConfigProperty String simplestValue(); - @Config("host.name") + @ConfigProperty(name="host.name") String hostName(); - @Config("host.name") + @ConfigProperty(name="host.name") DynamicValue<String> getDynamicValue(); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java index 9952b18..778d689 100644 --- a/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java +++ b/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java @@ -18,11 +18,12 @@ */ package annottext; -import org.apache.tamaya.inject.api.Config; + +import javax.config.inject.ConfigProperty; public class InheritedAnnotatedConfigBean extends AnnotatedConfigBean { - @Config("someMoreValue") + @ConfigProperty(name="someMoreValue") public String someMoreValue; public String notConfigured; http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java index 87f8be7..03bfd54 100644 --- a/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java +++ b/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java @@ -18,13 +18,6 @@ */ package annottext; -import org.apache.tamaya.inject.api.Config; -import org.apache.tamaya.inject.api.DynamicValue; -import org.apache.tamaya.inject.api.NoConfig; - -import java.util.ArrayList; -import java.util.List; - /** * An example showing some basic annotations, using an interface to be proxied by the * configuration system, nevertheless extending the overall Configuration interface. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java new file mode 100644 index 0000000..0ae2843 --- /dev/null +++ b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.inject; + +import javax.config.spi.ConfigSource; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by Anatole on 12.01.2015. + */ +public class TestConfigSource implements ConfigSource { + + private Map<String,String> properties = new HashMap<>(); + + public TestConfigSource(){ + properties.put("env.stage", "ET"); + properties.put("simple_value", "aSimpleValue"); + properties.put("host.name", "tamaya01.incubator.apache.org"); + properties.put("anotherValue", "HALLO!"); + properties.put("NonAnnotatedConfigBean.classFieldKey", "Class-Field-Value"); + properties.put("NonAnnotatedConfigBean.fieldKey", "Field-Value"); + properties.put("annottext.NonAnnotatedConfigBean.fullKey", "Fullkey-Value"); + properties.put("someMoreValue", "s'more"); + } + + @Override + public int getOrdinal() { + return 0; + } + + @Override + public String getName() { + return getClass().getName(); + } + + @Override + public String getValue(String key) { + return properties.get(key); + } + + @Override + public Map<String, String> getProperties() { + return properties; + } + + @Override + public Set<String> getPropertyNames() { + return properties.keySet(); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java deleted file mode 100644 index 20de8e8..0000000 --- a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.inject; - -import org.apache.tamaya.spi.PropertySource; -import org.apache.tamaya.spi.PropertyValue; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by Anatole on 12.01.2015. - */ -public class TestPropertySource implements PropertySource { - - private Map<String,String> properties = new HashMap<>(); - - public TestPropertySource(){ - properties.put("env.stage", "ET"); - properties.put("simple_value", "aSimpleValue"); - properties.put("host.name", "tamaya01.incubator.apache.org"); - properties.put("anotherValue", "HALLO!"); - properties.put("NonAnnotatedConfigBean.classFieldKey", "Class-Field-Value"); - properties.put("NonAnnotatedConfigBean.fieldKey", "Field-Value"); - properties.put("annottext.NonAnnotatedConfigBean.fullKey", "Fullkey-Value"); - properties.put("someMoreValue", "s'more"); - } - - @Override - public int getOrdinal() { - return 0; - } - - @Override - public String getName() { - return getClass().getName(); - } - - @Override - public PropertyValue get(String key) { - return PropertyValue.of(key,properties.get(key),getName()); - } - - @Override - public Map<String, PropertyValue> getProperties() { - Map<String,PropertyValue> result = new HashMap<>(); - for(Map.Entry<String,String> en:properties.entrySet()){ - result.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName())); - } - return result; - } - - @Override - public boolean isScannable() { - return true; - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java index a071584..856ca4c 100644 --- a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java +++ b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java @@ -18,18 +18,15 @@ */ package org.apache.tamaya.inject.internal; -import org.apache.tamaya.ConfigurationProvider; import org.apache.tamaya.inject.api.DynamicValue; -import org.apache.tamaya.inject.api.Config; import org.apache.tamaya.inject.api.UpdatePolicy; -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.apache.tamaya.spi.PropertySource; -import org.apache.tamaya.spi.PropertyValue; import org.junit.Test; -import org.apache.tamaya.Configuration; - +import javax.config.ConfigProvider; +import javax.config.inject.ConfigProperty; +import javax.config.spi.ConfigProviderResolver; +import javax.config.spi.ConfigSource; +import javax.config.spi.Converter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; @@ -42,13 +39,13 @@ import static org.junit.Assert.*; */ public class DefaultDynamicValueTest { - @Config("a") + @ConfigProperty(name="a") String myValue; - @Config("a") + @ConfigProperty(name="a") String myValue2; - @Config("a") + @ConfigProperty(name="a") void setterMethod(String value){ } @@ -62,10 +59,10 @@ public class DefaultDynamicValueTest { } }; - private Map<String,PropertyValue> properties = new HashMap<>(); - private Configuration config = ConfigurationProvider.createConfiguration( - ConfigurationProvider.getConfigurationContextBuilder().addPropertySources( - new PropertySource() { + private Map<String,String> properties = new HashMap<>(); + private javax.config.Config config = ConfigProviderResolver.instance().getBuilder() + .withSources( + new ConfigSource() { @Override public int getOrdinal() { return 0; @@ -77,26 +74,22 @@ public class DefaultDynamicValueTest { } @Override - public PropertyValue get(String key) { + public String getValue(String key) { return properties.get(key); } @Override - public Map<String, PropertyValue> getProperties() { + public Map<String, String> getProperties() { return properties; } - @Override - public boolean isScannable() { - return false; - } } - ).build()); + ).build(); @Test public void testOf_Field() throws Exception { DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), - ConfigurationProvider.getConfiguration()); + ConfigProvider.getConfig()); assertNotNull(val); } @@ -109,7 +102,7 @@ public class DefaultDynamicValueTest { @Test public void testCommitAndGet() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); assertNotNull(val); @@ -118,7 +111,7 @@ public class DefaultDynamicValueTest { @Test public void testCommitAndGets() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.EXPLICIT); @@ -126,14 +119,14 @@ public class DefaultDynamicValueTest { assertEquals("aValue",val.evaluateValue()); // change config val.get(); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); assertTrue(val.updateValue()); assertEquals("aValue2", val.commitAndGet()); } @Test public void testCommit() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.EXPLICIT); @@ -141,7 +134,7 @@ public class DefaultDynamicValueTest { assertEquals("aValue", val.evaluateValue()); // change config val.get(); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); assertEquals("aValue2", val.evaluateValue()); assertTrue(val.updateValue()); val.commit(); @@ -160,37 +153,37 @@ public class DefaultDynamicValueTest { @Test public void testAddRemoveListener() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.IMMEDIATE); val.addListener(consumer); // change config val.get(); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); val.get(); assertNotNull(event); event = null; val.removeListener(consumer); - properties.put("a",PropertyValue.of("a","aValue3","test")); + properties.put("a","aValue3"); val.updateValue(); assertNull(event); } @Test public void testGet() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.IMMEDIATE); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); val.updateValue(); assertEquals("aValue2", val.get()); } @Test public void testUpdateValue() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.EXPLICIT); @@ -205,25 +198,25 @@ public class DefaultDynamicValueTest { @Test public void testEvaluateValue() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.EXPLICIT); assertNotNull(val.get()); assertEquals("aValue",val.evaluateValue()); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); assertEquals("aValue2", val.evaluateValue()); } @Test public void testGetNewValue() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.EXPLICIT); val.get(); assertNull(val.getNewValue()); - properties.put("a",PropertyValue.of("a","aValue2","test")); + properties.put("a","aValue2"); val.get(); assertNotNull(val.getNewValue()); assertEquals("aValue2", val.getNewValue()); @@ -239,7 +232,7 @@ public class DefaultDynamicValueTest { @Test public void testIfPresent() throws Exception { - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"), config); val.setUpdatePolicy(UpdatePolicy.IMMEDIATE); @@ -255,7 +248,7 @@ public class DefaultDynamicValueTest { config); val.setUpdatePolicy(UpdatePolicy.IMMEDIATE); assertEquals("bla", val.orElse("bla")); - properties.put("a",PropertyValue.of("a","aValue","test")); + properties.put("a","aValue"); val.updateValue(); assertEquals("aValue", val.orElse("bla")); } @@ -305,10 +298,10 @@ public class DefaultDynamicValueTest { // })); // } - private static final class DoublicatingConverter implements PropertyConverter<String>{ + private static final class DoublicatingConverter implements Converter<String> { @Override - public String convert(String value, ConversionContext context) { + public String convert(String value) { return value + value; } } http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource b/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource new file mode 100644 index 0000000..60a2faf --- /dev/null +++ b/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy current the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +org.apache.tamaya.inject.TestConfigSource \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource ---------------------------------------------------------------------- diff --git a/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource deleted file mode 100644 index 5dfb894..0000000 --- a/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource +++ /dev/null @@ -1,19 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy current the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -org.apache.tamaya.inject.TestPropertySource \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/pom.xml ---------------------------------------------------------------------- diff --git a/modules/jndi/pom.xml b/modules/jndi/pom.xml index 805729b..a91072f 100644 --- a/modules/jndi/pom.xml +++ b/modules/jndi/pom.xml @@ -35,12 +35,6 @@ under the License. <dependencies> <dependency> <groupId>org.apache.tamaya</groupId> - <artifactId>tamaya-api</artifactId> - <version>${tamaya-apicore.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.tamaya</groupId> <artifactId>tamaya-core</artifactId> <version>${tamaya-apicore.version}</version> <scope>provided</scope> @@ -55,7 +49,7 @@ under the License. </dependency> <dependency> <groupId>org.apache.tamaya</groupId> - <artifactId>tamaya-spisupport</artifactId> + <artifactId>tamaya-base</artifactId> <version>${project.version}</version> </dependency> <dependency> http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java ---------------------------------------------------------------------- diff --git a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java new file mode 100644 index 0000000..8e5b7ac --- /dev/null +++ b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java @@ -0,0 +1,182 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tamaya.jndi; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NameClassPair; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.apache.tamaya.base.configsource.BaseConfigSource; +import org.osgi.service.component.annotations.Component; + +/** + * Propertysource that accesses JNDI as source for configuration entries. + */ +@Component +public class JNDIConfigSource extends BaseConfigSource { + /** The logger used. */ + private static final Logger LOG = Logger.getLogger(JNDIConfigSource.class.getName()); + + /** + * Default ordinal to be used, as defined by {@link javax.config.spi.ConfigSource#getOrdinal()} documentation. + */ + private static final int DEFAULT_ORDINAL = 200; + + /** The root context, not null. */ + private Context context; + /** The scanable property, default is {@code false}. */ + private boolean scannable = false; + + /** + * Creates a new instance. + * @param name the name of the property source, see {@link javax.config.spi.ConfigSource#getName()}. + * @param context the root context to be used, not null. + */ + public JNDIConfigSource(String name, Context context){ + super(name); + this.context = Objects.requireNonNull(context); + } + + /** + * Creates a new instance. + * @param name the name of the property source, see {@link javax.config.spi.ConfigSource#getName()}. + * @throws NamingException if {@code new InitialContext()} throws an exception. + */ + public JNDIConfigSource(String name) throws NamingException { + super(name); + this.context = new InitialContext(); + } + + /** + * Creates a new instance, using {@code "jndi"} as property source name. + * @throws NamingException if {@code new InitialContext()} throws an exception. + */ + public JNDIConfigSource() throws NamingException { + this("jndi"); + setDefaultOrdinal(DEFAULT_ORDINAL); + } + + /** + * If the property source is not scanable, an empty map is returned, otherwise + * the current JNDI context is mapped to configuration map: + * <ul> + * <li>For each leave entry one entry is created.</li> + * <li>The key is the fully path of parent contexts, separated by a '.'.</li> + * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li> + * </ul> + * @return a map representation of the JNDI tree. + */ + @Override + public Map<String, String> getProperties() { + if(scannable){ + try { + return toMap(this.context); + } catch (NamingException e) { + LOG.log(Level.WARNING, "Error scanning JNDI tree.", e); + } + } + return Collections.emptyMap(); + } + + + /** + * If set to true, the property source will return a String representation of the JNDI + * tree when calling {@code getProperties()}. + * @see #getProperties() + * @param val true, to activate scanable (default is false). + */ + public void setScannable(boolean val){ + this.scannable = val; + } + + @Override + public String getValue(String key) { + try { + key = key.replace('.', '/'); + Object o = context.lookup(key); + return o.toString(); + } catch (NamingException e) { + LOG.log(Level.FINER, "Failed to lookup key in JNDI: " + key, e); + return null; + } + } + + @Override + protected String toStringValues() { + return super.toStringValues() + + "\n context=" + context + '\''; + } + + /** + * Maps the given JNDI Context to a {@code Map<String,String>}: + * mapped to configuration map: + * <ul> + * <li>For each leave entry one entry is created.</li> + * <li>The key is the fully path of parent contexts, separated by a '.'.</li> + * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li> + * </ul> + * @param ctx the JNDI context, not null. + * @return the corresponding map, never null. + * @throws NamingException If some JNDI issues occur. + */ + public static Map<String,String> toMap(Context ctx) throws NamingException { + String namespace = ctx instanceof InitialContext ? ctx.getNameInNamespace() : ""; + Map<String, String> map = new HashMap<>(); + NamingEnumeration<NameClassPair> list = ctx.list(namespace); + while (list.hasMoreElements()) { + NameClassPair next = list.next(); + String name = next.getName(); + String jndiPath = namespace + name; + try { + Object lookup = ctx.lookup(jndiPath); + if (namespace.isEmpty()) { + if (lookup instanceof Context) { + Map<String, String> childMap = toMap((Context) lookup); + for (Map.Entry<String, String> en : childMap.entrySet()) { + map.put(name + "." + en.getKey(), en.getValue()); + } + } else { + map.put(name, String.valueOf(lookup)); + } + }else{ + if (lookup instanceof Context) { + Map<String, String> childMap = toMap((Context) lookup); + for (Map.Entry<String, String> en : childMap.entrySet()) { + map.put(namespace + "." + name + "." + en.getKey(), en.getValue()); + } + } else { + map.put(namespace + "." + name, String.valueOf(lookup)); + } + } + } catch (Exception t) { + map.put(namespace + "." + name, "ERROR: " + t.getMessage()); + } + } + return map; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java ---------------------------------------------------------------------- diff --git a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java deleted file mode 100644 index d2b549b..0000000 --- a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.jndi; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NameClassPair; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; - -import org.apache.tamaya.spi.PropertySource; -import org.apache.tamaya.spi.PropertyValue; -import org.apache.tamaya.spisupport.propertysource.BasePropertySource; -import org.osgi.service.component.annotations.Component; - -/** - * Propertysource that accesses JNDI as source for configuration entries. - */ -@Component -public class JNDIPropertySource extends BasePropertySource { - /** The logger used. */ - private static final Logger LOG = Logger.getLogger(JNDIPropertySource.class.getName()); - - /** - * Default ordinal to be used, as defined by {@link PropertySource#getOrdinal()} documentation. - */ - private static final int DEFAULT_ORDINAL = 200; - - /** The root context, not null. */ - private Context context; - /** The scanable property, default is {@code false}. */ - private boolean scannable = false; - - /** - * Creates a new instance. - * @param name the name of the property source, see {@link PropertySource#getName()}. - * @param context the root context to be used, not null. - */ - public JNDIPropertySource(String name, Context context){ - super(name); - this.context = Objects.requireNonNull(context); - } - - /** - * Creates a new instance. - * @param name the name of the property source, see {@link PropertySource#getName()}. - * @throws NamingException if {@code new InitialContext()} throws an exception. - */ - public JNDIPropertySource(String name) throws NamingException { - super(name); - this.context = new InitialContext(); - } - - /** - * Creates a new instance, using {@code "jndi"} as property source name. - * @throws NamingException if {@code new InitialContext()} throws an exception. - */ - public JNDIPropertySource() throws NamingException { - this("jndi"); - setDefaultOrdinal(DEFAULT_ORDINAL); - } - - /** - * If the property source is not scanable, an empty map is returned, otherwise - * the current JNDI context is mapped to configuration map: - * <ul> - * <li>For each leave entry one entry is created.</li> - * <li>The key is the fully path of parent contexts, separated by a '.'.</li> - * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li> - * </ul> - * @return a map representation of the JNDI tree. - */ - @Override - public Map<String, PropertyValue> getProperties() { - if(scannable){ - try { - return PropertyValue.map(toMap(this.context), getName()); - } catch (NamingException e) { - LOG.log(Level.WARNING, "Error scanning JNDI tree.", e); - } - } - return Collections.emptyMap(); - } - - @Override - public boolean isScannable() { - return scannable; - } - - /** - * If set to true, the property source will return a String representation of the JNDI - * tree when calling {@code getProperties()}. - * @see #getProperties() - * @param val true, to activate scanable (default is false). - */ - public void setScannable(boolean val){ - this.scannable = val; - } - - @Override - public PropertyValue get(String key) { - try { - key = key.replace('.', '/'); - Object o = context.lookup(key); - return PropertyValue.of(key, o.toString(), getName()); - } catch (NamingException e) { - LOG.log(Level.FINER, "Failed to lookup key in JNDI: " + key, e); - return null; - } - } - - @Override - protected String toStringValues() { - return super.toStringValues() + - "\n context=" + context + '\''; - } - - /** - * Maps the given JNDI Context to a {@code Map<String,String>}: - * mapped to configuration map: - * <ul> - * <li>For each leave entry one entry is created.</li> - * <li>The key is the fully path of parent contexts, separated by a '.'.</li> - * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li> - * </ul> - * @param ctx the JNDI context, not null. - * @return the corresponding map, never null. - * @throws NamingException If some JNDI issues occur. - */ - public static Map<String,String> toMap(Context ctx) throws NamingException { - String namespace = ctx instanceof InitialContext ? ctx.getNameInNamespace() : ""; - Map<String, String> map = new HashMap<>(); - NamingEnumeration<NameClassPair> list = ctx.list(namespace); - while (list.hasMoreElements()) { - NameClassPair next = list.next(); - String name = next.getName(); - String jndiPath = namespace + name; - try { - Object lookup = ctx.lookup(jndiPath); - if (namespace.isEmpty()) { - if (lookup instanceof Context) { - Map<String, String> childMap = toMap((Context) lookup); - for (Map.Entry<String, String> en : childMap.entrySet()) { - map.put(name + "." + en.getKey(), en.getValue()); - } - } else { - map.put(name, String.valueOf(lookup)); - } - }else{ - if (lookup instanceof Context) { - Map<String, String> childMap = toMap((Context) lookup); - for (Map.Entry<String, String> en : childMap.entrySet()) { - map.put(namespace + "." + name + "." + en.getKey(), en.getValue()); - } - } else { - map.put(namespace + "." + name, String.valueOf(lookup)); - } - } - } catch (Exception t) { - map.put(namespace + "." + name, "ERROR: " + t.getMessage()); - } - } - return map; - } -}
