Example usage for org.jdom2 Element Element

List of usage examples for org.jdom2 Element Element

Introduction

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

Prototype

public Element(final String name, final String uri) 

Source Link

Document

Creates a new element with the supplied (local) name and a namespace given by a URI.

Usage

From source file:com.bc.ceres.nbmgen.NbmGenTool.java

License:Open Source License

private static void addPluginElement(Element pluginsElement, String groupId, String artifactId,
        Map<String, String> configuration, Namespace ns) {
    Element pluginElement = new Element("plugin", ns);
    Element groupIdElement = new Element("groupId", ns);
    groupIdElement.setText(groupId);//from w  w w .  j av a 2s .  c o m
    pluginElement.addContent(groupIdElement);
    Element artifactIdElement = new Element("artifactId", ns);
    artifactIdElement.setText(artifactId);
    pluginElement.addContent(artifactIdElement);
    Element configurationElement = new Element("configuration", ns);
    for (Map.Entry<String, String> entry : configuration.entrySet()) {
        Element keyElement = new Element(entry.getKey(), ns);
        keyElement.setText(entry.getValue());
        configurationElement.addContent(keyElement);
    }
    pluginElement.addContent(configurationElement);
    pluginsElement.addContent(pluginElement);
}

From source file:com.bc.ceres.nbmgen.NbmGenTool.java

License:Open Source License

private static Element getOrAddElement(Element parent, String name, int index, Namespace ns) {
    Element child = parent.getChild(name, ns);
    if (child == null) {
        child = new Element(name, ns);
        if (index >= 0) {
            parent.addContent(index, child);
        } else {//from w ww  . j  av  a  2  s. co  m
            parent.addContent(child);

        }
    }
    return child;
}

From source file:com.bennavetta.util.tycho.impl.DefaultWrapperGenerator.java

License:Apache License

private void writeModules(List<String> modules, File pomFile) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document pom = builder.build(pomFile);
    Namespace pomNs = pom.getRootElement().getNamespace();
    Element modulesElem = pom.getRootElement().getChild("modules", pomNs);
    if (modulesElem == null) {
        modulesElem = new Element("modules", pomNs);
        pom.getRootElement().addContent(modulesElem);
    }//w w w .  j  ava 2s .c  om
    for (String module : modules) {
        boolean exists = false;
        for (Element existingModule : modulesElem.getChildren()) {
            if (existingModule.getTextTrim().equals(module)) {

                exists = true;
                break;
            }
        }
        if (!exists) {
            Element moduleElem = new Element("module", pomNs);
            moduleElem.setText(module);
            modulesElem.addContent(moduleElem);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat().setIndent("\t"));
    try (FileOutputStream out = new FileOutputStream(pomFile)) {
        xout.output(pom, out);
    }
}

From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java

License:Apache License

/**
 * This method generates a changeset document, which describes what nodes
 * must be added and replaced. It generates it from the SVRLInterpreter
 * report passed at constructor./*  w ww  .  j  av a2  s  . co  m*/
 * 
 * @param pathToConfiguration path to the runtime configuration.
 * 
 * @param reportDocument the report document (objective solution description).
 * 
 * @return The generated changeset document.
 * 
 * @throws JDOMException
 *             If there are problems at JDOM2 XML parsings
 * @throws IOException
 *             I/O problems
 * @throws SaxonApiException
 *             problems with Saxon API while transforming metamodel
 *             suggestions into partial autocomplete nodes
 * @throws ParserConfigurationException
 *             problems with javax.xml APIs while transforming metamodel
 *             suggestions into partial autocomplete nodes
 */
