Example usage for org.jdom2 Element setAttribute

List of usage examples for org.jdom2 Element setAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element setAttribute.

Prototype

public Element setAttribute(final String name, final String value) 

Source Link

Document

This sets an attribute value for this element.

Usage

From source file:com.collir24.policyextractor.Extract.java

License:Apache License

private static Document buildDocument(List<ModulePermissions> modulePermissions) {
    Element modulePolicy = new Element("modulePolicy");
    for (ModulePermissions mps : modulePermissions) {
        Element module = new Element("module");
        module.setAttribute("name", mps.getModuleName());
        Set<String> policySet = new HashSet<String>();
        for (ModulePermission mp : mps.getPermissions()) {
            Element permRequired = new Element("permRequired");
            permRequired.setAttribute("line", Integer.toString(mp.getLine()));
            permRequired.setAttribute("className", mp.getClassName());
            for (String s : mp.getPolicy()) {
                Element perm = new Element("perm");
                perm.setText(s);//from  w w  w  . j  ava2  s.  c  o m
                permRequired.addContent(perm);
            }
            module.addContent(permRequired);
            // TODO: say what caused the permission to be required - see key
            policySet.addAll(mp.getPolicy());
        }
        CDATA policyData = new CDATA(generatePolicy(policySet));
        module.addContent(policyData);
        modulePolicy.addContent(module);
    }
    return new Document(modulePolicy);
}

From source file:com.cybernostics.jsp2thymeleaf.api.elements.JspTagElementConverter.java

