Example usage for org.jdom2 Document hasRootElement

List of usage examples for org.jdom2 Document hasRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document hasRootElement.

Prototype

public boolean hasRootElement() 

Source Link

Document

This will return true if this document has a root element, false otherwise.

Usage

From source file:com.archimatetool.editor.model.impl.EditorModelManager.java

License:Open Source License

private void loadState() throws IOException, JDOMException {
    if (backingFile.exists()) {
        Document doc = JDOMUtils.readXMLFile(backingFile);
        if (doc.hasRootElement()) {
            Element rootElement = doc.getRootElement();
            for (Object e : rootElement.getChildren("model")) { //$NON-NLS-1$
                Element modelElement = (Element) e;
                String filePath = modelElement.getAttributeValue("file"); //$NON-NLS-1$
                if (filePath != null) {
                    loadModel(new File(filePath));
                }/*w w  w. java  2  s. c o m*/
            }
        }
    }
}

From source file:nl.b3p.imro.harvester.parser.ParserFactory.java

License:Open Source License

public static ROType getROType(URL inputXmlFullPath) throws IOException, JDOMException, URISyntaxException {
    Document inputXml = null;

    if (!inputXmlFullPath.toExternalForm().startsWith("file:")) {

        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

        HttpGet httpGet = new HttpGet(inputXmlFullPath.toURI());
        HttpResponse response = client.execute(httpGet);
        int statuscode = response.getStatusLine().getStatusCode();

        if (statuscode >= 200 && statuscode <= 299) {
            HttpEntity entity = response.getEntity();

            inputXml = new SAXBuilder().build(entity.getContent());
        } else {/*w w w.jav  a  2 s  .c o  m*/
            String statusLine = response.getStatusLine().getReasonPhrase();
            throw new IOException(statuscode + ": " + statusLine);
        }
    } else {
        inputXml = new SAXBuilder().build(inputXmlFullPath);
    }
    if (!inputXml.hasRootElement()) {
        throw new IllegalArgumentException("Document contains no root element");
    }
    Element rootElem = inputXml.getRootElement();

    if (isElementEqual(rootElem, IMRO2006_ROOTELEMENT)) {// || isElementEqual(rootElem, IMRO2008_PCPROOTELEMENT)) {
        return ROType.IMRO2006;
    } else if (isElementEqual(rootElem, IMRO2008_ROOTELEMENT)) {// || isElementEqual(rootElem, IMRO2008_PCPROOTELEMENT)) {
        return ROType.IMRO2008;
    } else if (isElementEqual(rootElem, IMRO2012V10_ROOTELEMENT)) {
        return ROType.IMRO2012V10;
    } else if (isElementEqual(rootElem, IMRO2012V11_ROOTELEMENT)) {
        return ROType.IMRO2012V11;
    } else if (isElementEqual(rootElem, STRI2012V1_ROOTELEMENT_GELEIDEFORMULIER)
            || isElementEqual(rootElem, STRI2012V1_ROOTELEMENT_MANIFEST)
            || isElementEqual(rootElem, STRI2012V2_ROOTELEMENT_GELEIDEFORMULIER)
            || isElementEqual(rootElem, STRI2012V2_ROOTELEMENT_MANIFEST)) {
        return ROType.STRI2012;
    } else if (isElementEqual(rootElem, STRI2008_ROOTELEMENT_GELEIDEFORMULIER)
            || isElementEqual(rootElem, STRI2008_ROOTELEMENT_MANIFEST)) {
        return ROType.STRI2008;
    } else if (isElementEqual(rootElem, STRI2006_ROOTELEMENT_GELEIDEFORMULIER)
            || isElementEqual(rootElem, STRI2006_ROOTELEMENT_MANIFEST)) {
        return ROType.STRI2006;
    } else {
        log.error("Unrecognized root element: " + rootElem);
        return ROType.UNKNOWN;
    }
}

From source file:org.apache.maven.io.util.AbstractJDOMWriter.java

License:Apache License

public final void write(final T source, final Document document, final Writer writer, final Format jdomFormat,
        final DocumentModifier modifier) throws java.io.IOException {
    if (modifier != null) {
        modifier.preProcess(document);/*from   w ww .  j a va 2s  .co  m*/
    }
    update(source, new IndentationCounter(0), document.getRootElement());
    if (modifier != null) {
        modifier.postProcess(document);
    }
    // Override XMLOutputter to correct initial comment trailing newlines.
    final XMLOutputter outputter = new XMLOutputter(new AbstractXMLOutputProcessor() {
        /**
         * This will handle printing of a {@link Document}.
         *
         * @param out    <code>Writer</code> to use.
         * @param fstack the FormatStack
         * @param nstack the NamespaceStack
         * @param doc    <code>Document</code> to write.
         * @throws IOException if the destination Writer fails
         */
        @Override
        protected void printDocument(Writer out, FormatStack fstack, NamespaceStack nstack, Document doc)
                throws IOException {

            // If there is no root element then we cannot use the normal ways to
            // access the ContentList because Document throws an exception.
            // so we hack it and just access it by index.
            List<Content> list = doc.hasRootElement() ? doc.getContent()
                    : new ArrayList<Content>(doc.getContentSize());
            if (list.isEmpty()) {
                final int sz = doc.getContentSize();
                for (int i = 0; i < sz; i++) {
                    list.add(doc.getContent(i));
                }
            }

            printDeclaration(out, fstack);

            Walker walker = buildWalker(fstack, list, true);
            if (walker.hasNext()) {
                while (walker.hasNext()) {

                    final Content c = walker.next();
                    // we do not ignore Text-like things in the Document.
                    // the walker creates the indenting for us.
                    if (c == null) {
                        // but, what we do is ensure it is all whitespace, and not CDATA
                        final String padding = walker.text();
                        if (padding != null && Verifier.isAllXMLWhitespace(padding) && !walker.isCDATA()) {
                            // we do not use the escaping or text* method because this
                            // content is outside of the root element, and thus is not
                            // strict text.
                            write(out, padding);
                        }
                    } else {
                        switch (c.getCType()) {
                        case Comment:
                            printComment(out, fstack, (Comment) c);
                            // This modification we have made to the overridden method in order
                            // to correct newline declarations.
                            write(out, fstack.getLineSeparator());
                            break;
                        case DocType:
                            printDocType(out, fstack, (DocType) c);
                            break;
                        case Element:
                            printElement(out, fstack, nstack, (Element) c);
                            if (walker.hasNext()) {
                                // This modification we have made to the overridden method in order
                                // to correct newline declarations.
                                write(out, fstack.getLineSeparator());
                            }
                            break;
                        case ProcessingInstruction:
                            printProcessingInstruction(out, fstack, (ProcessingInstruction) c);
                            break;
                        case Text:
                            final String padding = ((Text) c).getText();
                            if (padding != null && Verifier.isAllXMLWhitespace(padding)) {
                                // we do not use the escaping or text* method because this
                                // content is outside of the root element, and thus is not
                                // strict text.
                                write(out, padding);
                            }
                        default:
                            // do nothing.
                        }
                    }

                }

                if (fstack.getLineSeparator() != null) {
                    write(out, fstack.getLineSeparator());
                }
            }
        }
    });

    outputter.setFormat(jdomFormat);
    outputter.output(document, writer);
}

From source file:org.jumpmind.metl.core.runtime.component.AbstractXMLComponentRuntime.java

License:Open Source License

protected Map<Element, Namespace> removeNamespaces(Document document) {
    Map<Element, Namespace> namespaces = new HashMap<Element, Namespace>();
    if (ignoreNamespace && document.hasRootElement()) {
        namespaces.put(document.getRootElement(), document.getRootElement().getNamespace());
        document.getRootElement().setNamespace(null);
        for (Element el : document.getRootElement().getDescendants(new ElementFilter())) {
            Namespace nsp = el.getNamespace();
            if (nsp != null) {
                el.setNamespace(null);/* w w  w  .j a  va  2s .  c om*/
                namespaces.put(el, nsp);
            }
        }
    }
    return namespaces;
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private void fillStackWithStaticParentElements(Stack<DocElement> parentStack, DocElement firstDocElement,
        Document generatedXml) {

    Element elementToPutOnStack = null;
    Map<Element, Namespace> namespaces = null;

    // if the generatedXml doc is empty then start a new one and use it for
    // search/*from  www.  j a v a 2  s. co m*/
    if (!generatedXml.hasRootElement()) {
        Element newRootElement = templateDoc.getRootElement().clone();
        generatedXml.setRootElement(newRootElement);
        namespaces = removeNamespaces(generatedXml);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(generatedXml.getRootElement());
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement();
        } else {
            elementToPutOnStack = generatedXml.getRootElement();
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(generatedXml, namespaces);
    } else {
        // we already have a genertedXml going, but need other static
        // elements from the template
        namespaces = removeNamespaces(templateDoc);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(templateDoc.getRootElement());
        // TODO: do something here for when the attribute is more than one
        // level away from the entity
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement().clone();
        } else {
            // throw some exception here
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(templateDoc, namespaces);
    }
}

From source file:org.mycore.mir.wizard.command.MIRWizardLoadClassifications.java

License:Open Source License

@Override
public void doExecute() {
    Session currentSession = MCRHIBConnection.instance().getSession();

    try {/*from   w  ww . j  av  a2  s.c  o m*/
        String result = "";
        Element classifications = MCRURIResolver.instance().resolve(CLASSIFICATIONS_CFG);

        for (Element classification : classifications.getChildren()) {
            String classifURL = classification.getAttributeValue("url");

            MCRContent content = new MCRURLContent(new URL(classifURL));

            try {
                Document classif = content.asXML();
                if (classif.hasRootElement() && classif.getRootElement().getChildren().size() > 0) {
                    MCRCategory category = MCRXMLTransformer.getCategory(classif);

                    result += MCRTranslation.translate("component.mir.wizard.loadClassification",
                            category.getCurrentLabel().orElseThrow(() -> new MCRException(
                                    "Classification " + category.getId() + " has no label.")));

                    Transaction tx = currentSession.beginTransaction();
                    try {
                        DAO.addCategory(null, category);
                        tx.commit();

                        result += MCRTranslation.translate("component.mir.wizard.done").concat(".\n");
                    } catch (HibernateException e) {
                        tx.rollback();
                        result += MCRTranslation.translate("component.mir.wizard.error", e.toString())
                                .concat(".\n");
                        e.printStackTrace();
                    }
                }
            } catch (MCRException ex) {
                result += MCRTranslation.translate("component.mir.wizard.loadClassification.error", classifURL)
                        .concat("\n");

                this.result.setResult(result);
                this.result.setSuccess(false);
                return;
            }
        }

        this.result.setResult(result);
        this.result.setSuccess(true);
    } catch (Exception ex) {
        this.result.setResult(ex.toString());
        this.result.setSuccess(false);
    }
}