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/20 00:59:13 UTC
[3/7] incubator-tamaya git commit: - Minimalized API. - Propagated
change to rest of modules.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/defaultconfig/src/main/java/org/apache/tamaya/defaults/package-info.java
----------------------------------------------------------------------
diff --git a/modules/defaultconfig/src/main/java/org/apache/tamaya/defaults/package-info.java b/modules/defaultconfig/src/main/java/org/apache/tamaya/defaults/package-info.java
new file mode 100644
index 0000000..7edba91
--- /dev/null
+++ b/modules/defaultconfig/src/main/java/org/apache/tamaya/defaults/package-info.java
@@ -0,0 +1,26 @@
+/*
+ * 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.
+ */
+/**
+ * This package provides an decorator for {@link org.apache.tamaya.defaults.ConfigurationWithDefaults}
+ * that allows additionally to pass default values either as Strings or typed
+ * objects.
+ *
+ * @see org.apache.tamaya.defaults.ConfigurationWithDefaults
+ */
+package org.apache.tamaya.defaults;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/defaultconfig/src/main/resources/META-INF/services/org.apache.tamaya.adapter.spi.ConfigurationAdapter
----------------------------------------------------------------------
diff --git a/modules/defaultconfig/src/main/resources/META-INF/services/org.apache.tamaya.adapter.spi.ConfigurationAdapter b/modules/defaultconfig/src/main/resources/META-INF/services/org.apache.tamaya.adapter.spi.ConfigurationAdapter
new file mode 100644
index 0000000..56fc494
--- /dev/null
+++ b/modules/defaultconfig/src/main/resources/META-INF/services/org.apache.tamaya.adapter.spi.ConfigurationAdapter
@@ -0,0 +1,17 @@
+# 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.
+org.apache.tamaya.defaults.internal.ConfigurationWithDefaultsAdapter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/formats/pom.xml
----------------------------------------------------------------------
diff --git a/modules/formats/pom.xml b/modules/formats/pom.xml
index f85a9d4..96282f5 100644
--- a/modules/formats/pom.xml
+++ b/modules/formats/pom.xml
@@ -42,6 +42,11 @@ under the License.
</dependency>
<dependency>
<groupId>org.apache.tamaya.ext</groupId>
+ <artifactId>tamaya-builder</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tamaya.ext</groupId>
<artifactId>tamaya-resources</artifactId>
<version>${project.version}</version>
</dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/formats/src/main/java/org/apache/tamaya/format/FlattenedDefaultPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/formats/src/main/java/org/apache/tamaya/format/FlattenedDefaultPropertySource.java b/modules/formats/src/main/java/org/apache/tamaya/format/FlattenedDefaultPropertySource.java
index 9d2097f..a1d510a 100644
--- a/modules/formats/src/main/java/org/apache/tamaya/format/FlattenedDefaultPropertySource.java
+++ b/modules/formats/src/main/java/org/apache/tamaya/format/FlattenedDefaultPropertySource.java
@@ -18,8 +18,8 @@
*/
package org.apache.tamaya.format;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
+import org.apache.tamaya.builder.spi.PropertySource;
+import org.apache.tamaya.builder.spi.PropertyValue;
import java.util.Collections;
import java.util.HashMap;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/injection/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java b/modules/injection/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
index de770db..c31f946 100644
--- a/modules/injection/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
+++ b/modules/injection/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
@@ -20,7 +20,7 @@ package org.apache.tamaya.inject.internal;
import org.apache.tamaya.ConfigException;
import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.builder.ConfigurationBuilder;
+import org.apache.tamaya.builder.PropertySourceBasedConfigurationBuilder;
import org.apache.tamaya.inject.api.ConfiguredItemSupplier;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.api.Config;
@@ -66,7 +66,7 @@ public class DefaultDynamicValueTest {
};
private Map<String,String> properties = new HashMap<>();
- private Configuration config = new ConfigurationBuilder().addPropertySources(
+ private Configuration config = new PropertySourceBasedConfigurationBuilder().addPropertySources(
new PropertySource() {
@Override
public int getOrdinal() {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/pom.xml
----------------------------------------------------------------------
diff --git a/modules/pom.xml b/modules/pom.xml
index 43f75e5..e99b6eb 100644
--- a/modules/pom.xml
+++ b/modules/pom.xml
@@ -33,6 +33,10 @@ under the License.
<packaging>pom</packaging>
<modules>
+ <module>servicecontext</module>
+ <module>adaptersupport</module>
+ <module>types</module>
+ <module>defaultconfig</module>
<module>builder</module>
<module>classloader-support</module>
<module>collections</module>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContext.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContext.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContext.java
new file mode 100644
index 0000000..56dae8d
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContext.java
@@ -0,0 +1,67 @@
+/*
+ * 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.servicecontext;
+
+import java.util.List;
+
+
+/**
+ * This class models the component that is managing the lifecycle current the
+ * services used by the Configuration API.
+ */
+public interface ServiceContext {
+
+ /**
+ * @return ordinal of the ServiceContext. The one with the highest ordinal will be taken.
+ */
+ int ordinal();
+
+ /**
+ * Access a service singleton via its type.
+ * If multiple implementations for the very serviceType exist then
+ * the one with the highest {@link javax.annotation.Priority} will be used.
+ *
+ * @param <T> the type of the service type.
+ * @param serviceType the service type.
+ * @return The instance to be used, or {@code null}
+ * @throws org.apache.tamaya.ConfigException if there are multiple service implementations with the maximum priority.
+ */
+ <T> T getService(Class<T> serviceType);
+
+ /**
+ * Access a list current services, given its type. The bootstrap mechanism should
+ * order the instance for precedence, hereby the most significant should be
+ * first in order.
+ *
+ * @param serviceType
+ * the service type.
+ * @param <T> the type of the list element returned by this method
+ * @return The instance to be used, never {@code null}
+ */
+ <T> List<T> getServices(Class<T> serviceType);
+
+ /**
+ * 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.
+ */
+ int getPriority(Object o);
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContextManager.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContextManager.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContextManager.java
new file mode 100644
index 0000000..5749fc4
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/ServiceContextManager.java
@@ -0,0 +1,116 @@
+/*
+ * 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.servicecontext;
+
+import java.util.Objects;
+import java.util.ServiceLoader;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ * This singleton provides access to the services available in the current {@link ServiceContext}. The
+ * behaviour can be adapted, by calling {@link ServiceContextManager#set(ServiceContext)} before accessing any
+ * services.
+ */
+public final class ServiceContextManager {
+
+ /** The logger used. */
+ private static final Logger LOG = Logger.getLogger(ServiceContextManager.class.getName());
+
+ /**
+ * The ServiceProvider used.
+ */
+ private static volatile ServiceContext serviceContextProviderDelegate;
+
+ /**
+ * Private singletons constructor.
+ */
+ private ServiceContextManager() {
+ }
+
+ /**
+ * Load the {@link ServiceContext} to be used.
+ *
+ * @return {@link ServiceContext} to be used for loading the services.
+ */
+ private static ServiceContext loadDefaultServiceProvider() {
+ ServiceContext highestServiceContext = null;
+ try {
+ int highestOrdinal = 0;
+ for (ServiceContext serviceContext : ServiceLoader.load(ServiceContext.class)) {
+ if(highestServiceContext==null){
+ highestServiceContext = serviceContext;
+ }else if (serviceContext.ordinal() > highestOrdinal) {
+ highestServiceContext = serviceContext;
+ highestOrdinal = serviceContext.ordinal();
+ }
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException("ServiceContext not loadable", e);
+ }
+ if (highestServiceContext==null){
+ throw new IllegalStateException("No ServiceContext found");
+ }
+ LOG.info("Using Service Context of type: " + highestServiceContext.getClass().getName());
+ return highestServiceContext;
+ }
+
+ /**
+ * Replace the current {@link ServiceContext} in use.
+ *
+ * @param serviceContextProvider the new {@link ServiceContext}, not null.
+ * @return the currently used context after setting it.
+ */
+ public static ServiceContext set(ServiceContext serviceContextProvider) {
+ ServiceContext currentContext = ServiceContextManager.serviceContextProviderDelegate;
+ Objects.requireNonNull(serviceContextProvider);
+
+ synchronized (ServiceContextManager.class) {
+ if (ServiceContextManager.serviceContextProviderDelegate == null) {
+ ServiceContextManager.serviceContextProviderDelegate = serviceContextProvider;
+ LOG.log(Level.INFO, "Using ServiceProvider: " + serviceContextProvider.getClass().getName());
+ } else {
+ LOG.log(Level.WARNING, "Replacing ServiceProvider " +
+ ServiceContextManager.serviceContextProviderDelegate.getClass().getName() +
+ " with: " + serviceContextProvider.getClass().getName());
+ ServiceContextManager.serviceContextProviderDelegate = serviceContextProvider;
+ }
+ }
+
+ return currentContext;
+ }
+
+ /**
+ * Ge {@link ServiceContext}. If necessary the {@link ServiceContext} will be laziliy loaded.
+ *
+ * @return the {@link ServiceContext} used.
+ */
+ public static ServiceContext getServiceContext() {
+ if (serviceContextProviderDelegate == null) {
+ synchronized (ServiceContextManager.class) {
+ if (serviceContextProviderDelegate == null) {
+ serviceContextProviderDelegate = loadDefaultServiceProvider();
+ }
+ }
+ }
+ return serviceContextProviderDelegate;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/DefaultServiceContext.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/DefaultServiceContext.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/DefaultServiceContext.java
new file mode 100644
index 0000000..3f2bfb7
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/DefaultServiceContext.java
@@ -0,0 +1,155 @@
+/*
+ * 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.servicecontext.internal;
+
+import org.apache.tamaya.servicecontext.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.servicecontext.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 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 IllegalStateException 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 IllegalStateException(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/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIActivator.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIActivator.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIActivator.java
new file mode 100644
index 0000000..3eac8b9
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIActivator.java
@@ -0,0 +1,51 @@
+/*
+ * 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.servicecontext.internal;
+
+import org.apache.tamaya.servicecontext.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/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceComparator.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceComparator.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceComparator.java
new file mode 100644
index 0000000..87d6881
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceComparator.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.servicecontext.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/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceContext.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceContext.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceContext.java
new file mode 100644
index 0000000..7669361
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceContext.java
@@ -0,0 +1,98 @@
+/*
+ * 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.servicecontext.internal;
+
+import org.apache.tamaya.servicecontext.ServiceContext;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+
+import javax.annotation.Priority;
+import java.util.ArrayList;
+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();
+ }
+ }
+
+ /**
+ * 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 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;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceLoader.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceLoader.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceLoader.java
new file mode 100644
index 0000000..dc43801
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/OSGIServiceLoader.java
@@ -0,0 +1,156 @@
+/*
+ * 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.servicecontext.internal;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+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/7144e3f9/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/PriorityServiceComparator.java
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/PriorityServiceComparator.java b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/PriorityServiceComparator.java
new file mode 100644
index 0000000..3895cb0
--- /dev/null
+++ b/modules/servicecontext/src/main/java/org/apache/tamaya/servicecontext/internal/PriorityServiceComparator.java
@@ -0,0 +1,67 @@
+/*
+ * 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.servicecontext.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/7144e3f9/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$InvalidPriorityInterface
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$InvalidPriorityInterface b/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$InvalidPriorityInterface
new file mode 100644
index 0000000..f203fa6
--- /dev/null
+++ b/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$InvalidPriorityInterface
@@ -0,0 +1,18 @@
+# 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.
+org.apache.tamaya.core.internal.DefaultServiceContextTest$InvalidPriorityImpl1
+org.apache.tamaya.core.internal.DefaultServiceContextTest$InvalidPriorityImpl2
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$MultiImplsInterface
----------------------------------------------------------------------
diff --git a/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$MultiImplsInterface b/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$MultiImplsInterface
new file mode 100644
index 0000000..b144790
--- /dev/null
+++ b/modules/servicecontext/src/test/resources/services/org.apache.tamaya.servicecontext.internal.DefaultServiceContextTest$MultiImplsInterface
@@ -0,0 +1,20 @@
+# 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.
+
+org.apache.tamaya.core.internal.DefaultServiceContextTest$MultiImpl1
+org.apache.tamaya.core.internal.DefaultServiceContextTest$MultiImpl2
+org.apache.tamaya.core.internal.DefaultServiceContextTest$MultiImpl3
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/PriorityServiceComparator.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/PriorityServiceComparator.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/PriorityServiceComparator.java
new file mode 100644
index 0000000..c7e3656
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/PriorityServiceComparator.java
@@ -0,0 +1,67 @@
+/*
+ * 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.builder.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/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/PropertyConverterManager.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/PropertyConverterManager.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/PropertyConverterManager.java
new file mode 100644
index 0000000..1fcfb22
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/PropertyConverterManager.java
@@ -0,0 +1,449 @@
+/*
+ * 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.types.internal;
+
+import org.apache.tamaya.ConfigException;
+import org.apache.tamaya.servicecontext.ServiceContext;
+import org.apache.tamaya.servicecontext.ServiceContextManager;
+import org.apache.tamaya.types.TypeLiteral;
+import org.apache.tamaya.types.spi.ConversionContext;
+import org.apache.tamaya.types.spi.PropertyConverter;
+
+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 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) {
+ ServiceContext serviceContext = ServiceContextManager.getServiceContext();
+ int prio = serviceContext.getPriority(o1) - serviceContext.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.types.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(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 org.apache.tamaya.types.internal.converters.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/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/ReflectionUtil.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/ReflectionUtil.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/ReflectionUtil.java
new file mode 100644
index 0000000..da8a74c
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/ReflectionUtil.java
@@ -0,0 +1,42 @@
+///*
+// * 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.builder.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/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/adapters/DefaultTypedConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/adapters/DefaultTypedConfiguration.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/adapters/DefaultTypedConfiguration.java
new file mode 100644
index 0000000..8f919e1
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/adapters/DefaultTypedConfiguration.java
@@ -0,0 +1,154 @@
+/*
+ * 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.types.internal.adapters;
+
+import org.apache.tamaya.ConfigException;
+import org.apache.tamaya.Configuration;
+import org.apache.tamaya.ConfigurationProvider;
+import org.apache.tamaya.types.TypeLiteral;
+import org.apache.tamaya.types.TypedConfiguration;
+import org.apache.tamaya.types.internal.PropertyConverterManager;
+import org.apache.tamaya.types.spi.ConversionContext;
+import org.apache.tamaya.types.spi.PropertyConverter;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Implementation of the {@link TypedConfiguration} API.
+ */
+public class DefaultTypedConfiguration implements TypedConfiguration {
+ /**
+ * The logger.
+ */
+ private static final Logger LOG = Logger.getLogger(DefaultTypedConfiguration.class.getName());
+
+ private Configuration configuration;
+
+ private PropertyConverterManager propertyConverterManager = new PropertyConverterManager();
+
+ /**
+ * Constructor.
+ * @param configuration The configuration to be decorated.
+ */
+ public DefaultTypedConfiguration(Configuration configuration){
+ this.configuration = Objects.requireNonNull(configuration);
+ }
+
+ private Configuration getConfig(){
+ return this.configuration!=null?this.configuration:ConfigurationProvider.getConfiguration();
+ }
+
+ @Override
+ public String get(String key) {
+ return getConfig().get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return getConfig().getProperties();
+ }
+
+ /**
+ * Accesses the current String value for the given key and tries to convert it
+ * using the {@link org.apache.tamaya.types.spi.PropertyConverter} instances provided by
+ * the current context.
+ *
+ * @param key the property's absolute, or relative path, e.g. @code
+ * a/b/c/d.myProperty}.
+ * @param type The target type required, not null.
+ * @param <T> the value type
+ * @return the converted value, never null.
+ */
+ @Override
+ public <T> T get(String key, Class<T> type) {
+ return get(key, (TypeLiteral<T>)TypeLiteral.of(type));
+ }
+
+ /**
+ * Accesses the current String value for the given key and tries to convert it
+ * using the {@link org.apache.tamaya.types.spi.PropertyConverter} instances provided by the current
+ * context.
+ *
+ * @param key the property's absolute, or relative path, e.g. @code
+ * a/b/c/d.myProperty}.
+ * @param type The target type required, not null.
+ * @param <T> the value type
+ * @return the converted value, never null.
+ */
+ @Override
+ public <T> T get(String key, TypeLiteral<T> type) {
+ return convertValue(key, get(key), type);
+ }
+
+ @Override
+ public <T> void addPropertyConverter(TypeLiteral<T> typeToConvert, PropertyConverter<T> propertyConverter) {
+ this.propertyConverterManager.register(typeToConvert, propertyConverter);
+ }
+
+ @Override
+ public Map<TypeLiteral<?>, List<PropertyConverter<?>>> getPropertyConverters() {
+ return this.propertyConverterManager.getPropertyConverters();
+ }
+
+ @Override
+ public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> type) {
+ return this.propertyConverterManager.getPropertyConverters(type);
+ }
+
+ @Override
+ public void removePropertyConverters(TypeLiteral<?> typeToConvert, PropertyConverter<?>... converters) {
+ removePropertyConverters(typeToConvert, Arrays.asList(converters));
+ }
+
+ @Override
+ public void removePropertyConverters(TypeLiteral<?> typeToConvert, Collection<PropertyConverter<?>> converters) {
+ List<? extends PropertyConverter<?>> existing = this.propertyConverterManager.getPropertyConverters(typeToConvert);
+ if(existing!=null) {
+ existing.removeAll(converters);
+ }
+ }
+
+
+ protected <T> T convertValue(String key, String value, TypeLiteral<T> type) {
+ if (value != null) {
+ List<PropertyConverter<T>> converters = propertyConverterManager.getPropertyConverters(type);
+ ConversionContext context = new ConversionContext.Builder(this, key, type).build();
+ for (PropertyConverter<T> converter : converters) {
+ try {
+ T t = converter.convert(value, context);
+ if (t != null) {
+ return t;
+ }
+ } catch (Exception e) {
+ LOG.log(Level.INFO, "PropertyConverter: " + converter + " failed to convert value: " + value, e);
+ }
+ }
+ throw new ConfigException("Unparseable config value for type: " + type.getRawType().getName() + ": " + key +
+ ", supported formats: " + context.getSupportedFormats());
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigDecimalConverter.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigDecimalConverter.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigDecimalConverter.java
new file mode 100644
index 0000000..27a997e
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigDecimalConverter.java
@@ -0,0 +1,63 @@
+/*
+ * 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.types.internal.converters;
+
+import org.apache.tamaya.types.spi.ConversionContext;
+import org.apache.tamaya.types.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;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigIntegerConverter.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigIntegerConverter.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigIntegerConverter.java
new file mode 100644
index 0000000..f7941cf
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BigIntegerConverter.java
@@ -0,0 +1,94 @@
+/*
+ * 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.types.internal.converters;
+
+import org.apache.tamaya.types.spi.ConversionContext;
+import org.apache.tamaya.types.spi.PropertyConverter;
+
+import java.math.BigInteger;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Converter, converting from String to BigInteger, the supported format is one of the following:
+ * <ul>
+ * <li>0xFFFFFF</li>
+ * <li>0XFFFFAC</li>
+ * <li>23257352735276352753</li>
+ * <li>-0xFFFFFF</li>
+ * <li>-0XFFFFAC</li>
+ * <li>-23257352735276352753</li>
+ * </ul>
+ */
+public class BigIntegerConverter implements PropertyConverter<BigInteger> {
+
+ /** The logger. */
+ private static final Logger LOG = Logger.getLogger(BigIntegerConverter.class.getName());
+ /** Converter used to decode hex, octal values. */
+ private final ByteConverter byteConverter = new ByteConverter();
+
+ @Override
+ public BigInteger convert(String value, ConversionContext context) {
+ context.addSupportedFormats(getClass(), "[-]0X.. (hex)", "[-]0x... (hex)", "<bigint> -> new BigInteger(bigint)");
+ String trimmed = Objects.requireNonNull(value).trim();
+ if(trimmed.startsWith("0x") || trimmed.startsWith("0X")){
+ LOG.finest("Parsing Hex value to BigInteger: " + value);
+ trimmed = trimmed.substring(2);
+ StringBuilder decimal = new StringBuilder();
+ for(int offset = 0;offset < trimmed.length();offset+=2){
+ if(offset==trimmed.length()-1){
+ LOG.finest("Invalid Hex-Byte-String: " + value);
+ return null;
+ }
+ byte val = byteConverter.convert("0x" + trimmed.substring(offset, offset + 2), context);
+ if(val<10){
+ decimal.append('0').append(val);
+ } else{
+ decimal.append(val);
+ }
+ }
+ return new BigInteger(decimal.toString());
+ } else if(trimmed.startsWith("-0x") || trimmed.startsWith("-0X")){
+ LOG.finest("Parsing Hex value to BigInteger: " + value);
+ trimmed = trimmed.substring(3);
+ StringBuilder decimal = new StringBuilder();
+ for(int offset = 0;offset < trimmed.length();offset+=2){
+ if(offset==trimmed.length()-1){
+ LOG.finest("Invalid Hex-Byte-String: " + trimmed);
+ return null;
+ }
+ byte val = byteConverter.convert("0x" + trimmed.substring(offset, offset + 2), context);
+ if(val<10){
+ decimal.append('0').append(val);
+ } else{
+ decimal.append(val);
+ }
+ }
+ return new BigInteger('-' + decimal.toString());
+ }
+ try{
+ return new BigInteger(trimmed);
+ } catch(Exception e){
+ LOG.log(Level.FINEST, "Failed to parse BigInteger from: " + value, e);
+ return null;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/7144e3f9/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BooleanConverter.java
----------------------------------------------------------------------
diff --git a/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BooleanConverter.java b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BooleanConverter.java
new file mode 100644
index 0000000..ed5dec3
--- /dev/null
+++ b/modules/types/src/main/java/org/apache/tamaya/types/internal/converters/BooleanConverter.java
@@ -0,0 +1,57 @@
+/*
+ * 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.types.internal.converters;
+
+import org.apache.tamaya.types.spi.ConversionContext;
+import org.apache.tamaya.types.spi.PropertyConverter;
+
+import java.util.Locale;
+import java.util.Objects;
+import java.util.logging.Logger;
+
+/**
+ * Converter, converting from String to Boolean.
+ */
+public class BooleanConverter implements PropertyConverter<Boolean> {
+
+ private final Logger LOG = Logger.getLogger(getClass().getName());
+
+ @Override
+ public Boolean convert(String value, ConversionContext context) {
+ context.addSupportedFormats(getClass(), "yes (ignore case)", "y (ignore case)", "true (ignore case)", "t (ignore case)", "no (ignore case)", "n (ignore case)", "false (ignore case)", "f (ignore case)");
+ String ignoreCaseValue = Objects.requireNonNull(value)
+ .trim()
+ .toLowerCase(Locale.ENGLISH);
+ switch(ignoreCaseValue) {
+ case "yes":
+ case "y":
+ case "true":
+ case "t":
+ return Boolean.TRUE;
+ case "no":
+ case "n":
+ case "false":
+ case "f":
+ return Boolean.FALSE;
+ default:
+ LOG.finest("Unknown boolean value encountered: " + value);
+ }
+ return null;
+ }
+}