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:com.zimbra.cs.dav.property.ResourceProperty.java

License:Open Source License

public Element toElement(DavContext ctxt, Element parent, boolean nameOnly) {
    Element elem = parent.addElement(mName);
    if (nameOnly) {
        return elem;
    }/*from   w w w. j a  v a 2  s. com*/

    if (mValue != null) {
        if (mLocale != null) {
            elem.addAttribute(DavElements.E_LANG, mLocale.toString());
        }
        elem.setText(mValue);
    } else {
        for (Element child : mChildren) {
            elem.add(child.createCopy());
        }
    }
    return elem;
}

From source file:com.zimbra.cs.dav.property.ResourceProperty.java

License:Open Source License

public Element toElement(boolean nameOnly) {
    Element elem = org.dom4j.DocumentHelper.createElement(mName);
    if (nameOnly) {
        return elem;
    }/*from w ww . ja  va2s.c o m*/

    if (mValue != null) {
        if (mLocale != null) {
            elem.addAttribute(DavElements.E_LANG, mLocale.toString());
        }
        elem.setText(mValue);
    } else {
        for (Element child : mChildren) {
            elem.add(child.createCopy());
        }
    }
    return elem;
}

From source file:cz.fi.muni.xkremser.editor.server.OAIPMHClientImpl.java

License:Open Source License

