You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tamaya.apache.org by an...@apache.org on 2016/07/15 12:04:45 UTC
[19/21] incubator-tamaya git commit: - Minimalized current API for
further discussions.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java
deleted file mode 100644
index b0533b0..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java
+++ /dev/null
@@ -1,278 +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.core.internal;
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.apache.tamaya.spi.PropertyValueCombinationPolicy;
-import org.apache.tamaya.spi.ServiceContextManager;
-
-import javax.annotation.Priority;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.logging.Logger;
-
-/**
- * Default Implementation of a simple ConfigurationContext.
- */
-public class DefaultConfigurationContext implements ConfigurationContext {
- /** The logger used. */
- private final static Logger LOG = Logger.getLogger(DefaultConfigurationContext.class.getName());
- /**
- * Cubcomponent handling {@link org.apache.tamaya.spi.PropertyConverter} instances.
- */
- private final PropertyConverterManager propertyConverterManager = new PropertyConverterManager();
-
- /**
- * The current unmodifiable list of loaded {@link org.apache.tamaya.spi.PropertySource} instances.
- */
- private List<PropertySource> immutablePropertySources;
-
- /**
- * The current unmodifiable list of loaded {@link org.apache.tamaya.spi.PropertyFilter} instances.
- */
- private List<PropertyFilter> immutablePropertyFilters;
-
- /**
- * The overriding policy used when combining PropertySources registered to evalute the final configuration
- * values.
- */
- private PropertyValueCombinationPolicy propertyValueCombinationPolicy;
-
- /**
- * Lock for internal synchronization.
- */
- private final ReentrantReadWriteLock propertySourceLock = new ReentrantReadWriteLock();
-
- /** Comparator used for ordering property sources. */
- private final PropertySourceComparator propertySourceComparator = new PropertySourceComparator();
-
- /** Comparator used for ordering property filters. */
- private final PropertyFilterComparator propertyFilterComparator = new PropertyFilterComparator();
-
-
- /**
- * The first time the Configuration system gets invoked we do initialize
- * all our {@link org.apache.tamaya.spi.PropertySource}s and
- * {@link org.apache.tamaya.spi.PropertyFilter}s which are known at startup.
- */
- public DefaultConfigurationContext() {
- List<PropertySource> propertySources = new ArrayList<>();
-
- // first we load all PropertySources which got registered via java.util.ServiceLoader
- propertySources.addAll(ServiceContextManager.getServiceContext().getServices(PropertySource.class));
-
- // after that we add all PropertySources which get dynamically registered via their PropertySourceProviders
- propertySources.addAll(evaluatePropertySourcesFromProviders());
-
- // now sort them according to their ordinal values
- Collections.sort(propertySources, new PropertySourceComparator());
-
- immutablePropertySources = Collections.unmodifiableList(propertySources);
- LOG.info("Registered " + immutablePropertySources.size() + " property sources: " +
- immutablePropertySources);
-
- // as next step we pick up the PropertyFilters pretty much the same way
- List<PropertyFilter> propertyFilters = new ArrayList<>();
- propertyFilters.addAll(ServiceContextManager.getServiceContext().getServices(PropertyFilter.class));
- Collections.sort(propertyFilters, new PropertyFilterComparator());
- immutablePropertyFilters = Collections.unmodifiableList(propertyFilters);
- LOG.info("Registered " + immutablePropertyFilters.size() + " property filters: " +
- immutablePropertyFilters);
-
- immutablePropertyFilters = Collections.unmodifiableList(propertyFilters);
- LOG.info("Registered " + immutablePropertyFilters.size() + " property filters: " +
- immutablePropertyFilters);
- propertyValueCombinationPolicy = ServiceContextManager.getServiceContext().getService(PropertyValueCombinationPolicy.class);
- if(propertyValueCombinationPolicy==null) {
- propertyValueCombinationPolicy = PropertyValueCombinationPolicy.DEFAULT_OVERRIDING_COLLECTOR;
- }
- LOG.info("Using PropertyValueCombinationPolicy: " + propertyValueCombinationPolicy);
- }
-
- DefaultConfigurationContext(DefaultConfigurationContextBuilder builder) {
- List<PropertySource> propertySources = new ArrayList<>();
- // first we load all PropertySources which got registered via java.util.ServiceLoader
- propertySources.addAll(builder.propertySources.values());
- // now sort them according to their ordinal values
- Collections.sort(propertySources, propertySourceComparator);
- immutablePropertySources = Collections.unmodifiableList(propertySources);
- LOG.info("Registered " + immutablePropertySources.size() + " property sources: " +
- immutablePropertySources);
-
- // as next step we pick up the PropertyFilters pretty much the same way
- List<PropertyFilter> propertyFilters = new ArrayList<>();
- propertyFilters.addAll(ServiceContextManager.getServiceContext().getServices(PropertyFilter.class));
- Collections.sort(propertyFilters, propertyFilterComparator);
- immutablePropertyFilters = Collections.unmodifiableList(propertyFilters);
- LOG.info("Registered " + immutablePropertyFilters.size() + " property filters: " +
- immutablePropertyFilters);
-
- propertyValueCombinationPolicy = builder.combinationPolicy;
- if(propertyValueCombinationPolicy==null){
- propertyValueCombinationPolicy = ServiceContextManager.getServiceContext().getService(PropertyValueCombinationPolicy.class);
- }
- if(propertyValueCombinationPolicy==null){
- propertyValueCombinationPolicy = PropertyValueCombinationPolicy.DEFAULT_OVERRIDING_COLLECTOR;
- }
- LOG.info("Using PropertyValueCombinationPolicy: " + propertyValueCombinationPolicy);
- }
-
- /**
- * Pick up all {@link org.apache.tamaya.spi.PropertySourceProvider}s and return all the
- * {@link org.apache.tamaya.spi.PropertySource}s they like to register.
- */
- private Collection<? extends PropertySource> evaluatePropertySourcesFromProviders() {
- List<PropertySource> propertySources = new ArrayList<>();
- Collection<PropertySourceProvider> propertySourceProviders = ServiceContextManager.getServiceContext().getServices(PropertySourceProvider.class);
- for (PropertySourceProvider propertySourceProvider : propertySourceProviders) {
- Collection<PropertySource> sources = propertySourceProvider.getPropertySources();
- LOG.finer("PropertySourceProvider " + propertySourceProvider.getClass().getName() +
- " provided the following property sources: " + sources);
- propertySources.addAll(sources);
- }
-
- return propertySources;
- }
-
- @Override
- public void addPropertySources(PropertySource... propertySourcesToAdd) {
- Lock writeLock = propertySourceLock.writeLock();
- try {
- writeLock.lock();
- List<PropertySource> newPropertySources = new ArrayList<>(this.immutablePropertySources);
- newPropertySources.addAll(Arrays.asList(propertySourcesToAdd));
- Collections.sort(newPropertySources, new PropertySourceComparator());
-
- this.immutablePropertySources = Collections.unmodifiableList(newPropertySources);
- } finally {
- writeLock.unlock();
- }
- }
-
- private static class PropertySourceComparator implements Comparator<PropertySource>, Serializable {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Order property source reversely, the most important come first.
- *
- * @param source1 the first PropertySource
- * @param source2 the second PropertySource
- * @return the comparison result.
- */
- private int comparePropertySources(PropertySource source1, PropertySource source2) {
- if (source1.getOrdinal() < source2.getOrdinal()) {
- return -1;
- } else if (source1.getOrdinal() > source2.getOrdinal()) {
- return 1;
- } else {
- return source1.getClass().getName().compareTo(source2.getClass().getName());
- }
- }
-
- @Override
- public int compare(PropertySource source1, PropertySource source2) {
- return comparePropertySources(source1, source2);
- }
- }
-
- private static class PropertyFilterComparator implements Comparator<PropertyFilter>, Serializable{
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Compare 2 filters for ordering the filter chain.
- *
- * @param filter1 the first filter
- * @param filter2 the second filter
- * @return the comparison result
- */
- private int comparePropertyFilters(PropertyFilter filter1, PropertyFilter filter2) {
- Priority prio1 = filter1.getClass().getAnnotation(Priority.class);
- Priority prio2 = filter2.getClass().getAnnotation(Priority.class);
- int ord1 = prio1 != null ? prio1.value() : 0;
- int ord2 = prio2 != null ? prio2.value() : 0;
-
- if (ord1 < ord2) {
- return -1;
- } else if (ord1 > ord2) {
- return 1;
- } else {
- return filter1.getClass().getName().compareTo(filter2.getClass().getName());
- }
- }
-
- @Override
- public int compare(PropertyFilter filter1, PropertyFilter filter2) {
- return comparePropertyFilters(filter1, filter2);
- }
- }
-
- @Override
- public List<PropertySource> getPropertySources() {
- return immutablePropertySources;
- }
-
- @Override
- public <T> void addPropertyConverter(TypeLiteral<T> typeToConvert, PropertyConverter<T> propertyConverter) {
- propertyConverterManager.register(typeToConvert, propertyConverter);
- LOG.info("Added PropertyConverter: " + propertyConverter.getClass().getName());
- }
-
- @Override
- public Map<TypeLiteral<?>, List<PropertyConverter<?>>> getPropertyConverters() {
- return propertyConverterManager.getPropertyConverters();
- }
-
- @Override
- public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> targetType) {
- return propertyConverterManager.getPropertyConverters(targetType);
- }
-
- @Override
- public List<PropertyFilter> getPropertyFilters() {
- return immutablePropertyFilters;
- }
-
- @Override
- public PropertyValueCombinationPolicy getPropertyValueCombinationPolicy(){
- return propertyValueCombinationPolicy;
- }
-
- @Override
- public ConfigurationContextBuilder toBuilder() {
- return ConfigurationProvider.getConfigurationContextBuilder().setContext(this);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java
deleted file mode 100644
index 944a1e0..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java
+++ /dev/null
@@ -1,153 +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.core.internal;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValueCombinationPolicy;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Default implementation of {@link org.apache.tamaya.spi.ConfigurationContextBuilder}.
- */
-public class DefaultConfigurationContextBuilder implements ConfigurationContextBuilder {
-
- final Map<String, PropertySource> propertySources = new HashMap<>();
- final List<PropertyFilter> propertyFilters = new ArrayList<>();
- final Map<TypeLiteral<?>, List<PropertyConverter<?>>> propertyConverters = new HashMap<>();
- PropertyValueCombinationPolicy combinationPolicy;
-
- public DefaultConfigurationContextBuilder(){
- }
-
- @Override
- public ConfigurationContextBuilder setContext(ConfigurationContext context) {
- this.propertySources.clear();
- for(PropertySource ps:context.getPropertySources()) {
- this.propertySources.put(ps.getName(), ps);
- }
- this.propertyFilters.clear();
- this.propertyFilters.addAll(context.getPropertyFilters());
- this.propertyConverters.clear();
- this.propertyConverters.putAll(context.getPropertyConverters());
- this.combinationPolicy = context.getPropertyValueCombinationPolicy();
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder addPropertySources(Collection<PropertySource> propertySourcesToAdd) {
- for(PropertySource ps:propertySourcesToAdd){
- if(this.propertySources.containsKey(ps.getName())){
- throw new ConfigException("Duplicate PropertySource: " + ps.getName());
- }
- }
- for(PropertySource ps:propertySourcesToAdd) {
- this.propertySources.put(ps.getName(), ps);
- }
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder addPropertySources(PropertySource... propertySourcesToAdd) {
- return addPropertySources(Arrays.asList(propertySourcesToAdd));
- }
-
- @Override
- public ConfigurationContextBuilder removePropertySources(Collection<String> propertySourcesToRemove) {
- for(String key: propertySourcesToRemove){
- this.propertySources.remove(key);
- }
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder removePropertySources(String... propertySourcesToRemove) {
- return removePropertySources(Arrays.asList(propertySourcesToRemove));
- }
-
- @Override
- public ConfigurationContextBuilder addPropertyFilters(Collection<PropertyFilter> filters) {
- this.propertyFilters.addAll(filters);
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder addPropertyFilters(PropertyFilter... filters) {
- return addPropertyFilters(Arrays.asList(filters));
- }
-
- @Override
- public ConfigurationContextBuilder removePropertyFilters(Collection<PropertyFilter> filters) {
- this.propertyFilters.removeAll(filters);
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder removePropertyFilters(PropertyFilter... filters) {
- return removePropertyFilters(Arrays.asList(filters));
- }
-
- @Override
- public <T> ConfigurationContextBuilder addPropertyConverter(TypeLiteral<T> typeToConvert, PropertyConverter<T> propertyConverter) {
- List<PropertyConverter<?>> converters = this.propertyConverters.get(typeToConvert);
- if(converters==null){
- converters = new ArrayList<>();
- this.propertyConverters.put(typeToConvert, converters);
- }
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder removePropertyConverters(TypeLiteral<?> typeToConvert, PropertyConverter<?>... converters) {
- return removePropertyConverters(typeToConvert, Arrays.asList(converters));
- }
-
- @Override
- public ConfigurationContextBuilder removePropertyConverters(TypeLiteral<?> typeToConvert, Collection<PropertyConverter<?>> converters) {
- List<PropertyConverter<?>> existing = this.propertyConverters.get(typeToConvert);
- if(existing!=null) {
- existing.removeAll(converters);
- }
- return this;
- }
-
- @Override
- public ConfigurationContextBuilder setPropertyValueCombinationPolicy(PropertyValueCombinationPolicy policy) {
- this.combinationPolicy = Objects.requireNonNull(policy);
- return this;
- }
-
- @Override
- public ConfigurationContext build() {
- return new DefaultConfigurationContext(this);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationProvider.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationProvider.java
deleted file mode 100644
index 4330b7e..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationProvider.java
+++ /dev/null
@@ -1,65 +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.core.internal;
-
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.ConfigurationProviderSpi;
-import org.apache.tamaya.spi.ServiceContextManager;
-
-/**
- * Implementation of the Configuration API. This class uses the current {@link org.apache.tamaya.spi.ConfigurationContext} to evaluate the
- * chain of {@link org.apache.tamaya.spi.PropertySource} and {@link org.apache.tamaya.spi.PropertyFilter}
- * instance to evaluate the current Configuration.
- */
-public class DefaultConfigurationProvider implements ConfigurationProviderSpi {
-
- private ConfigurationContext context = new DefaultConfigurationContext();
- private Configuration config = new DefaultConfiguration(context);
-
- @Override
- public Configuration getConfiguration() {
- return config;
- }
-
- @Override
- public ConfigurationContext getConfigurationContext() {
- return context;
- }
-
- @Override
- public ConfigurationContextBuilder getConfigurationContextBuilder() {
- return ServiceContextManager.getServiceContext().getService(ConfigurationContextBuilder.class);
- }
-
- @Override
- public void setConfigurationContext(ConfigurationContext context){
- // TODO think on a SPI or move event part into API...
- this.config = new DefaultConfiguration(context);
- this.context = context;
- }
-
-
- @Override
- public boolean isConfigurationContextSettable() {
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java
deleted file mode 100644
index 9738b76..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java
+++ /dev/null
@@ -1,156 +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.core.internal;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spi.ServiceContext;
-
-import javax.annotation.Priority;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * This class implements the (default) {@link org.apache.tamaya.spi.ServiceContext} interface and hereby uses the JDK
- * {@link java.util.ServiceLoader} to load the services required.
- */
-public final class DefaultServiceContext implements ServiceContext {
- /**
- * List current services loaded, per class.
- */
- private final ConcurrentHashMap<Class<?>, List<Object>> servicesLoaded = new ConcurrentHashMap<>();
- /**
- * Singletons.
- */
- private final Map<Class<?>, Object> singletons = new ConcurrentHashMap<>();
-
- @Override
- public <T> T getService(Class<T> serviceType) {
- Object cached = singletons.get(serviceType);
- if (cached == null) {
- Collection<T> services = getServices(serviceType);
- if (services.isEmpty()) {
- cached = null;
- } else {
- cached = getServiceWithHighestPriority(services, serviceType);
- }
- if(cached!=null) {
- singletons.put(serviceType, cached);
- }
- }
- return serviceType.cast(cached);
- }
-
- /**
- * Loads and registers services.
- *
- * @param <T> the concrete type.
- * @param serviceType The service type.
- * @return the items found, never {@code null}.
- */
- @Override
- public <T> List<T> getServices(final Class<T> serviceType) {
- List<T> found = (List<T>) servicesLoaded.get(serviceType);
- if (found != null) {
- return found;
- }
- List<T> services = new ArrayList<>();
- try {
- for (T t : ServiceLoader.load(serviceType)) {
- services.add(t);
- }
- services = Collections.unmodifiableList(services);
- } catch (Exception e) {
- Logger.getLogger(DefaultServiceContext.class.getName()).log(Level.WARNING,
- "Error loading services current type " + serviceType, e);
- }
- final List<T> previousServices = List.class.cast(servicesLoaded.putIfAbsent(serviceType, (List<Object>) services));
- return previousServices != null ? previousServices : services;
- }
-
- /**
- * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such
- * annotation is present, a default priority is returned (1);
- * @param o the instance, not null.
- * @return a priority, by default 1.
- */
- public static int getPriority(Object o){
- int prio = 1; //X TODO discuss default priority
- Priority priority = o.getClass().getAnnotation(Priority.class);
- if (priority != null) {
- prio = priority.value();
- }
- return prio;
- }
-
- /**
- * @param services to scan
- * @param <T> type of the service
- *
- * @return the service with the highest {@link javax.annotation.Priority#value()}
- *
- * @throws ConfigException if there are multiple service implementations with the maximum priority
- */
- private <T> T getServiceWithHighestPriority(Collection<T> services, Class<T> serviceType) {
-
- // we do not need the priority stuff if the list contains only one element
- if (services.size() == 1) {
- return services.iterator().next();
- }
-
- Integer highestPriority = null;
- int highestPriorityServiceCount = 0;
- T highestService = null;
-
- for (T service : services) {
- int prio = getPriority(service);
- if (highestPriority == null || highestPriority < prio) {
- highestService = service;
- highestPriorityServiceCount = 1;
- highestPriority = prio;
- } else if (highestPriority == prio) {
- highestPriorityServiceCount++;
- }
- }
-
- if (highestPriorityServiceCount > 1) {
- throw new ConfigException(MessageFormat.format("Found {0} implementations for Service {1} with Priority {2}: {3}",
- highestPriorityServiceCount,
- serviceType.getName(),
- highestPriority,
- services));
- }
-
- return highestService;
- }
-
- @Override
- public int ordinal() {
- return 1;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIActivator.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIActivator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIActivator.java
deleted file mode 100644
index 8a54d35..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIActivator.java
+++ /dev/null
@@ -1,53 +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.core.internal;
-
-
-
-import org.apache.tamaya.spi.ServiceContextManager;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-import java.util.logging.Logger;
-
-/**
- * A bundle activator that registers the {@link OSGIServiceLoader}.
- */
-public class OSGIActivator implements BundleActivator {
-
- private static final Logger LOG = Logger.getLogger(OSGIActivator.class.getName());
-
- private OSGIServiceLoader serviceLoader;
-
- @Override
- public void start(BundleContext context) {
- // Register marker service
- ServiceContextManager.set(new OSGIServiceContext(context));
- LOG.info("Registered OSGI enabled ServiceContext...");
- serviceLoader = new OSGIServiceLoader();
- context.addBundleListener(serviceLoader);
- }
-
- @Override
- public void stop(BundleContext context) {
- if(serviceLoader!=null) {
- context.removeBundleListener(serviceLoader);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java
deleted file mode 100644
index bfc34bc..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java
+++ /dev/null
@@ -1,69 +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.core.internal;
-
-import org.osgi.framework.ServiceReference;
-
-import javax.annotation.Priority;
-import java.util.Comparator;
-
-/**
- * Comparator implementation for odering services loaded based on their increasing priority values.
- */
-class OSGIServiceComparator implements Comparator<ServiceReference> {
-
- @Override
- public int compare(ServiceReference o1, ServiceReference o2) {
- int prio = getPriority(o1) - getPriority(o2);
- if (prio < 0) {
- return 1;
- } else if (prio > 0) {
- return -1;
- } else {
- return 0; //o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
- }
- }
-
- /**
- * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such
- * annotation is present, a default priority is returned (1);
- *
- * @param o the instance, not null.
- * @return a priority, by default 1.
- */
- public static int getPriority(Object o) {
- return getPriority(o.getClass());
- }
-
- /**
- * Checks the given type optionally annotated with a @Priority. If present the annotation's value s evaluated.
- * If no such annotation is present, a default priority is returned (1);
- *
- * @param type the type, not null.
- * @return a priority, by default 1.
- */
- public static int getPriority(Class type) {
- int prio = 1;
- Priority priority = (Priority)type.getAnnotation(Priority.class);
- if (priority != null) {
- prio = priority.value();
- }
- return prio;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java
deleted file mode 100644
index 4cc6749..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java
+++ /dev/null
@@ -1,83 +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.core.internal;
-
-import org.apache.tamaya.spi.ServiceContext;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * ServiceContext implementation based on OSGI Service mechanisms.
- */
-public class OSGIServiceContext implements ServiceContext{
-
- private static final OSGIServiceComparator REF_COMPARATOR = new OSGIServiceComparator();
-
- private final BundleContext bundleContext;
-
- public OSGIServiceContext(BundleContext bundleContext){
- this.bundleContext = Objects.requireNonNull(bundleContext);
- }
-
- public boolean isInitialized(){
- return bundleContext != null;
- }
-
-
- @Override
- public int ordinal() {
- return 10;
- }
-
- @Override
- public <T> T getService(Class<T> serviceType) {
- ServiceReference<T> ref = this.bundleContext.getServiceReference(serviceType);
- if(ref!=null){
- return this.bundleContext.getService(ref);
- }
- return null;
- }
-
- @Override
- public <T> List<T> getServices(Class<T> serviceType) {
- List<ServiceReference<T>> refs = new ArrayList<>();
- try {
- refs.addAll(this.bundleContext.getServiceReferences(serviceType, null));
- Collections.sort(refs, REF_COMPARATOR);
- List<T> services = new ArrayList<>(refs.size());
- for(ServiceReference<T> ref:refs){
- T service = bundleContext.getService(ref);
- if(service!=null) {
- services.add(service);
- }
- }
- return services;
- } catch (InvalidSyntaxException e) {
- e.printStackTrace();
- return Collections.emptyList();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java
deleted file mode 100644
index 7cd98d2..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java
+++ /dev/null
@@ -1,157 +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.core.internal;
-
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.util.ConcurrentModificationException;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceFactory;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * An bundle listener that registers services defined in META-INF/services, when a bundle is starting.
- *
- * @author anatole@apache.org
- */
-public class OSGIServiceLoader implements BundleListener {
- // Provide logging
- private static final Logger log = Logger.getLogger(OSGIServiceLoader.class.getName());
-
- private Map<Class, ServiceTracker<Object,Object>> services = new ConcurrentHashMap<>();
-
- @Override
- public void bundleChanged(BundleEvent bundleEvent) {
- // Parse and create metadta on STARTING
- if (bundleEvent.getType() == BundleEvent.STARTED) {
- Bundle bundle = bundleEvent.getBundle();
- if (bundle.getEntry("META-INF/services/") == null) {
- return;
- }
- Enumeration<String> entryPaths = bundle.getEntryPaths("META-INF/services/");
- while (entryPaths.hasMoreElements()) {
- String entryPath = entryPaths.nextElement();
- if(!entryPath.endsWith("/")) {
- processEntryPath(bundle, entryPath);
- }
- }
- }
- }
-
- private void processEntryPath(Bundle bundle, String entryPath) {
- try {
- String serviceName = entryPath.substring("META-INF/services/".length());
- Class<?> serviceClass = bundle.loadClass(serviceName);
-
- URL child = bundle.getEntry(entryPath);
- InputStream inStream = child.openStream();
-
- BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
- String implClassName = br.readLine();
- while (implClassName != null){
- int hashIndex = implClassName.indexOf("#");
- if (hashIndex > 0) {
- implClassName = implClassName.substring(0, hashIndex-1);
- }
- else if (hashIndex == 0) {
- implClassName = "";
- }
- implClassName = implClassName.trim();
- if (implClassName.length() > 0) {
- try {
- // Load the service class
- Class<?> implClass = bundle.loadClass(implClassName);
- if (!serviceClass.isAssignableFrom(implClass)) {
- log.warning("Configured service: " + implClassName + " is not assignble to " +
- serviceClass.getName());
- continue;
- }
- // Provide service properties
- Hashtable<String, String> props = new Hashtable<>();
- props.put(Constants.VERSION_ATTRIBUTE, bundle.getVersion().toString());
- String vendor = bundle.getHeaders().get(Constants.BUNDLE_VENDOR);
- props.put(Constants.SERVICE_VENDOR, (vendor != null ? vendor : "anonymous"));
- // Translate annotated @Priority into a service ranking
- props.put(Constants.SERVICE_RANKING,
- String.valueOf(PriorityServiceComparator.getPriority(implClass)));
-
- // Register the service factory on behalf of the intercepted bundle
- JDKUtilServiceFactory factory = new JDKUtilServiceFactory(implClass);
- BundleContext bundleContext = bundle.getBundleContext();
- bundleContext.registerService(serviceName, factory, props);
- }
- catch(Exception e){
- log.log(Level.SEVERE,
- "Failed to load service class using ServiceLoader logic: " + implClassName, e);
- }
- }
- implClassName = br.readLine();
- }
- br.close();
- }
- catch (RuntimeException rte) {
- throw rte;
- }
- catch (Exception e) {
- log.log(Level.SEVERE, "Failed to read services from: " + entryPath, e);
- }
- }
-
-
- /**
- * Service factory simply instantiating the configured service.
- */
- static class JDKUtilServiceFactory implements ServiceFactory
- {
- private final Class<?> serviceClass;
-
- public JDKUtilServiceFactory(Class<?> serviceClass) {
- this.serviceClass = serviceClass;
- }
-
- @Override
- public Object getService(Bundle bundle, ServiceRegistration registration) {
- try {
- return serviceClass.newInstance();
- }
- catch (Exception ex) {
- ex.printStackTrace();
- throw new IllegalStateException("Cannot instanciate service", ex);
- }
- }
-
- @Override
- public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java
deleted file mode 100644
index c0cfca6..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java
+++ /dev/null
@@ -1,67 +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.core.internal;
-
-import javax.annotation.Priority;
-import java.util.Comparator;
-
-/**
- * Comparator implementation for odering services loaded based on their increasing priority values.
- */
-public class PriorityServiceComparator implements Comparator<Object> {
-
- @Override
- public int compare(Object o1, Object o2) {
- int prio = getPriority(o1) - getPriority(o2);
- if (prio < 0) {
- return 1;
- } else if (prio > 0) {
- return -1;
- } else {
- return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
- }
- }
-
- /**
- * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such
- * annotation is present, a default priority is returned (1);
- *
- * @param o the instance, not null.
- * @return a priority, by default 1.
- */
- public static int getPriority(Object o) {
- return getPriority(o.getClass());
- }
-
- /**
- * Checks the given type optionally annotated with a @Priority. If present the annotation's value s evaluated.
- * If no such annotation is present, a default priority is returned (1);
- *
- * @param type the type, not null.
- * @return a priority, by default 1.
- */
- public static int getPriority(Class type) {
- int prio = 1;
- Priority priority = (Priority)type.getAnnotation(Priority.class);
- if (priority != null) {
- prio = priority.value();
- }
- return prio;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java
deleted file mode 100644
index 2ec48b4..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java
+++ /dev/null
@@ -1,448 +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.core.internal;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.core.internal.converters.EnumConverter;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.ServiceContextManager;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Manager that deals with {@link org.apache.tamaya.spi.PropertyConverter} instances.
- * This class is thread-safe.
- */
-public class PropertyConverterManager {
- /**
- * The logger used.
- */
- private static final Logger LOG = Logger.getLogger(PropertyConverterManager.class.getName());
- /**
- * The registered converters.
- */
- private final Map<TypeLiteral<?>, List<PropertyConverter<?>>> converters = new ConcurrentHashMap<>();
- /**
- * The transitive converters.
- */
- private final Map<TypeLiteral<?>, List<PropertyConverter<?>>> transitiveConverters = new ConcurrentHashMap<>();
- /**
- * The lock used.
- */
- private final ReadWriteLock lock = new ReentrantReadWriteLock();
-
- private static final Comparator<Object> PRIORITY_COMPARATOR = new Comparator<Object>() {
-
- @Override
- public int compare(Object o1, Object o2) {
- int prio = DefaultServiceContext.getPriority(o1) - DefaultServiceContext.getPriority(o2);
- if (prio < 0) {
- return 1;
- } else if (prio > 0) {
- return -1;
- } else {
- return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
- }
- }
- };
-
- /**
- * Constructor.
- */
- public PropertyConverterManager() {
- this(true);
- }
-
- public PropertyConverterManager(boolean init) {
- if (init) {
- initConverters();
- }
- }
-
- /**
- * Registers the default converters provided out of the box.
- */
- protected void initConverters() {
- for (PropertyConverter conv : ServiceContextManager.getServiceContext().getServices(PropertyConverter.class)) {
- Type type = TypeLiteral.getGenericInterfaceTypeParameters(conv.getClass(), PropertyConverter.class)[0];
- register(TypeLiteral.of(type), conv);
- }
- }
-
- /**
- * Registers a ew converter instance.
- *
- * @param targetType the target type, not null.
- * @param converter the converter, not null.
- * @param <T> the type.
- */
- public <T> void register(TypeLiteral<T> targetType, PropertyConverter<T> converter) {
- Objects.requireNonNull(converter);
- Lock writeLock = lock.writeLock();
- try {
- writeLock.lock();
- List converters = List.class.cast(this.converters.get(targetType));
- List<PropertyConverter<?>> newConverters = new ArrayList<>();
- if (converters != null) {
- newConverters.addAll(converters);
- }
- newConverters.add(converter);
- Collections.sort(newConverters, PRIORITY_COMPARATOR);
- this.converters.put(targetType, Collections.unmodifiableList(newConverters));
- // evaluate transitive closure for all inherited supertypes and implemented interfaces
- // direct implemented interfaces
- for (Class<?> ifaceType : targetType.getRawType().getInterfaces()) {
- converters = List.class.cast(this.transitiveConverters.get(TypeLiteral.of(ifaceType)));
- newConverters = new ArrayList<>();
- if (converters != null) {
- newConverters.addAll(converters);
- }
- newConverters.add(converter);
- Collections.sort(newConverters, PRIORITY_COMPARATOR);
- this.transitiveConverters.put(TypeLiteral.of(ifaceType), Collections.unmodifiableList(newConverters));
- }
- Class<?> superClass = targetType.getRawType().getSuperclass();
- while (superClass != null && !superClass.equals(Object.class)) {
- converters = List.class.cast(this.transitiveConverters.get(TypeLiteral.of(superClass)));
- newConverters = new ArrayList<>();
- if (converters != null) {
- newConverters.addAll(converters);
- }
- newConverters.add(converter);
- Collections.sort(newConverters, PRIORITY_COMPARATOR);
- this.transitiveConverters.put(TypeLiteral.of(superClass), Collections.unmodifiableList(newConverters));
- for (Class<?> ifaceType : superClass.getInterfaces()) {
- converters = List.class.cast(this.transitiveConverters.get(TypeLiteral.of(ifaceType)));
- newConverters = new ArrayList<>();
- if (converters != null) {
- newConverters.addAll(converters);
- }
- newConverters.add(converter);
- Collections.sort(newConverters, PRIORITY_COMPARATOR);
- this.transitiveConverters.put(TypeLiteral.of(ifaceType), Collections.unmodifiableList(newConverters));
- }
- superClass = superClass.getSuperclass();
- }
- } finally {
- writeLock.unlock();
- }
- }
-
- /**
- * Allows to evaluate if a given target type is supported.
- *
- * @param targetType the target type, not null.
- * @return true, if a converter for the given type is registered, or a default one can be created.
- */
- public boolean isTargetTypeSupported(TypeLiteral<?> targetType) {
- return converters.containsKey(targetType) || transitiveConverters.containsKey(targetType) || createDefaultPropertyConverter(targetType) != null;
- }
-
- /**
- * Get a map of all property converters currently registered. This will not contain the converters that
- * may be created, when an instance is adapted, which provides a String constructor or compatible
- * factory methods taking a single String instance.
- *
- * @return the current map of instantiated and registered converters.
- * @see #createDefaultPropertyConverter(org.apache.tamaya.TypeLiteral)
- */
- public Map<TypeLiteral<?>, List<PropertyConverter<?>>> getPropertyConverters() {
- Lock readLock = lock.readLock();
- try {
- readLock.lock();
- return new HashMap<>(this.converters);
- } finally {
- readLock.unlock();
- }
- }
-
- /**
- * Get the list of all current registered converters for the given target type.
- * If not converters are registered, they component tries to create and register a dynamic
- * converter based on String costructor or static factory methods available.
- * The converters provided are of the following type and returned in the following order:
- * <ul>
- * <li>Converters mapped explicitly to the required target type are returned first, ordered
- * by decreasing priority. This means, if explicit converters are registered these are used
- * primarly for converting a value.</li>
- * <li>The target type of each explicitly registered converter also can be transitively mapped to
- * 1) all directly implemented interfaces, 2) all its superclasses (except Object), 3) all the interfaces
- * implemented by its superclasses. These groups of transitive converters is returned similarly in the
- * order as mentioned, whereas also here a priority based decreasing ordering is applied.</li>
- * <li>java.lang wrapper classes and native types are automatically mapped.</li>
- * <li>If no explicit converters are registered, for Enum types a default implementation is provided that
- * compares the configuration values with the different enum members defined (cases sensitive mapping).</li>
- * </ul>
- * <p>
- * So given that list above directly registered mappings always are tried first, before any transitive mapping
- * should be used. Also in all cases @Priority annotations are honored for ordering of the converters in place.
- * Transitive conversion is supported for all directly implemented interfaces (including inherited ones) and
- * the inheritance hierarchy (exception Object). Superinterfaces of implemented interfaces are ignored.
- *
- * @param targetType the target type, not null.
- * @param <T> the type class
- * @return the ordered list of converters (may be empty for not convertible types).
- * @see #createDefaultPropertyConverter(org.apache.tamaya.TypeLiteral)
- */
- public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> targetType) {
- Lock readLock = lock.readLock();
- List<PropertyConverter<T>> converterList = new ArrayList<>();
- List<PropertyConverter<T>> converters;
- // direct mapped converters
- try {
- readLock.lock();
- addConvertersToList(List.class.cast(this.converters.get(targetType)), converterList);
- } finally {
- readLock.unlock();
- }
- // transitive converter
- try {
- readLock.lock();
- addConvertersToList(List.class.cast(this.transitiveConverters.get(targetType)), converterList);
- } finally {
- readLock.unlock();
- }
- // handling of java.lang wrapper classes
- TypeLiteral<T> boxedType = mapBoxedType(targetType);
- if (boxedType != null) {
- try {
- readLock.lock();
- addConvertersToList(List.class.cast(this.converters.get(boxedType)), converterList);
- } finally {
- readLock.unlock();
- }
- }
- if (converterList.isEmpty()) {
- // adding any converters created on the fly, e.g. for enum types.
- PropertyConverter<T> defaultConverter = createDefaultPropertyConverter(targetType);
- if (defaultConverter != null) {
- register(targetType, defaultConverter);
- try {
- readLock.lock();
- addConvertersToList(List.class.cast(this.converters.get(targetType)), converterList);
- } finally {
- readLock.unlock();
- }
- }
- }
- // check for parametrized types, ignoring param type
- // direct mapped converters
- if(targetType.getType()!=null) {
- try {
- readLock.lock();
- addConvertersToList(List.class.cast(this.converters.get(
- TypeLiteral.of(targetType.getRawType()))), converterList);
- } finally {
- readLock.unlock();
- }
- }
- return converterList;
- }
-
- private <T> void addConvertersToList(Collection<PropertyConverter<T>> converters, List<PropertyConverter<T>> converterList) {
- if (converters != null) {
- for(PropertyConverter<T> conv:converters) {
- if(!converterList.contains(conv)) {
- converterList.add(conv);
- }
- }
- }
- }
-
- /**
- * Maps native types to the corresponding boxed types.
- *
- * @param targetType the native type.
- * @param <T> the type
- * @return the boxed type, or null.
- */
- private <T> TypeLiteral<T> mapBoxedType(TypeLiteral<T> targetType) {
- Type parameterType = targetType.getType();
- if (parameterType == int.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Integer.class));
- }
- if (parameterType == short.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Short.class));
- }
- if (parameterType == byte.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Byte.class));
- }
- if (parameterType == long.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Long.class));
- }
- if (parameterType == boolean.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Boolean.class));
- }
- if (parameterType == char.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Character.class));
- }
- if (parameterType == float.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Float.class));
- }
- if (parameterType == double.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Double.class));
- }
- if (parameterType == int[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Integer[].class));
- }
- if (parameterType == short[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Short[].class));
- }
- if (parameterType == byte[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Byte[].class));
- }
- if (parameterType == long[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Long[].class));
- }
- if (parameterType == boolean.class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Boolean.class));
- }
- if (parameterType == char[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Character[].class));
- }
- if (parameterType == float[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Float[].class));
- }
- if (parameterType == double[].class) {
- return TypeLiteral.class.cast(TypeLiteral.of(Double[].class));
- }
- return null;
- }
-
- /**
- * Creates a dynamic PropertyConverter for the given target type.
- *
- * @param targetType the target type
- * @param <T> the type class
- * @return a new converter, or null.
- */
- protected <T> PropertyConverter<T> createDefaultPropertyConverter(final TypeLiteral<T> targetType) {
- if (Enum.class.isAssignableFrom(targetType.getRawType())) {
- return new EnumConverter<>(targetType.getRawType());
- }
- PropertyConverter<T> converter = null;
- final Method factoryMethod = getFactoryMethod(targetType.getRawType(), "of", "valueOf", "instanceOf", "getInstance", "from", "fromString", "parse");
- if (factoryMethod != null) {
- converter = new DefaultPropertyConverter<>(factoryMethod, targetType.getRawType());
- }
- if (converter == null) {
- final Constructor<T> constr;
- try {
- constr = targetType.getRawType().getDeclaredConstructor(String.class);
- } catch (NoSuchMethodException e) {
- LOG.log(Level.FINEST, "No matching constrctor for " + targetType, e);
- return null;
- }
- converter = new PropertyConverter<T>() {
- @Override
- public T convert(String value, ConversionContext context) {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- @Override
- public Object run() {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- @Override
- public Object run() {
- constr.setAccessible(true);
- return null;
- }
- });
- return null;
- }
- });
- try {
- return constr.newInstance(value);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Error creating new PropertyConverter instance " + targetType, e);
- }
- return null;
- }
- };
- }
- return converter;
- }
-
- /**
- * Tries to evaluate a factory method that can be used to create an instance based on a String.
- *
- * @param type the target type
- * @param methodNames the possible static method names
- * @return the first method found, or null.
- */
- private Method getFactoryMethod(Class<?> type, String... methodNames) {
- Method m;
- for (String name : methodNames) {
- try {
- m = type.getDeclaredMethod(name, String.class);
- return m;
- } catch (NoSuchMethodException | RuntimeException e) {
- LOG.finest("No such factory method found on type: " + type.getName() + ", methodName: " + name);
- }
- }
- return null;
- }
-
- private static class DefaultPropertyConverter<T> implements PropertyConverter<T> {
-
- private final Method factoryMethod;
- private final Class<T> targetType;
-
- DefaultPropertyConverter(Method factoryMethod, Class<T> targetType){
- this.factoryMethod = Objects.requireNonNull(factoryMethod);
- this.targetType = Objects.requireNonNull(targetType);
- }
-
- @Override
- public T convert(String value, ConversionContext context) {
- context.addSupportedFormats(getClass(), "<String -> "+factoryMethod.toGenericString());
-
- if (!Modifier.isStatic(factoryMethod.getModifiers())) {
- throw new ConfigException(factoryMethod.toGenericString() +
- " is not a static method. Only static " +
- "methods can be used as factory methods.");
- }
- try {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- @Override
- public Object run() {
- factoryMethod.setAccessible(true);
- return null;
- }
- });
- Object invoke = factoryMethod.invoke(null, value);
- return targetType.cast(invoke);
- } catch (Exception e) {
- throw new ConfigException("Failed to decode '" + value + "'", e);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFilterComparator.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFilterComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFilterComparator.java
deleted file mode 100644
index abf22be..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFilterComparator.java
+++ /dev/null
@@ -1,60 +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.core.internal;
-
-import org.apache.tamaya.spi.PropertyFilter;
-
-import javax.annotation.Priority;
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * Comparator for PropertyFilters based on their priority annotations.
- */
-public class PropertyFilterComparator implements Comparator<PropertyFilter>, Serializable {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Compare 2 filters for ordering the filter chain.
- *
- * @param filter1 the first filter
- * @param filter2 the second filter
- * @return the comparison result
- */
- private int comparePropertyFilters(PropertyFilter filter1, PropertyFilter filter2) {
- Priority prio1 = filter1.getClass().getAnnotation(Priority.class);
- Priority prio2 = filter2.getClass().getAnnotation(Priority.class);
- int ord1 = prio1 != null ? prio1.value() : 0;
- int ord2 = prio2 != null ? prio2.value() : 0;
-
- if (ord1 < ord2) {
- return -1;
- } else if (ord1 > ord2) {
- return 1;
- } else {
- return filter1.getClass().getName().compareTo(filter2.getClass().getName());
- }
- }
-
- @Override
- public int compare(PropertyFilter filter1, PropertyFilter filter2) {
- return comparePropertyFilters(filter1, filter2);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFiltering.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFiltering.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFiltering.java
deleted file mode 100644
index 1872be4..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyFiltering.java
+++ /dev/null
@@ -1,147 +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.core.internal;
-
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.FilterContext;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertySource;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Implementation of the Configuration API. This class uses the current {@link ConfigurationContext} to evaluate the
- * chain of {@link PropertySource} and {@link PropertyFilter}
- * instance to evaluate the current Configuration.
- */
-public final class PropertyFiltering{
- /**
- * The logger.
- */
- private static final Logger LOG = Logger.getLogger(PropertyFiltering.class.getName());
-
- /**
- * The maximal number of filter cycles performed before aborting.
- */
- private static final int MAX_FILTER_LOOPS = 10;
-
- /**
- * Private singleton constructor.
- */
- private PropertyFiltering(){}
-
- public static String applyFilter(String key, Map<String,String> configData, ConfigurationContext configurationContext) {
- // Apply filters to values, prevent values filtered to null!
- String result = configData.get(key);
- for (int i = 0; i < MAX_FILTER_LOOPS; i++) {
- boolean changed = false;
- // Apply filters to values, prevent values filtered to null!
- FilterContext filterContext = new FilterContext(key, configData, true);
- for (PropertyFilter filter : configurationContext.getPropertyFilters()) {
- String newValue = filter.filterProperty(result, filterContext);
- if (newValue != null && !newValue.equals(result)) {
- changed = true;
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Filter - " + key + ": " + result + " -> " + newValue + " by " + filter);
- }
- } else if (result != null && !result.equals(newValue)) {
- changed = true;
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Filter - " + key + ": " + result + " -> " + newValue + " by " + filter);
- }
- }
- result = newValue;
- }
- if (!changed) {
- LOG.finest("Finishing filter loop, no changes detected.");
- break;
- } else {
- if (i == (MAX_FILTER_LOOPS - 1)) {
- if (LOG.isLoggable(Level.WARNING)) {
- LOG.warning("Maximal filter loop count reached, aborting filter evaluation after cycles: " + i);
- }
- } else {
- LOG.finest("Repeating filter loop, changes detected.");
- }
- }
- }
- return result;
- }
-
- public static Map<String, String> applyFilters(Map<String, String> inputMap, ConfigurationContext configurationContext) {
- Map<String, String> resultMap = new HashMap<>(inputMap);
- // Apply filters to values, prevent values filtered to null!
- Map<String, String> metaData = filterMetadata(inputMap);
- for (int i = 0; i < MAX_FILTER_LOOPS; i++) {
- AtomicInteger changes = new AtomicInteger();
- for (Map.Entry<String, String> entry : inputMap.entrySet()) {
- FilterContext filterContext = new FilterContext(entry.getKey(), inputMap, false);
- for (PropertyFilter filter : configurationContext.getPropertyFilters()) {
- final String k = entry.getKey();
- final String v = entry.getValue();
- String newValue = filter.filterProperty(v, filterContext);
- if (newValue != null && !newValue.equals(v)) {
- changes.incrementAndGet();
- LOG.finest("Filter - " + k + ": " + v + " -> " + newValue + " by " + filter);
- } else if (v != null && !v.equals(newValue)) {
- changes.incrementAndGet();
- LOG.finest("Filter - " + k + ": " + v + " -> " + newValue + " by " + filter);
- }
- // Remove null values
- if (null != newValue) {
- resultMap.put(k, newValue);
- }
- else{
- resultMap.remove(k);
- }
- }
- }
- if (changes.get() == 0) {
- LOG.finest("Finishing filter loop, no changes detected.");
- break;
- } else {
- if (i == (MAX_FILTER_LOOPS - 1)) {
- if (LOG.isLoggable(Level.WARNING)) {
- LOG.warning("Maximal filter loop count reached, aborting filter evaluation after cycles: " + i);
- }
- } else {
- LOG.finest("Repeating filter loop, changes detected: " + changes.get());
- }
- changes.set(0);
- }
- }
- return resultMap;
- }
-
- private static Map<String, String> filterMetadata(Map<String, String> inputMap) {
- Map<String,String> result = new HashMap<>();
- for(Map.Entry<String,String> en:inputMap.entrySet()){
- if(en.getKey().startsWith("_")){
- result.put(en.getKey(), en.getValue());
- }
- }
- return Collections.unmodifiableMap(result);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java
deleted file mode 100644
index 24ee1f2..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java
+++ /dev/null
@@ -1,54 +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.core.internal;
-
-import org.apache.tamaya.spi.PropertySource;
-
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * Comparator for ordering of PropertySources based on their ordinal method and class name.
- */
-public class PropertySourceComparator implements Comparator<PropertySource>, Serializable {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Order property source reversely, the most important come first.
- *
- * @param source1 the first PropertySource
- * @param source2 the second PropertySource
- * @return the comparison result.
- */
- private int comparePropertySources(PropertySource source1, PropertySource source2) {
- if (source1.getOrdinal() < source2.getOrdinal()) {
- return -1;
- } else if (source1.getOrdinal() > source2.getOrdinal()) {
- return 1;
- } else {
- return source1.getClass().getName().compareTo(source2.getClass().getName());
- }
- }
-
- @Override
- public int compare(PropertySource source1, PropertySource source2) {
- return comparePropertySources(source1, source2);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/ReflectionUtil.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/ReflectionUtil.java b/code/core/src/main/java/org/apache/tamaya/core/internal/ReflectionUtil.java
deleted file mode 100644
index 6c7a1d2..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/ReflectionUtil.java
+++ /dev/null
@@ -1,42 +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.core.internal;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-
-
-/**
- * Small utility class used by other parts.
- */
-public final class ReflectionUtil {
-
- private ReflectionUtil(){}
-
- public static ParameterizedType getParametrizedType(Class<?> clazz) {
- Type[] genericTypes = clazz.getGenericInterfaces();
- for (Type type : genericTypes) {
- if (type instanceof ParameterizedType) {
- return (ParameterizedType) type;
- }
-
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/43468987/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java
----------------------------------------------------------------------
diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java
deleted file mode 100644
index 2c17214..0000000
--- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java
+++ /dev/null
@@ -1,63 +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.core.internal.converters;
-
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Objects;
-import java.util.logging.Logger;
-
-/**
- * Converter, converting from String to BigDecimal, the supported format is one of the following:
- * <ul>
- * <li>232573527352.76352753</li>
- * <li>-23257352.735276352753</li>
- * <li>-0xFFFFFF (integral numbers only)</li>
- * <li>-0XFFFFAC (integral numbers only)</li>
- * <li>0xFFFFFF (integral numbers only)</li>
- * <li>0XFFFFAC (integral numbers only)</li>
- * </ul>
- */
-public class BigDecimalConverter implements PropertyConverter<BigDecimal>{
- /** The logger. */
- private static final Logger LOG = Logger.getLogger(BigDecimalConverter.class.getName());
- /** Converter to be used if the format is not directly supported by BigDecimal, e.g. for integral hex values. */
- private final BigIntegerConverter integerConverter = new BigIntegerConverter();
-
- @Override
- public BigDecimal convert(String value, ConversionContext context) {
- context.addSupportedFormats(getClass(), "<bigDecimal> -> new BigDecimal(String)");
-
- String trimmed = Objects.requireNonNull(value).trim();
- try{
- return new BigDecimal(trimmed);
- } catch(Exception e){
- LOG.finest("Parsing BigDecimal failed, trying BigInteger for: " + value);
- BigInteger bigInt = integerConverter.convert(value, context);
- if(bigInt!=null){
- return new BigDecimal(bigInt);
- }
- LOG.finest("Failed to parse BigDecimal from: " + value);
- return null;
- }
- }
-}