Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //========================================================================
  //Copyright 2007-2009 David Yu dyuproject@gmail.com
  //------------------------------------------------------------------------
  //Licensed 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 io.protostuff.runtime;
 
 import static io.protostuff.runtime.RuntimeEnv.ID_STRATEGY;
 
 import java.util.Map;
 import java.util.Set;
 
A schema that can be generated and cached at runtime for objects that have no schema. This is particularly useful for pojos from 3rd party libraries.

Author(s):
David Yu
Created:
Nov 9, 2009
 
 public final class RuntimeSchema<T> extends MappedSchema<T>
 {
 
     private static final Set<StringNO_EXCLUSIONS = Collections.emptySet();

    
Maps the baseClass to a specific non-interface/non-abstract typeClass and registers it (this must be done on application startup).

With this approach, there is no overhead of writing the type metadata if a baseClass field is serialized.

Returns true if the baseClass does not exist.

NOTE: This is only supported when RuntimeEnv.ID_STRATEGY is DefaultIdStrategy.

Throws:
java.lang.IllegalArgumentException if the typeClass is an interface or an abstract class.
 
     public static <T> boolean map(Class<? super T> baseClassClass<T> typeClass)
     {
         if ( instanceof DefaultIdStrategy)
             return ((DefaultIdStrategy).map(baseClasstypeClass);
 
         throw new RuntimeException(
                 "RuntimeSchema.map is only supported on DefaultIdStrategy");
     }

    
Returns true if this there is no existing one or the same schema has already been registered (this must be done on application startup).

NOTE: This is only supported when RuntimeEnv.ID_STRATEGY is DefaultIdStrategy.

 
     public static <T> boolean register(Class<T> typeClassSchema<T> schema)
     {
         if ( instanceof DefaultIdStrategy)
             return ((DefaultIdStrategy).registerPojo(typeClass,
                     schema);
 
         throw new RuntimeException(
                 "RuntimeSchema.register is only supported on DefaultIdStrategy");
     }

    
Returns true if the typeClass was not lazily created.

Method overload for backwards compatibility.

 
     public static boolean isRegistered(Class<?> typeClass)
     {
         return isRegistered(typeClass);
     }

    
Returns true if the typeClass was not lazily created.
 
    public static boolean isRegistered(Class<?> typeClassIdStrategy strategy)
    {
        return strategy.isRegistered(typeClass);
    }

    
Gets the schema that was either registered or lazily initialized at runtime.

Method overload for backwards compatibility.

    public static <T> Schema<T> getSchema(Class<T> typeClass)
    {
        return getSchema(typeClass);
    }

    
Gets the schema that was either registered or lazily initialized at runtime.
    public static <T> Schema<T> getSchema(Class<T> typeClass,
            IdStrategy strategy)
    {
        return strategy.getSchemaWrapper(typeClasstrue).getSchema();
    }

    
Returns the schema wrapper.

Method overload for backwards compatibility.

    static <T> HasSchema<T> getSchemaWrapper(Class<T> typeClass)
    {
        return getSchemaWrapper(typeClass);
    }

    
Returns the schema wrapper.
    static <T> HasSchema<T> getSchemaWrapper(Class<T> typeClass,
            IdStrategy strategy)
    {
        return strategy.getSchemaWrapper(typeClasstrue);
    }

    
Generates a schema from the given class.

Method overload for backwards compatibility.

    public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass)
    {
        return createFrom(typeClass);
    }

    
Generates a schema from the given class.
    public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
            IdStrategy strategy)
    {
        return createFrom(typeClassstrategy);
    }

    
Generates a schema from the given class with the exclusion of certain fields.
    public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
            String[] exclusionsIdStrategy strategy)
    {
        HashSet<Stringset = new HashSet<>();
        for (String exclusion : exclusions)
            set.add(exclusion);
        return createFrom(typeClasssetstrategy);
    }

    
Generates a schema from the given class with the exclusion of certain fields.
    public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
            Set<StringexclusionsIdStrategy strategy)
    {
        if (typeClass.isInterface()
                || Modifier.isAbstract(typeClass.getModifiers()))
        {
            throw new RuntimeException(
                    "The root object can neither be an abstract "
                            + "class nor interface: \"" + typeClass.getName());
        }
        final Map<Stringjava.lang.reflect.FieldfieldMap = findInstanceFields(typeClass);
        final ArrayList<Field<T>> fields = new ArrayList<>(
                fieldMap.size());
        int i = 0;
        int maxFieldMapping = 0;
        boolean annotated = false;
        for (java.lang.reflect.Field f : fieldMap.values())
        {
            if (!exclusions.contains(f.getName()))
            {
                if (f.getAnnotation(Deprecated.class) != null)
                {
                    // this field should be ignored by ProtoStuff.
                    // preserve its field number for backward-forward compat
                    i++;
                    continue;
                }
                final Tag tag = f.getAnnotation(Tag.class);
                final int fieldMapping;
                final String name;
                if (tag == null)
                {
                    // Fields gets assigned mapping tags according to their
                    // definition order
                    if (annotated)
                    {
                        throw new RuntimeException(
                                "When using annotation-based mapping, "
                                        + "all fields must be annotated with @"
                                        + Tag.class.getSimpleName());
                    }
                    fieldMapping = ++i;
                    name = f.getName();
                }
                else
                {
                    // Fields gets assigned mapping tags according to their
                    // annotation
                    if (!annotated && !fields.isEmpty())
                    {
                        throw new RuntimeException(
                                "When using annotation-based mapping, "
                                        + "all fields must be annotated with @"
                                        + Tag.class.getSimpleName());
                    }
                    annotated = true;
                    fieldMapping = tag.value();
                    if (fieldMapping < 1)
                    {
                        throw new RuntimeException("Invalid field number: "
                                + fieldMapping + " on " + typeClass);
                    }
                    name = tag.alias().isEmpty() ? f.getName() : tag.alias();
                }
                final Field<T> field = RuntimeFieldFactory.getFieldFactory(
                        f.getType(), strategy).create(fieldMappingnamef,
                        strategy);
                fields.add(field);
                maxFieldMapping = Math.max(maxFieldMappingfieldMapping);
            }
        }
        return new RuntimeSchema<>(typeClassfieldsmaxFieldMapping,
                RuntimeEnv.newInstantiator(typeClass));
    }

    
