de.ppi.deepsampler.persistence.bean.ext.MapPrimitiveKeyExtension Maven / Gradle / Ivy
Show all versions of deepsampler-persistence Show documentation
/*
* Copyright 2022 PPI AG (Hamburg, Germany)
* This program is made available under the terms of the MIT License.
*/
package de.ppi.deepsampler.persistence.bean.ext;
import de.ppi.deepsampler.persistence.bean.PersistentBeanConverter;
import de.ppi.deepsampler.persistence.bean.ReflectionTools;
import de.ppi.deepsampler.persistence.error.PersistenceException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
/**
* This {@link BeanConverterExtension} is able to convert {@link Map}s into a persistable model that can be sent to
* the underlying persistence api and vice versa.
*
* This extension is limited to {@link Map}s that have a primitive key (i.e. wrapper types of primitives, since {@link Map}s can't
* hold primitives directly)
*
* The values of the {@link Map} can either be primitives (i.e. wrappers) or complex objects. In the first case, the values will be
* sent directly to the persistence api. In the latter case, the values will be converted to {@link de.ppi.deepsampler.persistence.model.PersistentBean}s
* during the serialization process.
*
* The original {@link Map}-types are preserved in most cases. But in some rare cases this is not possible because the original {@link Map}s
* are not visible, or don't provide a adequate constructor. This is i.e. the case for {@link Map}s that have been created using
* {@link Collections#unmodifiableMap(Map)}. In cases like this, the original {@link Map} is replaced by a common {@link HashMap}.
*
* This is a default extension that is always active.
*/
public class MapPrimitiveKeyExtension extends StandardBeanConverterExtension {
@Override
public boolean isProcessable(Class> beanClass, ParameterizedType beanType) {
return Map.class.isAssignableFrom(ReflectionTools.getClass(beanClass))
&& beanType.getActualTypeArguments().length == 2
&& ReflectionTools.hasPrimitiveTypeParameters(beanType);
}
@Override
@SuppressWarnings("unchecked")
public Object convert(Object originalBean, ParameterizedType beanType, PersistentBeanConverter persistentBeanConverter) {
if (!(originalBean instanceof Map)) {
throw new PersistenceException("The type %s is not a Map but we tried to apply the %s on it.",
originalBean.getClass().getName(),
getClass().getName());
}
Map