Example usage for org.jdom2 Element clone

List of usage examples for org.jdom2 Element clone

Introduction

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

Prototype

@Override
public Element clone() 

Source Link

Document

This returns a deep clone of this element.

Usage

From source file:carb.view.NewsParseur.java

static String getTexte() throws DataConversionException {

    Element elementNews = racineNews.getChild("allnews");

    Element newsTrouvee = null;/*  w  w  w.ja  v a  2 s  .  c  o  m*/
    Element courant = null;

    // dateString = dateDuJour.date(); // quand il sera toujours  jour              
    List listNews = elementNews.getChildren("news");
    Iterator i = listNews.iterator();

    int dateTrouvee = 0;

    while (dateTrouvee != 1 & i.hasNext()) {// tant que la date n'est pas trouv et qu'il reste des news
        //  analyser
        courant = (Element) i.next();

        String dateActuelle = courant.getChild("date").getText(); // petit test de date              
        if (dateActuelle.equals(dateString)) { // si on trouve une news aujourd'hui         
            dateTrouvee = 1;
            newsTrouvee = courant.clone();

        }
    }

    if (dateTrouvee == 1) {
        return newsTrouvee.getChild("text").getText();
    } else {
        System.out.println("Il y a eu une couille");
        return null;
    }

}

From source file:carb.view.NewsParseur.java

static String getTitre() throws DataConversionException {

    Element elementNews = racineNews.getChild("allnews");
    Element newsTrouvee = null;//from ww w .j  a  v  a  2 s  . c o  m
    Element courant = null;
    // dateString = dateDuJour.date(); // quand il sera toujours  jour              
    List listNews = elementNews.getChildren("news");
    Iterator i = listNews.iterator();

    int dateTrouvee = 0;

    while (dateTrouvee != 1 & i.hasNext()) {// tant que la date n'est pas trouv et qu'il reste des news
        //  analyser
        courant = (Element) i.next();
        String dateActuelle = courant.getChild("date").getText(); // petit test de date              
        if (dateActuelle.equals(dateString)) { // si on trouve une news aujourd'hui         
            dateTrouvee = 1;
            newsTrouvee = courant.clone();
        }
    }

    if (dateTrouvee == 1) {
        return newsTrouvee.getChild("title").getText();
    } else {
        System.out.println("Il y a eu une couille");
        return null;
    }
}

From source file:com.athena.chameleon.engine.core.PDFDocGenerator.java

License:Apache License

/**
 * ear  Applications //www  .  j  a v a 2  s . com
 * (type : war - Web, jar - EJB)
 * 
 * @param rootData
 * @param upload
 * @param type
 * @return
 * @throws Exception
 */
public static List<Element> setChildDeployData(PDFMetadataDefinition rootData, Upload upload, String type)
        throws Exception {

    List<Element> childs = new ArrayList<Element>();
    List<Element> childs2;
    Iterator iterator = null;
    if (type.equals("war")) {
        iterator = rootData.getWarDefinitionMap().entrySet().iterator();
    } else if (type.equals("jar")) {
        iterator = rootData.getJarDefinitionMap().entrySet().iterator();
    }

    Element section;
    File childXml = null;
    while (iterator.hasNext()) {
        childs2 = new ArrayList<Element>();
        Entry entry = (Entry) iterator.next();
        AnalyzeDefinition data = (AnalyzeDefinition) entry.getValue();

        if (type.equals("war")) {
            childXml = new File(PDFDocGenerator.class.getResource("/xml/war_application.xml").getFile());
        } else if (type.equals("jar")) {
            childXml = new File(PDFDocGenerator.class.getResource("/xml/jar_application.xml").getFile());
        }

        org.jdom2.Document chapterDoc = new SAXBuilder().build(childXml);

        Element root = chapterDoc.getRootElement();

        section = new Element("section");
        section.setAttribute("title", String.valueOf(entry.getKey()));

        for (Element e : root.getChildren()) {
            childs2.add(e.clone());
        }

        for (Element e : childs2) {
            section.addContent(e);
        }
        setDynamicSection(section, data, upload);

        childs.add(section);
    }

    return childs;
}

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

License:Apache License

/**
 * Recursive method that mixes two XML trees in the following way:
 * <ul>/*  w w w . j  a  va2  s  .  com*/
 * <li>If a child exists at the source leaf but not at destination, the
 * element is copied as a child to the destination leaf</li>
 * <li>If a child exists at both the source and the destination leafs and
 * the source child has children, this method is recursively called to mix
 * both children</li>
 * </ul>
 * Some important remarks:
 * <ul>
 * <li>Equality comparison is not made via common methods but via
 * {@link JDOMUtils#elementsEqualAtCNameAndAttributes(Element, Element)}
 * .</li>
 * <li>Results of this method are returned as changes to the
 * destinationLeaf.</li>
 * <li>An attribute may be appended to all the elements added to the
 * destination leaf by this method.</li>
 * <li>Elements of a concrete namespace can be ignored by this method, if desired.</li>
 * </ul>
 * 
 * @param sourceLeaf
 *            The source leaf to mix into the destination leaf. It remains
 *            unchanged.
 * @param destinationLeaf
 *            The destination leaf, where the source leaf will be mixed
 *            into. Results will be returned as changes at this element, so
 *            IT WILL NOT REMAIN UNCHANGED AFTER THIS METHOD (normally). You
 *            should consider using {@link Element#clone()} if necessary.
 * @param metadataAttributeToAppend
 *            an attribute to be appended to each element added by this
 *            method to the destinationLeaf. If a node with descendants is
 *            added, the attribute will be added only to the top-level
 *            element (not to all the descendants). If null, no attribute
 *            will be added.
 * @param ignoreNamespaceURIIfTextPresent any element whose namespace URI matches this one 
 *            will be ignored if the source element has text content. 
 *            If null, no element is ignored.
 */
private void mixTreesRecursive(Element sourceLeaf, Element destinationLeaf, Attribute metadataAttributeToAppend,
        String ignoreNamespaceURIIfTextPresent) {
    List<Content> sourceLeafContent = sourceLeaf.getContent();
    //j is the index for "only-element" content
    for (int i = 0, j = 0; i < sourceLeafContent.size(); i++) {
        Content currentContent = sourceLeafContent.get(i);
        if (!(currentContent instanceof Element)) {
            continue;
        }

        Element currentSourceChild = (Element) currentContent;

        Element currentDestinationChild = searchElementEqualAtCNameAndAttributes(destinationLeaf.getChildren(),
                currentSourceChild);

        if (currentDestinationChild == null) {

            if (ignoreNamespaceURIIfTextPresent != null && !destinationLeaf.getTextNormalize().equals("")
                    && ignoreNamespaceURIIfTextPresent.equals(currentSourceChild.getNamespaceURI())) {
                continue;
            }

            // There is not equivalent node at destination, so we copy the
            // whole currentSourceChild.
            Element elementToAdd = currentSourceChild.clone();
            if (metadataAttributeToAppend != null) {
                elementToAdd.setAttribute(metadataAttributeToAppend.clone());
            }
            destinationLeaf.addContent(j, elementToAdd);
        } else {
            // Element exists at destination. If it has children, we recurse
            // to fill them (they might be not completely filled).
            if (currentSourceChild.getChildren().size() > 0) {
                mixTreesRecursive(currentSourceChild, currentDestinationChild, metadataAttributeToAppend,
                        ignoreNamespaceURIIfTextPresent);
            }
        }
        j++;
    }
}

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//  ww w.  java  2 s. co  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.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 av  a2  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.izforge.izpack.util.xmlmerge.action.CompleteAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement) {
    if (originalElement != null) {
        outputParentElement.addContent((Element) originalElement.clone());
    } else {//ww w. j  av  a 2 s  .  c o m
        if (patchElement != null) {
            outputParentElement.addContent((Element) patchElement.clone());
        }
    }
}

From source file:com.izforge.izpack.util.xmlmerge.action.DeleteAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement) {
    if (originalElement != null && patchElement == null) {
        outputParentElement.addContent((Element) originalElement.clone());
    }/*from  w  w  w  .j  a v a 2s.c o m*/
}

From source file:com.izforge.izpack.util.xmlmerge.action.DtdInsertAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement)
        throws AbstractXmlMergeException {

    Element element;/*  w ww  .j a v a2s  .  co  m*/

    if (originalElement != null) {
        element = (Element) originalElement.clone();
    } else {
        element = (Element) patchElement.clone();
    }

    DTD dtd = getDTD(outputParentElement);

    List<DTDElement> dtdElements = dtd.getItemsByType(DTDElement.class);

    // Find the corresponding element
    DTDElement parentDtdElement = null;
    for (DTDElement dtdElement : dtdElements) {
        if (dtdElement.getName().equals(outputParentElement.getName())) {
            parentDtdElement = dtdElement;
        }
    }

    if (parentDtdElement == null) {
        throw new ElementException(element, "Element " + outputParentElement.getName() + " not defined in DTD");
    } else {

        DTDItem item = parentDtdElement.getContent();

        if (item instanceof DTDAny) {
            // the parent element accepts anything in any order
            outputParentElement.addContent(element);
        } else if (item instanceof DTDContainer) {

            // List existing elements in output parent element
            List<Element> existingChildren = outputParentElement.getChildren();

            if (existingChildren.size() == 0) {
                // This is the first child
                outputParentElement.addContent(element);
            } else {

                List<String> orderedDtdElements = getOrderedDtdElements((DTDContainer) item);

                int indexOfNewElementInDtd = orderedDtdElements.indexOf(element.getName());
                logger.fine("index of element " + element.getName() + ": " + indexOfNewElementInDtd);

                int pos = existingChildren.size();

                // Calculate the position in the parent where we insert the
                // element
                for (int i = 0; i < existingChildren.size(); i++) {
                    String elementName = (existingChildren.get(i)).getName();
                    logger.fine(
                            "index of child " + elementName + ": " + orderedDtdElements.indexOf(elementName));
                    if (orderedDtdElements.indexOf(elementName) > indexOfNewElementInDtd) {
                        pos = i;
                        break;
                    }
                }

                logger.fine("adding element " + element.getName() + " add in pos " + pos);
                outputParentElement.addContent(pos, element);

            }

        }

    }

}

From source file:com.izforge.izpack.util.xmlmerge.action.FullMergeAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement)
        throws AbstractXmlMergeException {

    logger.fine("Merging: " + originalElement + " (original) and " + patchElement + " (patch)");

    Mapper mapper = (Mapper) m_mapperFactory.getOperation(originalElement, patchElement);

    if (originalElement == null) {
        outputParentElement.addContent(mapper.map(patchElement));
    } else if (patchElement == null) {
        outputParentElement.addContent((Content) originalElement.clone());
    } else {/*from  w  w w  .ja  va2 s .  com*/

        Element workingElement = new Element(originalElement.getName(), originalElement.getNamespacePrefix(),
                originalElement.getNamespaceURI());
        addAttributes(workingElement, originalElement);

        logger.fine("Adding " + workingElement);
        outputParentElement.addContent(workingElement);

        doIt(workingElement, originalElement, patchElement);
    }

}