Untitled

 avatar
unknown
plain_text
2 years ago
2.3 kB
6
Indexable
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Map;

import static java.util.Optional.ofNullable;

public class JaxbMessageHandler {

    private final Map<Class<?>, Schema> classSchemaMap;

    public JaxbMessageHandler(Map<Class<?>, Schema> classSchemaMap) {
        this.classSchemaMap = classSchemaMap;
    }

    @SuppressWarnings("unchecked")
    public <T> T deserialize(String payload, Class<T> targetClass) {
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(payload.getBytes())) {
            JAXBContext jaxbContext = JAXBContext.newInstance(targetClass);
            Schema schema = schema(targetClass);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(schema);
            return (T) unmarshaller.unmarshal(inputStream);
        } catch (Exception e) {
            throw new XmlDeserializeException(e);
        }
    }

    public String serialize(Object object) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
            Schema schema = schema(object.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setSchema(schema);
            marshaller.marshal(object, outputStream);
            return outputStream.toString();
        } catch (Exception e) {
            throw new XmlSerializeException(e);
        }
    }

    private <T> Schema schema(Class<T> targetClass) {
        return ofNullable(classSchemaMap.get(targetClass))
                .orElseThrow(() -> new RuntimeException("Couldn't find schema registration for " + targetClass));
    }

    public static class XmlDeserializeException extends RuntimeException {

        public XmlDeserializeException(Throwable cause) {
            super(cause);
        }
    }

    public static class XmlSerializeException extends RuntimeException {

        public XmlSerializeException(Throwable cause) {
            super(cause);
        }
    }
}
Editor is loading...