@Override
public ArrayList<MetadataBundle> search(String url) {
    ArrayList<MetadataBundle> retList = new ArrayList<MetadataBundle>();
    try {/*from ww  w .  ja va  2 s .c o m*/
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (marc2mods == null) {
            if (!new File(config.getEditorHome() + MARC_TO_MODS_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_MODS_XSLT + " does not exist.");
                return retList;
            }
            marc2mods = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_MODS_XSLT), true);
        }
        InputStream marcStream = RESTHelper.get(url + MARC_METADATA_PREFIX, null, null, false);

        if (marc2dc == null) {
            if (!new File(config.getEditorHome() + MARC_TO_DC_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_DC_XSLT + " does not exist.");
                return retList;
            }
            marc2dc = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_DC_XSLT), true);
        }

        //            StringWriter writer = new StringWriter();
        //            IOUtils.copy(marcStream, writer, "UTF-8");
        //            String theString = writer.toString();
        //            System.out.println(theString);

        Document marcDoc = Dom4jUtils.loadDocument(marcStream, true);
        if (marcDoc.asXML().contains("idDoesNotExist") || marcDoc.asXML().contains("cannotDisseminateFormat")) {
            return retList;
        }

        MarcDocument mrc = new MarcDocument(marcDoc);
        MarcSpecificMetadata marcSpecific = new MarcSpecificMetadata(mrc.findSysno(), mrc.findBase(),
                mrc.find040a(), mrc.find080a(), mrc.find650a(), mrc.find260aCorrected(),
                mrc.find260bCorrected(), mrc.find260c());
        @SuppressWarnings("unused")
        InputStream dcStream = null;
        @SuppressWarnings("unused")
        boolean dcSuccess = true;
        try {
            dcStream = RESTHelper.get(url + OAI_METADATA_PREFIX, null, null, false);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            dcSuccess = false;
        }
        Document dcDoc = Dom4jUtils.transformDocument(marcDoc, marc2dc);
        //            Document dcDoc = Dom4jUtils.loadDocument(dcStream, true);
        Document modsDoc = Dom4jUtils.transformDocument(marcDoc, marc2mods);

        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(marcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(dcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(modsDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");

        Element dcElement = (Element) dcXPath.selectSingleNode(dcDoc);
        final DublinCore dc = DCUtils.getDC(DocumentHelper.createDocument(dcElement.createCopy()).asXML());
        dc.removeTrailingSlash();
        if (dc != null && dc.getTitle() != null && dc.getTitle().size() != 0 && dc.getTitle().get(0) != null
                && "".equals(dc.getTitle().get(0).trim())) {
            dc.addTitle("no title");
        }
        ModsType mods = BiblioModsUtils.getMods(XMLUtils.parseDocument(modsDoc.asXML(), true));
        final ModsCollection modsC = new ModsCollection();
        modsC.setMods(Arrays.asList(mods));
        MetadataBundle bundle = new MetadataBundle(dc, BiblioModsUtils.toModsClient(modsC), marcSpecific);
        retList.add(bundle);
        return retList;
    } catch (ParserConfigurationException e) {
        LOGGER.error(e.getMessage());
    } catch (SAXException e) {
        LOGGER.error(e.getMessage());
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return retList;
}

From source file:cz.mzk.editor.server.metadataDownloader.OAIPMHClientImpl.java

License:Open Source License

@Override
public ArrayList<MetadataBundle> search(String url, String base) {
    ArrayList<MetadataBundle> retList = new ArrayList<MetadataBundle>();
    try {/*w ww  .  ja  v  a2  s .  c  om*/
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (marc2mods == null) {
            if (!new File(config.getEditorHome() + MARC_TO_MODS_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_MODS_XSLT + " does not exist.");
                return retList;
            }
            marc2mods = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_MODS_XSLT), true);
        }
        InputStream marcStream = RESTHelper.get(url + MARC_METADATA_PREFIX, null, null, false);

        if (marc2dc == null) {
            if (!new File(config.getEditorHome() + MARC_TO_DC_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_DC_XSLT + " does not exist.");
                return retList;
            }
            marc2dc = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_DC_XSLT), true);
        }

        if (!checkAndReplace(marc2mods, false))
            checkAndReplace(marc2dc, true);

        //            StringWriter writer = new StringWriter();
        //            IOUtils.copy(marcStream, writer, "UTF-8");
        //            String theString = writer.toString();
        //            System.out.println(theString);

        Document marcDoc = Dom4jUtils.loadDocument(marcStream, true);
        if (marcDoc.asXML().contains("idDoesNotExist") || marcDoc.asXML().contains("cannotDisseminateFormat")) {
            return retList;
        }

        MarcDocument mrc = new MarcDocument(marcDoc);
        MarcSpecificMetadata marcSpecific = new MarcSpecificMetadata(mrc.findSysno(), base, mrc.find040a(),
                mrc.find080a(), mrc.find650a(), mrc.find260aCorrected(), mrc.find260bCorrected(),
                mrc.find260c(), mrc.find910b());
        @SuppressWarnings("unused")
        InputStream dcStream = null;
        @SuppressWarnings("unused")
        boolean dcSuccess = true;
        try {
            dcStream = RESTHelper.get(url + OAI_METADATA_PREFIX, null, null, false);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            dcSuccess = false;
        }
        Document dcDoc = Dom4jUtils.transformDocument(marcDoc, marc2dc);
        //            Document dcDoc = Dom4jUtils.loadDocument(dcStream, true);
        Document modsDoc = Dom4jUtils.transformDocument(marcDoc, marc2mods);

        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(marcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(dcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(modsDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");

        Element dcElement = (Element) dcXPath.selectSingleNode(dcDoc);
        final DublinCore dc = DCUtils.getDC(DocumentHelper.createDocument(dcElement.createCopy()).asXML());
        dc.removeTrailingSlash();
        if (dc != null && dc.getTitle() != null && dc.getTitle().size() != 0 && dc.getTitle().get(0) != null
                && "".equals(dc.getTitle().get(0).trim())) {
            dc.addTitle("no title");
        }
        ModsType mods = BiblioModsUtils.getMods(XMLUtils.parseDocument(modsDoc.asXML(), true));
        final ModsCollection modsC = new ModsCollection();
        modsC.getMods().addAll(Arrays.<ModsType>asList(mods));
        MetadataBundle bundle = new MetadataBundle(dc, BiblioModsUtils.toModsClient(modsC), marcSpecific);
        retList.add(bundle);
        return retList;
    } catch (ParserConfigurationException e) {
        LOGGER.error(e.getMessage());
    } catch (SAXException e) {
        LOGGER.error(e.getMessage());
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return retList;
}

From source file:de.innovationgate.wgpublisher.WebTMLDebugger.java

License:Open Source License

private void showTMLTags(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws HttpErrorException, IOException {
    String urlStr = request.getParameter("url");
    String indexStr = request.getParameter("index");

    if (urlStr != null) {
        urlStr = _dispatcher.getCore().getURLEncoder().decode(urlStr);
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        Document debugDoc;//from   w  w w .j  av  a2  s  .c o m
        for (int idx = 0; idx < debugDocuments.size(); idx++) {
            debugDoc = (Document) debugDocuments.get(idx);
            if (debugDoc.getRootElement().attributeValue("url", "").equals(urlStr)) {
                indexStr = String.valueOf(idx);
                break;
            }
        }
    }

    response.setContentType("text/html");

    if (indexStr != null) {
        int index = Integer.valueOf(indexStr).intValue();
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        if (index == -1) {
            index = debugDocuments.size() - 1;
        }
        if (index >= debugDocuments.size()) {
            throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                    "Index out of range: " + index + " where maximum index is " + (debugDocuments.size() - 1),
                    null);
        } else {
            Document doc = (Document) debugDocuments.get(index);
            Element element = (Element) doc.selectSingleNode(request.getParameter("root"));
            doc = DocumentFactory.getInstance().createDocument(element.createCopy());
            doc.getRootElement().addAttribute("index", String.valueOf(index));

            try {
                DOMWriter domWriter = new DOMWriter();
                org.w3c.dom.Document domDocument = domWriter.write(doc);

                Transformer trans = getDebugTagsTransformer(request.getParameter("throwAway") != null);
                trans.transform(new DOMSource(domDocument), new StreamResult(response.getOutputStream()));
            } catch (TransformerConfigurationException e) {
                response.sendError(500, e.getMessageAndLocation());
                e.printStackTrace();
            } catch (TransformerFactoryConfigurationError e) {
                response.sendError(500, e.getMessage());
                e.printStackTrace();
            } catch (TransformerException e) {
                response.sendError(500, e.getMessageAndLocation());
                e.printStackTrace();
            } catch (IOException e) {
                response.sendError(500, e.getMessage());
                e.printStackTrace();
            } catch (DocumentException e) {
                response.sendError(500, e.getMessage());
                e.printStackTrace();
            }
        }
    } else {
        throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                "You must include either parameter index or url to address the debug document to show", null);
    }
}

From source file:dk.netarkivet.deploy.Parameters.java

License:Open Source License

/**
 * Constructor. Inherits the parameters of the parent instance.
 *
 * @param parent The parameters of the parent instance.
 * @throws ArgumentNotValid If the parent is null.
 */// www . j a  va 2  s .c om
public Parameters(Parameters parent) throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(parent, "Parameter parent");
    // copy parent class paths
    classPaths = new ArrayList<Element>();
    for (Element e : parent.classPaths) {
        classPaths.add(e.createCopy());
    }
    // copy parent java options
    javaOptions = new ArrayList<Element>();
    for (Element e : parent.javaOptions) {
        javaOptions.add(e.createCopy());
    }
    // copy parent install dir (if any)
    if (parent.installDir != null) {
        installDir = parent.installDir.createCopy();
    }
    // copy parent install dir (if any)
    if (parent.machineUserName != null) {
        machineUserName = parent.machineUserName.createCopy();
    }
    // copy parent harvest database dir (if any)
    if (parent.hdDatabaseDir != null) {
        hdDatabaseDir = parent.hdDatabaseDir.createCopy();
    }
    // copy the parent archive database dir (if any)
    if (parent.arcDatabaseDir != null) {
        arcDatabaseDir = parent.arcDatabaseDir.createCopy();
    }
}

