Example usage for org.jdom2 Element setContent

List of usage examples for org.jdom2 Element setContent

Introduction

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

Prototype

public Element setContent(final Content child) 

Source Link

Document

Set this element's content to be the supplied child.

Usage

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Sort Child-Elements of the parent with the Comparator comp 
 * @param parent the parent Element/* www. j  a  v a  2 s  .  c om*/
 * @param comp the Comparator
 */
@SuppressWarnings({ "unchecked", "rawtypes" }) // Compiler-Errors with Generics are suppressed
private void sortElements(Element parent, Comparator comp) {
    logger.debug("sortElements(Element, Comparator) - start");

    // Create a new static list of child elements
    // and sort it.
    List<Element> children = new ArrayList<Element>(parent.getChildren());

    Collections.sort(children, comp);

    // remove from every Element the Parent-Node-Link
    ListIterator<Element> childrenIter = children.listIterator();

    while (childrenIter.hasNext()) {
        Object obj = childrenIter.next();
        if (obj instanceof Element)
            ((Element) obj).detach();
    }

    // set the new Child structure to the parent
    parent.setContent(children);

    logger.debug("sortElements(Element, Comparator) - end");
}

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);/*  w  ww  .j a  va2s.  c om*/
    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 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);//from   w  w w . j a va2 s.c  o  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.rometools.modules.content.io.ContentModuleGenerator.java

License:Open Source License

@Override
public void generate(final com.rometools.rome.feed.module.Module module, final org.jdom2.Element element) {
    // this is not necessary, it is done to avoid the namespace definition in every item.
    Element root = element;/*from  w w  w  .  j  a va 2s  . co m*/

    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) root.getParent();
    }

    root.addNamespaceDeclaration(CONTENT_NS);

    if (!(module instanceof ContentModule)) {
        return;
    }

    final ContentModule cm = (ContentModule) module;

    final List<String> encodeds = cm.getEncodeds();

    if (encodeds != null) {
        LOG.debug("{}", cm.getEncodeds().size());
        for (int i = 0; i < encodeds.size(); i++) {
            element.addContent(generateCDATAElement("encoded", encodeds.get(i).toString()));
        }
    }

    final List<ContentItem> contentItems = cm.getContentItems();

    if (contentItems != null && !contentItems.isEmpty()) {
        final Element items = new Element("items", CONTENT_NS);
        final Element bag = new Element("Bag", RDF_NS);
        items.addContent(bag);

        for (int i = 0; i < contentItems.size(); i++) {
            final ContentItem contentItem = contentItems.get(i);
            final Element li = new Element("li", RDF_NS);
            final Element item = new Element("item", CONTENT_NS);

            if (contentItem.getContentAbout() != null) {
                final Attribute about = new Attribute("about", contentItem.getContentAbout(), RDF_NS);
                item.setAttribute(about);
            }

            if (contentItem.getContentFormat() != null) {
                // LOG.debug( "Format");
                final Element format = new Element("format", CONTENT_NS);
                final Attribute formatResource = new Attribute("resource", contentItem.getContentFormat(),
                        RDF_NS);
                format.setAttribute(formatResource);

                item.addContent(format);
            }

            if (contentItem.getContentEncoding() != null) {
                // LOG.debug( "Encoding");
                final Element encoding = new Element("encoding", CONTENT_NS);
                final Attribute encodingResource = new Attribute("resource", contentItem.getContentEncoding(),
                        RDF_NS);
                encoding.setAttribute(encodingResource);
                item.addContent(encoding);
            }

            if (contentItem.getContentValue() != null) {
                final Element value = new Element("value", RDF_NS);

                if (contentItem.getContentValueParseType() != null) {
                    final Attribute parseType = new Attribute("parseType",
                            contentItem.getContentValueParseType(), RDF_NS);
                    value.setAttribute(parseType);
                }

                if (contentItem.getContentValueNamespaces() != null) {
                    final List<Namespace> namespaces = contentItem.getContentValueNamespaces();

                    for (int ni = 0; ni < namespaces.size(); ni++) {
                        value.addNamespaceDeclaration(namespaces.get(ni));
                    }
                }

                final List<Content> detached = new ArrayList<Content>();

                for (int c = 0; c < contentItem.getContentValueDOM().size(); c++) {
                    detached.add(contentItem.getContentValueDOM().get(c).clone().detach());
                }

                value.setContent(detached);
                item.addContent(value);
            } // end value

            li.addContent(item);
            bag.addContent(li);
        } // end contentItems loop

        element.addContent(items);
    }
}

From source file:delfos.group.results.groupevaluationmeasures.diversity.ils.IntraListSimilarity.java

License:Open Source License

private static synchronized Element getXMLElement(IntraListSimilarity intraListSimilarity,
        IntraListSimilarityByRecommendationLenght intraListSimilarityByRecommendationLenght) {

    double measureValue;
    if (intraListSimilarityByRecommendationLenght.size() >= intraListSimilarity.listSizeOfMeasure) {
        measureValue = intraListSimilarityByRecommendationLenght.getILS(intraListSimilarity.listSizeOfMeasure);
    } else {//from   ww  w  .j a  v a  2s.c  om
        measureValue = intraListSimilarityByRecommendationLenght
                .getILS(intraListSimilarityByRecommendationLenght.size());
    }

    Element ilsXMLElement = new Element(intraListSimilarity.getClass().getSimpleName());
    ilsXMLElement.setAttribute(GroupEvaluationMeasure.VALUE, Double.toString(measureValue));

    Element detailedElement = new Element("ILSdetailed");
    for (int listSize = 1; listSize <= intraListSimilarityByRecommendationLenght.size(); listSize++) {
        double intraListSimilarityValue = intraListSimilarityByRecommendationLenght.getILS(listSize);

        Element thisListSizeElement = new Element("Size");
        thisListSizeElement.setAttribute("k", Integer.toString(listSize));
        thisListSizeElement.setAttribute("ils", Double.toString(intraListSimilarityValue));
        detailedElement.addContent(thisListSizeElement);
    }

    ilsXMLElement.setContent(detailedElement);

    return ilsXMLElement;

}

From source file:delfos.results.evaluationmeasures.PRSpace.java

License:Open Source License

@Override
public MeasureResult getMeasureResult(RecommendationResults recommendationResults,
        RatingsDataset<? extends Rating> testDataset, RelevanceCriteria relevanceCriteria) {

    int maxLength = 0;
    for (int idUser : testDataset.allUsers()) {
        Collection<Recommendation> lr = recommendationResults.getRecommendationsForUser(idUser);

        if (lr.size() > maxLength) {
            maxLength = lr.size();/* w  w  w. ja v a  2s. co  m*/
        }
    }

    Map<Integer, ConfusionMatricesCurve> allUsersCurves = new TreeMap<>();

    for (int idUser : testDataset.allUsers()) {

        List<Boolean> resultados = new ArrayList<>(recommendationResults.usersWithRecommendations().size());
        Collection<Recommendation> recommendationList = recommendationResults.getRecommendationsForUser(idUser);

        try {
            Map<Integer, ? extends Rating> userRatings = testDataset.getUserRatingsRated(idUser);
            for (Recommendation r : recommendationList) {

                int idItem = r.getIdItem();
                resultados.add(relevanceCriteria.isRelevant(userRatings.get(idItem).getRatingValue()));
            }
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }

        try {
            allUsersCurves.put(idUser, new ConfusionMatricesCurve(resultados));
        } catch (IllegalArgumentException iae) {
            Global.showWarning("User " + idUser + ": " + iae.getMessage());
        }
    }

    ConfusionMatricesCurve agregada = ConfusionMatricesCurve.mergeCurves(allUsersCurves.values());

    double areaUnderPR = agregada.getAreaPRSpace();

    Element element = new Element(this.getName());
    element.setAttribute(EvaluationMeasure.VALUE_ATTRIBUTE_NAME, Double.toString(areaUnderPR));
    element.setContent(ConfusionMatricesCurveXML.getElement(agregada));

    Map<String, Double> detailedResult = new TreeMap<>();
    for (int i = 0; i < agregada.size(); i++) {
        double precisionAt = agregada.getPrecisionAt(i);
        detailedResult.put("Precision@" + i, precisionAt);
    }

    return new MeasureResult(this, areaUnderPR);
}

From source file:delfos.results.evaluationmeasures.roccurve.AreaUnderROC.java

License:Open Source License

@Override
public MeasureResult getMeasureResult(RecommendationResults recommendationResults,
        RatingsDataset<? extends Rating> testDataset, RelevanceCriteria relevanceCriteria) {
    List<ConfusionMatrix> matrices = new LinkedList<>();
    int maxLength = 0;

    for (Integer idUser : recommendationResults.usersWithRecommendations()) {
        Collection<Recommendation> recommendations = recommendationResults.getRecommendationsForUser(idUser);

        if (recommendations.size() > maxLength) {
            maxLength = recommendations.size();
        }/*from   ww  w. jav a  2  s  .  c  o  m*/
    }

    if (maxLength == 0) {
        return new MeasureResult(this, 0);
    }

    List<List<Boolean>> resultados = new ArrayList<>(recommendationResults.usersWithRecommendations().size());
    for (int idUser : testDataset.allUsers()) {
        Collection<Recommendation> recommendationList = recommendationResults.getRecommendationsForUser(idUser);
        List<Boolean> listaTransformada = new ArrayList<>(recommendationList.size());

        try {
            Map<Integer, ? extends Rating> userRatings = testDataset.getUserRatingsRated(idUser);
            recommendationList.stream().map((r) -> r.getIdItem()).map((idItem) -> {
                return idItem;
            }).forEach((idItem) -> {
                listaTransformada.add(relevanceCriteria.isRelevant(userRatings.get(idItem).getRatingValue()));
            });
            resultados.add(listaTransformada);
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }
    }

    Collection<Integer> allUsers = testDataset.allUsers();
    if (allUsers.isEmpty()) {
        throw new IllegalArgumentException("Cannot work without users.");
    }

    int truePositive = 0;
    int falseNegative = 0;
    int falsePositive = 0;
    int trueNegative = 0;
    int count = 0;

    //Inicialmente supone que todos son no recomendados
    if (Global.isVerboseAnnoying()) {
        Global.showInfoMessage("ROC with length " + 0 + " of " + maxLength + ".");
    }
    for (List<Boolean> recom : resultados) {
        for (Boolean recom1 : recom) {
            if (recom1) {
                falseNegative++;
            } else {
                trueNegative++;
            }
        }
        count++;
        if (allUsers.size() > 11 && (count % (allUsers.size() / 10.0) == 0)) {
            if (Global.isVerboseAnnoying()) {
                Global.showInfoMessage(" " + count * 100 / allUsers.size() + "% of users analysed.\n");
            }
        }
    }

    //calculada la matriz de confusin para tamao 0, se aade a la curva.
    matrices.add(new ConfusionMatrix(falsePositive, falseNegative, truePositive, trueNegative));

    Chronometer c = new Chronometer();
    c.reset();
    for (int kActual = 1; kActual < maxLength; kActual++) {
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("ROC with length " + kActual + " of " + maxLength + ".");
        }

        //            count = 0;
        for (List<Boolean> recom : resultados) {
            if (kActual < recom.size()) {
                if (recom.get(kActual)) {
                    truePositive++;
                    falseNegative--;
                } else {
                    falsePositive++;
                    trueNegative--;
                }
            }
        }
        //calculada la matriz de confusin para longitud kActual
        matrices.add(new ConfusionMatrix(falsePositive, falseNegative, truePositive, trueNegative));
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage(" in " + c.printPartialElapsed() + "\n");
        }
    }

    ConfusionMatricesCurve curve = new ConfusionMatricesCurve(matrices.toArray(new ConfusionMatrix[1]));

    if (Global.isVerboseAnnoying()) {
        Global.showInfoMessage("------------- Receiver Operator Characteristic --------------" + "\n");
        Global.showInfoMessage(curve.toString() + "\n");
    }

    double areaUnderROC = curve.getAreaPRSpace();

    Element element = new Element(this.getName());
    element.setAttribute(EvaluationMeasure.VALUE_ATTRIBUTE_NAME, Double.toString(areaUnderROC));
    element.setContent(ConfusionMatricesCurveXML.getElement(curve));

    return new MeasureResult(this, areaUnderROC);
}

From source file:jmri.jmrit.vsdecoder.StoreXmlVSDecoderAction.java

License:Open Source License

public void saveVSDecoderProfile(java.io.File f) {

    try {//from   www  . java  2s.  co  m
        Element root = new Element("VSDecoderConfig");
        Document doc = XmlFile.newDocument(root, XmlFile.dtdLocation + "vsdecoder-config.dtd");

        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/throttle-layout-config.xsl"?>
        /*TODO         java.util.Map<String,String> m = new java.util.HashMap<String,String>();
              m.put("type", "text/xsl");
              m.put("href", jmri.jmrit.XmlFile.xsltLocation + "throttle-layout-config.xsl");
              ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
              doc.addContent(0, p); */
        java.util.ArrayList<Element> children = new java.util.ArrayList<Element>(5);

        for (java.util.Iterator<VSDecoder> i = VSDecoderManager.instance().getVSDecoderList().iterator(); i
                .hasNext();) {
            VSDecoder vsd = i.next();
            children.add(vsd.getXml());
        }

        // Throttle-specific stuff below.  Kept for reference
        /*
              // throttle list window
              children.add(ThrottleFrameManager.instance().getThrottlesListPanel().getXml() );
                
              // throttle windows
              for (Iterator<ThrottleWindow> i = ThrottleFrameManager.instance().getThrottleWindows(); i.hasNext();) {
              ThrottleWindow tw = i.next();
              Element throttleElement = tw.getXml();
              children.add(throttleElement);
              }
              */
        // End Throttle-specific stuff.
        root.setContent(children);

        FileOutputStream o = new java.io.FileOutputStream(f);
        try {
            XMLOutputter fmt = new XMLOutputter();
            fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator"))
                    .setTextMode(Format.TextMode.PRESERVE));
            fmt.output(doc, o);
        } catch (IOException ex) {
            log.warn("Exception in storing VSDecoder xml: " + ex);
        } finally {
            o.close();
        }
    } catch (FileNotFoundException ex) {
        log.warn("Exception in storing VSDecoder xml: " + ex);
    } catch (IOException ex) {
        log.warn("Exception in storing VSDecoder xml: " + ex);
    }
}

From source file:jmri.jmrit.vsdecoder.VSDecoderPreferences.java

License:Open Source License

public void save() {
    if (prefFile == null) {
        return;/*  w  ww. j a v a2s.c  o m*/
    }
    XmlFile xf = new XmlFile() {
    }; // odd syntax is due to XmlFile being abstract
    xf.makeBackupFile(prefFile);
    File file = new File(prefFile);
    try {
        //The file does not exist, create it before writing
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            if (!parentDir.mkdir()) // make directory, check result
            {
                log.error("failed to make parent directory");
            }
        }
        if (!file.createNewFile()) // create file, check result
        {
            log.error("createNewFile failed");
        }
    } catch (Exception exp) {
        log.error("Exception while writing the new VSDecoder preferences file, may not be complete: " + exp);
    }

    try {
        Element root = new Element("vsdecoder-preferences");
        //Document doc = XmlFile.newDocument(root, XmlFile.dtdLocation+"vsdecoder-preferences.dtd");
        Document doc = XmlFile.newDocument(root);
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/throttle.xsl"?>
        /*TODO          java.util.Map<String,String> m = new java.util.HashMap<String,String>();
                     m.put("type", "text/xsl");
                     m.put("href", jmri.jmrit.XmlFile.xsltLocation+"throttles-preferences.xsl");
                     ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
                     doc.addContent(0,p);*/
        root.setContent(store());
        xf.writeXML(file, doc);
    } catch (Exception ex) {
        log.warn("Exception in storing vsdecoder preferences xml: " + ex);
    }
}

From source file:org.artifactory.update.security.v6.LowercaseUsernameXmlConverter.java

License:Open Source License

private void mergeUsers(Element root, Namespace namespace) {
    Element child = root.getChild("users", namespace);
    List users = child.getChildren("user", namespace);
    Map<String, Element> usernameToGroups = Maps.newHashMap();
    if (users != null && !users.isEmpty()) {
        Iterator iterator = users.iterator();
        while (iterator.hasNext()) {
            Element userElement = (Element) iterator.next();
            Element userNameElement = userElement.getChild("username", namespace);
            String userName = userNameElement.getText();
            String lowerCaseUsername = userName.toLowerCase();
            userNameElement.setText(lowerCaseUsername);
            if (!usernameToGroups.containsKey(lowerCaseUsername)) {
                usernameToGroups.put(lowerCaseUsername, userElement);
                addGroupsToUser(userElement, userElement, namespace);
                copyEmails(namespace, usernameToGroups, userElement, lowerCaseUsername);
            } else {
                String isAdmin = userElement.getChild("admin").getText();
                Element existingUserElement = usernameToGroups.get(lowerCaseUsername);
                addGroupsToUser(existingUserElement, userElement, namespace);
                if (Boolean.parseBoolean(isAdmin)) {
                    usernameToGroups.put(lowerCaseUsername, userElement);
                }//  w  w w  .j a va  2 s. com
                copyEmails(namespace, usernameToGroups, existingUserElement, lowerCaseUsername);
                addGroupsToUser(userElement, existingUserElement, namespace);
                iterator.remove();
            }
        }
    }
    root.removeChildren("users", namespace);
    Element usersElement = new Element("users", namespace);
    root.addContent(usersElement);
    for (Map.Entry<String, Element> elementEntry : usernameToGroups.entrySet()) {
        Element newUser = elementEntry.getValue();
        Element userElement = new Element("user", namespace);
        userElement.setContent(newUser.cloneContent());
        usersElement.addContent(userElement);
    }
}