Example usage for org.jdom2 Element getParentElement

List of usage examples for org.jdom2 Element getParentElement

Introduction

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

Prototype

final public Element getParentElement() 

Source Link

Document

A convenience method that returns any parent element for this element, or null if the element is unattached or is a root element.

Usage

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

private int injectElementsInDocument(final List<Element> stylizedElements, final Element ap, final Element apPr,
        final int arIndex) {
    int index = arIndex;
    final Element txBody = ap.getParentElement();
    int apIndex = txBody.indexOf(ap) + 1;
    boolean createNewAp = false;
    Element currentAp = ap;//  ww w.j  a va 2 s  .  c  om
    for (Element element : stylizedElements) {
        if (element.getName().equals(PPTXDocument.P_ELEMENT)) {
            currentAp = element;
            txBody.addContent(apIndex, currentAp);
            apIndex++;
            createNewAp = true;
        } else {
            if (createNewAp) {
                currentAp = new Element(PPTXDocument.P_ELEMENT, getNamespace());
                Element apPrToAdd = ObjectUtils.clone(apPr);
                if (apPrToAdd == null) {
                    apPrToAdd = new Element(PPTXDocument.PPR_ELEMENT, getNamespace());
                }
                final Element abuNone = new Element(PPTXDocument.BUNONE_ELEMENT, getNamespace());
                apPrToAdd.addContent(abuNone);
                currentAp.addContent(apPrToAdd);
                txBody.addContent(apIndex, currentAp);
                apIndex++;
                createNewAp = false;
            }
            if (currentAp == ap) {
                currentAp.addContent(index, element);
                index++;
            } else {
                currentAp.addContent(element);
            }
        }
    }
    return apIndex;
}

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

private void injectRemainsInDocument(final List<Element> remains, final Element ap, final Element apPr,
        final int apIndex) {
    if (CollectionUtils.isNotEmpty(remains)) {
        final Element txBody = ap.getParentElement();
        final Element apWithRemains = new Element(PPTXDocument.P_ELEMENT, getNamespace());
        if (apPr != null) {
            apWithRemains.addContent(apPr);
        }//w  w w  .jav  a 2 s .co m
        apWithRemains.addContent(remains);
        txBody.addContent(apIndex, apWithRemains);
    }
}

From source file:no.imr.stox.functions.utils.JDOMUtils.java

public static void getDataHeadersFromAttributes(Element elm, String topLevel, Collection<HeaderElm> set) {
    if (elm == null) {
        return;//ww  w . j  ava2 s  .  c  o  m
    }
    if (!elm.getName().equals(topLevel)) {
        getDataHeadersFromAttributes(elm.getParentElement(), topLevel, set);
    }
    elm.getAttributes().stream().forEach(a -> {
        set.add(new HeaderElm(elm.getName(), a.getName()));
    });
}

From source file:no.imr.stox.functions.utils.JDOMUtils.java

public static Element getTargetElm(Element elm, String elmLevel) {
    if (elm == null) {
        return null;
    }/*from w  w  w  .j av  a2 s .com*/
    if (elm.getName().equals(elmLevel)) {
        return elm;
    }
    return getTargetElm(elm.getParentElement(), elmLevel);
}

From source file:org.jreserve.gui.wrapper.jdom.JDomUtil.java

License:Open Source License

