View Javadoc
1   package xuml.tools.miuml.metamodel.extensions.jaxb;
2   
3   
4   
5   import javax.xml.validation.Schema;
6   import javax.xml.validation.SchemaFactory;
7   
8   import org.w3c.dom.Node;
9   import org.xml.sax.SAXException;
10  
11  import com.google.common.base.Preconditions;
12  
13  import jakarta.xml.bind.JAXBContext;
14  import jakarta.xml.bind.JAXBException;
15  import jakarta.xml.bind.Unmarshaller;
16  import jakarta.xml.bind.ValidationEvent;
17  import jakarta.xml.bind.ValidationEventHandler;
18  
19  /**
20   * Marshalls and unmarshalls xuml-tools extensions to the miuml metamodel
21   * schema.
22   * 
23   * @author dave
24   * 
25   */
26  public class Marshaller {
27  
28      private Unmarshaller unmarshaller;
29  
30      /**
31       * Constructor.
32       * 
33       */
34      public Marshaller() {
35  
36          try {
37              JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
38              unmarshaller = context.createUnmarshaller();
39              SchemaFactory sf = SchemaFactory
40                      .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
41              Schema schema = sf.newSchema(
42                      getClass().getResource("/xuml-tools-miuml-metamodel-extensions.xsd"));
43              unmarshaller.setSchema(schema);
44              unmarshaller.setEventHandler(new ValidationEventHandler() {
45                  @Override
46                  public boolean handleEvent(ValidationEvent event) {
47                      throw new RuntimeException(event.getMessage(), event.getLinkedException());
48                  }
49              });
50          } catch (JAXBException e) {
51              throw new RuntimeException(e);
52          } catch (SAXException e) {
53              throw new RuntimeException(e);
54          }
55      }
56  
57      /**
58       * Unmarshalls a {@link Node} to a JAXB object from the xuml-tools miuml
59       * extensions schema.
60       * 
61       * @param node
62       * @return
63       * @throws JAXBException
64       */
65      public synchronized Object unmarshal(Node node) throws JAXBException {
66          Preconditions.checkNotNull(node, "Node is null!");
67          return unmarshaller.unmarshal(node);
68      }
69  
70  }