net.aequologica.neo.parole.model.ParolesSerializer Maven / Gradle / Ivy
package net.aequologica.neo.parole.model;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
import static com.google.common.net.MediaType.JSON_UTF_8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import net.aequologica.neo.geppaequo.cmis.ECMHelper.Stream;
import net.aequologica.neo.geppaequo.document.DocumentHelper;
public class ParolesSerializer {
final protected ObjectMapper objectMapper;
public ParolesSerializer() {
this.objectMapper = new ObjectMapper();
this.objectMapper.enable(INDENT_OUTPUT);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.setSerializationInclusion(NON_NULL);
this.objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
this.objectMapper.registerModule(new JodaModule());
}
public void write(OutputStream outputStream, List paroles) throws IOException {
this.objectMapper.writeValue(outputStream, paroles);
}
public void write(Writer writer, List paroles) throws IOException {
this.objectMapper.writeValue(writer, paroles);
}
public List read(InputStream inputStream) throws IOException {
return this.objectMapper.readValue(inputStream, new TypeReference>() {});
}
public List read(Reader reader) throws IOException {
return this.objectMapper.readValue(reader, new TypeReference>() {});
}
public void write(Path path, List paroles) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
write(baos, paroles); // ?? "Encoding used will be UTF-8." ??
final byte[] byteArray = baos.toByteArray();
DocumentHelper.write(path, new Stream() {
@Override public String getMimeType() { return JSON_UTF_8.toString(); }
@Override public long getLength() { return byteArray.length; }
@Override public InputStream getInputStream() { return new ByteArrayInputStream(byteArray); }
});
}
public List read(Path path) throws IOException {
final InputStream inputStream = DocumentHelper.getInputStream(path);
if (inputStream == null) {
throw new FileNotFoundException(path.toString());
}
return read(inputStream);
}
}