Example usage for org.dom4j Document getDocType

List of usage examples for org.dom4j Document getDocType

Introduction

In this page you can find the example usage for org.dom4j Document getDocType.

Prototype

DocumentType getDocType();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.jboss.mx.metadata.XMLMetaData.java

License:Open Source License

/**
 * Constructs the Model MBean metadata. This implementation reads the
 * document type definition from the beginning of the XML file and picks
 * a corresponding XML builder based on the schema name. In case no
 * document type is defined the latest schema builder for this JBossMX
 * release is used. <p>/*from w ww .j av a  2s. c  o m*/
 *
 * The SAX parser implementation is selected by default based on JAXP
 * configuration. If you want to use JAXP to select the parser, you can
 * set the system property <tt>"javax.xml.parsers.SAXParserFactory"</tt>.
 * For example, to use Xerces you might define:   <br><pre>
 *
 *    java -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl ...
 *
 * </pre>
 *
 * In case you can't or don't want to use JAXP to configure the SAX parser
 * implementation you can override the SAX parser implementation by setting
 * an MBean descriptor field {@link XMBeanConstants#SAX_PARSER} to the
 * parser class string value.
 *
 * @return initialized MBean info
 * @throws NotCompliantMBeanException if there were errors building the
 *         MBean info from the given XML file.
 */
public MBeanInfo build() throws NotCompliantMBeanException {
    try {
        int version = NO_VERSION;

        if (versionString == null) {
            // by default, let JAXP pick the SAX parser
            SAXReader reader = new SAXReader();

            // check if user wants to override the SAX parser property
            if (properties.get(SAX_PARSER) != null) {
                try {
                    reader.setXMLReaderClassName(getStringProperty(SAX_PARSER));
                }

                catch (SAXException e) {
                    //Should log and ignore, I guess
                } // end of try-catch
            }
            // by default we validate
            reader.setValidation(true);

            // the user can override the validation by setting the VALIDATE property
            try {
                boolean validate = getBooleanProperty(XML_VALIDATION);
                reader.setValidation(validate);
            } catch (IllegalPropertyException e) {
                // FIXME: log the exception (warning)

                // fall through, use the default value
            }

            //supply it with our dtd locally.
            reader.setEntityResolver(new JBossEntityResolver());

            // get the element and start parsing...
            Document doc = reader.read(url);
            element = doc.getRootElement();
            DocumentType type = doc.getDocType();

            version = validateVersionString(type.getPublicID());
            if (version == NO_VERSION) {
                version = validateVersionString(type.getSystemID());
            } // end of if ()

        } else {
            version = validateVersionString(versionString);
        } // end of else

        if (element == null) {
            throw new IllegalStateException("No element supplied with explict version!");
        }
        // These are the known schemas for us. Pick the correct one based on
        // schema or default to the latest.docURL.endsWith(JBOSSMX_XMBEAN_DTD_1_0)
        if (version == JBOSS_XMBEAN_1_0 || version == JBOSS_XMBEAN_1_1 || version == JBOSS_XMBEAN_1_2) {
            // jboss_xmbean_1_0.dtd is the only implemented useful xmbean
            return new JBossXMBean10(mmbClassName, resourceClassName, element, properties).build();
        } else {
            throw new NotCompliantMBeanException("Unknown xmbean type " + versionString);
        } // end of else

    } catch (DocumentException e) {
        throw new JBossNotCompliantMBeanException("Error parsing the XML file, from XMLMetaData: ", e);
    }
}

From source file:org.mitre.jawb.gui.ReferenceEditor.java

License:Open Source License

private void save() {
    File temp = null;//from w  ww. ja  v a2  s .  c  o m
    // check our values
    if (aifURI == null || "".equals(dtdField.getText()) || "".equals(maiaField.getText())
            || "".equals(signalField.getText())) {
        GUIUtils.beep();
        return;
    }
    try {
        // make a temp copy replacing some URL's w/ external references
        Document doc = ATLASHelper.parse(aifURI);
        DocumentType doctype = doc.getDocType();
        Element corpus = doc.getRootElement();
        Element signal = corpus.element("SimpleSignal"); // first and only

        doctype.setSystemID(dtdField.getText());
        corpus.addAttribute("schemeLocation", maiaField.getText());
        signal.addAttribute("href", signalField.getText());

        temp = File.createTempFile("callisto", ".aif.xml");
        if (DEBUG >= 0)
            System.err.println("RefEdit.save: creating temp .aif in:\n    " + temp);

        OutputStream out = new FileOutputStream(temp);
        ATLASHelper.dump(doc, out);
        out.close();

        // ...and replace the ATLAS generated version
        File aif = new File(new URI(aifURI.toASCIIString()));
        File backup = new File(aif.toString() + "~");
        if (!(aif.renameTo(backup) && temp.renameTo(aif))) {
            System.err.println(
                    "RefEdit.Error rewriting aif: " + aifURI + "\n Failed to replace w/: " + temp.getPath());
            // renaming failed, without exception, so delete the temp file
            // catch exceptions so temp is nulled.
            try {
                temp.delete();
            } catch (Exception x) {
                /* ignore */ }
        }
        temp = null;

        // this exception was caused by renameTo, or earlier, in which case
        // the user's saved file is not the externalized version... but temp
        // still exists, and should be deleted if it does. The 'catch' is just
        // a "heads-up"
    } catch (Exception x) {
        GUIUtils.showError("Error rewriting aif:\n" + aifURI);
        x.printStackTrace();

    } finally {
        if (temp != null)
            temp.delete(); // clean up in case of errors
    }
    setDirty(false);
}

From source file:org.mitre.jawb.io.ATLASHelper.java

License:Open Source License

/**
 * Read in an .aif file from the specified URI, and write it out with
 * localized refernces to the output stream.
 * @param aifURI location of input .aif file. <strong>MUST BE ABSOLUTE.</strong>
 * @param out stream that localized version of input is written to
 * @param cheatMap A map of undocumented values that we use in Callisto
 *                 to store data in the AIF which ATLAS won't.
 *///w  ww. j a v  a 2  s  .c  o  m
public static void localize(URI aifURI, OutputStream out, Map cheatMap) throws IOException {
    if (DEBUG > 0)
        System.err.println("ATHelp.localize: aifURI=" + aifURI);

    Document doc = parse(aifURI);
    DocumentType doctype = doc.getDocType();
    Element corpus = doc.getRootElement();
    Element signal = getTextSignal(corpus);

    // Replace external ATLAS DTD reference w/ local reference
    URI localDTD = URLUtils.badURLToURI(Jawb.getResource("aif.dtd"));
    doctype.setSystemID(localDTD.toString());

    // Retrieve 'Cononical' MAIA Scheme and replace w/ local reference
    String maiaString = corpus.attributeValue("schemeLocation");
    Task task = findTask(maiaString, EXTERNAL);
    if (task == null) {
        // it could be an old file that still has a local MAIA URL
        String escapedMaia = maiaString.replaceAll(" ", "%20");
        if ((task = findTask(escapedMaia, LOCAL)) == null)
            throw new RuntimeException("Unrecognized Task: MAIA URI=" + maiaString);
    }
    corpus.addAttribute("schemeLocation", task.getLocalMaiaURI().toString());

    // It's possible to /not/ have a text signal referenced
    if (signal != null) {
        // If signal is relative URI, convert to absolute,
        // resolving against .aif file
        String signalHREF = signal.attributeValue("href");
        try {
            String path = aifURI.getRawPath();
            URI aifBase = aifURI.resolve(path.substring(0, path.lastIndexOf('/') + 1));
            URI signalURI = new URI(signalHREF);
            URI resolvedURI = aifBase.resolve(signalURI);

            if (DEBUG > 0) {
                System.err.println("ATHelp.localize:\n        base= " + aifBase + "\n      signal= " + signalURI
                        + "\n    resolved= " + resolvedURI);
            }
            signal.addAttribute("href", resolvedURI.toString());

        } catch (URISyntaxException x) {
            System.err.println("WARNING: aif file specifies invalid signal URI:"
                    + " not resolving:\n    aifURI=   " + aifURI + "\n    signalURI=" + signalHREF);
            System.err.println(x.getMessage());
        }
        // ATLAS ignores encoding so use the cheats
        cheatMap.put("encoding", signal.attributeValue("encoding"));
        cheatMap.put("mimeType", signal.attributeValue("mimeType"));
        cheatMap.put(SIGNAL_CHECKSUM, signal.attributeValue("checksum"));

        Element body = signal.element("body");
        if (body != null) {
            String signalEncoding = body.attributeValue("encoding");
            if (!"Base64".equalsIgnoreCase(signalEncoding))
                System.err.println("Unrecognized embeded signal encoding: '" + signalEncoding + "'");
            else {
                String embedded = body.getText();
                cheatMap.put(SIGNAL_DATA, Base64.decode(embedded));
            }
        }
    } // if (signal != null)

    dump(doc, out);
}

From source file:org.mitre.jawb.io.ATLASHelper.java

License:Open Source License

/**
 * Read in an .aif file from the specified URI, and write it out with
 * localized refernces to the output stream.
 * @param aifURI location of input .aif file. <strong>MUST BE ABSOLUTE.</strong>
 * @param out stream that localized version of input is written to
 * @param relativize rewrite the absolute signal URI as relative based on
 *                   input//from  w  w  w.j  a  va  2 s .  co m
 * @param cheatMap A map of undocumented values that we use in Callisto
 *                    to store data in the AIF which ATLAS won't.
 */
public static void externalize(URI aifURI, OutputStream out, boolean relativize, Map cheatMap)
        throws IOException {
    if (DEBUG > 0)
        System.err.println("ATHelp.externalize: aifURI=" + aifURI);

    Document doc = parse(aifURI);
    DocumentType doctype = doc.getDocType();
    Element corpus = doc.getRootElement();
    Element signal = getTextSignal(corpus);

    // Replace local ATLAS DTD reference w/ external reference
    doctype.setSystemID("http://www.nist.gov/speech/atlas/aif.dtd");

    // Replace local MAIA Scheme w/ external reference
    String maiaString = corpus.attributeValue("schemeLocation");
    Task task = findTask(maiaString, LOCAL);
    if (task == null)
        System.err.println("Unable to extern Maia: Unknown:\n  " + maiaString);
    else
        corpus.addAttribute("schemeLocation", task.getMaiaURI().toString());

    // It's possible to /not/ have a text signal referenced
    if (signal != null) {
        // Perhaps replace absolute URI with relative URI
        if (relativize) {
            String signalHREF = signal.attributeValue("href");
            try {
                String path = aifURI.getRawPath();
                URI aifBase = aifURI.resolve(path.substring(0, path.lastIndexOf('/') + 1));
                URI signalURI = new URI(signalHREF);
                URI relativeURI = aifBase.relativize(signalURI);

                if (DEBUG > 0) {
                    System.err.println("ATHelp.extern:\n      base= " + aifBase + "\n      signal= " + signalURI
                            + "\n    relative= " + relativeURI);
                }
                signal.addAttribute("href", relativeURI.toString());

            } catch (URISyntaxException x) {
                System.err.println("WARNING: aif file specifies invalid signal URI:"
                        + " not relativizing:\n    aifURI=   " + aifURI + "\n    signalURI=" + signalHREF);
                System.err.println(x.getMessage());
            }
        }

        // ATLAS ignores encoding so use the cheats
        signal.addAttribute("encoding", (String) cheatMap.get("encoding"));
        signal.addAttribute("mimeType", (String) cheatMap.get("mimeType"));

        if (cheatMap.get(SIGNAL_DATA) != null) {
            String embedded = Base64.encode((byte[]) cheatMap.get(SIGNAL_DATA));
            Element body = signal.addElement("body");
            body.addAttribute("encoding", "Base64");
            body.addText(embedded);
        }
    } // if (signal != null)

    dump(doc, out);
}

From source file:org.mitre.jawb.io.ATLASHelper.java

License:Open Source License

/**
   * Read in an .aif file from the specified URI, and write it out with
   * localized refernces to the output stream.
   * @param aifURI location of input .aif file. <strong>MUST BE ABSOLUTE.</strong>
   * @param out stream that localized version of input is written to
   * @param relativize rewrite the absolute signal URI as relative based on
   *                   input//from w  ww  . jav a2s  . c  o m
   * @param cheatMap A map of undocumented values that we use in Callisto
   *                    to store data in the AIF which ATLAS won't.
   */
public static void externalize(URI aifURI, InputStream in, OutputStream out, boolean relativize, Map cheatMap)
        throws IOException {
    //    if (DEBUG > 0)
    //      System.err.println ("ATHelp.externalize: aifURI="+aifURI);

    Document doc = parse(in);
    DocumentType doctype = doc.getDocType();
    Element corpus = doc.getRootElement();
    Element signal = getTextSignal(corpus);

    // Replace local ATLAS DTD reference w/ external reference
    doctype.setSystemID("http://www.nist.gov/speech/atlas/aif.dtd");

    // Replace local MAIA Scheme w/ external reference
    String maiaString = corpus.attributeValue("schemeLocation");
    Task task = findTask(maiaString, LOCAL);
    if (task == null)
        System.err.println("Unable to extern Maia: Unknown:\n  " + maiaString);
    else
        corpus.addAttribute("schemeLocation", task.getMaiaURI().toString());

    // It's possible to /not/ have a text signal referenced
    if (signal != null) {
        // Perhaps replace absolute URI with relative URI
        if (relativize) {
            String signalHREF = signal.attributeValue("href");
            try {
                String path = aifURI.getRawPath();
                URI aifBase = aifURI.resolve(path.substring(0, path.lastIndexOf('/') + 1));
                URI signalURI = new URI(signalHREF);
                URI relativeURI = aifBase.relativize(signalURI);

                if (DEBUG > 0) {
                    System.err.println("ATHelp.extern:\n      base= " + aifBase + "\n      signal= " + signalURI
                            + "\n    relative= " + relativeURI);
                }
                signal.addAttribute("href", relativeURI.toString());

            } catch (URISyntaxException x) {
                System.err.println("WARNING: aif file specifies invalid signal URI:"
                        + " not relativizing:\n    aifURI=   " + aifURI + "\n    signalURI=" + signalHREF);
                System.err.println(x.getMessage());
            }
        }

        // ATLAS ignores encoding so use the cheats
        signal.addAttribute("encoding", (String) cheatMap.get("encoding"));
        signal.addAttribute("mimeType", (String) cheatMap.get("mimeType"));

        if (cheatMap.get(SIGNAL_DATA) != null) {
            String embedded = Base64.encode((byte[]) cheatMap.get(SIGNAL_DATA));
            Element body = signal.addElement("body");
            body.addAttribute("encoding", "Base64");
            body.addText(embedded);
        }
    } // if (signal != null)

    dump(doc, out);
}

From source file:org.olat.ims.qti.qpool.ItemFileResourceValidator.java

License:Apache License

private boolean validateXml(InputStream in) {
    boolean valid = false;
    Document doc = readDocument(in);
    if (doc != null) {
        DocumentType docType = doc.getDocType();
        if (docType == null) {
            doc.addDocType("questestinterop", null, "ims_qtiasiv1p2p1.dtd");
        }//  w ww  .  ja  v  a  2s. c  om
        valid = validateDocument(doc);
    }
    return valid;
}

From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java

License:Open Source License

/**
* <p> This will print the <code>Document</code> to the given
* Writer./*  w  w w  . ja  v a  2 s.  co m*/
* </p>
*
* <p> Warning: using your own Writer may cause the outputter's
* preferred character encoding to be ignored.  If you use
* encodings other than UTF8, we recommend using the method that
* takes an OutputStream instead.  </p>
*
* <p>Note: as with all Writers, you may need to flush() yours
* after this method returns.</p>
*
* @param doc <code>Document</code> to format.
* @param out <code>Writer</code> to write to.
* @throws <code>IOException</code> - if there's any problem writing.
**/
public void output(Document doc, Writer writer) throws IOException {
    // Print out XML declaration
    if (indentLevel > 0)
        indent(writer, indentLevel);
    printDeclaration(doc, writer, encoding);

    if (doc.getDocType() != null) {
        if (indentLevel > 0)
            indent(writer, indentLevel);
        printDocType(doc.getDocType(), writer);
    }

    // Print out root element, as well as any root level
    // comments and processing instructions,
    // starting with no indentation
    Iterator i = doc.getRootElement().elements().iterator();
    while (i.hasNext()) {
        Object obj = i.next();
        if (obj instanceof Element) {
            output(doc.getRootElement(), writer); // at initial indentLevel
        } else if (obj instanceof Comment) {
            printComment((Comment) obj, writer, indentLevel);
        } else if (obj instanceof ProcessingInstruction) {
            printProcessingInstruction((ProcessingInstruction) obj, writer, indentLevel);
        } else if (obj instanceof CDATA) {
            printCDATASection((CDATA) obj, writer, indentLevel);
        }
    }

    // Output final line separator
    writer.write(lineSeparator);
}

From source file:org.unitime.banner.ant.MergeXml.java

License:Apache License

public void execute() throws BuildException {
    try {//from  w  ww .  ja  v a  2  s  .co m
        log("Merging " + iTarget + " with " + iSource);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                }
                return null;
            }
        });
        sax.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document targetDoc = sax.read(new File(iTarget));
        Document sourceDoc = sax.read(new File(iSource));

        merge(targetDoc.getRootElement(), sourceDoc.getRootElement());

        if (new File(iTarget).getName().equals("hibernate.cfg.xml")) {
            targetDoc.setDocType(sourceDoc.getDocType()); // Remove DOCTYPE
            Element sessionFactoryElement = targetDoc.getRootElement().element("session-factory");
            Vector<Element> mappings = new Vector<Element>();
            for (Iterator i = sessionFactoryElement.elementIterator("mapping"); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                mappings.add(mappingElement);
                sessionFactoryElement.remove(mappingElement);
            }
            for (Iterator i = mappings.iterator(); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                sessionFactoryElement.add(mappingElement);
            }
        }

        FileOutputStream fos = new FileOutputStream(iTarget);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(targetDoc);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException(e);
    }
}

From source file:org.xwiki.store.serialization.xml.internal.XMLWriter.java

License:Open Source License

/**
 * Write the <code>{@link Document}</code> declaration, and its <code>{@link DocumentType}</code>
 * if available to the output stream./*from w  w  w  .  j  a  va  2 s  .c o m*/
 * 
 * @param doc <code>{@link Document}</code> to be started, may specify a
 *            <code>{@link DocumentType}</code>.
 * @throws IOException a problem occurs during writing
 */
public void writeDocumentStart(final Document doc) throws IOException {
    writeDeclaration();

    if (doc.getDocType() != null) {
        super.indent();
        super.writeDocType(doc.getDocType());
    }
}

From source file:org.zenonpagetemplates.twoPhasesImpl.DocType.java

License:Open Source License

static public DocType generateDocTypeFromDOM4jDocument(Document document) {

    DocumentType documentType = document.getDocType();

    if (documentType == null) {
        return null;
    }//ww  w .j  av  a2s.  c om

    return new DocType(documentType.getName(), documentType.getPublicID(), documentType.getSystemID());
}