com.fitbur.jackson.databind.deser.BasicDeserializerFactory Maven / Gradle / Ivy
package com.fitbur.jackson.databind.deser;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import com.fitbur.jackson.annotation.JsonCreator;
import com.fitbur.jackson.core.JsonLocation;
import com.fitbur.jackson.databind.*;
import com.fitbur.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fitbur.jackson.databind.cfg.HandlerInstantiator;
import com.fitbur.jackson.databind.deser.impl.CreatorCollector;
import com.fitbur.jackson.databind.deser.std.*;
import com.fitbur.jackson.databind.ext.OptionalHandlerFactory;
import com.fitbur.jackson.databind.introspect.*;
import com.fitbur.jackson.databind.jsontype.NamedType;
import com.fitbur.jackson.databind.jsontype.TypeDeserializer;
import com.fitbur.jackson.databind.jsontype.TypeResolverBuilder;
import com.fitbur.jackson.databind.type.*;
import com.fitbur.jackson.databind.util.*;
/**
* Abstract factory base class that can provide deserializers for standard
* JDK classes, including collection classes and simple heuristics for
* "upcasting" common collection interface types
* (such as {@link java.util.Collection}).
*
* Since all simple deserializers are eagerly instantiated, and there is
* no additional introspection or customizability of these types,
* this factory is stateless.
*/
@SuppressWarnings("serial")
public abstract class BasicDeserializerFactory
extends DeserializerFactory
implements java.io.Serializable
{
private final static Class> CLASS_OBJECT = Object.class;
private final static Class> CLASS_STRING = String.class;
private final static Class> CLASS_CHAR_BUFFER = CharSequence.class;
private final static Class> CLASS_ITERABLE = Iterable.class;
private final static Class> CLASS_MAP_ENTRY = Map.Entry.class;
/**
* We need a placeholder for creator properties that don't have name
* but are marked with `@JsonWrapped` annotation.
*/
protected final static PropertyName UNWRAPPED_CREATOR_PARAM_NAME = new PropertyName("@JsonUnwrapped");
/* We do some defaulting for abstract Map classes and
* interfaces, to avoid having to use exact types or annotations in
* cases where the most common concrete Maps will do.
*/
@SuppressWarnings("rawtypes")
final static HashMap> _mapFallbacks =
new HashMap>();
static {
_mapFallbacks.put(Map.class.getName(), LinkedHashMap.class);
_mapFallbacks.put(ConcurrentMap.class.getName(), ConcurrentHashMap.class);
_mapFallbacks.put(SortedMap.class.getName(), TreeMap.class);
_mapFallbacks.put(java.util.NavigableMap.class.getName(), TreeMap.class);
_mapFallbacks.put(java.util.concurrent.ConcurrentNavigableMap.class.getName(),
java.util.concurrent.ConcurrentSkipListMap.class);
}
/* We do some defaulting for abstract Collection classes and
* interfaces, to avoid having to use exact types or annotations in
* cases where the most common concrete Collection will do.
*/
@SuppressWarnings("rawtypes")
final static HashMap> _collectionFallbacks =
new HashMap>();
static {
_collectionFallbacks.put(Collection.class.getName(), ArrayList.class);
_collectionFallbacks.put(List.class.getName(), ArrayList.class);
_collectionFallbacks.put(Set.class.getName(), HashSet.class);
_collectionFallbacks.put(SortedSet.class.getName(), TreeSet.class);
_collectionFallbacks.put(Queue.class.getName(), LinkedList.class);
// then JDK 1.6 types:
/* 17-May-2013, tatu: [databind#216] Should be fine to use straight Class references EXCEPT
* that some god-forsaken platforms (... looking at you, Android) do not
* include these. So, use "soft" references...
*/
_collectionFallbacks.put("java.util.Deque", LinkedList.class);
_collectionFallbacks.put("java.util.NavigableSet", TreeSet.class);
}
/*
/**********************************************************
/* Config
/**********************************************************
*/
/**
* Configuration settings for this factory; immutable instance (just like this
* factory), new version created via copy-constructor (fluent-style)
*/
protected final DeserializerFactoryConfig _factoryConfig;
/*
/**********************************************************
/* Life cycle
/**********************************************************
*/
protected BasicDeserializerFactory(DeserializerFactoryConfig config) {
_factoryConfig = config;
}
/**
* Method for getting current {@link DeserializerFactoryConfig}.
*
* Note that since instances are immutable, you can NOT change settings
* by accessing an instance and calling methods: this will simply create
* new instance of config object.
*/
public DeserializerFactoryConfig getFactoryConfig() {
return _factoryConfig;
}
protected abstract DeserializerFactory withConfig(DeserializerFactoryConfig config);
/*
/********************************************************
/* Configuration handling: fluent factories
/********************************************************
*/
/**
* Convenience method for creating a new factory instance with additional deserializer
* provider.
*/
@Override
public final DeserializerFactory withAdditionalDeserializers(Deserializers additional) {
return withConfig(_factoryConfig.withAdditionalDeserializers(additional));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link KeyDeserializers}.
*/
@Override
public final DeserializerFactory withAdditionalKeyDeserializers(KeyDeserializers additional) {
return withConfig(_factoryConfig.withAdditionalKeyDeserializers(additional));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link BeanDeserializerModifier}.
*/
@Override
public final DeserializerFactory withDeserializerModifier(BeanDeserializerModifier modifier) {
return withConfig(_factoryConfig.withDeserializerModifier(modifier));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link AbstractTypeResolver}.
*/
@Override
public final DeserializerFactory withAbstractTypeResolver(AbstractTypeResolver resolver) {
return withConfig(_factoryConfig.withAbstractTypeResolver(resolver));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link ValueInstantiators}.
*/
@Override
public final DeserializerFactory withValueInstantiators(ValueInstantiators instantiators) {
return withConfig(_factoryConfig.withValueInstantiators(instantiators));
}
/*
/**********************************************************
/* DeserializerFactory impl (partial): type mappings
/**********************************************************
*/
@Override
public JavaType mapAbstractType(DeserializationConfig config, JavaType type) throws JsonMappingException
{
// first, general mappings
while (true) {
JavaType next = _mapAbstractType2(config, type);
if (next == null) {
return type;
}
// Should not have to worry about cycles; but better verify since they will invariably occur... :-)
// (also: guard against invalid resolution to a non-related type)
Class> prevCls = type.getRawClass();
Class> nextCls = next.getRawClass();
if ((prevCls == nextCls) || !prevCls.isAssignableFrom(nextCls)) {
throw new IllegalArgumentException("Invalid abstract type resolution from "+type+" to "+next+": latter is not a subtype of former");
}
type = next;
}
}
/**
* Method that will find abstract type mapping for specified type, doing a single
* lookup through registered abstract type resolvers; will not do recursive lookups.
*/
private JavaType _mapAbstractType2(DeserializationConfig config, JavaType type)
throws JsonMappingException
{
Class> currClass = type.getRawClass();
if (_factoryConfig.hasAbstractTypeResolvers()) {
for (AbstractTypeResolver resolver : _factoryConfig.abstractTypeResolvers()) {
JavaType concrete = resolver.findTypeMapping(config, type);
if (concrete != null && concrete.getRawClass() != currClass) {
return concrete;
}
}
}
return null;
}
/*
/**********************************************************
/* JsonDeserializerFactory impl (partial): ValueInstantiators
/**********************************************************
*/
/**
* Value instantiator is created both based on creator annotations,
* and on optional externally provided instantiators (registered through
* module interface).
*/
@Override
public ValueInstantiator findValueInstantiator(DeserializationContext ctxt,
BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
ValueInstantiator instantiator = null;
// [JACKSON-633] Check @JsonValueInstantiator before anything else
AnnotatedClass ac = beanDesc.getClassInfo();
Object instDef = ctxt.getAnnotationIntrospector().findValueInstantiator(ac);
if (instDef != null) {
instantiator = _valueInstantiatorInstance(config, ac, instDef);
}
if (instantiator == null) {
/* Second: see if some of standard Jackson/JDK types might provide value
* instantiators.
*/
instantiator = _findStdValueInstantiator(config, beanDesc);
if (instantiator == null) {
instantiator = _constructDefaultValueInstantiator(ctxt, beanDesc);
}
}
// finally: anyone want to modify ValueInstantiator?
if (_factoryConfig.hasValueInstantiators()) {
for (ValueInstantiators insts : _factoryConfig.valueInstantiators()) {
instantiator = insts.findValueInstantiator(config, beanDesc, instantiator);
// let's do sanity check; easier to spot buggy handlers
if (instantiator == null) {
throw JsonMappingException.from(ctxt.getParser(),
"Broken registered ValueInstantiators (of type "+insts.getClass().getName()+"): returned null ValueInstantiator");
}
}
}
// Sanity check: does the chosen instantatior have incomplete creators?
if (instantiator.getIncompleteParameter() != null) {
final AnnotatedParameter nonAnnotatedParam = instantiator.getIncompleteParameter();
final AnnotatedWithParams ctor = nonAnnotatedParam.getOwner();
throw new IllegalArgumentException("Argument #"+nonAnnotatedParam.getIndex()+" of constructor "+ctor+" has no property name annotation; must have name when multiple-parameter constructor annotated as Creator");
}
return instantiator;
}
private ValueInstantiator _findStdValueInstantiator(DeserializationConfig config,
BeanDescription beanDesc)
throws JsonMappingException
{
if (beanDesc.getBeanClass() == JsonLocation.class) {
return new JsonLocationInstantiator();
}
return null;
}
/**
* Method that will construct standard default {@link ValueInstantiator}
* using annotations (like @JsonCreator) and visibility rules
*/
protected ValueInstantiator _constructDefaultValueInstantiator(DeserializationContext ctxt,
BeanDescription beanDesc)
throws JsonMappingException
{
CreatorCollector creators = new CreatorCollector(beanDesc, ctxt.getConfig());
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
// need to construct suitable visibility checker:
final DeserializationConfig config = ctxt.getConfig();
VisibilityChecker> vchecker = config.getDefaultVisibilityChecker();
vchecker = intr.findAutoDetectVisibility(beanDesc.getClassInfo(), vchecker);
/* 24-Sep-2014, tatu: Tricky part first; need to merge resolved property information
* (which has creator parameters sprinkled around) with actual creator
* declarations (which are needed to access creator annotation, amongst other things).
* Easiest to combine that info first, then pass it to remaining processing.
*/
/* 15-Mar-2015, tatu: Alas, this won't help with constructors that only have implicit
* names. Those will need to be resolved later on.
*/
Map creatorDefs = _findCreatorsFromProperties(ctxt,
beanDesc);
/* Important: first add factory methods; then constructors, so
* latter can override former!
*/
_addDeserializerFactoryMethods(ctxt, beanDesc, vchecker, intr, creators, creatorDefs);
// constructors only usable on concrete types:
if (beanDesc.getType().isConcrete()) {
_addDeserializerConstructors(ctxt, beanDesc, vchecker, intr, creators, creatorDefs);
}
return creators.constructValueInstantiator(config);
}
protected Map _findCreatorsFromProperties(DeserializationContext ctxt,
BeanDescription beanDesc) throws JsonMappingException
{
Map result = Collections.emptyMap();
for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
Iterator it = propDef.getConstructorParameters();
while (it.hasNext()) {
AnnotatedParameter param = it.next();
AnnotatedWithParams owner = param.getOwner();
BeanPropertyDefinition[] defs = result.get(owner);
final int index = param.getIndex();
if (defs == null) {
if (result.isEmpty()) { // since emptyMap is immutable need to create a 'real' one
result = new LinkedHashMap();
}
defs = new BeanPropertyDefinition[owner.getParameterCount()];
result.put(owner, defs);
} else {
if (defs[index] != null) {
throw new IllegalStateException("Conflict: parameter #"+index+" of "+owner
+" bound to more than one property; "+defs[index]+" vs "+propDef);
}
}
defs[index] = propDef;
}
}
return result;
}
public ValueInstantiator _valueInstantiatorInstance(DeserializationConfig config,
Annotated annotated, Object instDef)
throws JsonMappingException
{
if (instDef == null) {
return null;
}
ValueInstantiator inst;
if (instDef instanceof ValueInstantiator) {
return (ValueInstantiator) instDef;
}
if (!(instDef instanceof Class)) {
throw new IllegalStateException("AnnotationIntrospector returned key deserializer definition of type "
+instDef.getClass().getName()
+"; expected type KeyDeserializer or Class instead");
}
Class> instClass = (Class>)instDef;
if (ClassUtil.isBogusClass(instClass)) {
return null;
}
if (!ValueInstantiator.class.isAssignableFrom(instClass)) {
throw new IllegalStateException("AnnotationIntrospector returned Class "+instClass.getName()
+"; expected Class");
}
HandlerInstantiator hi = config.getHandlerInstantiator();
if (hi != null) {
inst = hi.valueInstantiatorInstance(config, annotated, instClass);
if (inst != null) {
return inst;
}
}
return (ValueInstantiator) ClassUtil.createInstance(instClass,
config.canOverrideAccessModifiers());
}
protected void _addDeserializerConstructors
(DeserializationContext ctxt, BeanDescription beanDesc, VisibilityChecker> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
Map creatorParams)
throws JsonMappingException
{
// First things first: the "default constructor" (zero-arg
// constructor; whether implicit or explicit) is NOT included
// in list of constructors, so needs to be handled separately.
AnnotatedConstructor defaultCtor = beanDesc.findDefaultConstructor();
if (defaultCtor != null) {
if (!creators.hasDefaultCreator() || intr.hasCreatorAnnotation(defaultCtor)) {
creators.setDefaultCreator(defaultCtor);
}
}
// may need to keep track for [#725]
List implicitCtors = null;
for (AnnotatedConstructor ctor : beanDesc.getConstructors()) {
final boolean isCreator = intr.hasCreatorAnnotation(ctor);
BeanPropertyDefinition[] propDefs = creatorParams.get(ctor);
final int argCount = ctor.getParameterCount();
// some single-arg factory methods (String, number) are auto-detected
if (argCount == 1) {
BeanPropertyDefinition argDef = (propDefs == null) ? null : propDefs[0];
boolean useProps = _checkIfCreatorPropertyBased(intr, ctor, argDef);
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[1];
PropertyName name = (argDef == null) ? null : argDef.getFullName();
AnnotatedParameter arg = ctor.getParameter(0);
properties[0] = constructCreatorProperty(ctxt, beanDesc, name, 0, arg,
intr.findInjectableValueId(arg));
creators.addPropertyCreator(ctor, isCreator, properties);
} else {
/*boolean added = */ _handleSingleArgumentConstructor(ctxt, beanDesc, vchecker, intr, creators,
ctor, isCreator,
vchecker.isCreatorVisible(ctor));
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (argDef != null) {
((POJOPropertyBuilder) argDef).removeConstructors();
}
}
// regardless, fully handled
continue;
}
// 2 or more args; all params must have names or be injectable
// 14-Mar-2015, tatu (2.6): Or, as per [#725], implicit names will also
// do, with some constraints. But that will require bit post processing...
AnnotatedParameter nonAnnotatedParam = null;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int explicitNameCount = 0;
int implicitWithCreatorCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = ctor.getParameter(i);
BeanPropertyDefinition propDef = (propDefs == null) ? null : propDefs[i];
Object injectId = intr.findInjectableValueId(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
if (injectId != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++explicitNameCount;
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
if (isCreator && (name != null && !name.isEmpty())) {
++implicitWithCreatorCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
if (nonAnnotatedParam == null) {
nonAnnotatedParam = param;
}
}
final int namedCount = explicitNameCount + implicitWithCreatorCount;
// Ok: if named or injectable, we have more work to do
if (isCreator || (explicitNameCount > 0) || (injectCount > 0)) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(ctor, isCreator, properties);
continue;
}
if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// Secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(ctor, isCreator, properties);
continue;
}
// otherwise, epic fail?
// 16-Mar-2015, tatu: due to [#725], need to be more permissive. For now let's
// only report problem if there's no implicit name
PropertyName impl = _findImplicitParamName(nonAnnotatedParam, intr);
if (impl == null || impl.isEmpty()) {
// Let's consider non-static inner class as a special case...
int ix = nonAnnotatedParam.getIndex();
if ((ix == 0) && ClassUtil.isNonStaticInnerClass(ctor.getDeclaringClass())) {
throw new IllegalArgumentException("Non-static inner classes like "
+ctor.getDeclaringClass().getName()+" can not use @JsonCreator for constructors");
}
throw new IllegalArgumentException("Argument #"+ix
+" of constructor "+ctor+" has no property name annotation; must have name when multiple-parameter constructor annotated as Creator");
}
}
// [#725]: as a fallback, all-implicit names may work as well
if (!creators.hasDefaultCreator()) {
if (implicitCtors == null) {
implicitCtors = new LinkedList();
}
implicitCtors.add(ctor);
}
}
// last option, as per [#725]: consider implicit-names-only, visible constructor,
// if just one found
if ((implicitCtors != null) && !creators.hasDelegatingCreator()
&& !creators.hasPropertyBasedCreator()) {
_checkImplicitlyNamedConstructors(ctxt, beanDesc, vchecker, intr,
creators, implicitCtors);
}
}
protected void _checkImplicitlyNamedConstructors(DeserializationContext ctxt,
BeanDescription beanDesc, VisibilityChecker> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
List implicitCtors) throws JsonMappingException
{
AnnotatedConstructor found = null;
SettableBeanProperty[] foundProps = null;
// Further checks: (a) must have names for all parameters, (b) only one visible
// Also, since earlier matching of properties and creators relied on existence of
// `@JsonCreator` (or equivalent) annotation, we need to do bit more re-inspection...
main_loop:
for (AnnotatedConstructor ctor : implicitCtors) {
if (!vchecker.isCreatorVisible(ctor)) {
continue;
}
// as per earlier notes, only end up here if no properties associated with creator
final int argCount = ctor.getParameterCount();
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = ctor.getParameter(i);
final PropertyName name = _findParamName(param, intr);
// must have name (implicit fine)
if (name == null || name.isEmpty()) {
continue main_loop;
}
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, param.getIndex(),
param, /*injectId*/ null);
}
if (found != null) { // only one allowed
found = null;
break;
}
found = ctor;
foundProps = properties;
}
// found one and only one visible? Ship it!
if (found != null) {
creators.addPropertyCreator(found, /*isCreator*/ false, foundProps);
BasicBeanDescription bbd = (BasicBeanDescription) beanDesc;
// Also: add properties, to keep error messages complete wrt known properties...
for (SettableBeanProperty prop : foundProps) {
PropertyName pn = prop.getFullName();
if (!bbd.hasProperty(pn)) {
BeanPropertyDefinition newDef = SimpleBeanPropertyDefinition.construct(
ctxt.getConfig(), prop.getMember(), pn);
bbd.addProperty(newDef);
}
}
}
}
protected boolean _checkIfCreatorPropertyBased(AnnotationIntrospector intr,
AnnotatedWithParams creator, BeanPropertyDefinition propDef)
{
JsonCreator.Mode mode = intr.findCreatorBinding(creator);
if (mode == JsonCreator.Mode.PROPERTIES) {
return true;
}
if (mode == JsonCreator.Mode.DELEGATING) {
return false;
}
// If explicit name, or inject id, property-based
if (((propDef != null) && propDef.isExplicitlyNamed())
|| (intr.findInjectableValueId(creator.getParameter(0)) != null)) {
return true;
}
if (propDef != null) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
String implName = propDef.getName();
if (implName != null && !implName.isEmpty()) {
if (propDef.couldSerialize()) {
return true;
}
}
}
// in absence of everything else, default to delegating
return false;
}
protected boolean _handleSingleArgumentConstructor(DeserializationContext ctxt,
BeanDescription beanDesc, VisibilityChecker> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
AnnotatedConstructor ctor, boolean isCreator, boolean isVisible)
throws JsonMappingException
{
// otherwise either 'simple' number, String, or general delegate:
Class> type = ctor.getRawParameterType(0);
if (type == String.class || type == CharSequence.class) {
if (isCreator || isVisible) {
creators.addStringCreator(ctor, isCreator);
}
return true;
}
if (type == int.class || type == Integer.class) {
if (isCreator || isVisible) {
creators.addIntCreator(ctor, isCreator);
}
return true;
}
if (type == long.class || type == Long.class) {
if (isCreator || isVisible) {
creators.addLongCreator(ctor, isCreator);
}
return true;
}
if (type == double.class || type == Double.class) {
if (isCreator || isVisible) {
creators.addDoubleCreator(ctor, isCreator);
}
return true;
}
if (type == boolean.class || type == Boolean.class) {
if (isCreator || isVisible) {
creators.addBooleanCreator(ctor, isCreator);
}
return true;
}
// Delegating Creator ok iff it has @JsonCreator (etc)
if (isCreator) {
creators.addDelegatingCreator(ctor, isCreator, null);
return true;
}
return false;
}
protected void _addDeserializerFactoryMethods
(DeserializationContext ctxt, BeanDescription beanDesc, VisibilityChecker> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
Map creatorParams)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
final boolean isCreator = intr.hasCreatorAnnotation(factory);
final int argCount = factory.getParameterCount();
// zero-arg methods must be annotated; if so, are "default creators" [JACKSON-850]
if (argCount == 0) {
if (isCreator) {
creators.setDefaultCreator(factory);
}
continue;
}
final BeanPropertyDefinition[] propDefs = creatorParams.get(factory);
// some single-arg factory methods (String, number) are auto-detected
if (argCount == 1) {
BeanPropertyDefinition argDef = (propDefs == null) ? null : propDefs[0];
boolean useProps = _checkIfCreatorPropertyBased(intr, factory, argDef);
if (!useProps) { // not property based but delegating
/*boolean added=*/ _handleSingleArgumentFactory(config, beanDesc, vchecker, intr, creators,
factory, isCreator);
// otherwise just ignored
continue;
}
// fall through if there's name
} else {
// more than 2 args, must have @JsonCreator
if (!isCreator) {
continue;
}
}
// 1 or more args; all params must have name annotations
AnnotatedParameter nonAnnotatedParam = null;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int implicitNameCount = 0;
int explicitNameCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = factory.getParameter(i);
BeanPropertyDefinition propDef = (propDefs == null) ? null : propDefs[i];
Object injectId = intr.findInjectableValueId(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
if (injectId != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++implicitNameCount;
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
if (isCreator) {
if (name != null && !name.isEmpty()) {
++implicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
}
/* 25-Sep-2014, tatu: Actually, we may end up "losing" naming due to higher-priority constructor
* (see TestCreators#testConstructorCreator() test). And just to avoid running into that problem,
* let's add one more work around
*/
/*
PropertyName name2 = _findExplicitParamName(param, intr);
if (name2 != null && !name2.isEmpty()) {
// Hmmh. Ok, fine. So what are we to do with it... ?
// For now... skip. May need to revisit this, should this become problematic
continue main_loop;
}
*/
if (nonAnnotatedParam == null) {
nonAnnotatedParam = param;
}
}
final int namedCount = explicitNameCount + implicitNameCount;
// Ok: if named or injectable, we have more work to do
if (isCreator || explicitNameCount > 0 || injectCount > 0) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(factory, isCreator, properties);
} else if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// [712] secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(factory, isCreator, properties);
} else { // otherwise, epic fail
throw new IllegalArgumentException("Argument #"+nonAnnotatedParam.getIndex()
+" of factory method "+factory+" has no property name annotation; must have name when multiple-parameter constructor annotated as Creator");
}
}
}
}
protected boolean _handleSingleArgumentFactory(DeserializationConfig config,
BeanDescription beanDesc, VisibilityChecker> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
AnnotatedMethod factory, boolean isCreator)
throws JsonMappingException
{
Class> type = factory.getRawParameterType(0);
if (type == String.class || type == CharSequence.class) {
if (isCreator || vchecker.isCreatorVisible(factory)) {
creators.addStringCreator(factory, isCreator);
}
return true;
}
if (type == int.class || type == Integer.class) {
if (isCreator || vchecker.isCreatorVisible(factory)) {
creators.addIntCreator(factory, isCreator);
}
return true;
}
if (type == long.class || type == Long.class) {
if (isCreator || vchecker.isCreatorVisible(factory)) {
creators.addLongCreator(factory, isCreator);
}
return true;
}
if (type == double.class || type == Double.class) {
if (isCreator || vchecker.isCreatorVisible(factory)) {
creators.addDoubleCreator(factory, isCreator);
}
return true;
}
if (type == boolean.class || type == Boolean.class) {
if (isCreator || vchecker.isCreatorVisible(factory)) {
creators.addBooleanCreator(factory, isCreator);
}
return true;
}
if (isCreator) {
creators.addDelegatingCreator(factory, isCreator, null);
return true;
}
return false;
}
/**
* Method that will construct a property object that represents
* a logical property passed via Creator (constructor or static
* factory method)
*/
protected SettableBeanProperty constructCreatorProperty(DeserializationContext ctxt,
BeanDescription beanDesc, PropertyName name, int index,
AnnotatedParameter param,
Object injectableValueId)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
PropertyMetadata metadata;
{
if (intr == null) {
metadata = PropertyMetadata.STD_REQUIRED_OR_OPTIONAL;
} else {
Boolean b = intr.hasRequiredMarker(param);
boolean req = (b != null && b.booleanValue());
String desc = intr.findPropertyDescription(param);
Integer idx = intr.findPropertyIndex(param);
String def = intr.findPropertyDefaultValue(param);
metadata = PropertyMetadata.construct(req, desc, idx, def);
}
}
// 15-Oct-2015, tatu: Not 100% if context needed; removing it does not make any
// existing unit tests fail. Still seems like the right thing to do.
JavaType t0 = beanDesc.resolveType(param.getParameterType());
BeanProperty.Std property = new BeanProperty.Std(name, t0,
intr.findWrapperName(param),
beanDesc.getClassAnnotations(), param, metadata);
JavaType type = resolveType(ctxt, beanDesc, t0, param);
if (type != t0) {
property = property.withType(type);
}
// Is there an annotation that specifies exact deserializer?
JsonDeserializer> deser = findDeserializerFromAnnotation(ctxt, param);
// If yes, we are mostly done:
type = modifyTypeByAnnotation(ctxt, param, type);
// Type deserializer: either comes from property (and already resolved)
TypeDeserializer typeDeser = (TypeDeserializer) type.getTypeHandler();
// or if not, based on type being referenced:
if (typeDeser == null) {
typeDeser = findTypeDeserializer(config, type);
}
// Note: contextualization of typeDeser _should_ occur in constructor of CreatorProperty
// so it is not called directly here
SettableBeanProperty prop = new CreatorProperty(name, type, property.getWrapperName(),
typeDeser, beanDesc.getClassAnnotations(), param, index, injectableValueId,
metadata);
if (deser != null) {
// As per [Issue#462] need to ensure we contextualize deserializer before passing it on
deser = ctxt.handlePrimaryContextualization(deser, prop, type);
prop = prop.withValueDeserializer(deser);
}
return prop;
}
protected PropertyName _findParamName(AnnotatedParameter param, AnnotationIntrospector intr)
{
if (param != null && intr != null) {
PropertyName name = intr.findNameForDeserialization(param);
if (name != null) {
return name;
}
// 14-Apr-2014, tatu: Need to also consider possible implicit name
// (for JDK8, or via paranamer)
String str = intr.findImplicitPropertyName(param);
if (str != null && !str.isEmpty()) {
return PropertyName.construct(str);
}
}
return null;
}
protected PropertyName _findImplicitParamName(AnnotatedParameter param, AnnotationIntrospector intr)
{
String str = intr.findImplicitPropertyName(param);
if (str != null && !str.isEmpty()) {
return PropertyName.construct(str);
}
return null;
}
@Deprecated // in 2.6, remove from 2.7
protected PropertyName _findExplicitParamName(AnnotatedParameter param, AnnotationIntrospector intr)
{
if (param != null && intr != null) {
return intr.findNameForDeserialization(param);
}
return null;
}
@Deprecated // in 2.6, remove from 2.7
protected boolean _hasExplicitParamName(AnnotatedParameter param, AnnotationIntrospector intr)
{
if (param != null && intr != null) {
PropertyName n = intr.findNameForDeserialization(param);
return (n != null) && n.hasSimpleName();
}
return false;
}
/*
/**********************************************************
/* JsonDeserializerFactory impl: array deserializers
/**********************************************************
*/
@Override
public JsonDeserializer> createArrayDeserializer(DeserializationContext ctxt,
ArrayType type, final BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
JavaType elemType = type.getContentType();
// Very first thing: is deserializer hard-coded for elements?
JsonDeserializer