-
Notifications
You must be signed in to change notification settings - Fork 485
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #702 from Netflix/custom-converters
Add a Decoder that accepts custom TypeConverters
- Loading branch information
Showing
6 changed files
with
211 additions
and
138 deletions.
There are no files selected for viewing
129 changes: 129 additions & 0 deletions
129
archaius2-core/src/main/java/com/netflix/archaius/AbstractRegistryDecoder.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
package com.netflix.archaius; | ||
|
||
import com.netflix.archaius.api.Decoder; | ||
import com.netflix.archaius.api.TypeConverter; | ||
import com.netflix.archaius.exceptions.ParseException; | ||
|
||
import java.lang.reflect.Constructor; | ||
import java.lang.reflect.Method; | ||
import java.lang.reflect.Type; | ||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
import java.util.Collections; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.stream.Stream; | ||
|
||
/** | ||
* A {@code Decoder} implementation that also implements {@code TypeConverter.Registry}, and delegates to a supplied | ||
* collection of converter factories. | ||
*/ | ||
abstract class AbstractRegistryDecoder implements Decoder, TypeConverter.Registry { | ||
|
||
private final Map<Type, TypeConverter<?>> cache = new ConcurrentHashMap<>(); | ||
|
||
private final List<TypeConverter.Factory> factories; | ||
|
||
AbstractRegistryDecoder(Collection<? extends TypeConverter.Factory> factories) { | ||
this.factories = Collections.unmodifiableList(new ArrayList<>(factories)); | ||
} | ||
|
||
@Override | ||
public <T> T decode(Class<T> type, String encoded) { | ||
return decode((Type) type, encoded); | ||
} | ||
|
||
@Override | ||
public <T> T decode(Type type, String encoded) { | ||
try { | ||
if (encoded == null) { | ||
return null; | ||
} | ||
@SuppressWarnings("unchecked") | ||
TypeConverter<T> converter = (TypeConverter<T>) getOrCreateConverter(type); | ||
if (converter == null) { | ||
throw new RuntimeException("No converter found for type '" + type + "'"); | ||
} | ||
return converter.convert(encoded); | ||
} catch (Exception e) { | ||
throw new ParseException("Error decoding type `" + type.getTypeName() + "`", e); | ||
} | ||
} | ||
|
||
@Override | ||
public Optional<TypeConverter<?>> get(Type type) { | ||
return Optional.ofNullable(getOrCreateConverter(type)); | ||
} | ||
|
||
private TypeConverter<?> getOrCreateConverter(Type type) { | ||
TypeConverter<?> converter = cache.get(type); | ||
if (converter == null) { | ||
converter = resolve(type); | ||
if (converter == null) { | ||
return null; | ||
} | ||
TypeConverter<?> existing = cache.putIfAbsent(type, converter); | ||
if (existing != null) { | ||
converter = existing; | ||
} | ||
} | ||
return converter; | ||
} | ||
|
||
/** | ||
* Iterate through all TypeConverter#Factory's and return the first TypeConverter that matches | ||
* @param type | ||
* @return | ||
*/ | ||
private TypeConverter<?> resolve(Type type) { | ||
return factories.stream() | ||
.flatMap(factory -> factory.get(type, this).map(Stream::of).orElseGet(Stream::empty)) | ||
.findFirst() | ||
.orElseGet(() -> findValueOfTypeConverter(type)); | ||
} | ||
|
||
/** | ||
* @param type | ||
* @param <T> | ||
* @return Return a converter that uses reflection on either a static valueOf or ctor(String) to convert a string value to the | ||
* type. Will return null if neither is found | ||
*/ | ||
private static <T> TypeConverter<T> findValueOfTypeConverter(Type type) { | ||
if (!(type instanceof Class)) { | ||
return null; | ||
} | ||
|
||
@SuppressWarnings("unchecked") | ||
Class<T> cls = (Class<T>) type; | ||
|
||
// Next look a valueOf(String) static method | ||
Method method; | ||
try { | ||
method = cls.getMethod("valueOf", String.class); | ||
return value -> { | ||
try { | ||
return (T) method.invoke(null, value); | ||
} catch (Exception e) { | ||
throw new ParseException("Error converting value '" + value + "' to '" + type.getTypeName() + "'", e); | ||
} | ||
}; | ||
} catch (NoSuchMethodException e1) { | ||
// Next look for a T(String) constructor | ||
Constructor<T> c; | ||
try { | ||
c = cls.getConstructor(String.class); | ||
return value -> { | ||
try { | ||
return (T) c.newInstance(value); | ||
} catch (Exception e) { | ||
throw new ParseException("Error converting value", e); | ||
} | ||
}; | ||
} catch (NoSuchMethodException e) { | ||
return null; | ||
} | ||
} | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
archaius2-core/src/main/java/com/netflix/archaius/CustomDecoder.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package com.netflix.archaius; | ||
|
||
import com.netflix.archaius.api.TypeConverter; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
import java.util.List; | ||
import java.util.Objects; | ||
|
||
/** | ||
* A configurable {@code Decoder} implementation which allows extension through custom {@code TypeConverter.Factory} | ||
* instances. The custom factories are searched first, and if no appropriate converter is found, the default | ||
* converters used by {@code DefaultDecoder} will be consulted. | ||
*/ | ||
public class CustomDecoder extends AbstractRegistryDecoder { | ||
private CustomDecoder(Collection<? extends TypeConverter.Factory> typeConverterFactories) { | ||
super(typeConverterFactories); | ||
} | ||
|
||
/** | ||
* Create a new {@code CustomDecoder} with the supplied {@code TypeConverter.Factory} instances installed. | ||
* The default converter factories will still be registered, but will be installed AFTER any custom ones, | ||
* giving callers the opportunity to override the behavior of the default converters. | ||
* | ||
* @param customTypeConverterFactories the collection of converter factories to use for this decoder | ||
*/ | ||
public static CustomDecoder create(Collection<? extends TypeConverter.Factory> customTypeConverterFactories) { | ||
Objects.requireNonNull(customTypeConverterFactories, "customTypeConverterFactories == null"); | ||
List<TypeConverter.Factory> factories = new ArrayList<>(customTypeConverterFactories); | ||
factories.addAll(DefaultDecoder.DEFAULT_FACTORIES); | ||
return new CustomDecoder(factories); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
archaius2-core/src/test/java/com/netflix/archaius/CustomDecoderTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package com.netflix.archaius; | ||
|
||
import com.netflix.archaius.api.TypeConverter; | ||
import org.junit.Assert; | ||
import org.junit.Test; | ||
|
||
import java.lang.reflect.Type; | ||
import java.util.Collections; | ||
import java.util.Optional; | ||
|
||
public class CustomDecoderTest { | ||
|
||
@Test | ||
public void testCustomTypeConverters() { | ||
TypeConverter<String> stringConverter = String::toUpperCase; | ||
TypeConverter<Long> longConverter = value -> Long.parseLong(value) * 2; | ||
TypeConverter.Factory factory = (type, registry) -> { | ||
if ((type instanceof Class<?> && ((Class<?>) type).isAssignableFrom(String.class))) { | ||
return Optional.of(stringConverter); | ||
} else if (type.equals(Long.class)) { // override default converter | ||
return Optional.of(longConverter); | ||
} | ||
return Optional.empty(); | ||
}; | ||
CustomDecoder decoder = CustomDecoder.create(Collections.singletonList(factory)); | ||
Assert.assertEquals("FOO", decoder.decode((Type) CharSequence.class, "foo")); | ||
Assert.assertEquals("FOO", decoder.decode((Type) String.class, "foo")); | ||
// default is overridden | ||
Assert.assertEquals(Long.valueOf(6), decoder.decode((Type) Long.class, "3")); | ||
// default converter is used | ||
Assert.assertEquals(Integer.valueOf(3), decoder.decode((Type) Integer.class, "3")); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters