Example usage for org.dom4j DocumentFactory createDocument

List of usage examples for org.dom4j DocumentFactory createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentFactory createDocument.

Prototype

public Document createDocument() 

Source Link

Usage

From source file:VersionRelease.java

License:Open Source License

public void run() {
    processDir(jbossHome);/*from www.  j  a  v  a  2 s .  com*/
    try {
        DocumentFactory df = DocumentFactory.getInstance();
        Document doc = df.createDocument();
        Element root = doc.addElement("jar-versions");
        Iterator iter = jars.iterator();
        while (iter.hasNext()) {
            JarInfo info = (JarInfo) iter.next();
            info.writeXML(root);
        }

        File versionsXml = new File(jbossHome, "jar-versions.xml");
        FileWriter versionInfo = new FileWriter(versionsXml);
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(versionInfo, outformat);
        writer.setEscapeText(true);
        writer.write(doc);
        writer.flush();
        versionInfo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:architecture.common.license.License.java

License:Apache License

public String toXML() {
    DocumentFactory factory = DocumentFactory.getInstance();
    Document document = factory.createDocument();
    Element root = document.addElement("license");

    root.addAttribute("id", String.valueOf(getLicenseId()));
    root.addAttribute("name", getName());
    if (edition != null)
        root.addAttribute("edition", getEdition());
    root.addAttribute("creationDate", formatDate(getCreationDate()));
    root.addAttribute("version", getVersion().getVersionString());
    root.addAttribute("type", getType().name());
    if (getClient() != null) {
        Element client = root.addElement("client");
        if (getClient().getName() != null)
            client.addAttribute("name", getClient().getName());
        if (getClient().getCompany() != null)
            client.addAttribute("company", getClient().getCompany());
    }/*w  w w  . j a v  a  2 s.  co m*/

    for (Module m : getModules()) {
        Element me = root.addElement("module");
        me.addAttribute("name", m.getName());
    }

    for (java.util.Map.Entry<String, String> entry : getProperties().entrySet()) {
        Element prop = root.addElement("property");
        prop.addAttribute("name", (String) entry.getKey());
        prop.setText((String) entry.getValue());
    }
    return document.asXML();
}

From source file:at.jabberwocky.impl.core.io.PacketReader.java

private Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = docFactory;
    Document document = df.createDocument();
    Element parent = null;/*from   w ww. j  a v  a2 s . co  m*/
    XmlPullParser pp = parser;
    int count = 0;
    while (true) {
        int type = -1;
        type = pp.nextToken();
        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");
            if (loc >= 0) {
                document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1));
            } else {
                document.addProcessingInstruction(text, "");
            }
            break;
        }
        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }
            break;
        }
        case XmlPullParser.CDSECT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addCDATA(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;

        }
        case XmlPullParser.ENTITY_REF: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have an entityref outside of the root document");
                }
            }
            break;
        }
        case XmlPullParser.END_DOCUMENT: {
            return document;
        }
        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = null;
            // Do not include the namespace if this is the start tag of a new packet
            // This avoids including "jabber:client", "jabber:server" or
            // "jabber:component:accept"
            if ("jabber:client".equals(qname.getNamespaceURI())
                    || "jabber:server".equals(qname.getNamespaceURI())
                    || "jabber:component:accept".equals(qname.getNamespaceURI())
                    || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) {
                newElement = df.createElement(pp.getName());
            } else {
                newElement = df.createElement(qname);
            }
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());
            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }
            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }
            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }
            parent = newElement;
            count++;
            break;
        }
        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }
            count--;
            if (count < 1) {
                return document;
            }
            break;
        }
        case XmlPullParser.TEXT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;
        }
        default:
        }
    }
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param searchResults/*from  w  w w  .  j  a  va2  s . c o  m*/
 * 
 * @return {@link Document} containing the {@link SearchResults} in XML form.
 */
public static Document genoogleOutputToXML(List<SearchResults> searchResults) {
    assert searchResults != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Document doc = factory.createDocument();
    doc.setName("genoogle");

    Element output = doc.addElement(Genoogle.SOFTWARE_NAME);
    output.addAttribute("version", Genoogle.VERSION.toString());
    output.addAttribute("copyright", Genoogle.COPYRIGHT);

    Element iterationsElement = output.addElement("iterations");
    for (int i = 0; i < searchResults.size(); i++) {
        SearchResults searchResult = searchResults.get(i);

        Element iterationElement = iterationsElement.addElement("iteration");
        iterationElement.addAttribute("number", String.valueOf(i));

        SymbolList query = searchResult.getParams().getQuery();
        if (query instanceof RichSequence) {
            iterationElement.addAttribute("query", ((RichSequence) query).getHeader());
        }

        iterationElement.add(searchResultToXML(searchResult));
    }

    return doc;
}

