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

com.sap.cloud.mt.subscription.StreamToJsonConverter Maven / Gradle / Ivy

There is a newer version: 3.3.1
Show newest version
/******************************************************************************
 * © 2020 SAP SE or an SAP affiliate company. All rights reserved.            *
 ******************************************************************************/
package com.sap.cloud.mt.subscription;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class StreamToJsonConverter {
    private static final Logger logger = LoggerFactory.getLogger(StreamToJsonConverter.class);
    private final Class clazz;

    public StreamToJsonConverter(Class clazz) {
        this.clazz = clazz;
    }

    public T asJson(InputStream inputStream, Charset charset) throws IOException {
        try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            if (clazz == String.class) {
                return (T) asString(bufferedReader);
            } else {
                try {
                    return Tools.getObjectMapper().readValue(bufferedReader, clazz);
                } catch (IOException e) {
                    logger.error("Could not convert return value to class {}, message is {}", clazz, e);
                    return null;
                }
            }
        }
    }

    private String asString(BufferedReader bufferedReader) throws IOException {
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) builder.append(line);
        return builder.toString();
    }

    public T asJson(String input) throws IOException {
        if (clazz == String.class) {
            return (T) input;
        } else {
            try {
                return Tools.getObjectMapper().readValue(input, clazz);
            } catch (IOException e) {
                logger.error("Could not convert return value to class {}, message is {}", clazz, e);
                return null;
            }
        }
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy