View Javadoc
1   package xuml.tools.miuml.metamodel.jaxb;
2   
3   import java.io.InputStream;
4   
5   import javax.xml.transform.stream.StreamSource;
6   import javax.xml.validation.Schema;
7   import javax.xml.validation.SchemaFactory;
8   
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   * Uunmarshals {@link Domains}.
21   * 
22   * @author dave
23   * 
24   */
25  public class Marshaller {
26  
27      private Unmarshaller unmarshaller;
28  
29      /**
30       * Constructor.
31       */
32      public Marshaller() {
33  
34          try {
35              JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
36              unmarshaller = context.createUnmarshaller();
37              SchemaFactory sf = SchemaFactory
38                      .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
39              Schema schema = sf.newSchema(getClass().getResource("/miuml-metamodel.xsd"));
40              unmarshaller.setSchema(schema);
41              unmarshaller.setEventHandler(new ValidationEventHandler() {
42                  @Override
43                  public boolean handleEvent(ValidationEvent event) {
44                      throw new RuntimeException(event.getMessage(), event.getLinkedException());
45                  }
46              });
47          } catch (JAXBException e) {
48              throw new RuntimeException(e);
49          } catch (SAXException e) {
50              throw new RuntimeException(e);
51          }
52      }
53  
54      /**
55       * Unmarshals the xml in the {@link InputStream} to a {@link Domains}.
56       * Throws a {@link RuntimeException} if anything goes wrong.
57       * 
58       * @param is
59       * @return
60       */
61      public synchronized Domains unmarshal(InputStream is) {
62          Preconditions.checkNotNull(is, "InputStream is null!");
63          try {
64              return unmarshaller.unmarshal(new StreamSource(is), Domains.class).getValue();
65          } catch (JAXBException e) {
66              throw new RuntimeException(e);
67          }
68      }
69  
70  }