From source file:bio.pih.genoogle.io.Output.java

public static Element genoogleXmlHeader() {
    DocumentFactory factory = DocumentFactory.getInstance();

    Document doc = factory.createDocument();
    doc.setName("genoogle");

    Map<String, String> xslProcessing = Maps.newHashMap();
    xslProcessing.put("type", "text/xsl");
    xslProcessing.put("href", "results.xsl");
    ProcessingInstruction xsltInstruction = DocumentHelper.createProcessingInstruction("xml-stylesheet",
            xslProcessing);//from ww  w  .j a v  a  2  s . c  o  m
    doc.add(xsltInstruction);

    Element output = doc.addElement("genoogle");
    output.addElement("references").addAttribute("program", Genoogle.SOFTWARE_NAME)
            .addAttribute("version", Double.toString(Genoogle.VERSION))
            .addAttribute("copyright", Genoogle.COPYRIGHT);
    return output;
}

From source file:com.arc.mw.util.StateSaver.java

License:Open Source License

/**
 * Save the state of the root object into the given file.
 * @param out ascii stream to write to./* ww  w. j av  a2s  .  c  om*/
 * @param object object whose state is to be saved.
 * @exception IOException error occurred in writing file.
 */
public static void saveState(Writer out, IXMLSavable object) throws IOException {
    DocumentFactory factory = DocumentFactory.getInstance();
    Document document = factory.createDocument();
    Element e = factory.createElement("root");
    object.saveState(e);
    document.setRootElement(e);
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    writer.write(document);
}

From source file:com.blocks.framework.utils.date.XMLDom4jUtils.java

License:Open Source License

/**
 * /*from w w  w .j  a v a2 s .  com*/
 *
 * @return Document 
 * @throws XMLDocException
 */
public static Document createDocument() {
    DocumentFactory factory = new DocumentFactory();
    Document document = factory.createDocument();
    return document;
}

From source file:com.liferay.alloy.tools.builder.base.BaseBuilder.java

License:Open Source License

protected List<Component> getAllComponents() throws Exception {
    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    Document doc = factory.createDocument();

    String taglibsXML = "<components></components>";

    Document taglibsDoc = SAXReaderUtil
            .read(new InputSource(new ByteArrayInputStream(taglibsXML.getBytes("utf-8"))));

    Element root = taglibsDoc.getRootElement();

    for (Document currentDoc : getComponentDefinitionDocs()) {
        currentDoc = _getExtendedDocument(currentDoc);

        Element currentRoot = currentDoc.getRootElement();

        String defaultPackage = currentRoot.attributeValue("short-name");
        List<Element> extComponentNodes = currentRoot.elements("component");

        for (Element extComponent : extComponentNodes) {
            String extComponentPackage = Convert.toString(extComponent.attributeValue("package"),
                    defaultPackage);//from w ww. ja  v a2s . c  o m

            extComponent.addAttribute("package", extComponentPackage);
        }

        Element authors = currentRoot.element("author");

        List<Element> components = currentRoot.elements("component");

        for (Element component : components) {
            Element copy = component.createCopy();
            Element componentAuthors = copy.element("authors");

            if ((authors != null) && (componentAuthors == null)) {
                copy.add(authors.createCopy());
            }

            root.add(copy);
        }

        List<org.dom4j.Attribute> attributes = currentRoot.attributes();

        for (org.dom4j.Attribute attribute : attributes) {
            root.addAttribute(attribute.getName(), attribute.getValue());
        }
    }

    doc.add(root.createCopy());

    return getComponents(doc);
}

From source file:com.liferay.alloy.tools.builder.base.BaseBuilder.java

License:Open Source License

