
fatjar.implementations.jaxb.JaxbXML Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of FatJar Show documentation
Show all versions of FatJar Show documentation
FatJar simple API to quick prototyping and portable web services
package fatjar.implementations.jaxb;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Optional;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import fatjar.Log;
import fatjar.XML;
public class JaxbXML implements XML {
@SuppressWarnings("unchecked")
public Optional fromXML(byte[] xmlData, Class tClass) {
try {
return Optional.ofNullable((T) JAXBContext.newInstance(tClass).createUnmarshaller().unmarshal(new ByteArrayInputStream(xmlData)));
} catch (Exception e) {
Log.error("got exception while creating object from xml, exception: " + e);
return Optional.empty();
}
}
public Optional toXML(T object) {
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Marshaller marshaller = JAXBContext.newInstance(object.getClass()).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(object, outStream);
return Optional.of(new String(outStream.toByteArray()));
} catch (Exception e) {
Log.error("got exception while creating object from xml, exception: " + e);
return Optional.empty();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy