Example usage for org.dom4j Element createCopy

List of usage examples for org.dom4j Element createCopy

Introduction

In this page you can find the example usage for org.dom4j Element createCopy.

Prototype

Element createCopy();

Source Link

Document

Creates a deep copy of this element The new element is detached from its parent, and getParent() on the clone will return null.

Usage

From source file:gjset.server.GameServer.java

License:Open Source License

/**
 * Tell every client to send this message.
 *
 * @param message/*from  w w w. java 2s.  c o  m*/
 */
public void sendMessage(Element message) {
    Iterator<PlayerClientHandler> iterator = clients.iterator();

    while (iterator.hasNext()) {
        iterator.next().sendMessage(message.createCopy());
    }
}

From source file:itensil.kb.web.KbServlet.java

License:Open Source License

/**
 *  /listByRef//from ww w.  j  a v a 2s.  c o  m
 *
 *  Output:
 *      article header list
 *
 */
@SuppressWarnings("unchecked")
@ContentType("text/xml")
public void webListByRef(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String uri = request.getParameter("uri");
    String refId = request.getParameter("refId");
    if (!Check.isEmpty(uri) && !Check.isEmpty(refId)) {
        RepositoryHelper.beginTransaction();
        RepositoryHelper.useReadOnly();
        uri = RepositoryHelper.resolveUri(uri);
        Document doc = XMLDocument.readStream(RepositoryHelper.loadContent(uri));
        Document resDoc = DocumentHelper.createDocument();
        Element resRoot = resDoc.addElement("articles");
        for (Element elem : (List<Element>) doc.getRootElement().elements("article")) {
            if (refId.equals(elem.attributeValue("refId"))) {
                // just the node, no content
                elem.setText("");
                resRoot.add(elem.createCopy());
            }
        }
        RepositoryHelper.commitTransaction();
        if (resRoot.hasContent())
            ServletUtil.cacheTimeout(response, 27);
        else
            ServletUtil.noCache(response);
        resDoc.write(response.getWriter());
    } else {
        throw new NotFoundException("[blank]");
    }
}

From source file:net.unicon.academus.apps.ConfigHelper.java

License:Open Source License

public static Element handle(Element configElement, boolean handleDataSource) {
    // Resolve imports
    List elist = configElement.selectNodes("//import");
    if (!elist.isEmpty()) {
        for (Iterator it = elist.iterator(); it.hasNext();) {
            Element e = (Element) it.next();

            String fname = null;/*from   w  ww.  ja  v  a2s.  c  o  m*/
            Attribute t = e.attribute("src");
            if (t == null) {
                throw new IllegalArgumentException("Element <import> must contain an attribute 'src'.");
            }
            fname = t.getValue();

            String xpath = null;
            t = e.attribute("select");
            if (t == null) {
                throw new IllegalArgumentException("Element <import> must contain an attribute 'select'.");
            }
            xpath = t.getValue();

            Element e2 = null;
            try {

                // first try the classloader
                URL url = ConfigHelper.class.getResource(fname);

                // next try an url
                if (url == null) {
                    try {
                        url = new URL(fname);
                    } catch (MalformedURLException mue) {
                        // try a file
                        File f = new File(fname);
                        if (!f.exists()) {
                            throw new Exception(); // will get caught below
                        }
                        url = new URL("file", null, fname);
                    }
                }
                e2 = (Element) ConfigHelper.handle((new SAXReader()).read(url.toString()).getRootElement())
                        .selectSingleNode(xpath);
            } catch (Exception ex) {
                throw new RuntimeException(
                        "Unable to import requested document (" + fname + ") and xpath (" + xpath + ")", ex);
            }

            if (e2 == null)
                throw new IllegalArgumentException(
                        "XPath expression [" + xpath + "] failed to resolve into an element.");

            // Replace the import with the selected node definition
            e.getParent().add(e2.detach());
            e.detach();
        }
    }

    elist = configElement.selectNodes("//copy-of");
    if (!elist.isEmpty()) {
        for (Iterator it = elist.iterator(); it.hasNext();) {
            Element e = (Element) it.next();

            String xpath = null;
            Attribute t = e.attribute("select");
            if (t == null) {
                throw new IllegalArgumentException("Element <copy-of> must contain an attribute 'select'.");
            }
            xpath = t.getValue();

            Element e2 = (Element) configElement.selectSingleNode(xpath);
            if (e2 == null)
                throw new IllegalArgumentException(
                        "The given xpath expression did not resolve into a node: " + xpath);

            // Replace the copy-of with the selected node definition
            e.getParent().add(e2.createCopy());
            e.detach();
        }
    }

    elist = configElement.selectNodes("//value-of");
    if (!elist.isEmpty()) {
        for (Iterator it = elist.iterator(); it.hasNext();) {
            Element e = (Element) it.next();

            String xpath = null;
            Attribute t = e.attribute("select");
            if (t == null) {
                throw new IllegalArgumentException("Element <value-of> must contain an attribute 'select'.");
            }
            xpath = t.getValue();

            Element e2 = (Element) configElement.selectSingleNode(xpath);
            if (e2 == null)
                throw new IllegalArgumentException(
                        "The given xpath expression did not resolve into a node: " + xpath);

            // Replace the value-of with the text of the selected node definition
            e.getParent().setText(e2.getText());
            e.detach();
        }
    }

    if (handleDataSource) {
        String jndiName = null;
        Element el = (Element) configElement.selectSingleNode("jndi-ref");
        if (el != null)
            jndiName = el.getText();

        // Bootstrap datasources...
        elist = configElement.selectNodes("//*[@needsDataSource='true']");
        if (jndiName != null && !elist.isEmpty()) {
            try {
                DataSource ds = new AcademusDataSource();

                for (Iterator it = elist.iterator(); it.hasNext();) {
                    Element e = (Element) it.next();

                    Attribute impl = e.attribute("impl");
                    if (impl == null)
                        throw new IllegalArgumentException("Elements with the 'needsDataSource' attribute "
                                + " must have an 'impl' attribute.");

                    Class.forName(impl.getValue())
                            .getDeclaredMethod("bootstrap", new Class[] { DataSource.class })
                            .invoke(null, new Object[] { ds });
                }
            } catch (Throwable e) {
                throw new RuntimeException("Failed the DataSource bootstrapping", e);
            }
        }
    }

    return configElement;
}

From source file:nl.tue.gale.ae.processor.xmlmodule.ForModule.java

License:Open Source License

@SuppressWarnings("unchecked")
public Element traverse(Element element, Resource resource) throws ProcessorException {
    try {//w  w w.j  a v a 2  s .  c o m
        GaleContext gale = GaleContext.of(resource);
        String expr = element.attributeValue("expr");
        String var = element.attributeValue("var");
        List<Object> alist = new LinkedList<Object>();
        Object list = gale.eval(expr);
        if (list.getClass().isArray())
            for (Object o : (Object[]) list)
                alist.add(o);
        else
            for (Object o : (Iterable<Object>) list)
                alist.add(o);
        if (alist.size() == 0) {
            element.getParent().remove(element);
            return null;
        }

        // optionally sort the array
        String sort = element.attributeValue("sort");
        if (sort != null && !"".equals(sort)) {
            final boolean ascending = ("false".equals(element.attributeValue("ascending")) ? false : true);
            List<Object[]> slist = new ArrayList<Object[]>();
            for (Object o : alist) {
                Object result = null;
                if (o instanceof Concept) {
                    CacheSession<EntityValue> session = gale.openUmSession();
                    session.setBaseUri(((Concept) o).getUri());
                    result = gale.cm().evaluate(gale.cr(), sort,
                            Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale, "session",
                                    "nl.tue.gale.common.cache.CacheSession", session, "value",
                                    "nl.tue.gale.dm.data.Concept", o));
                } else {
                    CacheSession<EntityValue> session = gale.openUmSession();
                    result = gale.cm().evaluate(gale.cr(), sort,
                            Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale, "session",
                                    "nl.tue.gale.common.cache.CacheSession", session, "value",
                                    o.getClass().getName(), o));
                }
                slist.add(new Object[] { result, o });
            }
            Collections.sort(slist, new Comparator<Object[]>() {
                public int compare(Object[] arg0, Object[] arg1) {
                    Object o1 = arg0[0];
                    Object o2 = arg1[0];
                    if (!ascending) {
                        Object temp = o1;
                        o1 = o2;
                        o2 = temp;
                    }
                    if (o1 == null)
                        return (o2 == null ? 0 : -1);
                    if (o2 == null)
                        return 1;
                    if (o1 instanceof Number)
                        return (new Double(((Number) o1).doubleValue()))
                                .compareTo(new Double(((Number) o2).doubleValue()));
                    return o1.toString().compareTo(o2.toString());
                }
            });
            alist.clear();
            for (Object[] o : slist)
                alist.add(o[1]);
        }

        // process for-loop
        String guid = GaleUtil.newGUID();
        resource.put(guid, alist.toArray());

        Element parent = element.getParent();
        int index = parent.indexOf(element);
        Pattern p = Pattern.compile("\\Q%" + var + "\\E\\W");
        for (int i = 0; i < alist.size(); i++) {
            Element clone = element.createCopy();
            Object object = ((Object[]) resource.get(guid))[i];
            String type = object.getClass().getName();
            if (type.indexOf("_$$_") >= 0)
                type = type.substring(0, type.indexOf("_$$_"));
            if (object instanceof Concept) {
                replace(clone, p, ((Concept) object).getUri().toString());
            } else if (object instanceof String) {
                replace(clone, p, (String) object);
            } else if (object instanceof Number || object instanceof Boolean) {
                replace(clone, p, object.toString());
            } else {
                replace(clone, p,
                        "((" + type + ")((Object[])gale.getResource().get(\"" + guid + "\"))[" + i + "])");
            }
            processor.traverseChildren(clone, resource);
            for (Node n : (List<Node>) clone.content()) {
                parent.content().add(index, n);
                index++;
            }
        }
        element.detach();
    } catch (Exception e) {
        e.printStackTrace();
        return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
    }
    return null;
}

From source file:nz.govt.natlib.ndha.common.dublincore.DublinCoreFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public DublinCore normalizeRoot(String xml) throws DocumentException {
    DublinCore dc = new DublinCore();
    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(xml));
    Element record = document.getRootElement();
    Iterator eitr = record.elementIterator();
    Element dcDoc = dc.getDocument().getRootElement();
    while (eitr.hasNext()) {
        Element element = (Element) eitr.next();
        dcDoc.add(element.createCopy());
    }// w w  w  .  j  a  v  a 2  s  .  co m
    return dc;
}

From source file:org.axonframework.migration.eventstore.LegacyAxonEventUpcaster.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//www .j  ava  2  s. c om
public IntermediateRepresentation upcast(IntermediateRepresentation event) {
    Element rootNode = ((Document) event.getContents()).getRootElement();
    if (rootNode.attribute("eventRevision") == null) {
        rootNode.addAttribute("eventRevision", "0");
        Element metaData = rootNode.addElement("metaData").addElement("values");
        Iterator<Element> children = rootNode.elementIterator();
        while (children.hasNext()) {
            Element childNode = children.next();
            String childName = childNode.getName();
            if ("eventIdentifier".equals(childName)) {
                addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid");
                rootNode.remove(childNode);
            } else if ("timestamp".equals(childName)) {
                addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime");
                rootNode.remove(childNode);
            }
        }
    }
    Document document = new DefaultDocument();
    Element newRoot = document.addElement("domain-event");
    Element payload = newRoot.addElement("payload");
    String objectType = rootNode.getName().replaceAll("\\_\\-", "\\$");
    payload.addAttribute("class", objectType);
    Set<String> forbiddenPayloadElements = new HashSet<String>(
            Arrays.asList("metaData", "aggregateIdentifier", "sequenceNumber", "timestamp"));
    for (Object node : rootNode.elements()) {
        Element element = (Element) node;
        if (!forbiddenPayloadElements.contains(element.getName())) {
            payload.add(element.createCopy());
        } else {
            newRoot.add(element.createCopy());
        }
    }
    newRoot.addElement("timestamp").addText(extractMetaDataValue(newRoot, "_timestamp"));
    newRoot.addElement("eventIdentifier").addText(extractMetaDataValue(newRoot, "_identifier"));
    String eventRevision = rootNode.attribute("eventRevision").getValue();
    payload.addAttribute("eventRevision", eventRevision);
    return new Dom4jRepresentation(document, DomainEventMessage.class.getName(),
            Integer.parseInt(eventRevision));
}

From source file:org.b5chat.crossfire.plugin.admin.AdminConsole.java

License:Open Source License

/**
 * Rebuilds the generated model./*w  w  w  . j  a va2 s . co  m*/
 */
private static synchronized void rebuildModel() {
    Document doc = DocumentFactory.getInstance().createDocument();
    generatedModel = coreModel.createCopy();
    doc.add(generatedModel);

    // Add in all overrides.
    for (Element element : overrideModels.values()) {
        // See if global settings are overriden.
        Element appName = (Element) element.selectSingleNode("//adminconsole/global/appname");
        if (appName != null) {
            Element existingAppName = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/appname");
            existingAppName.setText(appName.getText());
            if (appName.attributeValue("plugin") != null) {
                existingAppName.addAttribute("plugin", appName.attributeValue("plugin"));
            }
        }
        Element appLogoImage = (Element) element.selectSingleNode("//adminconsole/global/logo-image");
        if (appLogoImage != null) {
            Element existingLogoImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/logo-image");
            existingLogoImage.setText(appLogoImage.getText());
            if (appLogoImage.attributeValue("plugin") != null) {
                existingLogoImage.addAttribute("plugin", appLogoImage.attributeValue("plugin"));
            }
        }
        Element appLoginImage = (Element) element.selectSingleNode("//adminconsole/global/login-image");
        if (appLoginImage != null) {
            Element existingLoginImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/login-image");
            existingLoginImage.setText(appLoginImage.getText());
            if (appLoginImage.attributeValue("plugin") != null) {
                existingLoginImage.addAttribute("plugin", appLoginImage.attributeValue("plugin"));
            }
        }
        Element appVersion = (Element) element.selectSingleNode("//adminconsole/global/version");
        if (appVersion != null) {
            Element existingVersion = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/version");
            if (existingVersion != null) {
                existingVersion.setText(appVersion.getText());
                if (appVersion.attributeValue("plugin") != null) {
                    existingVersion.addAttribute("plugin", appVersion.attributeValue("plugin"));
                }
            } else {
                ((Element) generatedModel.selectSingleNode("//adminconsole/global"))
                        .add(appVersion.createCopy());
            }
        }
        // Tabs
        for (Object o : element.selectNodes("//tab")) {
            Element tab = (Element) o;
            String id = tab.attributeValue("id");
            Element existingTab = getElemnetByID(id);
            // Simple case, there is no existing tab with the same id.
            if (existingTab == null) {
                // Make sure that the URL on the tab is set. If not, default to the
                // url of the first item.
                if (tab.attributeValue("url") == null) {
                    Element firstItem = (Element) tab.selectSingleNode("//item[@url]");
                    if (firstItem != null) {
                        tab.addAttribute("url", firstItem.attributeValue("url"));
                    }
                }
                generatedModel.add(tab.createCopy());
            }
            // More complex case -- a tab with the same id already exists.
            // In this case, we have to overrite only the difference between
            // the two elements.
            else {
                overrideTab(existingTab, tab);
            }
        }
    }
}

From source file:org.b5chat.crossfire.plugin.admin.AdminConsole.java

License:Open Source License

