Example usage for org.dom4j Element addAttribute

List of usage examples for org.dom4j Element addAttribute

Introduction

In this page you can find the example usage for org.dom4j Element addAttribute.

Prototype

Element addAttribute(QName qName, String value);

Source Link

Document

Adds the attribute value of the given fully qualified name.

Usage

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** contributionsschema?schema */
public static Document createConfigurationPointSchema(ConfigurationPoint configurationPoint, String version) {
    Document doc = createDocument();

    // <xsd:schema>
    Element schemaRoot = doc.addElement("xsd:schema", W3C_XML_SCHEMA_NS_URI);

    schemaRoot.addNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
    schemaRoot.addNamespace("beans", BEANS_NAMESPACE_URI);
    schemaRoot.addNamespace("springext", SPRINGEXT_BASE_URI);
    schemaRoot.addNamespace("", configurationPoint.getNamespaceUri());

    schemaRoot.addAttribute("targetNamespace", configurationPoint.getNamespaceUri());

    // <xsd:include schemaLocation="contribution schema" />
    Set<String> includings = createTreeSet();

    for (Contribution contrib : configurationPoint.getContributions()) {
        Schema contribSchema = contrib.getSchemas().getVersionedSchema(version);

        if (contribSchema == null) {
            contribSchema = contrib.getSchemas().getMainSchema();
        }// ww w  . j  a  v a2  s  .  co m

        if (contribSchema != null) {
            includings.add(contribSchema.getName());
        }
    }

    for (String including : includings) {
        Element includeElement = schemaRoot.addElement("xsd:include");

        includeElement.addAttribute("schemaLocation", including);
    }

    if (configurationPoint.getDefaultElementName() != null) {
        //  <xsd:import namespace="http://www.springframework.org/schema/beans"
        //              schemaLocation="http://www.springframework.org/schema/beans/spring-beans.xsd" />
        Element importBeans = schemaRoot.addElement("xsd:import");
        importBeans.addAttribute("namespace", BEANS_NAMESPACE_URI);
        importBeans.addAttribute("schemaLocation", BEANS_NAMESPACE_URI + "/spring-beans.xsd");

        //  <xsd:import namespace="http://www.alibaba.com/schema/springext/base"
        //              schemaLocation="http://www.alibaba.com/schema/springext/springext-base.xsd" />
        Element importSpringextBase = schemaRoot.addElement("xsd:import");
        importSpringextBase.addAttribute("namespace", SPRINGEXT_BASE_URI);
        importSpringextBase.addAttribute("schemaLocation", SPRINGEXT_BASE_XSD);

        // <xsd:element name="defaultElementName" type="springext:referenceableBeanType" />
        Element element = schemaRoot.addElement("xsd:element");
        element.addAttribute("name", configurationPoint.getDefaultElementName());
        element.addAttribute("type", "springext:referenceableBeanType");
    }

    return doc;
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** schema?includes */
public static Transformer getTransformerWhoAddsIndirectIncludes(final Map<String, Schema> includes) {
    return new Transformer() {
        public void transform(Document document, String systemId) {
            Element root = document.getRootElement();

            root.addNamespace("xsd", W3C_XML_SCHEMA_NS_URI);

            // <xsd:schema>
            if (W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) && "schema".equals(root.getName())) {
                Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
                QName includeName = DocumentHelper.createQName("include", xsd);

                // for each <xsd:include>
                for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
                    i.next();/* w ww .j av  a 2 s.co m*/
                    i.remove();
                }

                // includes
                @SuppressWarnings("unchecked")
                List<Node> nodes = root.elements();
                int i = 0;

                for (Schema includedSchema : includes.values()) {
                    Element includeElement = DocumentHelper.createElement(includeName);
                    nodes.add(i++, includeElement);

                    includeElement.addAttribute("schemaLocation", includedSchema.getName());
                }
            }
        }
    };
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** ?URI? */
public static Transformer getAddPrefixTransformer(final SchemaSet schemas, String prefix) {
    if (prefix != null) {
        if (!prefix.endsWith("/")) {
            prefix += "/";
        }/*from   www . j a  v  a 2  s . c o  m*/
    }

    final String normalizedPrefix = prefix;

    return new Transformer() {
        public void transform(Document document, String systemId) {
            if (normalizedPrefix != null) {
                Element root = document.getRootElement();

                // <xsd:schema>
                if (W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) && "schema".equals(root.getName())) {
                    Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
                    QName includeName = DocumentHelper.createQName("include", xsd);
                    QName importName = DocumentHelper.createQName("import", xsd);

                    // for each <xsd:include>
                    for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
                        Element includeElement = (Element) i.next();
                        String schemaLocation = trimToNull(includeElement.attributeValue("schemaLocation"));

                        if (schemaLocation != null) {
                            schemaLocation = getNewSchemaLocation(schemaLocation, null, systemId);

                            if (schemaLocation != null) {
                                includeElement.addAttribute("schemaLocation", schemaLocation);
                            }
                        }
                    }

                    // for each <xsd:import>
                    for (Iterator<?> i = root.elementIterator(importName); i.hasNext();) {
                        Element importElement = (Element) i.next();
                        String schemaLocation = importElement.attributeValue("schemaLocation");
                        String namespace = trimToNull(importElement.attributeValue("namespace"));

                        if (schemaLocation != null || namespace != null) {
                            schemaLocation = getNewSchemaLocation(schemaLocation, namespace, systemId);

                            if (schemaLocation != null) {
                                importElement.addAttribute("schemaLocation", schemaLocation);
                            }
                        }
                    }
                }
            }
        }

        private String getNewSchemaLocation(String schemaLocation, String namespace, String systemId) {
            // ?schemaLocation
            if (schemaLocation != null) {
                Schema schema = schemas.findSchema(schemaLocation);

                if (schema != null) {
                    return normalizedPrefix + schema.getName();
                } else {
                    return schemaLocation; // location??
                }
            }

            // ??namespace
            if (namespace != null) {
                Set<Schema> nsSchemas = schemas.getNamespaceMappings().get(namespace);

                if (nsSchemas != null && !nsSchemas.isEmpty()) {
                    // ?nsschema?schema
                    String versionedExtension = getVersionedExtension(systemId);

                    if (versionedExtension != null) {
                        for (Schema schema : nsSchemas) {
                            if (schema.getName().endsWith(versionedExtension)) {
                                return normalizedPrefix + schema.getName();
                            }
                        }
                    }

                    // schema?beans.xsd?beans-2.5.xsd?beans-2.0.xsd
                    return normalizedPrefix + nsSchemas.iterator().next().getName();
                }
            }

            return null;
        }

        /** spring-aop-2.5.xsd?-2.5.xsd */
        private String getVersionedExtension(String systemId) {
            if (systemId != null) {
                int dashIndex = systemId.lastIndexOf("-");
                int slashIndex = systemId.lastIndexOf("/");

                if (dashIndex > slashIndex) {
                    return systemId.substring(dashIndex);
                }
            }

            return null;
        }
    };
}