public Document getSingleChangesetDocument(String pathToConfiguration, Document reportDocument)
        throws JDOMException, IOException, SaxonApiException, ParserConfigurationException {
    Element resultRoot = new Element("changeset", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
    resultRoot.addNamespaceDeclaration(NAMESPACE_AUTOCONF_METADATA); // To
    // prevent
    // several
    // "xmlns:*****"
    // attributes
    // to
    // appear
    // everywhere
    Document result = new Document(resultRoot);
    Element reportElement = reportDocument.getRootElement();
    for (Element currentDiscrepancyElement : reportElement.getChildren()) {
        boolean isCreate = false;
        Element interestingPathsElement = currentDiscrepancyElement.getChild("interestingPaths",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        String searchPathText = interestingPathsElement.getAttributeValue("search-path");
        String basePathText = interestingPathsElement.getAttributeValue("base-path");
        String keySubpathText = interestingPathsElement.getAttributeValue("key-subpath");
        // First, we look for a path to search the element where discrepancy
        // took place (if it exists)
        String[] docAndPath;
        String searchPathInternal;
        if (searchPathText == null) {
            docAndPath = divideDocAndPath(basePathText);
            searchPathInternal = docAndPath[1] + "[" + keySubpathText + "]";
        } else {
            docAndPath = divideDocAndPath(searchPathText);
            searchPathInternal = docAndPath[1];
        }
        if (!documentCache.containsKey(docAndPath[0])) {
            documentCache.put(docAndPath[0],
                    loadJDOMDocumentFromFile(new File(pathToConfiguration + "/" + docAndPath[0])));
        }
        Document currentDoc = documentCache.get(docAndPath[0]);
        List<Element> discordingElementAtDocList = performJAXENXPath(searchPathInternal, currentDoc,
                Filters.element(), xpathNamespaces);
        if (discordingElementAtDocList.size() == 0) {
            isCreate = true;
        }
        if (isCreate) {
            Element nodeToCreate = currentDiscrepancyElement
                    .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                    .clone();
            //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
            nodeToCreate.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
            boolean thereAreMetamodelSuggestions = currentDiscrepancyElement
                    .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren()
                    .size() > 0;
            if (thereAreMetamodelSuggestions) {
                Element metamodelSuggestionUntransformed = currentDiscrepancyElement
                        .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                Document suggestionMiniDocument = new Document(metamodelSuggestionUntransformed);
                Document suggestionMiniDocumentTransformed = performXSLT(suggestionMiniDocument,
                        xsltTransformMetamodelDocument);
                Element metamodelSuggestion = suggestionMiniDocumentTransformed.getRootElement();
                Attribute metadataAttribute = new Attribute("autogen-from", "metamodel",
                        NAMESPACE_AUTOCONF_METADATA);
                mixTreesRecursive(metamodelSuggestion, nodeToCreate, metadataAttribute,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
            } else {
                Attribute mayNeedManualCompletion = new Attribute("may-need-completion", "true",
                        NAMESPACE_AUTOCONF_METADATA);
                nodeToCreate.setAttribute(mayNeedManualCompletion);
            }
            Element createNodeElement = new Element("add-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
            final String REGEXP_TO_GET_PARENT_PATH = "(.+)(/[^\\[\\]/]+(\\[.+\\])?)$";
            Pattern patternToGetParentPath = Pattern.compile(REGEXP_TO_GET_PARENT_PATH);
            Matcher matcherToGetParentPath = patternToGetParentPath.matcher(searchPathInternal);
            matcherToGetParentPath.matches();
            String pathToParent = matcherToGetParentPath.group(1);
            Attribute pathToParentAttr = new Attribute("underParentAtPath", pathToParent);
            Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
            createNodeElement.setAttribute(documentToChangeAttr);
            createNodeElement.setAttribute(pathToParentAttr);
            createNodeElement.addContent(nodeToCreate);
            resultRoot.addContent(createNodeElement);

        } else {
            for (int i = 0; i < discordingElementAtDocList.size(); i++) {
                Element nodeToModify = currentDiscrepancyElement
                        .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
                nodeToModify.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
                Element discordingElementAtDoc = discordingElementAtDocList.get(i);
                mixTreesRecursive(discordingElementAtDoc, nodeToModify, null,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
                Element replaceNodeElement = new Element("replace-node",
                        AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
                Attribute pathToElementAttr = new Attribute("atPath",
                        generateAttributeBasedPath(discordingElementAtDoc));
                Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
                replaceNodeElement.setAttribute(documentToChangeAttr);
                replaceNodeElement.setAttribute(pathToElementAttr);
                replaceNodeElement.addContent(nodeToModify);
                resultRoot.addContent(replaceNodeElement);
            }
        }
    }
    return result;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlinterpreter.SVRLInterpreterProcessor.java

License:Apache License

/**
 * Method that actually performs the process
 * @param intermediateResults a list of intermediate results.
 * @return the resulting report//w ww .  j a  v  a  2 s  .c  o  m
 * @throws SaxonApiException if a XQuery query fails.
 * @throws IOException required by internal methods, but it will never be thrown (normally)
 * @throws JDOMException if there are problems at XML Parsing
 */
public Document process(List<List<String>> intermediateResults)
        throws SaxonApiException, JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Element rootElement = new Element("report", NAMESPACE_SVRL_INTERPETER_REPORT);
    Document result = new Document(rootElement);
    Map<String, List<Element>> queryCache = performXPathMetamodelSuggestionQueries(
            listOfListsToSingleList(intermediateResults, 0));
    for (int i = 0; i < intermediateResults.size(); i++) {
        List<String> intermediateResult = intermediateResults.get(i);
        Element currentDiscrepancyElement = new Element("discrepancy", NAMESPACE_SVRL_INTERPETER_REPORT);
        rootElement.addContent(currentDiscrepancyElement);

        String partialNodeString = saxonQuery(intermediateResult.get(1));
        Reader partialNodeStringReader = new StringReader(partialNodeString);
        Document partialNodeDoc = builder.build(partialNodeStringReader);
        Element partialNode = partialNodeDoc.getRootElement().detach();

        Element currentInterestingPathsElement = new Element("interestingPaths",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "mandatory-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "base-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "key-subpath",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        moveAndRemoveNSOfAttr(partialNode, currentInterestingPathsElement, "search-path",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentInterestingPathsElement);

        Element currentSuggestedPartialNodeElement = new Element("suggestedPartialNode",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentSuggestedPartialNodeElement);

        currentSuggestedPartialNodeElement.addContent(partialNode);

        Element currentMetamodelSuggestionsElement = new Element("metamodelSuggestions",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(currentMetamodelSuggestionsElement);

        List<Element> queryResults = queryCache.get(intermediateResult.get(0));
        for (Element queryResult : queryResults) {
            currentMetamodelSuggestionsElement.addContent(queryResult.clone());
        }

    }
    return result;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java

License:Apache License

/**
 * This method generates a XML element (as a JDOM2 element) from a XPath path token of the form
 * \/<i>qualified name</i>[<i>attributesFilter</i>]
 * @param pathToken the path token/*w  ww. ja  va2s.  c  o  m*/
 * @param namespaces a {@link Collection} of {@link Namespace} objects, describing the known prefix-namespace mappings
 * @return a {@link Element} object as described by the pathToken
 * @throws IllegalArgumentException if the path token is invalid and/or there are errors at the filter as described by {@link JDOMUtils#generateAttributeListFromFilter(String, Collection)}
 * @throws IndexOutOfBoundsException if the filter specifies an attribute count token and its number does not match the number of attributes, as described by {@link JDOMUtils#generateAttributeListFromFilter(String, Collection)}
 * @see JDOMUtils#generateAttributeListFromFilter(String, Collection)
 */
private static Element generateElementFromPathToken(String pathToken, Collection<Namespace> namespaces) {
    Pattern pattern = Pattern.compile("^" + REGEXP_PATH_TOKEN + "$");
    Matcher matcher = pattern.matcher(pathToken);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Invalid path token: " + pathToken);
    }
    String name = matcher.group("name");
    String pref = matcher.group("pref");
    String filter = matcher.group("filter");

    if (filter != null && !filter.matches(REGEXP_ATTRIBUTES_FILTER)) {
        throw new IllegalArgumentException("Invalid path filter: " + filter);
    }
    Namespace namespace = JDOMUtils.solveNamespaceForPrefix(pref, namespaces);
    //Namespace not found
    if (namespace == null) {
        throw new IllegalArgumentException(
                "Namespace prefix '" + pref + "' at path token is not defined at namespaces parameter.");
    }
    Element result = new Element(name, namespace);
    if (filter != null) {
        List<Attribute> attributeList = JDOMUtils.generateAttributeListFromFilter(filter, namespaces);
        result.setAttributes(attributeList);
    }

    return result;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java

License:Apache License

/**
 * Given a selectFromPath, it queries the runtime configuration to get the selectable values pointed by that path
 * and generates the met:possibleValues element that describes it.
 * @param selectFromPath the path to select from (including a document function, relative to the runtime configuration)
 * @param metamodelDoc the metamodel document, to extract probabilities from.
 * @param originalPath the path of the original element at the document
 * @return the desired met:possibleValues
 * @throws IOException If there are I/O errors while loading documents to select values from.
 * @throws JDOMException If there are problems at XML parsing while loading documents to select values from.
 *//*from   w w  w.java2  s  . co  m*/
private Element getPossibleValuesElement(String selectFromPath, Document metamodelDoc, String originalPath)
        throws JDOMException, IOException {
    Element possibleValuesElement = new Element("possibleValues",
            AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);

    List<String> gatheredPossibleValues = new ArrayList<>();

    if (selectFromPath.contains("|")) {
        String[] singlePaths = selectFromPath.split("\\|");
        for (int i = 0; i < singlePaths.length; i++) {
            String singlePath = singlePaths[i];
            gatheredPossibleValues.addAll(getSelectableValuesFromSinglePath(singlePath));
        }
    } else {
        gatheredPossibleValues = getSelectableValuesFromSinglePath(selectFromPath);
    }

    for (String possibleValue : gatheredPossibleValues) {
        Element currentPosibleValueElement = new Element("possibleValue",
                AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);
        String queryFrequencyStr = "sum(" + originalPath + "/" + metamodelAttributesPrefix + "Value[./@"
                + metamodelAttributesPrefix + "ValueAttr='" + possibleValue + "']/@" + metamodelAttributesPrefix
                + "Frequency)";
        String queryParentFrequencyStr = "sum(" + originalPath + "/@" + metamodelAttributesPrefix
                + "Frequency)";
        List<Double> queryFrequencyResults;
        List<Double> queryParentFrequencyResults;
        if (metamodelDoc != null) {
            queryFrequencyResults = performJAXENXPath(queryFrequencyStr, metamodelDoc, Filters.fdouble());
            queryParentFrequencyResults = performJAXENXPath(queryParentFrequencyStr, metamodelDoc,
                    Filters.fdouble());

        } else {
            queryFrequencyResults = Collections.emptyList();
            queryParentFrequencyResults = Collections.emptyList();
        }

        if (queryParentFrequencyResults.size() > 0 && queryFrequencyResults.size() > 0) {
            double myFrequency = queryFrequencyResults.get(0);
            double myParentFrequency = queryParentFrequencyResults.get(0);
            double probability = myFrequency / myParentFrequency;
            String formattedProbability = String.format(Locale.US, "%.2f", probability);
            if (!formattedProbability.equalsIgnoreCase("nan")) {
                Attribute probabilityAttribute = new Attribute("probability", formattedProbability);
                currentPosibleValueElement.setAttribute(probabilityAttribute);
            }
        }

        currentPosibleValueElement.setText(possibleValue);
        possibleValuesElement.addContent(currentPosibleValueElement);
    }

    return possibleValuesElement;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.SVRLMultipathInterpreterMain.java

License:Apache License

/**
 * This method performs the actual svrl interpretation process (which constitutes the objective solving process).
 * @param svrlDocument the SVRL document (i.e. the objective description)
 * @return the svrl interpreter report (i.e. the objective solution)
 * @throws JDOMException if there are XML problems
 * @throws IOException if there are I/O problems.
 *///from   w w w  .j a v  a 2 s .  c  o m
public Document interpret(Document svrlDocument) throws JDOMException, IOException {
    Element resultRootElement = new Element("report", AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
    Document result = new Document(resultRootElement);
    List<String> pathsListRepeated = getPathsFromDocument(svrlDocument);
    PathGroupsGenerator pathGroupsGenerator = new PathGroupsGenerator();
    List<PathGroup> pathGroups = pathGroupsGenerator.getPathGroups(pathsListRepeated);
    PartialNodeGenerator partialNodeGenerator = new PartialNodeGenerator(this.xpathNamespaces,
            this.pathToConfiguration, this.pathToMetamodel, this.metamodelAttributesPrefix);
    for (PathGroup pathGroup : pathGroups) {
        Element currentDiscrepancyElement = new Element("discrepancy",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);

        Element currentInterestingPathsElement = new Element("interestingPaths",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);

        // '/.[text()=something]' tokens should not be used to look for elements at the metamodel and/or search paths, as text DOES NOT identify elements according to our convention.
        String fixedBasePath = pathGroup.getBasePath().replaceAll("\\]/\\.\\[(?<bracketContent>[^\\]]+)\\]$",
                "]");

        currentInterestingPathsElement.setAttribute("search-path",
                "doc('" + pathGroup.getDocumentPath() + "')" + fixedBasePath);
        currentDiscrepancyElement.addContent(currentInterestingPathsElement);

        Element suggestedPartialNodeElement = new Element("suggestedPartialNode",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
        currentDiscrepancyElement.addContent(suggestedPartialNodeElement);
        Element partialNode = partialNodeGenerator.generatePartialNode(pathGroup);
        suggestedPartialNodeElement.addContent(partialNode);

        File metamodelDocFile = new File(pathGroup.getDocumentPath());
        if (!metamodelDocFile.isAbsolute()) {
            metamodelDocFile = new File(this.pathToMetamodel, pathGroup.getDocumentPath());
        }
        List<Element> metamodelSuggestedNodeList;
        try {
            Document metamodelDoc = documentCache.get(metamodelDocFile.getAbsolutePath());
            if (metamodelDoc == null) {
                metamodelDoc = loadJDOMDocumentFromFile(metamodelDocFile);
                documentCache.put(metamodelDocFile.getAbsolutePath(), metamodelDoc);
            }
            metamodelSuggestedNodeList = performJAXENXPath(fixedBasePath, metamodelDoc);
        } catch (IOException e) {
            metamodelSuggestedNodeList = Collections.emptyList();
        }

        Element metamodelSuggestionsElement = new Element("metamodelSuggestions",
                AutoconfXMLConstants.NAMESPACE_SVRL_INTERPETER_REPORT);
        for (Element metamodelSuggestedNode : metamodelSuggestedNodeList) {
            metamodelSuggestionsElement.addContent(metamodelSuggestedNode.clone());
        }
        currentDiscrepancyElement.addContent(metamodelSuggestionsElement);

        resultRootElement.addContent(currentDiscrepancyElement);
    }

    return result;
}

From source file:com.cybernostics.jsp2thymeleaf.JSP2Thymeleaf.java

private Element createFragmentDef(List<Content> contents) {
    Element html = new Element("html", xmlns);

    ActiveNamespaces.get().forEach(ns -> html.addNamespaceDeclaration(ns));
    html.addContent(NEWLINE);//  www  . j  ava  2  s  .c o m
    Element head = new Element("head", xmlns);
    html.addContent(head);
    html.addContent(NEWLINE);
    Element title = new Element("title", xmlns);
    title.setText("Thymeleaf Fragment Definition");
    head.addContent(NEWLINE);
    head.addContent(title);
    head.addContent(NEWLINE);
    Element body = new Element("body", xmlns);
    html.addContent(body);
    html.addContent(NEWLINE);
    body.addContent(contents);
    return html;
}

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  w w w.ja  v a2 s.com
    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);
}