private static void overrideTab(Element tab, Element overrideTab) {
    // Override name, url, description.
    if (overrideTab.attributeValue("name") != null) {
        tab.addAttribute("name", overrideTab.attributeValue("name"));
    }//  w w w  .  ja v a 2  s . c o  m
    if (overrideTab.attributeValue("url") != null) {
        tab.addAttribute("url", overrideTab.attributeValue("url"));
    }
    if (overrideTab.attributeValue("description") != null) {
        tab.addAttribute("description", overrideTab.attributeValue("description"));
    }
    if (overrideTab.attributeValue("plugin") != null) {
        tab.addAttribute("plugin", overrideTab.attributeValue("plugin"));
    }
    // Override sidebar items.
    for (@SuppressWarnings("unchecked")
    Iterator<Element> i = overrideTab.elementIterator(); i.hasNext();) {
        Element sidebar = (Element) i.next();
        String id = sidebar.attributeValue("id");
        Element existingSidebar = getElemnetByID(id);
        // Simple case, there is no existing sidebar with the same id.
        if (existingSidebar == null) {
            tab.add(sidebar.createCopy());
        }
        // More complex case -- a sidebar with the same id already exists.
        // In this case, we have to overrite only the difference between
        // the two elements.
        else {
            overrideSidebar(existingSidebar, sidebar);
        }
    }
}

From source file:org.b5chat.crossfire.plugin.admin.AdminConsole.java

License:Open Source License

private static void overrideSidebar(Element sidebar, Element overrideSidebar) {
    // Override name.
    if (overrideSidebar.attributeValue("name") != null) {
        sidebar.addAttribute("name", overrideSidebar.attributeValue("name"));
    }/*from w ww. j a  v  a2  s  .  c  om*/
    if (overrideSidebar.attributeValue("plugin") != null) {
        sidebar.addAttribute("plugin", overrideSidebar.attributeValue("plugin"));
    }
    // Override entries.
    for (@SuppressWarnings("unchecked")
    Iterator<Element> i = overrideSidebar.elementIterator(); i.hasNext();) {
        Element entry = (Element) i.next();
        String id = entry.attributeValue("id");
        Element existingEntry = getElemnetByID(id);
        // Simple case, there is no existing sidebar with the same id.
        if (existingEntry == null) {
            sidebar.add(entry.createCopy());
        }
        // More complex case -- an entry with the same id already exists.
        // In this case, we have to overrite only the difference between
        // the two elements.
        else {
            overrideEntry(existingEntry, entry);
        }
    }
}

From source file:org.b5chat.crossfire.plugin.admin.AdminConsole.java

License:Open Source License

private static void overrideEntry(Element entry, Element overrideEntry) {
    // Override name.
    if (overrideEntry.attributeValue("name") != null) {
        entry.addAttribute("name", overrideEntry.attributeValue("name"));
    }/*from   w  w w  . j a  v a  2  s.  co m*/
    if (overrideEntry.attributeValue("url") != null) {
        entry.addAttribute("url", overrideEntry.attributeValue("url"));
    }
    if (overrideEntry.attributeValue("description") != null) {
        entry.addAttribute("description", overrideEntry.attributeValue("description"));
    }
    if (overrideEntry.attributeValue("plugin") != null) {
        entry.addAttribute("plugin", overrideEntry.attributeValue("plugin"));
    }
    // Override any sidebars contained in the entry.
    for (@SuppressWarnings("unchecked")
    Iterator<Element> i = overrideEntry.elementIterator(); i.hasNext();) {
        Element sidebar = (Element) i.next();
        String id = sidebar.attributeValue("id");
        Element existingSidebar = getElemnetByID(id);
        // Simple case, there is no existing sidebar with the same id.
        if (existingSidebar == null) {
            entry.add(sidebar.createCopy());
        }
        // More complex case -- a sidebar with the same id already exists.
        // In this case, we have to overrite only the difference between
        // the two elements.
        else {
            overrideSidebar(existingSidebar, sidebar);
        }
    }
}