From source file:dk.netarkivet.deploy.XmlStructure.java

License:Open Source License

/**
 * Constructor. Creating a new instance of this data-structure from the branch of another instance.
 *
 * @param subTreeRoot The root of the tree for this instance
 *//*from  w  w w.j  a v a2s  .  c  om*/
public XmlStructure(Element subTreeRoot) {
    ArgumentNotValid.checkNotNull(subTreeRoot, "Element tree");
    root = subTreeRoot.createCopy();
}

From source file:dk.netarkivet.deploy.XmlStructure.java

License:Open Source License

/**
 * The current tree will be overwritten by the overwriter tree. The new branches in overwriter will be added to the
 * current tree. For the leafs which are present in both overwriter and current, the value in the current-leaf will
 * be overwritten by the overwriter-leaf.
 * <p>/*from www.java  2  s.  c o m*/
 * The subtrees which exists in both the overwriter and the current tree, this function will be run recursively on
 * these subtrees.
 *
 * @param current The base element
 * @param overwriter The element to have its values overwrite the base element
 * @throws IllegalState If a leaf in current is about to be replaced by a tree
 */
@SuppressWarnings("unchecked")
private void overWriting(Element current, Element overwriter) throws IllegalState {
    ArgumentNotValid.checkNotNull(current, "Element current");
    ArgumentNotValid.checkNotNull(overwriter, "Element overwriter");
    // get the attributes to be overwritten
    List<Element> attributes = overwriter.elements();
    List<Element> addElements = new ArrayList<Element>();

    // add branch if it does not exists
    for (Element e : attributes) {
        // find corresponding attribute in current element
        List<Element> curElems = current.elements(e.getName());

        // if no such elements in current tree, add branch.
        if (curElems.isEmpty()) {
            addElements.add(e);
        } else {
            //
            List<Element> overElems = overwriter.elements(e.getName());

            // if the lists have a 1-1 ratio, then overwrite
            if (curElems.size() == 1 && overElems.size() == 1) {
                // only one branch, thus overwrite
                Element curE = curElems.get(0);
                // if leaf overwrite value, otherwise repeat for branches.
                if (curE.isTextOnly()) {
                    curE.setText(e.getText().trim()); // TODO Is this necessary
                } else {
                    overWriting(curE, e);
                }
            } else {
                // a different amount of current branches exist (not 0).
                // Therefore remove the branches in current tree,
                // and add replacements.
                for (Element curE : curElems) {
                    current.remove(curE);
                }
                // add only current branch, since the others will follow.
                addElements.add(e);
            }
        }
    }

    // add all the new branches to the current branch.
    for (Element e : addElements) {
        current.add(e.createCopy());
    }
}

From source file:gjset.server.game.GameController.java

License:Open Source License

/**
 * //w  ww.  ja v a 2 s  .  co m
 * process the indicated message from the server.
 *
 * @param message
 */
private void processMessage(ServerMessage message) {
    // Start by getting the player id.
    int playerId = message.client.getPlayerId();

    // Now see if this was a command.
    Element responseElement = null;
    Element commandElement = message.rootElement.element("command");
    if (commandElement != null) {
        String commandType = commandElement.attributeValue("type", "");
        if (commandType.equals("drawcards")) {
            responseElement = requestDrawCards(playerId);
        } else if (commandType.equals("callset")) {
            responseElement = callSet(playerId);
        } else if (commandType.equals("selectcard")) {
            Element cardElement = commandElement.element("card");
            Card card = new Card(cardElement);
            responseElement = toggleSelection(playerId, card);
        } else if (commandType.equals("joinasplayer")) {
            // This is an initialization message.
            String username = commandElement.element("username").getText();

            responseElement = bindClient(message.client, username);
        } else if (commandType.equals("startgame")) {
            // For now, we'll just automatically start the game.
            startNewGame();
        } else if (commandType.equals("dropout")) {
            handleDropOut(message.client);
        }
    }

    // See if we need to send a response to the player.
    if (responseElement != null) {
        // Add the original command so that the client can cross reference it, if necessary.
        responseElement.add(commandElement.createCopy());

        // Send the result back to the player that sent it in.
        message.client.sendMessage(responseElement);

        // Check to see if we need to update all players with new data.
        String result = responseElement.attributeValue("result", "false");
        if (result.equals("success")) {
            updateAllPlayers();
        }
    }
}

From source file:gjset.server.game.GameController.java

License:Open Source License

/**
 * send game updates to all of the players.
 *
 *///from  w ww .  j  a v  a 2 s . co  m
private void updateAllPlayers() {
    // Start by building the update XML.
    Element gameUpdate = model.getUpdateRepresentation();

    List<PlayerClientHandler> clients = server.getClients();
    Iterator<PlayerClientHandler> iterator = clients.iterator();

    while (iterator.hasNext()) {
        PlayerClientHandler client = iterator.next();
        client.sendMessage(gameUpdate.createCopy());
    }

}