| 1 | |
package com.aurea.maven.plugins.util; |
| 2 | |
|
| 3 | |
import java.io.InputStream; |
| 4 | |
import java.io.OutputStream; |
| 5 | |
|
| 6 | |
import javax.xml.bind.JAXBContext; |
| 7 | |
import javax.xml.bind.Marshaller; |
| 8 | |
import javax.xml.bind.Unmarshaller; |
| 9 | |
import javax.xml.bind.annotation.XmlRootElement; |
| 10 | |
|
| 11 | 0 | public class JAXBHelper { |
| 12 | |
|
| 13 | |
public static void marshal(Object o, OutputStream os) throws Exception { |
| 14 | |
try { |
| 15 | 0 | String jp = getJAXBPackage(o.getClass()); |
| 16 | 0 | if (jp != null) { |
| 17 | 0 | JAXBContext ctxt = JAXBContext.newInstance(getJAXBPackage(o.getClass())); |
| 18 | 0 | Marshaller m = ctxt.createMarshaller(); |
| 19 | 0 | m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); |
| 20 | 0 | m.marshal(o, os); |
| 21 | |
} |
| 22 | 0 | } catch (Exception e) { |
| 23 | 0 | e.printStackTrace(); |
| 24 | 0 | throw (e); |
| 25 | 0 | } |
| 26 | 0 | } |
| 27 | |
|
| 28 | |
public static Object unmarshal(Class<?> c, InputStream is) throws Exception { |
| 29 | |
|
| 30 | 0 | Object result = null; |
| 31 | 0 | String jp = getJAXBPackage(c); |
| 32 | |
|
| 33 | |
try { |
| 34 | 0 | if (jp != null) { |
| 35 | 0 | JAXBContext ctxt = JAXBContext.newInstance(c); |
| 36 | 0 | Unmarshaller um = ctxt.createUnmarshaller(); |
| 37 | 0 | result = um.unmarshal(is); |
| 38 | |
} |
| 39 | 0 | } catch (Exception e) { |
| 40 | 0 | e.printStackTrace(); |
| 41 | 0 | throw (e); |
| 42 | 0 | } |
| 43 | |
|
| 44 | 0 | return result; |
| 45 | |
} |
| 46 | |
|
| 47 | |
@SuppressWarnings("unchecked") |
| 48 | |
private static String getJAXBPackage(@SuppressWarnings("rawtypes") Class clazz) { |
| 49 | 0 | if (clazz.getAnnotation(XmlRootElement.class) != null) { |
| 50 | 0 | return clazz.getPackage().getName(); |
| 51 | |
} else { |
| 52 | 0 | if (clazz.getSuperclass() != null) { |
| 53 | 0 | return getJAXBPackage(clazz.getSuperclass()); |
| 54 | |
} else { |
| 55 | 0 | return null; |
| 56 | |
} |
| 57 | |
} |
| 58 | |
} |
| 59 | |
} |