View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.common.content;
20  
21  import java.io.IOException;
22  import java.io.OutputStream;
23  
24  import javax.xml.transform.Source;
25  
26  import org.jdom2.Document;
27  import org.jdom2.Element;
28  import org.jdom2.output.XMLOutputter;
29  import org.jdom2.transform.JDOMSource;
30  
31  /**
32   * Reads MCRContent from a JDOM XML document.
33   * 
34   * @author Frank L\u00FCtzenkichen
35   */
36  public class MCRJDOMContent extends MCRXMLContent {
37  
38      private Document jdom;
39  
40      /**
41       * @param jdom the JDOM XML document to read from 
42       */
43      public MCRJDOMContent(Document jdom) {
44          super();
45          this.jdom = jdom;
46          super.docType = jdom.getDocType() == null ? jdom.getRootElement().getName()
47              : jdom.getDocType()
48                  .getElementName();
49      }
50  
51      /**
52       * Alternative constructor for newly created root elements
53       * that do not have a Document parent yet, which is a very 
54       * common use case.
55       * 
56       * @param jdom the JDOM XML root element to read from 
57       */
58      public MCRJDOMContent(Element jdom) {
59          this(new Document(jdom));
60      }
61  
62      @Override
63      public Source getSource() {
64          JDOMSource source = new JDOMSource(jdom);
65          source.setSystemId(systemId);
66          return source;
67      }
68  
69      @Override
70      public void sendTo(OutputStream out) throws IOException {
71          if (jdom == null) {
72              throw new IOException("JDOM document is null and cannot be written to OutputStream");
73          }
74          new XMLOutputter(format).output(jdom, out);
75      }
76  
77      @Override
78      public Document asXML() {
79          return jdom;
80      }
81  }