protected Document mergeXMLAttributes(Document doc1, Document doc2) {
    Element doc2Root = doc2.getRootElement();
    Element doc1Root = doc1.getRootElement();
    Element docRoot = doc2Root.createCopy();

    docRoot.clearContent();/*from  w ww.  j a va  2 s .  c o m*/

    if (doc1Root != null) {
        Iterator<Object> attributesIterator = doc1Root.attributeIterator();

        while (attributesIterator.hasNext()) {
            org.dom4j.Attribute attribute = (org.dom4j.Attribute) attributesIterator.next();

            if (attribute.getName().equals("extends")) {
                continue;
            }

            docRoot.addAttribute(attribute.getName(), attribute.getValue());
        }

        Element descriptionElement = doc1Root.element("description");

        if (descriptionElement != null) {
            docRoot.add(descriptionElement.createCopy());
        }
    }

    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    Document doc = factory.createDocument();
    doc.setRootElement(docRoot);

    List<Element> doc2Components = doc2Root.elements(_COMPONENT);

    for (Element doc2Component : doc2Components) {
        Element component = doc2Component.createCopy();

        String name = doc2Component.attributeValue("name");

        Element doc1Component = getComponentNode(doc1, name);

        if (doc1Component != null) {
            Element doc1ComponentDescriptionElement = doc1Component.element("description");

            if (doc1ComponentDescriptionElement != null) {
                Element descriptionElement = component.element("description");

                if (descriptionElement != null) {
                    component.remove(descriptionElement);
                }

                component.add(doc1ComponentDescriptionElement.createCopy());
            }

            Iterator<Object> attributesIterator = doc1Component.attributeIterator();

            while (attributesIterator.hasNext()) {
                org.dom4j.Attribute attribute = (org.dom4j.Attribute) attributesIterator.next();

                component.addAttribute(attribute.getName(), attribute.getValue());
            }

            Element doc1AttributesNode = doc1Component.element(_ATTRIBUTES);

            Element attributesNode = component.element(_ATTRIBUTES);

            if ((doc1AttributesNode != null) && (attributesNode != null)) {
                List<Element> doc1Attributes = doc1AttributesNode.elements(_ATTRIBUTE);

                List<Element> attributes = attributesNode.elements(_ATTRIBUTE);

                for (Element doc1Attribute : doc1Attributes) {
                    Element attribute = getElementByName(attributes, doc1Attribute.elementText("name"));

                    if (attribute != null) {
                        attributesNode.remove(attribute);
                    }

                    attributesNode.add(doc1Attribute.createCopy());
                }
            }

            Element doc1EventsNode = doc1Component.element(_EVENTS);

            Element eventsNode = component.element(_EVENTS);

            if ((doc1EventsNode != null) && (eventsNode != null)) {
                List<Element> doc1Events = doc1EventsNode.elements(_EVENT);

                List<Element> events = eventsNode.elements(_EVENT);

                for (Element doc1Event : doc1Events) {
                    Element event = getElementByName(events, doc1Event.elementText("name"));

                    if (event != null) {
                        eventsNode.add(event);
                    }

                    eventsNode.add(doc1Event.createCopy());
                }
            }
        }

        doc.getRootElement().add(component);
    }

    if (doc1Root != null) {
        List<Element> doc1Components = doc1Root.elements(_COMPONENT);

        for (Element doc1Component : doc1Components) {
            Element component = doc1Component.createCopy();

            String name = doc1Component.attributeValue("name");

            Element doc2Component = getComponentNode(doc2, name);

            if (doc2Component == null) {
                doc.getRootElement().add(component);
            }
        }
    }

    return doc;
}

From source file:com.openedit.users.filesystem.FileSystemUserManager.java

License:Open Source License

public void saveUser(User user) throws UserManagerException {
    if (user.isVirtual()) {
        log.error("Cannot save virtual users: " + user.getUserName());
        return;/*ww w  .  j  a v a 2  s.  c  om*/
    }
    DocumentFactory factory = DocumentFactory.getInstance();
    Document doc = factory.createDocument();
    Element userElem = doc.addElement("user");
    userElem.addAttribute("enabled", Boolean.toString(user.isEnabled()));
    if (user.getUserName() == null) {
        int id = getUserIdCounter().incrementCount();
        String newid = String.valueOf(id);
        user.setId(newid);
    }
    Element userNameElem = userElem.addElement("user-name");
    userNameElem.setText(user.getUserName());

    Element passwordElem = userElem.addElement("password");
    //
    if (user.getPassword() != null && !user.getPassword().equals("")) {
        String ps = user.getPassword();
        ps = encrypt(ps);
        //password may have changed we should set it so it's not in plain text anymore.
        user.setPassword(ps);
        passwordElem.setText(ps);
    }
    Element creationDateElem = userElem.addElement("creation-date");
    if (user.getCreationDate() != null) {
        creationDateElem.setText(String.valueOf(user.getCreationDate().getTime()));
    } else {
        creationDateElem.setText(String.valueOf(System.currentTimeMillis()));
    }

    //Tuan add property lastLogined-Time
    Element lastLoginTime = userElem.addElement("lastLogined-Time");
    lastLoginTime.setText(DateStorageUtil.getStorageUtil().formatForStorage(new Date()));

    MapPropertyContainer map = (MapPropertyContainer) user.getPropertyContainer();
    if (map != null) {
        Element propertiesElem = map.createPropertiesElement("properties");
        userElem.add(propertiesElem);
    }
    if (user.getGroups() != null) {
        for (Iterator iter = user.getGroups().iterator(); iter.hasNext();) {
            Group group = (Group) iter.next();
            Element child = userElem.addElement("group");
            child.addAttribute("id", group.getId());
        }
    }
    File file = loadUserFile(user.getUserName());
    getXmlUtil().saveXml(doc, file);
    getUserNameToUserMap().put(user.getUserName(), user);
}