You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by ma...@apache.org on 2014/09/15 01:27:08 UTC
[19/21] git commit: Add TypeConverterRegistry and test.
Add TypeConverterRegistry and test.
- Implements LOG4J2-827.
Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/cbf19ade
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/cbf19ade
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/cbf19ade
Branch: refs/heads/master
Commit: cbf19adeeef756bdc931dc57f72125f9dffe2547
Parents: 5fea1da
Author: Matt Sicker <ma...@apache.org>
Authored: Sun Sep 14 18:24:26 2014 -0500
Committer: Matt Sicker <ma...@apache.org>
Committed: Sun Sep 14 18:24:26 2014 -0500
----------------------------------------------------------------------
.../plugins/convert/TypeConverterRegistry.java | 161 +++++++++++++++++++
.../convert/TypeConverterRegistryTest.java | 80 +++++++++
2 files changed, 241 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/cbf19ade/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistry.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistry.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistry.java
new file mode 100644
index 0000000..dc9f9a6
--- /dev/null
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistry.java
@@ -0,0 +1,161 @@
+/*
+ * 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.logging.log4j.core.config.plugins.convert;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.Map;
+import java.util.UnknownFormatConversionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
+import org.apache.logging.log4j.core.config.plugins.util.PluginType;
+import org.apache.logging.log4j.core.util.Assert;
+import org.apache.logging.log4j.core.util.ReflectionUtil;
+import org.apache.logging.log4j.core.util.TypeUtil;
+import org.apache.logging.log4j.status.StatusLogger;
+
+/**
+ * Registry for {@link TypeConverter} plugins.
+ *
+ * @since 2.1
+ */
+public class TypeConverterRegistry {
+
+ private static final Logger LOGGER = StatusLogger.getLogger();
+ private static volatile TypeConverterRegistry INSTANCE;
+ private static final Object INSTANCE_LOCK = new Object();
+
+ private final ConcurrentMap<Type, TypeConverter<?>> registry = new ConcurrentHashMap<Type, TypeConverter<?>>();
+
+ /**
+ * Gets the singleton instance of the TypeConverterRegistry.
+ *
+ * @return the singleton instance.
+ */
+ public static TypeConverterRegistry getInstance() {
+ TypeConverterRegistry result = INSTANCE;
+ if (result == null) {
+ synchronized (INSTANCE_LOCK) {
+ result = INSTANCE;
+ if (result == null) {
+ INSTANCE = result = new TypeConverterRegistry();
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Finds a {@link TypeConverter} for the given {@link Type}, falling back to an assignment-compatible TypeConverter
+ * if none exist for the given type. That is, if the given Type does not have a TypeConverter, but another Type
+ * which can be assigned to the given Type <em>does</em> have a TypeConverter, then that TypeConverter will be
+ * used and registered.
+ *
+ * @param type the Type to find a TypeConverter for (must not be {@code null}).
+ * @return a TypeConverter for the given Type.
+ * @throws UnknownFormatConversionException if no TypeConverter can be found for the given type.
+ */
+ public TypeConverter<?> findCompatibleConverter(final Type type) {
+ Assert.requireNonNull(type, "No type was provided");
+ final TypeConverter<?> primary = registry.get(type);
+ // cached type converters
+ if (primary != null) {
+ return primary;
+ }
+ // dynamic enum support
+ if (type instanceof Class<?>) {
+ final Class<?> clazz = (Class<?>) type;
+ if (clazz.isEnum()) {
+ return registerEnumType(clazz.asSubclass(Enum.class));
+ }
+ }
+ // look for compatible converters
+ for (final Map.Entry<Type, TypeConverter<?>> entry : registry.entrySet()) {
+ final Type key = entry.getKey();
+ if (TypeUtil.isAssignable(type, key)) {
+ LOGGER.debug("Found compatible TypeConverter<{}> for type [{}].", key, type);
+ final TypeConverter<?> value = entry.getValue();
+ registry.putIfAbsent(type, value);
+ return value;
+ }
+ }
+ throw new UnknownFormatConversionException(type.toString());
+ }
+
+ private TypeConverterRegistry() {
+ LOGGER.debug("TypeConverterRegistry initializing.");
+ final PluginManager manager = new PluginManager(TypeConverters.CATEGORY);
+ manager.collectPlugins();
+ loadKnownTypeConverters(manager.getPlugins().values());
+ registerPrimitiveTypes();
+ }
+
+ private void loadKnownTypeConverters(final Collection<PluginType<?>> knownTypes) {
+ for (final PluginType<?> knownType : knownTypes) {
+ if (TypeConverter.class.isAssignableFrom(knownType.getPluginClass())) {
+ @SuppressWarnings("unchecked") // but we just DID check it!
+ final Class<? extends TypeConverter<?>> pluginClass =
+ (Class<? extends TypeConverter<?>>) knownType.getPluginClass();
+ final Type conversionType = getTypeConverterSupportedType(pluginClass);
+ final TypeConverter<?> converter = ReflectionUtil.instantiate(pluginClass);
+ if (registry.putIfAbsent(conversionType, converter) != null) {
+ LOGGER.warn("Found a TypeConverter [{}] for type [{}] that already exists.", converter,
+ conversionType);
+ }
+ }
+ }
+ }
+
+ private static Type getTypeConverterSupportedType(final Class<? extends TypeConverter<?>> typeConverterClass) {
+ for (final Type type : typeConverterClass.getGenericInterfaces()) {
+ if (type instanceof ParameterizedType) {
+ final ParameterizedType pType = (ParameterizedType) type;
+ if (TypeConverter.class.equals(pType.getRawType())) {
+ // TypeConverter<T> has only one type argument (T), so return that
+ return pType.getActualTypeArguments()[0];
+ }
+ }
+ }
+ return Void.TYPE;
+ }
+
+ private void registerPrimitiveTypes() {
+ registerTypeAlias(Boolean.class, Boolean.TYPE);
+ registerTypeAlias(Byte.class, Byte.TYPE);
+ registerTypeAlias(Character.class, Character.TYPE);
+ registerTypeAlias(Double.class, Double.TYPE);
+ registerTypeAlias(Float.class, Float.TYPE);
+ registerTypeAlias(Integer.class, Integer.TYPE);
+ registerTypeAlias(Long.class, Long.TYPE);
+ registerTypeAlias(Short.class, Short.TYPE);
+ }
+
+ private void registerTypeAlias(final Type knownType, final Type aliasType) {
+ registry.putIfAbsent(aliasType, registry.get(knownType));
+ }
+
+ private <E extends Enum<E>> TypeConverter<E> registerEnumType(final Class<E> type) {
+ final TypeConverter<E> converter = new EnumConverter<E>(type);
+ registry.putIfAbsent(type, converter);
+ return converter;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/cbf19ade/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java
new file mode 100644
index 0000000..f9e757d
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.logging.log4j.core.config.plugins.convert;
+
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.instanceOf;
+import static org.junit.Assert.*;
+
+public class TypeConverterRegistryTest {
+
+ @Test(expected = NullPointerException.class)
+ public void testFindNullConverter() throws Exception {
+ TypeConverterRegistry.getInstance().findCompatibleConverter(null);
+ }
+
+ @Test
+ public void testFindBooleanConverter() throws Exception {
+ final TypeConverter<?> converter = TypeConverterRegistry.getInstance().findCompatibleConverter(Boolean.class);
+ assertNotNull(converter);
+ assertTrue((Boolean) converter.convert("TRUE"));
+ }
+
+ @Test
+ public void testFindPrimitiveBooleanConverter() throws Exception {
+ final TypeConverter<?> converter = TypeConverterRegistry.getInstance().findCompatibleConverter(Boolean.TYPE);
+ assertNotNull(converter);
+ assertTrue((Boolean) converter.convert("tRUe"));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testFindCharSequenceConverterUsingStringConverter() throws Exception {
+ final TypeConverter<CharSequence> converter = (TypeConverter<CharSequence>)
+ TypeConverterRegistry.getInstance().findCompatibleConverter(CharSequence.class);
+ assertNotNull(converter);
+ assertThat(converter, instanceOf(TypeConverters.StringConverter.class));
+ final CharSequence expected = "This is a test sequence of characters";
+ final CharSequence actual = converter.convert(expected.toString());
+ assertEquals(expected, actual);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testFindNumberConverter() throws Exception {
+ final TypeConverter<Number> numberTypeConverter = (TypeConverter<Number>)
+ TypeConverterRegistry.getInstance().findCompatibleConverter(Number.class);
+ assertNotNull(numberTypeConverter);
+ // TODO: is there a specific converter this should return?
+ }
+
+ public static enum Foo {
+ I, PITY, THE
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testFindEnumConverter() throws Exception {
+ final TypeConverter<Foo> fooTypeConverter = (TypeConverter<Foo>)
+ TypeConverterRegistry.getInstance().findCompatibleConverter(Foo.class);
+ assertNotNull(fooTypeConverter);
+ assertEquals(Foo.I, fooTypeConverter.convert("i"));
+ assertEquals(Foo.PITY, fooTypeConverter.convert("pity"));
+ assertEquals(Foo.THE, fooTypeConverter.convert("THE"));
+ }
+}