From 29402fc27e21b808212f2fa29ce51619d1b83265 Mon Sep 17 00:00:00 2001 From: Edouard DUPIN Date: Sat, 3 Feb 2024 18:46:30 +0100 Subject: [PATCH] [DEV] add csv serializator for user export --- pom.xml | 7 ++- .../serializer/CSVMessageBodyWritter.java | 57 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/org/kar/archidata/serializer/CSVMessageBodyWritter.java diff --git a/pom.xml b/pom.xml index 6fdeb90..9e2b685 100644 --- a/pom.xml +++ b/pom.xml @@ -107,7 +107,12 @@ com.fasterxml.jackson.core jackson-databind - 2.16.0 + 2.16.1 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + 2.16.1 jakarta.servlet diff --git a/src/org/kar/archidata/serializer/CSVMessageBodyWritter.java b/src/org/kar/archidata/serializer/CSVMessageBodyWritter.java new file mode 100644 index 0000000..edbf5f3 --- /dev/null +++ b/src/org/kar/archidata/serializer/CSVMessageBodyWritter.java @@ -0,0 +1,57 @@ +package org.kar.archidata.serializer; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; + +import com.fasterxml.jackson.dataformat.csv.CsvMapper; +import com.fasterxml.jackson.dataformat.csv.CsvSchema; + +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.ext.MessageBodyWriter; +import jakarta.ws.rs.ext.Provider; + +/** + * Body writter use in jersey with : + * In your main: + * ```java + * rc.register(new CSVMessageBodyWritter()); + * ``` + * + * and in the produce element: + * ```java + * @GET + * @Produces("text/csv") + * public List getData() {} + * ``` + */ +@Provider +@Produces("text/csv") +public class CSVMessageBodyWritter implements MessageBodyWriter> { + + @Override + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return List.class.isAssignableFrom(type); + } + + @Override + public long getSize(List data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return 0; + } + + @Override + public void writeTo(List data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) + throws IOException, WebApplicationException { + if (data != null && data.size() > 0) { + CsvMapper mapper = new CsvMapper(); + Object o = data.get(0); + CsvSchema schema = mapper.schemaFor(o.getClass()).withHeader(); + mapper.writer(schema).writeValue(entityStream, data); + } + } +}