All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.contextfw.web.application.internal.util.AttributeHandler Maven / Gradle / Ivy

package net.contextfw.web.application.internal.util;

import java.util.HashMap;
import java.util.Map;

import net.contextfw.web.application.configuration.KeyValue;
import net.contextfw.web.application.configuration.Configuration;
import net.contextfw.web.application.internal.ToStringSerializer;
import net.contextfw.web.application.serialize.AttributeJsonSerializer;
import net.contextfw.web.application.serialize.AttributeSerializer;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
public class AttributeHandler implements ObjectAttributeSerializer {
    
    private final Map,  AttributeSerializer> serializers = 
        new HashMap,  AttributeSerializer>();
    
    private ToStringSerializer toStringSerializer = new ToStringSerializer();
    
    @SuppressWarnings("unchecked")
    @Inject
    public AttributeHandler(Injector injector, Configuration conf) {
        
        for (KeyValue, Class>> entry : conf
                .get(Configuration.ATTRIBUTE_SERIALIZER)) {
            serializers.put(
                    entry.getKey(), 
                    (AttributeSerializer) injector.getInstance(entry.getValue()));
        }
        
        for (KeyValue, Class>> entry : conf
                .get(Configuration.ATTRIBUTE_JSON_SERIALIZER)) {
            serializers.put(
                    entry.getKey(), 
                    (AttributeSerializer) injector.getInstance(entry.getValue()));
        }

    }
    
    @Override
    public String serialize(Object source) {
        if (source != null) {
            Class cl = source.getClass();
            if (serializers.containsKey(cl)) {
                return serializers.get(cl).serialize(source);
            } else {
                return toStringSerializer.serialize(source);
            }
        } else {
            return null;
        }
    }
}