View Javadoc
1   package ejava.examples.ejbwar.inventory.bo;
2   
3   import java.io.InputStream;
4   import java.io.Serializable;
5   import java.io.StringWriter;
6   
7   import javax.persistence.Column;
8   import javax.persistence.MappedSuperclass;
9   import javax.persistence.Version;
10  import javax.xml.bind.JAXBContext;
11  import javax.xml.bind.JAXBException;
12  import javax.xml.bind.Marshaller;
13  import javax.xml.bind.Unmarshaller;
14  import javax.xml.bind.annotation.XmlAttribute;
15  
16  /**
17   * This class provides base definition and helper methods for representations
18   * within the inventory domain.
19   */
20  @SuppressWarnings("serial")
21  @MappedSuperclass
22  public abstract class InventoryRepresentation implements Serializable {
23  	public static final String NAMESPACE = "http://webejb.ejava.info/inventory";
24  	
25  	@Version
26  	@Column(name="VERSION")
27  	private int version;
28  	
29  	/**
30  	 * This property is added to each entity so that we can have better 
31  	 * control over concurrent updates
32  	 * @return
33  	 */
34  	@XmlAttribute(required=true)
35  	public int getVersion() { return version; }
36  	public void setVersion(int version) {
37  		this.version = version;
38  	}
39  	
40  	/**
41  	 * Our toString() implementation will take advantage of the JAXB defintion
42  	 * for the class and marshall the object as an XML string.
43  	 */
44  	@Override
45  	public String toString() {
46  		try {
47  			JAXBContext jbx = JAXBContext.newInstance(getClass());
48  			Marshaller marshaller = jbx.createMarshaller();
49  			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
50  			StringWriter writer = new StringWriter();
51  			marshaller.marshal(this, writer);
52  			return writer.toString();
53  		} catch (JAXBException ex) {
54  			throw new RuntimeException("unexpected JAXB error marshalling object:", ex);
55  		}
56  	}
57  	
58  	/**
59  	 * This method will unmarshall the specified class from the provided 
60  	 * XML input stream.
61  	 * @param clazz
62  	 * @param is
63  	 * @return
64  	 */
65  	@SuppressWarnings("unchecked")
66  	public static <T> T unmarshall(Class<T> clazz, InputStream is) {
67  		try {
68  			JAXBContext jbx = JAXBContext.newInstance(clazz);
69  			Unmarshaller marshaller = jbx.createUnmarshaller();
70  			return (T) marshaller.unmarshal(is);
71  		} catch (JAXBException ex) {
72  			throw new RuntimeException("unexpected JAXB error marshalling object:", ex);
73  		}
74  	}
75  }