Example usage for org.jdom2 Element getContent

List of usage examples for org.jdom2 Element getContent

Introduction

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

Prototype

@Override
public List<Content> getContent() 

Source Link

Document

This returns the full content of the element as a List which may contain objects of type Text, Element, Comment, ProcessingInstruction, CDATA, and EntityRef.

Usage

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>//from w ww . j  ava  2 s. co  m
 * <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.eds.Model.XMLProcessor.java

License:Apache License

public AuthToken ProcessUIDAuthResponse(ServiceResponse response) {

    BufferedReader reader = response.getReader();
    String authTokenXML = "";
    AuthToken authToken = new AuthToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        authToken.setErrorMessage(ProcessAuthError(response.getErrorNumber(), response.getErrorStream()));
        return authToken;
    }//from   ww  w  . j a v  a2 s  .c o  m
    if (null != reader) {
        try {
            String line = "";
            while ((line = reader.readLine()) != null) {
                authTokenXML += line;
            }
            StringReader stringReader = new StringReader(authTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);
            Content timeout = root.getContent().get(1);

            if (content.getValue() != null) {
                authToken.setAuthToken(content.getValue());
                authToken.setAuthTimeout(timeout.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing UID auth response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            authToken.setErrorMessage(errorMessage);
        }
    }
    return authToken;
}

From source file:com.eds.Model.XMLProcessor.java

License:Apache License

public SessionToken ProcessCreateSessionResponse(ServiceResponse response) {
    BufferedReader reader = response.getReader();
    String line = "";
    String sessionTokenXML = "";
    // Check for errors
    SessionToken sessionToken = new SessionToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        sessionToken.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {/*from w w w. ja v a2 s. com*/
        if (null != reader) {
            try {
                while ((line = reader.readLine()) != null) {
                    sessionTokenXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing create session response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                sessionToken.setApiErrorMessage(errorMessage);
            }
        }
        /*
         * Parse String to XML and the get the value
         */
        try {
            StringReader stringReader = new StringReader(sessionTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);

            if (content.getValue() != null) {
                sessionToken.setSessionToken(content.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            sessionToken.setApiErrorMessage(errorMessage);
        }
    }
    return sessionToken;

}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a session token object from an EDS API Response
 *//*  w w w .jav a2 s.  co  m*/
public SessionToken buildSessionToken(Response response) {
    BufferedReader reader = response.getRead();
    String sessionTokenXML = "";
    // Check for errors
    SessionToken sessionToken = new SessionToken();
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        sessionToken.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        if (null != reader) {
            try {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sessionTokenXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing create session response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                sessionToken.setApiErrorMessage(errorMessage);
            }
        }
        /*
         * Parse String to XML and the get the value
         */
        try {
            StringReader stringReader = new StringReader(sessionTokenXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            Element root = doc.getRootElement();
            Content content = root.getContent().get(0);

            if (content.getValue() != null) {
                sessionToken.setSessionToken(content.getValue());
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            sessionToken.setApiErrorMessage(errorMessage);
        }
    }
    return sessionToken;

}

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

License:Open Source License

/**
 * Performs the actual merge between two source elements.
 *
 * @param parentOut The merged element/*from  w  w  w. j  av a  2s  .  c  om*/
 * @param origElement The first source element
 * @param patchElement The second source element
 * @throws AbstractXmlMergeException If an error occurred during the merge
 */
private void doIt(Element parentOut, Element origElement, Element patchElement)
        throws AbstractXmlMergeException {
    addAttributes(parentOut, patchElement);

    List<Content> origContentList = origElement.getContent();
    List<Content> patchContentList = patchElement.getContent();
    List<Content> unmatchedPatchContentList = new ArrayList<Content>();
    List<Content> matchedPatchContentList = new ArrayList<Content>();

    for (Content origContent : origContentList) {
        logger.fine("Checking original content: " + origContent + " for matching patch contents");
        if (origContent instanceof Element) {
            boolean patchMatched = false;

            for (Content patchContent : patchContentList) {
                logger.fine("Checking patch content: " + patchContent);

                if (patchContent instanceof Comment || patchContent instanceof Text) {
                    // skip and leave original comment or text
                    logger.fine("Skipped patch content: " + patchContent);
                } else if (!(patchContent instanceof Element)) {
                    throw new DocumentException(patchContent.getDocument(), "Contents of type "
                            + patchContent.getClass().getName() + " in patch document not supported");
                } else {
                    if (((Matcher) m_matcherFactory.getOperation((Element) patchContent, (Element) origContent))
                            .matches((Element) patchContent, (Element) origContent)) {
                        logger.fine("Apply matching patch: " + patchContent + " -> " + origContent);
                        applyAction(parentOut, (Element) origContent, (Element) patchContent);
                        patchMatched = true;
                        if (!matchedPatchContentList.contains(patchContent)) {
                            matchedPatchContentList.add(patchContent);
                        }
                    } else {
                        if (!unmatchedPatchContentList.contains(patchContent)) {
                            unmatchedPatchContentList.add(patchContent);
                        }
                    }
                    // Continue searching here for finding multiple matches
                }
            }

            if (!patchMatched) {
                logger.fine("Apply original: " + origContent);
                applyAction(parentOut, (Element) origContent, null);
            }
        } else if (origContent instanceof Comment || origContent instanceof Text) {
            // leave original comment or text
            parentOut.addContent((Content) origContent.clone());
        } else {
            throw new DocumentException(origContent.getDocument(), "Contents of type "
                    + origContent.getClass().getName() + " in original document not supported");
        }
    }

    for (Content unmatchedPatchContent : unmatchedPatchContentList) {
        if (!matchedPatchContentList.contains(unmatchedPatchContent)) {
            logger.fine("Apply unmatching patch: " + unmatchedPatchContent);
            applyAction(parentOut, null, (Element) unmatchedPatchContent);
        }
    }
}

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

License:Open Source License

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

    if (patchElement == null && originalElement != null) {
        outputParentElement.addContent((Element) originalElement.clone());

    } else {/*from www . ja va2s.c  o m*/
        List<Content> outputContent = outputParentElement.getContent();

        Iterator<Content> it = outputContent.iterator();

        int lastIndex = outputContent.size();

        while (it.hasNext()) {
            Content content = it.next();

            if (content instanceof Element) {
                Element element = (Element) content;

                if (element.getQualifiedName().equals(patchElement.getQualifiedName())) {
                    lastIndex = outputParentElement.indexOf(element);
                }
            }
        }

        List<Content> toAdd = new ArrayList<Content>();
        toAdd.add(patchElement);
        outputContent.addAll(Math.min(lastIndex + 1, outputContent.size()), toAdd);
    }
}

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

License:Open Source License

/**
 * Performs the actual merge between two source elements.
 *
 * @param parentOut The merged element/* ww  w  . j  ava2s .c o m*/
 * @param parentIn1 The first source element
 * @param parentIn2 The second source element
 * @throws AbstractXmlMergeException If an error occurred during the merge
 */
private void doIt(Element parentOut, Element parentIn1, Element parentIn2) throws AbstractXmlMergeException {

    addAttributes(parentOut, parentIn2);

    Content[] list1 = (Content[]) parentIn1.getContent().toArray(new Content[] {});
    Content[] list2 = (Content[]) parentIn2.getContent().toArray(new Content[] {});

    int offsetTreated1 = 0;
    int offsetTreated2 = 0;

    for (Content content1 : list1) {

        logger.fine("List 1: " + content1);

        if (content1 instanceof Comment || content1 instanceof Text) {
            parentOut.addContent((Content) content1.clone());
            offsetTreated1++;
        } else if (!(content1 instanceof Element)) {
            throw new DocumentException(content1.getDocument(),
                    "Contents of type " + content1.getClass().getName() + " not supported");
        } else {
            Element e1 = (Element) content1;

            // does e1 exist on list2 and has not yet been treated
            int posInList2 = -1;
            for (int j = offsetTreated2; j < list2.length; j++) {

                logger.fine("List 2: " + list2[j]);

                if (list2[j] instanceof Element) {

                    if (((Matcher) m_matcherFactory.getOperation(e1, (Element) list2[j])).matches(e1,
                            (Element) list2[j])) {
                        logger.fine("Match found: " + e1 + " and " + list2[j]);
                        posInList2 = j;
                        break;
                    }
                } else if (list2[j] instanceof Comment || list2[j] instanceof Text) {
                    // skip
                } else {
                    throw new DocumentException(list2[j].getDocument(),
                            "Contents of type " + list2[j].getClass().getName() + " not supported");
                }
            }

            // element found in second list, but there is some elements to
            // be treated before in second list
            while (posInList2 != -1 && offsetTreated2 < posInList2) {
                Content contentToAdd;
                if (list2[offsetTreated2] instanceof Element) {
                    applyAction(parentOut, null, (Element) list2[offsetTreated2]);
                } else {
                    // FIXME prevent double comments in output by enhancing applyAction() to
                    // Content type instead of Element
                    // Workaround: Add only comments from original document (List1)
                    if (!(list2[offsetTreated2] instanceof Comment)) {
                        contentToAdd = (Content) list2[offsetTreated2].clone();
                        parentOut.addContent(contentToAdd);
                    }
                }

                offsetTreated2++;
            }

            // element found in all lists
            if (posInList2 != -1) {

                applyAction(parentOut, (Element) list1[offsetTreated1], (Element) list2[offsetTreated2]);

                offsetTreated1++;
                offsetTreated2++;
            } else {
                // element not found in second list
                applyAction(parentOut, (Element) list1[offsetTreated1], null);
                offsetTreated1++;
            }
        }
    }

    // at the end of list1, are there some elements in list2 which must be still treated?
    while (offsetTreated2 < list2.length) {
        Content contentToAdd;
        if (list2[offsetTreated2] instanceof Element) {
            applyAction(parentOut, null, (Element) list2[offsetTreated2]);
        } else {
            // FIXME prevent double comments in output by enhancing applyAction() to Content
            // type instead of Element
            // Workaround: Add only comments from original document (List1)
            if (!(list2[offsetTreated2] instanceof Comment)) {
                contentToAdd = (Content) list2[offsetTreated2].clone();
                parentOut.addContent(contentToAdd);
            }
        }

        offsetTreated2++;
    }

}

From source file:com.jamfsoftware.jss.healthcheck.HealthCheck.java

License:Open Source License

/**
 * This method parses the ID out of an XML Object when multiple items
 * are returned from the API. (Like a list of Computer IDS).
 * @param object The XML Doc returned from the JSS
 * @return An array list of IDs/*from   ww  w .  j a  v  a  2s.co m*/
 */
public ArrayList<String> parseMultipleObjects(List<Element> object) {
    ArrayList<String> list_of_ids = new ArrayList<String>();
    //Starts at one because the first returned item is the size of the xml object
    for (int i = 1; i < object.size(); i++) {
        Element account = object.get(i);
        //Get the ID of the object, which is the first returned in the XML
        String id = account.getContent().get(0).getValue();
        //Add to list of IDS
        list_of_ids.add(id);
    }
    return list_of_ids;
}

From source file:com.rometools.modules.content.io.ContentModuleParser.java

License:Open Source License

protected String getXmlInnerText(final Element e) {
    final StringBuffer sb = new StringBuffer();
    final XMLOutputter xo = new XMLOutputter();
    final List<Content> children = e.getContent();
    sb.append(xo.outputString(children));

    return sb.toString();
}

From source file:com.rometools.modules.itunes.io.ITunesParser.java

License:Open Source License

protected String getXmlInnerText(final Element e) {
    final StringBuffer sb = new StringBuffer();
    final XMLOutputter xo = new XMLOutputter();
    final List<Content> children = e.getContent();
    sb.append(xo.outputString(children));
    return sb.toString();
}