com.sap.cloud.mt.subscription.StreamToJsonConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of multi-tenant-subscription Show documentation
Show all versions of multi-tenant-subscription Show documentation
Spring Boot Enablement Parent
/******************************************************************************
* © 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;
}
}
}
}