Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.ser;
  
  import java.util.*;
  
Factory class that can provide serializers for any regular Java beans (as defined by "having at least one get method recognizable as bean accessor" -- where java.lang.Object.getClass() does not count); as well as for "standard" JDK types. Latter is achieved by delegating calls to BasicSerializerFactory to find serializers both for "standard" JDK types (and in some cases, sub-classes as is the case for collection classes like java.util.Lists and java.util.Maps) and bean (value) classes.

Note about delegating calls to BasicSerializerFactory: although it would be nicer to use linear delegation for construction (to essentially dispatch all calls first to the underlying BasicSerializerFactory; or alternatively after failing to provide bean-based serializer}, there is a problem: priority levels for detecting standard types are mixed. That is, we want to check if a type is a bean after some of "standard" JDK types, but before the rest. As a result, "mixed" delegation used, and calls are NOT done using regular SerializerFactory interface but rather via direct calls to BasicSerializerFactory.

Finally, since all caching is handled by the serializer provider (not factory) and there is no configurability, this factory is stateless. This means that a global singleton instance can be used.

 
 public class BeanSerializerFactory
     extends BasicSerializerFactory
     implements java.io.Serializable // since 2.1
 {
     private static final long serialVersionUID = 1;

    
Like BasicSerializerFactory, this factory is stateless, and thus a single shared global (== singleton) instance can be used without thread-safety issues.
 
     public final static BeanSerializerFactory instance = new BeanSerializerFactory(null);
 
     /*
     /**********************************************************
     /* Life-cycle: creation, configuration
     /**********************************************************
      */

    
Constructor for creating instances with specified configuration.
 
     protected BeanSerializerFactory(SerializerFactoryConfig config)
     {
         super(config);
     }
    
    
Method used by module registration functionality, to attach additional serializer providers into this serializer factory. This is typically handled by constructing a new instance with additional serializers, to ensure thread-safe access.
 
     @Override
     {
         if ( == config) {
             return this;
         }
         /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;
          *    and we pretty much have to here either choose between losing subtype instance
          *    when registering additional serializers, or losing serializers.
          *    Instead, let's actually just throw an error if this method is called when subtype
          *    has not properly overridden this method; this to indicate problem as soon as possible.
          */
         if (getClass() != BeanSerializerFactory.class) {
             throw new IllegalStateException("Subtype of BeanSerializerFactory ("+getClass().getName()
                     +") has not properly overridden method 'withAdditionalSerializers': can not instantiate subtype with "
                     +"additional serializer definitions");
         }
         return new BeanSerializerFactory(config);
    }
    @Override
    protected Iterable<SerializerscustomSerializers() {
        return .serializers();
    }
    
    /*
    /**********************************************************
    /* SerializerFactory impl
    /**********************************************************
     */

    
Main serializer constructor method. We will have to be careful with respect to ordering of various method calls: essentially we want to reliably figure out which classes are standard types, and which are beans. The problem is that some bean Classes may implement standard interfaces (say, java.lang.Iterable.

Note: sub-classes may choose to complete replace implementation, if they want to alter priority of serializer lookups.

    @Override
    @SuppressWarnings("unchecked")
            JavaType origType)
        throws JsonMappingException
    {
        // Very first thing, let's check if there is explicit serializer annotation:
        final SerializationConfig config = prov.getConfig();
        BeanDescription beanDesc = config.introspect(origType);
        JsonSerializer<?> ser = findSerializerFromAnnotation(provbeanDesc.getClassInfo());
        if (ser != null) {
            return (JsonSerializer<Object>) ser;
        }
        boolean staticTyping;
        
        // Next: we may have annotations that further define types to use...
        JavaType type = modifyTypeByAnnotation(configbeanDesc.getClassInfo(), origType);
        if (type == origType) { // no changes, won't force static typing
            staticTyping = false;
        } else { // changes; assume static typing; plus, need to re-introspect if class differs
            staticTyping = true;
            if (type.getRawClass() != origType.getRawClass()) {
                beanDesc = config.introspect(type);
            }
        }
        // Then JsonSerializable, @JsonValue etc:
        ser = findSerializerByAnnotations(provtypebeanDesc);
        if (ser != null) {
            return (JsonSerializer<Object>) ser;
        }
        
        // Container types differ from non-container types
        // (note: called method checks for module-provided serializers)
        if (origType.isContainerType()) {
            if (!staticTyping) {
                staticTyping = usesStaticTyping(configbeanDescnull);
                // [JACKSON-822]: Need to figure out how to force passed parameterization
                //  to stick...
                /*
                if (property == null) {
                    JavaType t = origType.getContentType();
                    if (t != null && !t.hasRawClass(Object.class)) {
                        staticTyping = true;
                    }
                }
                */
            }
            // 03-Aug-2012, tatu: As per [Issue#40], may require POJO serializer...
            ser =  buildContainerSerializer(provtypebeanDescstaticTyping);
            if (ser != null) {
                return (JsonSerializer<Object>) ser;
            }
        } else {
            // Modules may provide serializers of POJO types:
            for (Serializers serializers : customSerializers()) {
                ser = serializers.findSerializer(configtypebeanDesc);
                if (ser != null) {
                    return (JsonSerializer<Object>) ser;
                }
            }
        }
        
        /* Otherwise, we will check "primary types"; both marker types that
         * indicate specific handling (JsonSerializable), or main types that have
         * precedence over container types
         */
        ser = findSerializerByLookup(typeconfigbeanDescstaticTyping);
        if (ser == null) {
            ser = findSerializerByPrimaryType(provtypebeanDescstaticTyping);
            if (ser == null) {
                /* And this is where this class comes in: if type is not a
                 * known "primary JDK type", perhaps it's a bean? We can still
                 * get a null, if we can't find a single suitable bean property.
                 */
                ser = findBeanSerializer(provtypebeanDesc);
                /* Finally: maybe we can still deal with it as an
                 * implementation of some basic JDK interface?
                 */
                if (ser == null) {
                    ser = findSerializerByAddonType(configtypebeanDescstaticTyping);
                }
            }
        }
        return (JsonSerializer<Object>) ser;
    }
    
    /*
    /**********************************************************
    /* Other public methods that are not part of
    /* JsonSerializerFactory API
    /**********************************************************
     */

    
Deprecated method; final to help identify problems with sub-classes, as this method will NOT be called any more in 2.1

Deprecated:
Since 2.1 (use variant without 'property' argument).
    @Deprecated
            JavaType typeBeanDescription beanDescBeanProperty property)
        throws JsonMappingException {
        return findBeanSerializer(provtypebeanDesc);
    }
    
    
Method that will try to construct a BeanSerializer for given class. Returns null if no properties are found.
    @SuppressWarnings("unchecked")
            JavaType typeBeanDescription beanDesc)
        throws JsonMappingException
    {
        // First things first: we know some types are not beans...
        if (!isPotentialBeanType(type.getRawClass())) {
            // 03-Aug-2012, tatu: Except we do need to allow serializers for Enums,
            //   as per [Issue#24]
            if (!type.isEnumType()) {
                return null;
            }
        }
        JsonSerializer<Objectserializer = constructBeanSerializer(provbeanDesc);
        // [JACKSON-440] Need to allow overriding actual serializer, as well...
        if (.hasSerializerModifiers()) {
            for (BeanSerializerModifier mod : .serializerModifiers()) {
                serializer = (JsonSerializer<Object>)mod.modifySerializer(prov.getConfig(),
                        beanDescserializer);
            }
        }
        return serializer;
    }

    

Deprecated:
Since 2.1
    @Deprecated
    public final TypeSerializer findPropertyTypeSerializer(JavaType baseType,
            SerializationConfig configAnnotatedMember accessorBeanProperty property)
        throws JsonMappingException {
        return findPropertyTypeSerializer(baseTypeconfigaccessor);
    }
    
    
Method called to create a type information serializer for values of given non-container property if one is needed. If not needed (no polymorphic handling configured), should return null.

Parameters:
baseType Declared type to use as the base type for type information serializer
Returns:
Type serializer to use for property values, if one is needed; null if not.
            SerializationConfig configAnnotatedMember accessor)
        throws JsonMappingException
    {
        AnnotationIntrospector ai = config.getAnnotationIntrospector();
        TypeResolverBuilder<?> b = ai.findPropertyTypeResolver(configaccessorbaseType);        
        // Defaulting: if no annotations on member, check value class
        if (b == null) {
            return createTypeSerializer(configbaseType);
        }
        Collection<NamedTypesubtypes = config.getSubtypeResolver().collectAndResolveSubtypes(
                accessorconfigaibaseType);
        return b.buildTypeSerializer(configbaseTypesubtypes);
    }

    
Method called to create a type information serializer for values of given container property if one is needed. If not needed (no polymorphic handling configured), should return null.

Parameters:
containerType Declared type of the container to use as the base type for type information serializer
Returns:
Type serializer to use for property value contents, if one is needed; null if not.
    
            SerializationConfig configAnnotatedMember accessor)
        throws JsonMappingException
    {
        JavaType contentType = containerType.getContentType();
        AnnotationIntrospector ai = config.getAnnotationIntrospector();
        TypeResolverBuilder<?> b = ai.findPropertyContentTypeResolver(configaccessorcontainerType);        
        // Defaulting: if no annotations on member, check value class
        if (b == null) {
            return createTypeSerializer(configcontentType);
        }
        Collection<NamedTypesubtypes = config.getSubtypeResolver().collectAndResolveSubtypes(accessor,
                configaicontentType);
        return b.buildTypeSerializer(configcontentTypesubtypes);
    }
    
    /*
    /**********************************************************
    /* Overridable non-public factory methods
    /**********************************************************
     */

    
Deprecated method; final to help identify problems with sub-classes, as this method will NOT be called any more in 2.1

Deprecated:
Since 2.1, do not pass 'property' argument
    @Deprecated
            BeanDescription beanDescBeanProperty property)
        throws JsonMappingException
    {
        return constructBeanSerializer(provbeanDesc);
    }
    
    
Method called to construct serializer for serializing specified bean type.