Generates a schema from the given class with the declared fields (inclusive) based from the given Map. The value of a the Map's entry will be the name used for the field (which enables aliasing).
    public static <T> RuntimeSchema<T> createFrom(Class<T> typeClass,
            Map<StringStringdeclaredFieldsIdStrategy strategy)
    {
        if (typeClass.isInterface()
                || Modifier.isAbstract(typeClass.getModifiers()))
        {
            throw new RuntimeException(
                    "The root object can neither be an abstract "
                            + "class nor interface: \"" + typeClass.getName());
        }
        final ArrayList<Field<T>> fields = new ArrayList<>(
                declaredFields.size());
        int i = 0;
        for (Map.Entry<StringStringentry : declaredFields.entrySet())
        {
            final java.lang.reflect.Field f;
            try
            {
                f = typeClass.getDeclaredField(entry.getKey());
            }
            catch (Exception e)
            {
                throw new IllegalArgumentException("Exception on field: "
                        + entry.getKey(), e);
            }
            final int mod = f.getModifiers();
            if (!Modifier.isStatic(mod) && !Modifier.isTransient(mod) && f.getAnnotation(Exclude.class) == null)
            {
                final Field<T> field = RuntimeFieldFactory.getFieldFactory(
                        f.getType(), strategy).create(++ientry.getValue(), f,
                        strategy);
                fields.add(field);
            }
        }
        return new RuntimeSchema<>(typeClassfieldsi,
                RuntimeEnv.newInstantiator(typeClass));
    }
            Class<?> typeClass)
    {
        LinkedHashMap<Stringjava.lang.reflect.FieldfieldMap = new LinkedHashMap<>();
        fill(fieldMaptypeClass);
        return fieldMap;
    }
    static void fill(Map<Stringjava.lang.reflect.FieldfieldMap,
            Class<?> typeClass)
    {
        if (Object.class != typeClass.getSuperclass())
            fill(fieldMaptypeClass.getSuperclass());
        for (java.lang.reflect.Field f : typeClass.getDeclaredFields())
        {
            int mod = f.getModifiers();
            if (!Modifier.isStatic(mod) && !Modifier.isTransient(mod) && f.getAnnotation(Exclude.class) == null)
                fieldMap.put(f.getName(), f);
        }
    }
    public final Instantiator<T> instantiator;
    public RuntimeSchema(Class<T> typeClassCollection<Field<T>> fields,
            int lastFieldNumberConstructor<T> constructor)
    {
        this(typeClassfieldslastFieldNumbernew DefaultInstantiator<>(
                constructor));
    }
    public RuntimeSchema(Class<T> typeClassCollection<Field<T>> fields,
            int lastFieldNumberInstantiator<T> instantiator)
    {
        super(typeClassfieldslastFieldNumber);
        this. = instantiator;
    }

    
Always returns true, everything is optional.
    @Override
    public boolean isInitialized(T message)
    {
        return true;
    }
    @Override
    public T newMessage()
    {
        return .newInstance();
    }

    
Invoked only when applications are having pipe io operations.
    @SuppressWarnings("unchecked")
    static <T> Pipe.Schema<T> resolvePipeSchema(Schema<T> schema,
            Class<? super T> clazzboolean throwIfNone)
    {
        if (Message.class.isAssignableFrom(clazz))
        {
            try
            {
                // use the pipe schema of code-generated messages if available.
                java.lang.reflect.Method m = clazz.getDeclaredMethod(
                        "getPipeSchema"new Class[] {});
                return (Pipe.Schema<T>) m.invoke(nullnew Object[] {});
            }
            catch (Exception e)
            {
                // ignore
            }
        }
        if (MappedSchema.class.isAssignableFrom(schema.getClass()))
            return ((MappedSchema<T>) schema).;
        if (throwIfNone)
            throw new RuntimeException("No pipe schema for: " + clazz);
        return null;
    }
New to GrepCode? Check out our FAQ X