com.envimate.mapmate.serialization.Serializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mapmate Show documentation
Show all versions of mapmate Show documentation
MapMate is a modern mapping framework in the scope of mapping data in
Json, XML, or YAML format into DTOs composed and vice versa.
/*
* Copyright (C) 2017 [Richard Hauswald, Nune Isabekyan] (envimate GmbH - https://envimate.com/)
*/
package com.envimate.mapmate.serialization;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
public class Serializer {
private final Map, TypeSpecificSerializer> typeSpecificSerializers;
private final Map, TypeSpecificGeneralizer> typeSpecificGeneralizers;
private final GeneralizationSerializer generalizationSerializer;
Serializer(final Map, TypeSpecificSerializer> typeSpecificSerializers,
final Map, TypeSpecificGeneralizer> typeSpecificGeneralizers,
final GeneralizationSerializer generalizationSerializer) {
this.typeSpecificSerializers = typeSpecificSerializers;
this.typeSpecificGeneralizers = typeSpecificGeneralizers;
this.generalizationSerializer = generalizationSerializer;
}
public static SerializerBuilder aSerializer() {
return new SerializerBuilder();
}
public String serialize(final Object object) {
final Class> type = object.getClass();
if (object instanceof String) {
return (String) object;
} else if (canBeSerialized(type)) {
final TypeSpecificSerializer typeSpecificSerializer = this.typeSpecificSerializers.get(type);
return typeSpecificSerializer.serialize(object);
} else if (canBeGeneralized(type)) {
final TypeSpecificGeneralizer typeSpecificGeneralizer = this.typeSpecificGeneralizers.get(object.getClass());
final Map generalization = typeSpecificGeneralizer.generalize(object);
return this.generalizationSerializer.serialize(generalization);
} else {
throw new UnsupportedOperationException(String.format("Cannot serialize %s of type %s", object, type));
}
}
Object generalize(final Object object) {
final Class> type = object.getClass();
if (type.isArray()) {
return generalizeArray((Object[]) object);
} else if (Iterable.class.isAssignableFrom(type)) {
final Iterable iterable = (Iterable) object;
final LinkedList linkedList = new LinkedList();
for (final Object o : iterable) {
linkedList.add(o);
}
return generalizeArray(linkedList.toArray());
} else if (Map.class.isAssignableFrom(type)) {
final Map