public static String getPath(Element e) {
    String path = "";
    while (e != null) {
        String name = e.getName();
        Element parent = e.getParentElement();
        if (parent != null)
            name += "[" + (parent.indexOf(e) + 1) + "]";

        if (path.length() > 0)
            path += "/";
        path += name;//from   ww w.  j  ava2 s. c  o  m

        e = parent;
    }
    return null;
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private void addModelAttributeXml(Stack<DocElement> parentStack, String attributeId, Object modelAttrValue,
        Document generatedXml, String entityId) {

    DocElement templateDocElement = entityAttributeDtls.get(attributeId);
    String value = modelAttrValue == null ? null : modelAttrValue.toString();
    Element newElement = null;//from   w  w w.  java 2  s .com
    Element templateParentElement = null;
    String templateParentXPath = null;
    Attribute newAttribute = null;
    Map<Element, Namespace> generatedDocNamespaces = null;
    Map<Element, Namespace> templateNamespaces = null;
    Stack<Element> parentsToAdd = new Stack<Element>();
    DocElement entityDocElement = entityAttributeDtls.get(entityId);

    generatedDocNamespaces = removeNamespaces(generatedXml);
    templateNamespaces = removeNamespaces(templateDoc);

    // we can be passed elements in the model that don't reside in the
    // template. If so, just ignore the field and do nothing
    if (templateDocElement != null) {
        // at this point, our stack should always currently have the entity
        // for this attribute as the top level of the stack

        // set up our new element or attribute to add
        if (templateDocElement.xmlElement != null) {
            // we have to add an element
            newElement = templateDocElement.xmlElement.clone();
            newElement.removeContent();
            removeAllAttributes(newElement);

            if (StringUtils.isEmpty(value)) {
                if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) {
                    newElement.setAttribute("nil", "true", getXmlNamespace());
                }
            } else {
                newElement.setText(value);
            }
        } else {
            // we have to add an attribute
            newAttribute = templateDocElement.xmlAttribute.clone();
            if (value != null) {
                newAttribute.setValue(value);
            }
        }

        // in this case the attribute is one lower than the entity and
        // should simply be attached to the entity
        if (templateDocElement.level - 1 == parentStack.peek().level) {
            if (newElement != null) {
                applyAttributeXPath(generatedXml, templateDocElement.xpath, value);
            } else {
                parentStack.peek().xmlElement.setAttribute(newAttribute);
            }
        } else {
            // the attribute doesn't hang directly off the entity
            // we must find its parent in the existing doc or fill static
            // content as appropriate

            // first get the parent element for this model attribute, and
            // gets its xpath
            XPathExpression<Element> expression = XPathFactory.instance().compile(templateDocElement.xpath,
                    Filters.element());
            List<Element> matches = expression.evaluate(templateDoc.getRootElement());
            if (matches.size() != 0) {
                templateParentElement = matches.get(0).getParentElement();
            } else {
                // throw an exception, we should always find the element in
                // the template
            }

            // now look for parent elements in the generated xml until we
            // find one
            // or we hit the entity itself
            boolean parentFound = false;
            do {
                templateParentXPath = XPathHelper.getRelativePath(entityDocElement.xmlElement,
                        templateParentElement);
                expression = XPathFactory.instance().compile(templateParentXPath, Filters.element());
                matches = expression.evaluate(parentStack.peek().xmlElement);
                if (matches.size() == 0) {
                    Element elementToAdd = templateParentElement.clone();
                    elementToAdd.removeContent();
                    removeAllAttributes(elementToAdd);
                    parentsToAdd.push(elementToAdd);
                    templateParentElement = templateParentElement.getParentElement();
                } else {
                    parentFound = true;
                }
            } while (parentFound == false);

            // add every parent we couldn't find up to the entity level
            Element elementToAddTo = matches.get(0);
            while (!parentsToAdd.isEmpty()) {
                elementToAddTo.addContent(0, parentsToAdd.peek());
                elementToAddTo = parentsToAdd.pop();
            }

            // add our model attribute to the latest level
            if (newElement != null) {
                applyAttributeXPath(generatedXml, templateDocElement.xpath, value);
            } else {
                elementToAddTo.setAttribute(newAttribute);
            }
        }
    }
    restoreNamespaces(templateDoc, templateNamespaces);
    restoreNamespaces(generatedXml, generatedDocNamespaces);
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private void applyAttributeXPath(Document generatedXml, String xpath, String value) {
    List<Object> matches = XPathFactory.instance().compile(xpath).evaluate(generatedXml.getRootElement());
    if (matches.size() == 0) {
        log(LogLevel.WARN, "XPath expression " + xpath + " did not find any matches");
        return;/* ww w  .  ja  v  a2 s  .c o  m*/
    }
    Object object = matches.get(0);
    if (object instanceof Element) {
        Element element = (Element) object;
        if (value != null) {
            element.setText(value.toString());
        } else {
            if (nullHandling.equals(NULL_HANDLING_REMOVE)) {
                Element parent = element.getParentElement();
                parent.removeContent(element);
            } else if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) {
                element.setAttribute("nil", "true", getXmlNamespace());
            }
        }
    } else if (object instanceof Attribute) {
        Attribute attribute = (Attribute) object;
        if (value != null) {
            attribute.setValue(value);
        }
    }
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private Map<String, DocElement> fillAttributeDetails(Document templateDoc) {

    Map<String, DocElement> attributeLevels = new HashMap<String, DocElement>();
    Map<Element, Namespace> namespaces = removeNamespaces(templateDoc);
    for (ComponentAttributeSetting compAttributeSetting : getComponent().getAttributeSettings()) {
        if (compAttributeSetting.getName().equals(XML_FORMATTER_XPATH)) {
            XPathExpression<Object> expression = XPathFactory.instance()
                    .compile(compAttributeSetting.getValue());
            List<Object> matches = expression.evaluate(templateDoc.getRootElement());
            if (matches.size() == 0) {
                log(LogLevel.WARN,//from w  w w . j  a  v a 2  s  .c  om
                        "XPath expression " + compAttributeSetting.getValue() + " did not find any matches");
            } else {
                if (matches.get(0) instanceof Element) {
                    Element element = (Element) matches.get(0);
                    // a model attribute could never be the root element of
                    // the doc
                    int level = 1;
                    Element elementToMatch = element.getParentElement();
                    while (!elementToMatch.getName().equalsIgnoreCase(templateDoc.getRootElement().getName())) {
                        elementToMatch = elementToMatch.getParentElement();
                        level++;
                    }
                    attributeLevels.put(compAttributeSetting.getAttributeId(),
                            new DocElement(level, element, null, compAttributeSetting.getValue()));
                }
                if (matches.get(0) instanceof Attribute) {
                    Attribute attribute = (Attribute) matches.get(0);
                    int level = 1;
                    Element elementToMatch = attribute.getParent();
                    while (!elementToMatch.getName().equalsIgnoreCase(templateDoc.getRootElement().getName())) {
                        elementToMatch = elementToMatch.getParentElement();
                        level++;
                    }
                    attributeLevels.put(compAttributeSetting.getAttributeId(),
                            new DocElement(level, null, attribute, compAttributeSetting.getValue()));
                }
            }
        }
    }
    restoreNamespaces(templateDoc, namespaces);
    return attributeLevels;
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private Map<String, DocElement> fillEntityDetails(Document templateDoc) {

    Map<String, DocElement> entityLevels = new HashMap<String, DocElement>();

    Map<Element, Namespace> namespaces = removeNamespaces(templateDoc);
    for (ComponentEntitySetting compEntitySetting : getComponent().getEntitySettings()) {
        if (compEntitySetting.getName().equals(XML_FORMATTER_XPATH)) {
            XPathExpression<Element> expression = XPathFactory.instance().compile(compEntitySetting.getValue(),
                    Filters.element());/*w w w.  j  a v a  2 s.c om*/
            List<Element> matches = expression.evaluate(templateDoc.getRootElement());
            if (matches.size() == 0) {
                log(LogLevel.WARN,
                        "XPath expression " + compEntitySetting.getValue() + " did not find any matches");
            } else {
                int level = 1;
                Element element = matches.get(0);
                if (!element.isRootElement()) {
                    Element elementToMatch = element.getParentElement();
                    while (!elementToMatch.getName().equalsIgnoreCase(templateDoc.getRootElement().getName())) {
                        elementToMatch = elementToMatch.getParentElement();
                        level++;
                    }
                }
                entityLevels.put(compEntitySetting.getEntityId(),
                        new DocElement(level, element, null, compEntitySetting.getValue()));
            }
        }
    }
    restoreNamespaces(templateDoc, namespaces);
    return entityLevels;
}

From source file:org.jumpmind.metl.core.runtime.component.XmlParser.java

License:Open Source License

@SuppressWarnings("unchecked")
protected void handleUsingXPath(Message inputMessage, ISendMessageCallback callback,
        boolean unitOfWorkBoundaryReached) {
    ArrayList<String> inputRows = ((TextMessage) inputMessage).getPayload();
    ArrayList<EntityData> payload = new ArrayList<EntityData>();
    if (inputRows != null) {
        for (String xml : inputRows) {
            SAXBuilder builder = new SAXBuilder();
            builder.setXMLReaderFactory(XMLReaders.NONVALIDATING);
            builder.setFeature("http://xml.org/sax/features/validation", false);
            try {
                Document document = builder.build(new StringReader(xml));
                removeNamespaces(document);
                for (XmlFormatterEntitySetting entitySetting : entitySettings) {
                    List<XmlFormatterAttributeSetting> attributeSettings = entitySetting.getAttributeSettings();
                    List<Element> entityMatches = (List<Element>) entitySetting.getExpression()
                            .evaluate(document.getRootElement());
                    for (Element element : entityMatches) {
                        String text = toXML(element);
                        Document childDocument = builder
                                .build(new ByteArrayInputStream(text.getBytes(Charset.forName("utf-8"))));
                        getComponentStatistics().incrementNumberEntitiesProcessed(threadNumber);
                        EntityData data = new EntityData();
                        for (XmlFormatterAttributeSetting attributeSetting : attributeSettings) {
                            boolean resultsFound = false;
                            Element targetElement = element;
                            Document targetDocument = childDocument;
                            do {
                                List<Object> attributeMatches = (List<Object>) attributeSetting.getExpression()
                                        .evaluate(targetDocument);
                                for (Object object : attributeMatches) {
                                    resultsFound = true;
                                    if (object instanceof Attribute) {
                                        data.put(attributeSetting.getSetting().getAttributeId(),
                                                ((Attribute) object).getValue());
                                    } else if (object instanceof Content) {
                                        data.put(attributeSetting.getSetting().getAttributeId(),
                                                ((Content) object).getValue());
                                    } else if (object instanceof Element) {
                                        data.put(attributeSetting.getSetting().getAttributeId(),
                                                ((Element) object).getTextTrim());
                                    }/*from  www .ja v a 2 s.c  o m*/
                                }

                                if (!resultsFound
                                        && !attributeSetting.getExpression().getExpression()
                                                .startsWith("/" + element.getName())
                                        && targetElement.getParentElement() != null) {
                                    targetElement = targetElement.getParentElement();
                                    targetDocument = builder.build(new ByteArrayInputStream(
                                            toXML(targetElement).getBytes(Charset.forName("utf-8"))));
                                } else if (!resultsFound) {
                                    info("Did not find a match for: %s\n in:\n %s",
                                            attributeSetting.getExpression().getExpression(), text);
                                    targetDocument = null;
                                    targetElement = null;
                                }
                            } while (!resultsFound && targetElement != null);
                        }
                        if (data.size() > 0) {
                            payload.add(data);
                        } else {
                            log(LogLevel.WARN,
                                    "Found entity element: <%s/> with no matching attributes.  Please make sure your xpath expressions match",
                                    element.getName());
                        }
                    }
                }

                if (payload.size() > rowsPerMessage) {
                    callback.sendEntityDataMessage(null, payload);
                    payload = new ArrayList<>();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    if (payload.size() > 0) {
        callback.sendEntityDataMessage(null, payload);
    }

}