From source file:com.alkacon.opencms.feeder.CmsFeedXmlContentHandler.java

License:Open Source License

/**
 * @see org.opencms.xml.content.CmsDefaultXmlContentHandler#validateAppinfoElement(org.dom4j.Element)
 *///from  w  w w .  j av  a2s. c  om
protected void validateAppinfoElement(Element appinfoElement) throws CmsXmlException {

    // create a document to validate
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement(APPINFO_APPINFO);
    // attach the default appinfo schema
    root.add(I_CmsXmlSchemaType.XSI_NAMESPACE);
    root.addAttribute(I_CmsXmlSchemaType.XSI_NAMESPACE_ATTRIBUTE_NO_SCHEMA_LOCATION,
            FEED_APPINFO_SCHEMA_SYSTEM_ID);
    // append the content from the appinfo node in the content definition 
    root.appendContent(appinfoElement);
    // now validate the document with the default appinfo schema
    CmsXmlUtils.validateXmlStructure(doc, CmsEncoder.ENCODING_UTF_8, new CmsXmlEntityResolver(null));
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

private void doUpgrade(String url) {
    Document doc = credentials.get(url).doc;
    String path = "//child::*[text() = '" + TreeObject.CATEGORY_FOLDER //$NON-NLS-1$
            + "' and count(@Universe) = 0 and count(@Url) = 0"//$NON-NLS-1$
            + "]";//$NON-NLS-1$
    List<Element> categorys = doc.selectNodes(path);

    for (Element elem : categorys) {
        Attribute attr = elem.attribute(URL);
        if (attr == null) {
            elem.addAttribute(URL, UnifyUrl(url));
        }// w  w  w.j a v  a2 s . c om
    }
    saveDocument(url);
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

private void addChild(TreeObject parent, TreeObject child) {
    if (parent.getParent() == null && parent.getDisplayName().equals("INVISIBLE ROOT")) {
        return;/*from  w ww.j av a 2s . c o m*/
    }
    if (parent.getServerRoot() == null) {
        return;
    }
    String xpath = getXPathForTreeObject(child);
    Document doc = credentials.get(UnifyUrl(parent.getServerRoot().getWsKey().toString())).doc;
    List<Element> models = doc.selectNodes(xpath);
    if (!models.isEmpty() && child instanceof TreeParent) {
        Element model = models.get(0);
        if (isAEXtentisObjects(model, child) == MODEL_LEVEL) {
            checkUpAllCategoryForModel((TreeParent) child);
        }
    }

    String catalog = synchronizeWithElem(child, (TreeParent) parent, true);
    Element elemFolder = getParentElement(parent);
    if (elemFolder != null) {
        String xpathTail = "";//$NON-NLS-1$
        String xpathTailOther = "']";//$NON-NLS-1$
        xpath = "child::*[name()='" + filterOutBlank(child.getDisplayName()) + "' and text()='" //$NON-NLS-1$//$NON-NLS-2$
                + child.getType();
        if (child.getType() == TreeObject.CATEGORY_FOLDER) {
            xpathTail = "' and @Url='" + getURLFromTreeObject(child);//$NON-NLS-1$
        }
        List<Element> list = elemFolder.selectNodes(xpath + xpathTail + xpathTailOther);
        if (list.isEmpty() && (catalog.equals("") || catalog == null)) {//$NON-NLS-1$
            Element childElem = elemFolder.addElement(filterOutBlank(child.getDisplayName()));
            childElem.setText(child.getType() + "");//$NON-NLS-1$
            if (child.getType() == TreeObject.CATEGORY_FOLDER) {
                childElem.addAttribute(URL, getURLFromTreeObject(child));
                childElem.addAttribute(REALNAME, child.getDisplayName());
            }
        }
    }
    saveDocument(parent);
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

private String synchronizeWithElem(TreeObject theObj, TreeParent folder, boolean fireEvent) {
    internalCheck = fireEvent;/*from   ww w  .j  av  a2 s . c om*/
    String catalogPath = "";//$NON-NLS-1$
    ArrayList<String> catalogs = checkUpCatalogRepositoryForTreeObject(theObj, folder);
    if (catalogs != null && folder.getType() != TreeObject.CATEGORY_FOLDER) {
        // create a catalog folder and insert the theObj into it
        TreeParent subFolder = folder;
        TreeParent category = null;
        for (String catalogName : catalogs) {
            // if (catalogName.equals(filterOutBlank(folder.getDisplayName())))
            // continue;
            category = null;
            for (TreeObject child : subFolder.getChildren()) {
                if (child.getDisplayName().equals(catalogName) && child.getType() == TreeObject.CATEGORY_FOLDER
                        && child instanceof TreeParent) {
                    category = (TreeParent) child;
                    subFolder = category;
                    break;
                }
            }

            if (category == null) {
                category = new TreeParent(catalogName, folder.getServerRoot(), TreeObject.CATEGORY_FOLDER, null,
                        null);
                subFolder.addChild(category);
                category.setServerRoot(folder.getServerRoot());
                addAttributeToCategoryElem(category, URL, getURLFromTreeObject(folder));
                saveDocument(folder);
                subFolder = category;
            }
        }

        boolean exist = false;
        for (TreeObject obj : category.getChildren()) {
            if (obj.getDisplayName().equals(theObj.getDisplayName()) && obj.getType() == theObj.getType()) {
                exist = true;
                break;
            }
        }

        if (!exist) {
            folder.removeChild(theObj);
            category.addChild(theObj);
        }

        catalogPath = catalogs.isEmpty() ? "" : catalogs.get(0);//$NON-NLS-1$
    } else {
        // check up the system catalog, create it and all system tree objects
        // into it if these objects are not categorized
        if (XSystemObjects.isExist(theObj.getType(), theObj.getDisplayName())) {
            TreeParent systemCatalog = null;
            for (TreeObject xobj : folder.getChildren()) {
                if (DEFAULT_CATALOG.equals(filterOutBlank(xobj.getDisplayName()))
                        && xobj.getType() == TreeObject.CATEGORY_FOLDER) {
                    systemCatalog = (TreeParent) xobj;
                    break;
                }
            }

            if (folder.getDisplayName().equals("System") && folder.getType() == TreeObject.CATEGORY_FOLDER) {
                return DEFAULT_CATALOG;
            }

            if (theObj.getParent() == null) {
                internalCheck = !fireEvent;
                return DEFAULT_CATALOG;
            }
            if (theObj.getServerRoot() != null) {
                String xpath = "//" + theObj.getServerRoot().getUser().getUsername() + "/"//$NON-NLS-1$//$NON-NLS-2$
                        + filterOutBlank(folder.getDisplayName()) + "//child::*[name() = 'System'"//$NON-NLS-1$
                        + " and @Url='" + getURLFromTreeObject(theObj) + "']";//$NON-NLS-1$//$NON-NLS-2$

                Document doc = credentials.get(UnifyUrl(folder.getServerRoot().getWsKey().toString())).doc;
                if (systemCatalog == null) {
                    List<Element> elems = doc.selectNodes(xpath);
                    if (elems.isEmpty()) {
                        systemCatalog = new TreeParent(DEFAULT_CATALOG, folder.getServerRoot(),
                                TreeObject.CATEGORY_FOLDER, null, null);
                        folder.addChild(systemCatalog);
                        folder.removeChild(theObj);
                        systemCatalog.addChild(theObj);
                        systemCatalog.setServerRoot(folder.getServerRoot());

                        Element elemFolder = getParentElement(folder);
                        Element elemSystem = elemFolder.addElement(systemCatalog.getDisplayName());
                        elemSystem.setText(TreeObject.CATEGORY_FOLDER + "");//$NON-NLS-1$
                        elemSystem.addAttribute(URL, getURLFromTreeObject(folder));
                        Element childElem = elemSystem.addElement(filterOutBlank(theObj.getDisplayName()));
                        childElem.setText(theObj.getType() + "");//$NON-NLS-1$

                        saveDocument(folder);
                    }
                } else {
                    boolean exist = false;

                    for (TreeObject xbj : systemCatalog.getChildren()) {
                        if (xbj.getDisplayName().equals(theObj.getDisplayName())
                                && xbj.getType() == theObj.getType()) {
                            exist = true;
                            break;
                        }

                    }
                    if (!exist) {
                        folder.removeChild(theObj);
                        systemCatalog.addChild(theObj);
                        List<Element> elems = doc.selectNodes(xpath);
                        if (!elems.isEmpty()) {
                            elems.get(0).addElement(filterOutBlank(theObj.getDisplayName()))
                                    .setText(theObj.getType() + "");//$NON-NLS-1$
                            saveDocument(folder);
                        }

                    }
                }
            }
            catalogPath = DEFAULT_CATALOG;
        }
    }

    // check up the catalog with none children
    checkUpCatalogHavingNoChildren(theObj, folder);

    if (theObj instanceof TreeParent) {
        TreeParent subParent = (TreeParent) theObj;
        for (TreeObject obj : subParent.getChildren()) {
            synchronizeWithElem(obj, subParent, fireEvent);
        }
    }

    internalCheck = !fireEvent;

    return catalogPath;
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

private void addAttributeToCategoryElem(TreeParent category, String attrName, String defaultAttrValue) {
    Element elem = locateCategoryElement(category);
    Attribute attr = elem.attribute(attrName);
    if (attr != null) {
        elem.remove(attr);/*w w  w. j  a  va 2  s. c  om*/
    }
    elem.addAttribute(attrName, defaultAttrValue);
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

public void makeUpDocWithImportCategory(String[] schemas, TreeParent serverRoot) {
    if (serverRoot.getServerRoot() == null) {
        return;/*from  w  w w  . j av a  2  s.c  o m*/
    }
    Document orgDoc = credentials.get(UnifyUrl(serverRoot.getServerRoot().getWsKey().toString())).doc;
    // spareDoc is meant to show the category when import digloag is launched
    spareDoc = (Document) orgDoc.clone();
    if (schemas != null) {
        for (String schema : schemas) {
            Element subRoot = parseElements(schema);
            String subRootXquery = "descendant::" + subRoot.getName() + "[text()='" + subRoot.getTextTrim() //$NON-NLS-1$//$NON-NLS-2$
                    + "']";//$NON-NLS-1$
            Element division = pingElement(subRootXquery, spareDoc.getRootElement());
            if (division == null || division.getParent() == null) {
                return;
            }
            Element divisionParent = division.getParent();
            divisionParent.remove(division);
            divisionParent.add((Element) subRoot.clone());
        }

        String url = getURLFromTreeObject(serverRoot);
        String urlXquery = "descendant::*[@Url != '" + url + "']";//$NON-NLS-1$//$NON-NLS-2$
        List<Element> elems = spareDoc.selectNodes(urlXquery);
        for (Element elem : elems) {
            elem.addAttribute("Url", url);//$NON-NLS-1$
        }
    }

    credentials.get(UnifyUrl(serverRoot.getServerRoot().getWsKey().toString())).doc = spareDoc;
    spareDoc = orgDoc;
    importCategories = schemas;
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

License:Open Source License

private void createCategoryForOrgDoc(String categoryToCreate, Element srcElem, Element tgtElem,
        TreeParent serverRoot) {//from w  w w.j  a v a  2 s. c  o m
    String[] xpathSnippetsToCreate = categoryToCreate.split("/");//$NON-NLS-1$
    int categoryBeginPos = 3;
    if (xpathSnippetsToCreate[3].equals("EventManagement")) {//$NON-NLS-1$
        categoryBeginPos = 4;
    }

    int pos = categoryToCreate.indexOf("/" + xpathSnippetsToCreate[categoryBeginPos]);//$NON-NLS-1$
    String categoryXpath = categoryToCreate.substring(0,
            pos + xpathSnippetsToCreate[categoryBeginPos].length() + 1);
    Element subParentElem = pingElement(categoryXpath, tgtElem);
    for (int i = categoryBeginPos + 1; i < xpathSnippetsToCreate.length; i++) {
        String categoryXpathSnippet = "child::" + xpathSnippetsToCreate[i] + "[text()='" //$NON-NLS-1$//$NON-NLS-2$
                + TreeObject.CATEGORY_FOLDER + "']";//$NON-NLS-1$
        Element newCategory = pingElement(categoryXpathSnippet, subParentElem);
        if (newCategory == null) {
            Element existedCategory = pingElement(categoryXpath + "/" + categoryXpathSnippet, srcElem);//$NON-NLS-1$
            newCategory = subParentElem.addElement(xpathSnippetsToCreate[i]);
            newCategory.setText(TreeObject.CATEGORY_FOLDER + "");//$NON-NLS-1$
            newCategory.addAttribute(URL, getURLFromTreeObject(serverRoot));
            newCategory.addAttribute(REALNAME, existedCategory.attributeValue(REALNAME));
        }
        categoryXpath += "/" + xpathSnippetsToCreate[i];//$NON-NLS-1$
        subParentElem = newCategory;
    }

    transferElementsWithCategoryPath(categoryToCreate, srcElem, tgtElem);
}