View Javadoc

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