@Override
protected Optional<Element> createElement(JspElementContext node, JSPElementNodeConverter context) {
    Optional<Element> element = super.createElement(node, context);
    if (element.isPresent()) {
        if (isElementEmbeddedInAttribute(node)) {

            HtmlAttributeValueContext parent = (HtmlAttributeValueContext) node.parent;
            String parentAttributeToReplace = getAttributeNamefor(parent);
            Element el = element.get();
            el.setAttribute("data-replace-parent-attribute-name", parentAttributeToReplace);
            el.setName("deleteme");

        }/*from  w  w  w.  j a v  a  2s.co m*/
    }
    return element;
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static void createRepoMd(String rootPath, RepoModule... repos) throws IOException {
    Document doc = new Document();
    Element root = new Element("repomd", REPONAMESPACE);
    doc.addContent(root);/*from  ww w  . j av a2s .  co  m*/
    root.addNamespaceDeclaration(RPMNAMESPACE);
    long now = System.currentTimeMillis();

    for (RepoModule repo : repos) {
        Element data = new Element("data", REPONAMESPACE);
        data.setAttribute("type", repo.getModule());
        Element location = new Element("location", REPONAMESPACE);
        File xmlGzFie = getXmlGzFile(repo, repo.getXmlGzCode());
        location.setAttribute("href", replacePath(FileUtils.getFileRelativePath(repo.getRootPath(), xmlGzFie)));
        data.addContent(location);
        Element checksum = new Element("checksum", REPONAMESPACE);
        checksum.setAttribute("type", ALGORITHM);
        checksum.setAttribute("pkgid", "YES");
        checksum.setText(repo.getXmlGzCode());
        data.addContent(checksum);
        Element size = new Element("size", REPONAMESPACE);
        size.setText(repo.getXmlGzSize() + "");
        data.addContent(size);
        Element timestamp = new Element("timestamp", REPONAMESPACE);
        timestamp.setText(now + "");
        data.addContent(timestamp);
        Element openCheckSum = new Element("open-checksum", REPONAMESPACE);
        openCheckSum.setAttribute("type", ALGORITHM);
        openCheckSum.setAttribute("pkgid", "YES");
        openCheckSum.setText(repo.getXmlCode());
        data.addContent(openCheckSum);
        Element openSize = new Element("open-size", REPONAMESPACE);
        openSize.setText(repo.getXmlSize() + "");
        data.addContent(openSize);
        Element revision = new Element("revision", REPONAMESPACE);
        data.addContent(revision);
        root.addContent(data);
    }
    File repoMd = new File(rootPath + File.separator + REPOPATH + File.separator + "repomd" + ".xml");
    xmlToFile(doc, repoMd);
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static RepoModule createOther(RpmData[] rpmdatas, String rootPath)
        throws IOException, NoSuchAlgorithmException {
    RepoModule repo = new RepoModule(rootPath, "other");
    Document doc = new Document();
    Element root = new Element("otherdata", OTHERNAMESPACE);
    doc.addContent(root);//from w  w  w  .  j  av  a2  s  . com
    root.setAttribute("packages", rpmdatas.length + "");

    for (RpmData rpmdata : rpmdatas) {
        RpmMetadata rpmMetadata = rpmdata.rpmMetadata;

        Element packAge = new Element("package", OTHERNAMESPACE);
        packAge.setAttribute("pkgid", HashFile.getsum(rpmdata.rpm, ALGORITHM));
        packAge.setAttribute("name", rpmMetadata.name);
        packAge.setAttribute("arch", rpmMetadata.architecture);

        root.addContent(packAge);

        Element version = new Element("version", OTHERNAMESPACE);
        version.setAttribute("epoch", rpmMetadata.epoch + "");
        version.setAttribute("ver", rpmMetadata.version);
        version.setAttribute("rel", rpmMetadata.release);
        packAge.setContent(version);

        for (ChangeLog log : rpmMetadata.changeLogs) {
            Element fileElement = new Element("changelog", OTHERNAMESPACE);
            fileElement.setAttribute("author", log.author);
            fileElement.setAttribute("date", log.date + "");
            fileElement.setText(log.text);
            packAge.addContent(fileElement);
        }
    }
    yumXmlSave(doc, repo);
    return repo;
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static RepoModule createPrimary(RpmData[] rpmdatas, String rootPath)
        throws IOException, NoSuchAlgorithmException {
    RepoModule repo = new RepoModule(rootPath, "primary");
    Document doc = new Document();
    Element root = new Element("metadata", COMMONNAMESPACE);
    doc.addContent(root);/* w w w. ja va  2s  . co  m*/
    root.addNamespaceDeclaration(RPMNAMESPACE);
    root.setAttribute("packages", rpmdatas.length + "");

    for (RpmData rpmdata : rpmdatas) {
        RpmMetadata rpmMetadata = rpmdata.rpmMetadata;

        Element packAge = new Element("package", COMMONNAMESPACE);
        packAge.setAttribute("type", "rpm");
        root.addContent(packAge);

        Element name = new Element("name", COMMONNAMESPACE);
        name.setText(rpmMetadata.name);
        packAge.addContent(name);

        Element arch = new Element("arch", COMMONNAMESPACE);
        arch.setText(rpmMetadata.architecture);
        packAge.addContent(arch);

        Element version = new Element("version", COMMONNAMESPACE);
        version.setAttribute("epoch", rpmMetadata.epoch + "");
        version.setAttribute("ver", rpmMetadata.version);
        version.setAttribute("rel", rpmMetadata.release);
        packAge.addContent(version);

        Element checksum = new Element("checksum", COMMONNAMESPACE);
        checksum.setAttribute("type", ALGORITHM);
        checksum.setAttribute("pkgid", "YES");
        checksum.setText(HashFile.getsum(rpmdata.rpm, ALGORITHM));
        packAge.addContent(checksum);

        Element summary = new Element("summary", COMMONNAMESPACE);
        summary.setText(rpmMetadata.summary);
        packAge.addContent(summary);

        Element description = new Element("description", COMMONNAMESPACE);
        description.setText(rpmMetadata.description);
        packAge.addContent(description);

        Element packager = new Element("packager", COMMONNAMESPACE);
        packager.setText(rpmMetadata.packager);
        packAge.addContent(packager);

        Element url = new Element("url", COMMONNAMESPACE);
        url.setText(rpmMetadata.url);
        packAge.addContent(url);

        Element time = new Element("time", COMMONNAMESPACE);
        time.setAttribute("file", rpmdata.rpm.lastModified() / 1000 + "");
        time.setAttribute("build", rpmMetadata.buildTime + "");
        packAge.addContent(time);

        Element size = new Element("size", COMMONNAMESPACE);
        size.setAttribute("package", rpmdata.rpm.length() + "");
        size.setAttribute("installed", rpmMetadata.installedSize + "");
        size.setAttribute("archive", rpmMetadata.archiveSize + "");
        packAge.addContent(size);

        Element location = new Element("location", COMMONNAMESPACE);
        location.setAttribute("href", replacePath(FileUtils.getFileRelativePath(rootPath, rpmdata.rpm)));
        packAge.addContent(location);

        Element format = new Element("format", COMMONNAMESPACE);
        packAge.addContent(format);

        Element license = new Element("license", RPMNAMESPACE);
        license.setText(rpmMetadata.license);
        format.addContent(license);

        Element vendor = new Element("vendor", RPMNAMESPACE);
        vendor.setText(rpmMetadata.vendor);
        format.addContent(vendor);

        Element group = new Element("group", RPMNAMESPACE);
        group.setText(rpmMetadata.group);
        format.addContent(group);

        Element buildhost = new Element("buildhost", RPMNAMESPACE);
        buildhost.setText(rpmMetadata.buildHost);
        format.addContent(buildhost);

        Element sourcerpm = new Element("sourcerpm", RPMNAMESPACE);
        sourcerpm.setText(rpmMetadata.sourceRpm);
        format.addContent(sourcerpm);

        Element headerRange = new Element("header-range", RPMNAMESPACE);
        headerRange.setAttribute("start", rpmMetadata.headerStart + "");
        headerRange.setAttribute("end", rpmMetadata.headerEnd + "");
        format.addContent(headerRange);

        Element provides = new Element("provides", RPMNAMESPACE);
        format.addContent(provides);
        addEntry(provides, rpmMetadata.provide, null);

        Element requires = new Element("requires", RPMNAMESPACE);
        format.addContent(requires);
        addEntry(requires, rpmMetadata.require, new PrivateRequireFilter());

        Element conflicts = new Element("conflicts", RPMNAMESPACE);
        format.addContent(conflicts);
        addEntry(conflicts, rpmMetadata.conflict, null);

        Element obsoletes = new Element("obsoletes", RPMNAMESPACE);
        format.addContent(obsoletes);
        addEntry(obsoletes, rpmMetadata.obsolete, null);

        YumFileter fileflter = new PrivateFileFilter();
        YumFileter fileDirflter = new PrivateFileDirFilter();
        for (com.github.cat.yum.store.model.File file : rpmMetadata.files) {
            if (StringUtils.isBlank(file.type)) {
                if (fileflter.filter(file.path)) {
                    continue;
                }
            } else if ("dir".equals(file.type)) {
                if (fileDirflter.filter(file.path)) {
                    continue;
                }
            }

            Element fileElemenrt = new Element("file", COMMONNAMESPACE);
            fileElemenrt.setText(file.path);
            if (!StringUtils.isBlank(file.type)) {
                fileElemenrt.setAttribute("type", file.type);
            }
            format.addContent(fileElemenrt);
        }
    }
    yumXmlSave(doc, repo);
    return repo;
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static RepoModule createFilelitsts(RpmData[] rpmdatas, String rootPath)
        throws IOException, NoSuchAlgorithmException {
    RepoModule repo = new RepoModule(rootPath, "filelists");
    Document doc = new Document();
    Element root = new Element("filelists", FILELISTSNAMESPACE);
    doc.addContent(root);/*w w  w. j  a va  2 s .co m*/
    root.setAttribute("packages", rpmdatas.length + "");

    for (RpmData rpmdata : rpmdatas) {
        RpmMetadata rpmMetadata = rpmdata.rpmMetadata;

        Element packAge = new Element("package", FILELISTSNAMESPACE);
        packAge.setAttribute("pkgid", HashFile.getsum(rpmdata.rpm, ALGORITHM));
        packAge.setAttribute("name", rpmMetadata.name);
        packAge.setAttribute("arch", rpmMetadata.architecture);
        root.addContent(packAge);

        Element version = new Element("version", FILELISTSNAMESPACE);
        version.setAttribute("epoch", rpmMetadata.epoch + "");
        version.setAttribute("ver", rpmMetadata.version);
        version.setAttribute("rel", rpmMetadata.release);
        packAge.setContent(version);

        for (com.github.cat.yum.store.model.File file : rpmMetadata.files) {
            Element fileElement = new Element("file", FILELISTSNAMESPACE);
            fileElement.setText(file.path);
            if (file.type != null) {
                fileElement.setAttribute("type", file.type);
            }
            packAge.addContent(fileElement);
        }
    }
    yumXmlSave(doc, repo);
    return repo;
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static void addEntry(Element parent, List<Entry> entrys, YumFileter filter) {
    for (Entry entry : entrys) {
        Element entryElement = new Element("entry", RPMNAMESPACE);
        String name = entry.name;
        if (null != filter && filter.filter(name)) {
            continue;
        }/*from   www.  j a v  a 2s .  c  om*/
        entryElement.setAttribute("name", name);
        if (null != entry.flags) {
            entryElement.setAttribute("flags", entry.flags);
        }
        if (null != entry.epoch) {
            entryElement.setAttribute("epoch", entry.epoch);
        }
        if (null != entry.version) {
            entryElement.setAttribute("ver", entry.version);
        }
        if (null != entry.release) {
            entryElement.setAttribute("rel", entry.release);
        }
        if (null != entry.pre) {
            entryElement.setAttribute("pre", entry.pre);
        }
        parent.addContent(entryElement);
    }
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

public void addCdsObject(CdsObject obj) {
    Element element = null;/*from   www  . ja  v  a  2s  . c o  m*/
    if (obj.isContainer()) {
        element = new Element("container", NS_DEFAULT);
        addProperty(element, obj, CdsConstants.PROPERTY_SEARCHABLE, "true");
    } else {
        element = new Element("item", NS_DEFAULT);
    }

    for (String reqProp : REQUIRED_PROPERTIES) {
        addProperty(element, obj, reqProp);
    }

    // TODO: temp fix, res location should be added to CdsObject as a property
    Resource res = obj.getResource();
    if (res != null && (filter.equals("*") || filter.contains("res"))) {
        Element resEl = new Element(CdsConstants.PROPERTY_RES, NS_DEFAULT);
        resEl.setAttribute("protocolInfo", "http-get:*:" + res.getMimeType() + ":*");
        resEl.setText(mediaLocation.toString() + "/" + obj.getId());
        element.addContent(resEl);
    }
    // END temp fix

    if (filter.equals("*")) {
        for (String property : obj.getProperties()) {
            if (!REQUIRED_PROPERTIES.contains(property)) {
                addProperty(element, obj, property);
            }
        }
    } else {
        String[] filterParts = filter.split("(?<!\\\\),");
        for (int i = 0; i < filterParts.length; i++) {
            filterParts[i] = filterParts[i].replaceAll("\\\\,", ",");
            if (!REQUIRED_PROPERTIES.contains(filterParts[i])) {
                addProperty(element, obj, filterParts[i]);
            }
        }
    }

    document.getRootElement().addContent(element);
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

private void addProperty(Element element, CdsObject obj, String property, String propertyValue) {

    if (property.contains("@")) {
        Element parentElement = null;
        String strParentElement = property.substring(0, property.indexOf('@'));
        if (strParentElement.equals("")) {
            parentElement = element;//from www  .j a va  2s . c o m
        } else {
            parentElement = element.getChild(removePrefix(strParentElement), getNamespace(strParentElement));
            if (parentElement == null) {
                parentElement = new Element(removePrefix(strParentElement), getNamespace(strParentElement));
                parentElement.setText(obj.getProperty(strParentElement));
                element.addContent(parentElement);
            }
        }
        parentElement.setAttribute(property.substring(property.indexOf('@') + 1), propertyValue);
    } else {
        Element newElement = new Element(removePrefix(property), getNamespace(property));
        newElement.setText(propertyValue);
        element.addContent(newElement);
    }
}

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

/**
 * show me where the money is//from  ww  w.j  a  va2  s  . com
 * @param elementSpec
 * @param value
 * @param appendCommand
 * @throws Exception
 */
public void populateDoc(String elementSpec, String value, String appendCommand) throws Exception {
    boolean valueIsNull = (null == value);

    String[] path = elementSpec.split("\\.");

    log.debug(elementSpec + " contains " + path.length + " elements");
    for (int q = 0; q < path.length; q++) {
        log.debug("path[" + q + "] = " + path[q]);
    }

    if (path.length == 0) {
        log.warn("Zero length element spec [" + elementSpec + "]?");
        return;
    }

    if (schemaDefined == false && firstCall == true) {
        if (schemaRoot != null) {
            /* use the element defined in the xmlselect... */
            log.debug("Not using a schema - so creating the root element with the first specified element ["
                    + schemaRoot + "]");
            buildDocument.setRootElement(new Element(schemaRoot));
        } else {
            log.debug("Not using a schema - so creating the root element with the first specified element ["
                    + path[0] + "]");
            log.debug("element spec: [" + elementSpec + "]");
            buildDocument.setRootElement(new Element(path[0]));
        }
        firstCall = false;
    }

    /** Get the root element from the document and the schema... **/

    elementPath[0] = buildDocument.getRootElement();
    schemaPath[0] = root;

    if (schemaDefined && elementPath[0].getName().equals(path[0]) == false) {
        log.warn("The first element [" + path[0] + " is not the root element");
        return;
    }

    /** Follow the element spec down the document and schema tree... **/

    int idx = 1;
    boolean elementCreated = false;
    boolean xToManyElement = false;
    XSDElement schemaElement = null;

    while (idx < path.length) {

        xToManyElement = false;

        if (path[idx].startsWith("@")) {
            /** ... attribute specified... **/
            idx++;
            break;
        } else {
            String childName = path[idx];
            Element parentElement = elementPath[idx - 1];
            Element docElement = findElement(parentElement, childName);

            if (schemaDefined == true) {

                schemaElement = schemaPath[idx - 1].getChild(path[idx]);

                if (schemaElement == null) {
                    log.warn("The element [" + path[idx] + "] is not in the schema...");
                    return;
                }

                schemaPath[idx] = schemaElement;
            }

            if (docElement == null) {
                log.debug("Element [" + path[idx] + "] does not exist - will create it");
                docElement = new Element(path[idx]);
                elementPath[idx] = docElement;

                addElementToDocument(schemaPath[idx - 1], elementPath[idx - 1], docElement);

                /** Clear any trigger new elements... **/
                StringBuffer tmp = new StringBuffer();
                for (int j = 0; j <= idx; j++) {
                    if (tmp.length() != 0) {
                        tmp.append(".");
                    }
                    tmp.append(path[j]);
                }
                triggerNew(tmp.toString());

                elementCreated = true;
            } else {
                log.debug("Element [" + path[idx] + "] does exist... checking if we should "
                        + "create a new one...");

                /** Check for any throw new triggers... **/
                StringBuffer tmp = new StringBuffer();
                for (int j = 0; j <= idx; j++) {
                    if (tmp.length() != 0) {
                        tmp.append(".");
                    }
                    tmp.append(path[j]);
                }

                if (triggerNew(tmp.toString()) == true) {
                    log.debug("New element trigger detected");
                    /** Create the element... **/
                    docElement = new Element(path[idx]);
                    elementPath[idx] = docElement;

                    addElementToDocument(schemaPath[idx - 1], elementPath[idx - 1], docElement);
                } else if (schemaDefined == true && schemaElement.xToMany() == true) {

                    /*
                     * Flag that a 0..m element has been found... if this is
                     * the element that we are going to populate (the last
                     * one in the while loop) then we will create a new one
                     * if it has not been created a fresh already. This
                     * enables, for example, address lines that come from a
                     * single database row to be mapped into a repeating XML
                     * element. Without this code the trigger mechanism
                     * would not create the new XML element and the address
                     * lines would be overwritten...
                     */
                    xToManyElement = true;

                } else {
                    /**
                     * Element is 0..1 so we will just follow the tree
                     * down...
                     **/
                    log.debug("X..1 cardinality... just keep going...");
                }

            }

            elementPath[idx] = docElement;

        }

        idx++;

    } // end while following the tree down...

    idx--;

    if (path[idx].startsWith("@")) {
        /** Set the attribute... **/
        if (valueIsNull == false) {
            log.debug("Setting attribute [" + path[idx] + "] (on " + path[idx - 1] + ") to [" + value + "]");
            elementPath[idx - 1].setAttribute(path[idx].substring(1, path[idx].length()), value);
        }
    } else {
        /** Set the element... **/

        boolean appendValid = false;
        String separatorChar = null;
        String[] appendParts;

        if (appendCommand != null && appendCommand.equals("") == false) {

            appendParts = appendCommand.split("[()]");

            if (appendParts.length != 2) {
                throw new Exception("append length not 2.  :(");
            }

            if (appendParts[1].equals("newline")) {
                separatorChar = "\n";
            } else if (appendParts[1].equals("comma")) {
                separatorChar = ", ";
            } else if (appendParts[1].equals("dash")) {
                separatorChar = " - ";
            } else if (appendParts[1].equals("space")) {
                separatorChar = " ";
            }

            appendValid = true;

        }

        if (appendValid) {

            if (valueIsNull == false) {
                log.debug("Append data to element [" + path[idx] + "] to [" + value + "]");

                String data = elementPath[idx].getText();

                data = data + separatorChar + value;

                elementPath[idx].setText(data);
            }
        } else {
            if (xToManyElement == true && elementCreated == false) {

                log.debug("Creating an 0..m element [" + path[idx] + "] with value [" + value + "]");
                Element docElement = new Element(path[idx]);

                // @todo may need to check if element is nullable...
                if (valueIsNull) {
                    docElement.setAttribute("nil", "true");
                }

                docElement.setText(value);
                elementPath[idx] = docElement;

                addElementToDocument(schemaPath[idx - 1], elementPath[idx - 1], docElement);
            } else {
                log.debug("Setting element [" + path[idx] + "] to [" + value + "]");

                elementPath[idx].setText(value);

                // @todo may need to check if element is nullable...
                if (valueIsNull) {
                    elementPath[idx].setAttribute("nil", "true");
                }

            }
        }

    }

    /*****
     * Useful for deep debugging... try { XMLOutputter xmlout = new
     * XMLOutputter();
     * xmlout.setFormat(org.jdom.output.Format.getPrettyFormat());
     * xmlout.output(buildDocument, System.out); } catch (Exception ex) {
     * System.out.println("EXCEPTION: " + ex.toString()); }
     *****/

}