io.dropwizard.java8.jersey.OptionalParamConverterProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dropwizard-java8 Show documentation
Show all versions of dropwizard-java8 Show documentation
Addon bundle for Dropwizard to support Java 8 features
The newest version!
package io.dropwizard.java8.jersey;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.jersey.internal.inject.Providers;
import org.glassfish.jersey.internal.util.ReflectionHelper;
import org.glassfish.jersey.internal.util.collection.ClassTypePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Singleton
public class OptionalParamConverterProvider implements ParamConverterProvider {
private final ServiceLocator locator;
@Inject
public OptionalParamConverterProvider(final ServiceLocator locator) {
this.locator = locator;
}
/**
* {@inheritDoc}
*/
@Override
public ParamConverter getConverter(final Class rawType, final Type genericType, final Annotation[] annotations) {
if (Optional.class.equals(rawType)) {
final List ctps = ReflectionHelper.getTypeArgumentAndClass(genericType);
final ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null;
if (ctp == null || ctp.rawClass() == String.class) {
return new ParamConverter() {
@Override
public T fromString(final String value) {
return rawType.cast(Optional.ofNullable(value));
}
@Override
public String toString(final T value) {
return value.toString();
}
};
}
final Set converterProviders = Providers.getProviders(locator, ParamConverterProvider.class);
for (ParamConverterProvider provider : converterProviders) {
final ParamConverter> converter = provider.getConverter(ctp.rawClass(), ctp.type(), annotations);
if (converter != null) {
return new ParamConverter() {
@Override
public T fromString(final String value) {
return rawType.cast(Optional.ofNullable(value).map(s -> converter.fromString(value)));
}
@Override
public String toString(final T value) {
return value.toString();
}
};
}
}
}
return null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy