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

pl.allegro.tech.hermes.api.helpers.Patch Maven / Gradle / Ivy

There is a newer version: 2.6.22
Show newest version
package pl.allegro.tech.hermes.api.helpers;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import pl.allegro.tech.hermes.api.PatchData;

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

import static com.google.common.base.Preconditions.checkNotNull;

public class Patch {

    private static final ObjectMapper MAPPER = new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.WRITE_NULL_MAP_VALUES)
            .registerModule(new JavaTimeModule());

    @SuppressWarnings("unchecked")
    public static  T apply(T object, PatchData patch) {
        checkNotNull(object);
        checkNotNull(patch);
        Map objectMap = MAPPER.convertValue(object, Map.class);
        return (T) MAPPER.convertValue(merge(objectMap, patch.getPatch()), object.getClass());
    }

    @SuppressWarnings("unchecked")
    private static Map merge(Map left, Map right) {
        Map merged = new HashMap<>(left);
        for (Map.Entry entry : right.entrySet()) {
            if (entry.getValue() instanceof Map && merged.containsKey(entry.getKey())) {
                Map nested = (Map) merged.get(entry.getKey());
                nested.putAll(merge(nested, (Map) entry.getValue()));
            } else {
                merged.put(entry.getKey(), entry.getValue());
            }
        }
        return merged;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy