/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.mixnet.commons.tools;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Adapter of jackson mapper to execute common transformations (from java to json, from json to java, from java to file
 * and from file to java)
 */
public class ConfigObjectMapper {

    private final ObjectMapper mapper = new ObjectMapper();

    public String fromJavaToJSON(final Object obj) throws JsonProcessingException {

        return mapper.writeValueAsString(obj);
    }

    public void fromJavaToJSONFile(final Object obj, final File dest) throws IOException {

        mapper.writerWithDefaultPrettyPrinter().writeValue(dest, obj);
    }

    public void fromJavaToJSONFileWithoutNull(final Object obj, final File dest) throws IOException {

        mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter().writeValue(dest, obj);
    }

    public <T> T fromJSONToJava(final String json, final Class<T> valueType) throws IOException {

        return mapper.readValue(json, valueType);
    }

    public <T> T fromJSONFileToJava(final File src, final Class<T> valueType) throws IOException {

        return mapper.readValue(src, valueType);
    }
}