Since:
2.1
    @SuppressWarnings("unchecked")
            BeanDescription beanDesc)
        throws JsonMappingException
    {
        // 13-Oct-2010, tatu: quick sanity check: never try to create bean serializer for plain Object
        // 05-Jul-2012, tatu: ... but we should be able to just return "unknown type" serializer, right?
        if (beanDesc.getBeanClass() == Object.class) {
            return prov.getUnknownTypeSerializer(Object.class);
//            throw new IllegalArgumentException("Can not create bean serializer for Object.class");
        }
        final SerializationConfig config = prov.getConfig();
        BeanSerializerBuilder builder = constructBeanSerializerBuilder(beanDesc);
        builder.setConfig(config);
        
        // First: any detectable (auto-detect, annotations) properties to serialize?
        List<BeanPropertyWriterprops = findBeanProperties(provbeanDescbuilder);
        if (props == null) {
            props = new ArrayList<BeanPropertyWriter>();
        }
        // [JACKSON-440] Need to allow modification bean properties to serialize:
        if (.hasSerializerModifiers()) {
            for (BeanSerializerModifier mod : .serializerModifiers()) {
                props = mod.changeProperties(configbeanDescprops);
            }
        }
        
        // Any properties to suppress?
        props = filterBeanProperties(configbeanDescprops);
        
        // [JACKSON-440] Need to allow reordering of properties to serialize
        if (.hasSerializerModifiers()) {
            for (BeanSerializerModifier mod : .serializerModifiers()) {
                props = mod.orderProperties(configbeanDescprops);
            }
        }
        /* And if Object Id is needed, some preparation for that as well: better
         * do before view handling, mostly for the custom id case which needs
         * access to a property
         */
        builder.setObjectIdWriter(constructObjectIdHandler(provbeanDescprops));
        
        builder.setProperties(props);
        builder.setFilterId(findFilterId(configbeanDesc));
        
        AnnotatedMember anyGetter = beanDesc.findAnyGetter();
        if (anyGetter != null) { // since 1.6
            if (config.canOverrideAccessModifiers()) {
                anyGetter.fixAccess();
            }
            JavaType type = anyGetter.getType(beanDesc.bindingsForBeanType());
            // copied from BasicSerializerFactory.buildMapSerializer():
            boolean staticTyping = config.isEnabled(.);
            JavaType valueType = type.getContentType();
            TypeSerializer typeSer = createTypeSerializer(configvalueType);
            // last 2 nulls; don't know key, value serializers (yet)
            MapSerializer mapSer = MapSerializer.construct(/* ignored props*/ nulltypestaticTyping,
                    typeSernullnull);
            BeanProperty.Std anyProp = new BeanProperty.Std(anyGetter.getName(), valueType,
                    beanDesc.getClassAnnotations(), anyGetter);
            builder.setAnyGetter(new AnyGetterWriter(anyPropanyGettermapSer));
        }
        // Next: need to gather view information, if any:
        processViews(configbuilder);
        
        // Finally: let interested parties mess with the result bit more...
        if (.hasSerializerModifiers()) {
            for (BeanSerializerModifier mod : .serializerModifiers()) {
                builder = mod.updateBuilder(configbeanDescbuilder);
            }
        }
        
        JsonSerializer<Objectser = (JsonSerializer<Object>) builder.build();
        /* However, after all modifications: no properties, no serializer
         * (note; as per [JACKSON-670], check was moved later on from an earlier location)
         */
        if (ser == null) {
            /* 27-Nov-2009, tatu: Except that as per [JACKSON-201], we are
             *   ok with that as long as it has a recognized class annotation
             *  (which may come from a mix-in too)
             */
            if (beanDesc.hasKnownClassAnnotations()) {
                return builder.createDummy();
            }
        }
        return ser;
    }
            BeanDescription beanDescList<BeanPropertyWriterprops)
        throws JsonMappingException
    {
        ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo();
        if (objectIdInfo == null) {
            return null;
        }
        ObjectIdGenerator<?> gen;
        Class<?> implClass = objectIdInfo.getGeneratorType();
        // Just one special case: Property-based generator is trickier
        if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work
            String propName = objectIdInfo.getPropertyName();
            BeanPropertyWriter idProp = null;
            for (int i = 0, len = props.size() ;; ++i) {
                if (i == len) {
                    throw new IllegalArgumentException("Invalid Object Id definition for "+beanDesc.getBeanClass().getName()
                            +": can not find property with name '"+propName+"'");
                }
                BeanPropertyWriter prop = props.get(i);
                if (propName.equals(prop.getName())) {
                    idProp = prop;
                    /* Let's force it to be the first property to output
                     * (although it may still get rearranged etc)
                     */
                    if (i > 0) {
                        props.remove(i);
                        props.add(0, idProp);
                    }
                    break;
                }
            }
            JavaType idType = idProp.getType();
            gen = new PropertyBasedObjectIdGenerator(objectIdInfoidProp);
            // one more thing: must ensure that ObjectIdWriter does not actually write the value:
            return ObjectIdWriter.construct(idTypenullgenobjectIdInfo.getAlwaysAsId());
            
        } 
        // other types are simpler
        JavaType type = prov.constructType(implClass);
        // Could require type to be passed explicitly, but we should be able to find it too:
        JavaType idType = prov.getTypeFactory().findTypeParameters(typeObjectIdGenerator.class)[0];
        gen = prov.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo);
        return ObjectIdWriter.construct(idTypeobjectIdInfo.getPropertyName(), gen,
                objectIdInfo.getAlwaysAsId());
    }

    
Method called to construct a filtered writer, for given view definitions. Default implementation constructs filter that checks active view type to views property is to be included in.
            Class<?>[] inViews)
    {
        return FilteredBeanPropertyWriter.constructViewBased(writerinViews);
    }
    
            BeanDescription beanDesc)
    {
        return new PropertyBuilder(configbeanDesc);
    }
        return new BeanSerializerBuilder(beanDesc);
    }

    
Method called to find filter that is configured to be used with bean serializer being built, if any.
    protected Object findFilterId(SerializationConfig configBeanDescription beanDesc)
    {
        return config.getAnnotationIntrospector().findFilterId(beanDesc.getClassInfo());
    }
    
    /*
    /**********************************************************
    /* Overridable non-public introspection methods
    /**********************************************************
     */
    
    
Helper method used to skip processing for types that we know can not be (i.e. are never consider to be) beans: things like primitives, Arrays, Enums, and proxy types.

Note that usually we shouldn't really be getting these sort of types anyway; but better safe than sorry.

    protected boolean isPotentialBeanType(Class<?> type)
    {
        return (ClassUtil.canBeABeanType(type) == null) && !ClassUtil.isProxyType(type);
    }

    
Method used to collect all actual serializable properties. Can be overridden to implement custom detection schemes.
            BeanDescription beanDescBeanSerializerBuilder builder)
        throws JsonMappingException
    {
        List<BeanPropertyDefinitionproperties = beanDesc.findProperties();
        final SerializationConfig config = prov.getConfig();
        // [JACKSON-429]: ignore specified types
        removeIgnorableTypes(configbeanDescproperties);
        
        // and possibly remove ones without matching mutator...
        if (config.isEnabled(.)) {
            removeSetterlessGetters(configbeanDescproperties);
        }
        
        // nothing? can't proceed (caller may or may not throw an exception)
        if (properties.isEmpty()) {
            return null;
        }
        // null is for value type serializer, which we don't have access to from here (ditto for bean prop)
        boolean staticTyping = usesStaticTyping(configbeanDescnull);
        PropertyBuilder pb = constructPropertyBuilder(configbeanDesc);
        
        ArrayList<BeanPropertyWriterresult = new ArrayList<BeanPropertyWriter>(properties.size());
        TypeBindings typeBind = beanDesc.bindingsForBeanType();
        for (BeanPropertyDefinition property : properties) {
            final AnnotatedMember accessor = property.getAccessor();
            // [JACKSON-762]: type id? Requires special handling:
            if (property.isTypeId()) {
                if (accessor != null) { // only add if we can access... but otherwise?
                    if (config.canOverrideAccessModifiers()) {
                        accessor.fixAccess();
                    }
                    builder.setTypeId(accessor);
                }
                continue;
            }
            // [JACKSON-235]: suppress writing of back references
            AnnotationIntrospector.ReferenceProperty refType = property.findReferenceType();
            if (refType != null && refType.isBackReference()) {
                continue;
            }
            if (accessor instanceof AnnotatedMethod) {
                result.add(_constructWriter(provpropertytypeBindpbstaticTyping, (AnnotatedMethodaccessor));
            } else {
                result.add(_constructWriter(provpropertytypeBindpbstaticTyping, (AnnotatedFieldaccessor));
            }
        }
        return result;
    }
    /*
    /**********************************************************
    /* Overridable non-public methods for manipulating bean properties
    /**********************************************************
     */
    
    
Overridable method that can filter out properties. Default implementation checks annotations class may have.
            BeanDescription beanDescList<BeanPropertyWriterprops)
    {
        AnnotationIntrospector intr = config.getAnnotationIntrospector();
        AnnotatedClass ac = beanDesc.getClassInfo();
        String[] ignored = intr.findPropertiesToIgnore(ac);
        if (ignored != null && ignored.length > 0) {
            HashSet<StringignoredSet = ArrayBuilders.arrayToSet(ignored);
            Iterator<BeanPropertyWriterit = props.iterator();
            while (it.hasNext()) {
                if (ignoredSet.contains(it.next().getName())) {
                    it.remove();
                }
            }
        }
        return props;
    }

    
Method called to handle view information for constructed serializer, based on bean property writers.

Note that this method is designed to be overridden by sub-classes if they want to provide custom view handling. As such it is not considered an internal implementation detail, and will be supported as part of API going forward.

    protected void processViews(SerializationConfig configBeanSerializerBuilder builder)
    {
        // [JACKSON-232]: whether non-annotated fields are included by default or not is configurable
        List<BeanPropertyWriterprops = builder.getProperties();
        boolean includeByDefault = config.isEnabled(.);
        final int propCount = props.size();
        int viewsFound = 0;
        BeanPropertyWriter[] filtered = new BeanPropertyWriter[propCount];
        // Simple: view information is stored within individual writers, need to combine:
        for (int i = 0; i < propCount; ++i) {
            BeanPropertyWriter bpw = props.get(i);
            Class<?>[] views = bpw.getViews();
            if (views == null) { // no view info? include or exclude by default?
                if (includeByDefault) {
                    filtered[i] = bpw;
                }
            } else {
                ++viewsFound;
                filtered[i] = constructFilteredBeanWriter(bpwviews);
            }
        }
        // minor optimization: if no view info, include-by-default, can leave out filtering info altogether:
        if (includeByDefault && viewsFound == 0) {
            return;
        }
        builder.setFilteredProperties(filtered);
    }

    
Method that will apply by-type limitations (as per [JACKSON-429]); by default this is based on com.fasterxml.jackson.annotation.JsonIgnoreType annotation but can be supplied by module-provided introspectors too.
    protected void removeIgnorableTypes(SerializationConfig configBeanDescription beanDesc,
            List<BeanPropertyDefinitionproperties)
    {
        AnnotationIntrospector intr = config.getAnnotationIntrospector();
        HashMap<Class<?>,Booleanignores = new HashMap<Class<?>,Boolean>();
        Iterator<BeanPropertyDefinitionit = properties.iterator();
        while (it.hasNext()) {
            BeanPropertyDefinition property = it.next();
            AnnotatedMember accessor = property.getAccessor();
            if (accessor == null) {
                it.remove();
                continue;
            }
            Class<?> type = accessor.getRawType();
            Boolean result = ignores.get(type);
            if (result == null) {
                BeanDescription desc = config.introspectClassAnnotations(type);
                AnnotatedClass ac = desc.getClassInfo();
                result = intr.isIgnorableType(ac);
                // default to false, non-ignorable
                if (result == null) {
                    result = .;
                }
                ignores.put(typeresult);
            }
            // lotsa work, and yes, it is ignorable type, so:
            if (result.booleanValue()) {
                it.remove();
            }
        }
    }

    
Helper method that will remove all properties that do not have a mutator.
    protected void removeSetterlessGetters(SerializationConfig configBeanDescription beanDesc,
            List<BeanPropertyDefinitionproperties)
    {
        Iterator<BeanPropertyDefinitionit = properties.iterator();
        while (it.hasNext()) {
            BeanPropertyDefinition property = it.next();
            // one caveat: as per [JACKSON-806], only remove implicit properties;
            // explicitly annotated ones should remain
            if (!property.couldDeserialize() && !property.isExplicitlyIncluded()) {
                it.remove();
            }
        }
    }
    
    /*
    /**********************************************************
    /* Internal helper methods
    /**********************************************************
     */

    
Secondary helper method for constructing BeanPropertyWriter for given member (field or method).
            BeanPropertyDefinition propDefTypeBindings typeContext,
            PropertyBuilder pbboolean staticTypingAnnotatedMember accessor)
        throws JsonMappingException
    {
        final String name = propDef.getName();
        if (prov.canOverrideAccessModifiers()) {
            accessor.fixAccess();
        }
        JavaType type = accessor.getType(typeContext);
        BeanProperty.Std property = new BeanProperty.Std(nametypepb.getClassAnnotations(), accessor);
        // Does member specify a serializer? If so, let's use it.
        JsonSerializer<?> annotatedSerializer = findSerializerFromAnnotation(prov,
                accessor);
        /* 02-Feb-2012, tatu: Unlike most other codepaths, Serializer produced
         *  here will NOT be resolved or contextualized, unless done here, so:
         */
        if (annotatedSerializer instanceof ResolvableSerializer) {
            ((ResolvableSerializerannotatedSerializer).resolve(prov);
        }
        if (annotatedSerializer instanceof ContextualSerializer) {
            annotatedSerializer = ((ContextualSerializerannotatedSerializer).createContextual(provproperty);
        }
        // And how about polymorphic typing? First special to cover JAXB per-field settings:
        TypeSerializer contentTypeSer = null;
        if (ClassUtil.isCollectionMapOrArray(type.getRawClass())) {
            contentTypeSer = findPropertyContentTypeSerializer(typeprov.getConfig(), accessor);
        }
        // and if not JAXB collection/array with annotations, maybe regular type info?
        TypeSerializer typeSer = findPropertyTypeSerializer(typeprov.getConfig(), accessor);
        BeanPropertyWriter pbw = pb.buildWriter(propDeftypeannotatedSerializer,
                        typeSercontentTypeSeraccessorstaticTyping);
        return pbw;
    }
New to GrepCode? Check out our FAQ X