Example usage for org.jdom2 Element setText

List of usage examples for org.jdom2 Element setText

Introduction

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

Prototype

public Element setText(final String text) 

Source Link

Document

Sets the content of the element to be the text given.

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);
    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);
    }// w  w w  .  java 2  s.co  m
    pluginElement.addContent(configurationElement);
    pluginsElement.addContent(pluginElement);
}

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);
    }//from  w ww.  j a  v a 2 s.c  o  m
    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.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 .j a v a 2  s  .  c om
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.PartialNodeGenerator.java

License:Apache License

/**
 * Method that, given a {@link PathGroup} object (representing a group of paths), generates a partial element (as an {@link Element} object) with all the information present at it.
 * @param pathGroup the {@link PathGroup} object
 * @return the partial element //ww  w  .  j a  v a2 s . c o  m
 * @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.
 * @throws IllegalArgumentException if the basePath or any subpath is invalid
 * @throws IndexOutOfBoundsException if a path token filter contains a count token and the number of attributes does not match.
 */
public Element generatePartialNode(PathGroup pathGroup) throws JDOMException, IOException {
    File metamodelDocFile = new File(pathGroup.getDocumentPath());
    if (!metamodelDocFile.isAbsolute()) {
        metamodelDocFile = new File(this.pathToMetamodel, pathGroup.getDocumentPath());
    }
    Document metamodelDoc;
    try {
        metamodelDoc = loadJDOMDocumentFromFile(metamodelDocFile);
    } catch (IOException e) {
        metamodelDoc = null;
    }

    List<String> basePathTokens = decomposePathTokens(pathGroup.getBasePath());
    String basePathToken = basePathTokens.get(basePathTokens.size() - 1);
    Pattern textAtCurrentNodePattern = Pattern.compile(REGEXP_TEXT_AT_CURRENT_NODE);
    Matcher textAtCurrentBasePathMatcher = textAtCurrentNodePattern.matcher(basePathToken);
    Element partialNode;
    if (textAtCurrentBasePathMatcher.matches()) {
        String text = textAtCurrentBasePathMatcher.group("textValue");
        basePathToken = basePathTokens.get(basePathTokens.size() - 2);
        partialNode = generateElementFromPathToken(basePathToken, xpathNamespaces);
        partialNode.setText(text);
    } else {
        partialNode = generateElementFromPathToken(basePathToken, xpathNamespaces);
    }
    String basePathSelectFrom = pathGroup.getBasePathSelectFrom();
    if (basePathSelectFrom != null && !(basePathSelectFrom.equals(""))) {
        partialNode.setText("");
        Element possibleValuesElement = getPossibleValuesElement(basePathSelectFrom, metamodelDoc,
                pathGroup.getBasePath());
        partialNode.addContent(possibleValuesElement);
    }
    for (String subpath : pathGroup.getSubPaths()) {
        List<String> subpathTokens = decomposePathTokens(subpath);
        Element currentElement = partialNode;
        for (int i = 0; i < subpathTokens.size(); i++) {
            String currentSubpathToken = subpathTokens.get(i);
            Matcher textAtCurrentNodeMatcher = textAtCurrentNodePattern.matcher(currentSubpathToken);
            if (textAtCurrentNodeMatcher.matches()) {
                String text = textAtCurrentNodeMatcher.group("textValue");
                currentElement.setText(text);
                continue;
            }
            List<Element> newChildList = performJAXENXPath("./" + currentSubpathToken, currentElement);
            if (newChildList.size() > 1) {
                throw new IllegalArgumentException(
                        "Subpath token '" + currentSubpathToken + "' yields more than one child");
            }
            Element newChild;
            if (newChildList.size() == 1) {
                newChild = newChildList.get(0);
            } else {
                newChild = generateElementFromPathToken(currentSubpathToken, xpathNamespaces);
                currentElement.addContent(newChild);
            }
            currentElement = newChild;
        }
        String subpathSelectFrom = pathGroup.getSubPathSelectFrom(subpath);
        if (subpathSelectFrom != null && !(subpathSelectFrom.equals(""))) {
            currentElement.setText("");
            Element possibleValuesElement = getPossibleValuesElement(subpathSelectFrom, metamodelDoc,
                    pathGroup.getBasePath() + "/" + subpath);
            currentElement.addContent(possibleValuesElement);
        }
    }
    return partialNode;
}

From source file:com.cats.version.VersionCfgParseAndSave.java

License:Apache License

public boolean saveVersionInfo(List<VersionInfo> infos, String fullPath) {
    try {/*w  w  w  .ja  va2 s  .c  o m*/
        Document doc = new Document();
        Element root = new Element("software-group");
        for (VersionInfo info : infos) {
            Element softEle = new Element("software");
            softEle.setAttribute("name", info.getAppName());
            Element versionCodeEle = new Element("latest-version-code");
            Element versionNameEle = new Element("latest-version");
            Element versionPathEle = new Element("latest-version-abspath");
            Element startupNameEle = new Element("latest-version-startup");

            versionCodeEle.setText(String.valueOf(info.getVersionCode()));
            versionNameEle.setText(info.getVersion());
            versionPathEle.setText(info.getPath());
            startupNameEle.setText(info.getStartupName());
            softEle.addContent(versionCodeEle);
            softEle.addContent(versionNameEle);
            softEle.addContent(versionPathEle);
            softEle.addContent(startupNameEle);

            List<VersionInfoDetail> details = info.getDetails();
            if (null != details) {
                Element detailEles = new Element("latest-version-detail");
                for (VersionInfoDetail verDetail : details) {
                    Element itemElem = new Element("item");
                    itemElem.setAttribute("name", verDetail.getTitle());

                    List<String> detailList = verDetail.getDetail();
                    for (String detailInfo : detailList) {
                        Element detailEle = new Element("detail");
                        detailEle.setText(detailInfo);
                        itemElem.addContent(detailEle);
                    }
                    detailEles.addContent(itemElem);
                }
                softEle.addContent(detailEles);
            }

            List<String> ignoreFiles = info.getIgnoreFiles();
            if (ignoreFiles != null) {
                Element ignoreEles = new Element("ignore-files");
                for (String ignoreInfo : ignoreFiles) {
                    Element ignoreItemEle = new Element("item");
                    ignoreItemEle.setText(ignoreInfo);
                    ignoreEles.addContent(ignoreItemEle);
                }
                softEle.addContent(ignoreEles);
            }
            root.addContent(softEle);
        }
        doc.setRootElement(root);

        //Save to xml file
        XMLOutputter xmlOut = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fullPath);
            xmlOut = new XMLOutputter(Format.getPrettyFormat());
            xmlOut.output(doc, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

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);
                permRequired.addContent(perm);
            }/*w  w w .  jav a  2  s .c o m*/
            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.JSP2Thymeleaf.java

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

    ActiveNamespaces.get().forEach(ns -> html.addNamespaceDeclaration(ns));
    html.addContent(NEWLINE);/*  w  ww  .ja v a  2 s .  c om*/
    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.dexterapps.android.translator.TranslateAndSaveAndroid.java

License:Apache License

private void generateXMLForCountry(String countryCode, List<String> translatedText,
        ArrayList<AndroidStringMapping> stringXmlDOM, HashMap<String, Integer> baseStringResourcesMapping,
        String outPutFolder) {//from ww w  .  j a  v a2  s . c  o m
    Element resources = new Element("resources");
    Document doc = new Document(resources);

    //System.out.println("Generating XML");

    //int totalNumberOfStrings = 0;
    for (int i = 0; i < stringXmlDOM.size(); i++) {
        AndroidStringMapping stringMapping = stringXmlDOM.get(i);

        if (stringMapping.getType().equalsIgnoreCase("string")) {
            Element string = new Element("string");
            string.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //To get the attribute value, use the hasmap and then string array
            int translatedTextIndex = baseStringResourcesMapping.get(stringMapping.getAttributeValue());
            string.setText(translatedText.get(translatedTextIndex));

            //Add element to root
            doc.getRootElement().addContent(string);
        } else if (stringMapping.getType().equalsIgnoreCase("string-array")) {
            Element stringArray = new Element("string-array");
            stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //Since this is String array it will have a list of string items, get the list of string items

            ArrayList<String> stringArrayItems = (ArrayList<String>) stringMapping.getAttributeValue();

            for (int j = 0; j < stringArrayItems.size(); j++) {
                int translatedTextIndex = baseStringResourcesMapping.get(stringArrayItems.get(j));
                stringArray.addContent(new Element("item").setText(translatedText.get(translatedTextIndex)));
            }

            //Add element to root
            doc.getRootElement().addContent(stringArray);
        } else {
            Element stringArray = new Element("plurals");
            stringArray.setAttribute(new Attribute("name", stringMapping.getAttributeName()));

            //Since this is plurals it will have a list of string items with values, get the list of string items

            ArrayList<AndroidStringPlurals> stringPluralItems = (ArrayList<AndroidStringPlurals>) stringMapping
                    .getAttributeValue();

            for (int j = 0; j < stringPluralItems.size(); j++) {

                int translatedTextIndex = baseStringResourcesMapping
                        .get(stringPluralItems.get(j).getAttributeValue());
                Element pluralItem = new Element("item");
                pluralItem.setAttribute("quantity", stringPluralItems.get(j).getAttributeName());
                pluralItem.setText(translatedText.get(translatedTextIndex));

                stringArray.addContent(pluralItem);
            }

            //Add element to root
            doc.getRootElement().addContent(stringArray);
        }
    }

    // new XMLOutputter().output(doc, System.out);
    XMLOutputter xmlOutput = new XMLOutputter();

    try {
        // System.out.println("Saving File");
        Format format = Format.getPrettyFormat();
        format.setEncoding("UTF-8");
        xmlOutput.setFormat(format);

        File file = new File(outPutFolder + "/values-" + countryCode);
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File(outPutFolder + "/values-" + countryCode + "/strings.xml");
        FileOutputStream fop = new FileOutputStream(file);
        xmlOutput.output(doc, fop);
        System.out.println("Translation Successful !!");

        // System.out.println("File Saved!");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

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  www  .j  a  v a  2 s . c  om*/
    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  . c o m
    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;
}