Example usage for org.dom4j Document add

List of usage examples for org.dom4j Document add

Introduction

In this page you can find the example usage for org.dom4j Document add.

Prototype

void add(Node node);

Source Link

Document

Adds the given Node or throws IllegalAddException if the given node is not of a valid type.

Usage

From source file:com.thoughtworks.go.server.domain.xml.UsersXmlViewModel.java

License:Apache License

public Document toXml(XmlWriterContext writerContext) throws DocumentException, IOException {
    Document document = new DOMDocument();
    document.add(rootUsersNodeWithChildNodesFor(users));
    return document;
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlCollectionSerializer.java

License:BSD License

public Document createDocument(Collection<R> rs) {
    Document document = DocumentHelper.createDocument();
    Element element = createCollectionRootElement();

    for (R r : rs) {
        element.add(createElement(r, true));
    }/*from  w w  w . j  a  v  a2 s  . co  m*/

    configureRootElement(element);

    document.add(element);

    return document;
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer.java

License:BSD License

public Document createDocument(R root) {
    Document document = DocumentHelper.createDocument();
    Element element = createElement(root);

    configureRootElement(element);// w  ww.j  a v a 2  s . c  o  m

    document.add(element);

    return document;
}

From source file:fr.gouv.culture.vitam.extract.ExtractInfo.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("need file as target");
        return;//from   ww w . j  av a 2  s . c  om
    }
    StaticValues.initialize();
    Document document = DocumentFactory.getInstance().createDocument(StaticValues.CURRENT_OUTPUT_ENCODING);
    Element root = DocumentFactory.getInstance().createElement("extractkeywords");
    document.add(root);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(StaticValues.CURRENT_OUTPUT_ENCODING);
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(System.out, format);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return;
    }
    for (String string : args) {
        File file = new File(string);
        recursive(file, string, root, StaticValues.config, writer);
    }
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        try {
            writer.write(document);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.mashin.oep.model.Workflow.java

License:Open Source License

@Override
public void write(org.dom4j.Element parent) {
    Document document = parent.getDocument();
    parent.detach();/*w w  w .ja v  a2  s . c  om*/

    Element rootElement = document.addElement("workflow-app");
    Element graphicalInfoElement = DocumentHelper.createElement("workflow");

    XMLWriteUtils.writeWorkflowSchemaVersion(getSchemaVersion(), rootElement);
    XMLWriteUtils.writeSLAVersion(this, rootElement);
    XMLWriteUtils.writeTextPropertyAsAttribute(name, rootElement, "name");
    XMLWriteUtils.writePropertiesCollection(parameters, rootElement, "parameters", "property");
    XMLWriteUtils.writeGlobalProperty(global, rootElement);
    XMLWriteUtils.writeCredentialsCollection(credentials, rootElement);

    startNode.write(rootElement);
    for (Node node : nodes) {
        if (!(node.equals(startNode) || node.equals(endNode))) {
            node.write(rootElement);
        }
        graphicalInfoElement.addElement("node").addAttribute("name", node.getName())
                .addAttribute("x", node.getPosition().x + "").addAttribute("y", node.getPosition().y + "");
    }
    endNode.write(rootElement);

    XMLWriteUtils.writeSLAProperty(this, sla, rootElement);

    Comment graphicalInfoNode = null;
    try {
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
        writer.write(graphicalInfoElement);
        writer.flush();
        graphicalInfoNode = DocumentHelper.createComment(stringWriter.toString());
    } catch (Exception e) {
        graphicalInfoNode = DocumentHelper.createComment(graphicalInfoElement.asXML());
    }
    document.add(graphicalInfoNode);
}

From source file:net.windward.Acquire.Framework.java

License:BEER-WARE LICENSE

public final void IncomingMessage(String message) throws DocumentException, IOException {

    try {//  ww  w  . ja va  2  s  .c om
        long startTime = System.currentTimeMillis();
        // get the xml - we assume we always get a valid message from the server.
        SAXReader reader = new SAXReader();
        Document xml = reader.read(new StringReader(message));

        String rootName = xml.getRootElement().getName();

        if (rootName.equals("setup")) {
            System.out.println("Received setup message");
            if (log.isInfoEnabled())
                log.info("Recieved setup message");

            myGuid = xml.getRootElement().attribute("my-guid").getValue();
            Element elemMap = xml.getRootElement().element("map");
            GameMap map = new GameMap(Integer.parseInt(elemMap.attribute("width").getValue()),
                    Integer.parseInt(elemMap.attribute("height").getValue()));

            DataObjects dataSetup = xmlToData(xml);

            brain.Setup(map, dataSetup.me, dataSetup.hotels, dataSetup.players);

            // say ready
            Document docSetup = DocumentHelper.createDocument();
            Element elem = DocumentHelper.createElement("ready");
            docSetup.add(elem);
            tcpClient.SendMessage(docSetup.asXML());
        }

        else if (rootName.equals("query-card")) {
            DataObjects dataQuery = xmlToData(xml);
            int card = brain.QuerySpecialPowerBeforeTurn(dataQuery.map, dataQuery.me, dataQuery.hotels,
                    dataQuery.players);

            // send the selected card back
            Document docQueryCard = DocumentHelper.createDocument();
            Element elem = DocumentHelper.createElement("reply");
            docQueryCard.add(elem);
            elem.add(DocumentHelper.createAttribute(elem, "cmd", "query-card"));
            elem.add(DocumentHelper.createAttribute(elem, "msg-id",
                    xml.getRootElement().attribute("msg-id").getValue()));
            elem.add(DocumentHelper.createAttribute(elem, "card", "" + card));
            tcpClient.SendMessage(docQueryCard.asXML());
        }

        else if (rootName.equals("query-tile")) {
            DataObjects dataQueryTile = xmlToData(xml);
            PlayerPlayTile playTile = brain.QueryTileOnly(dataQueryTile.map, dataQueryTile.me,
                    dataQueryTile.hotels, dataQueryTile.players);

            // send the selected tile back
            Document docQueryCard = DocumentHelper.createDocument();
            Element elem = DocumentHelper.createElement("reply");
            docQueryCard.add(elem);
            elem.add(DocumentHelper.createAttribute(elem, "cmd", "query-tile"));
            elem.add(DocumentHelper.createAttribute(elem, "msg-id",
                    xml.getRootElement().attribute("msg-id").getValue()));

            if (playTile != null) {
                if (playTile.tile != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "tile-x", "" + playTile.tile.getX()));
                    elem.add(DocumentHelper.createAttribute(elem, "tile-y", "" + playTile.tile.getY()));
                }
                if (playTile.createdHotel != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "created-hotel",
                            playTile.createdHotel.getName()));
                }
                if (playTile.mergeSurvivor != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "merge-survivor",
                            playTile.mergeSurvivor.getName()));
                }
            }
            tcpClient.SendMessage(docQueryCard.asXML());
        }

        else if (rootName.equals("query-tile-purchase")) {
            DataObjects dataQueryTilePur = xmlToData(xml);
            PlayerTurn playTurn = brain.QueryTileAndPurchase(dataQueryTilePur.map, dataQueryTilePur.me,
                    dataQueryTilePur.hotels, dataQueryTilePur.players);

            // send the selected card back
            Document docQueryCard = DocumentHelper.createDocument();
            Element elem = DocumentHelper.createElement("reply");
            docQueryCard.add(elem);
            elem.add(DocumentHelper.createAttribute(elem, "cmd", "query-tile-purchase"));
            elem.add(DocumentHelper.createAttribute(elem, "msg-id",
                    xml.getRootElement().attribute("msg-id").getValue()));

            if (playTurn != null) {
                elem.add(DocumentHelper.createAttribute(elem, "card", "" + playTurn.getCard()));
                if (playTurn.tile != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "tile-x", "" + playTurn.tile.getX()));
                    elem.add(DocumentHelper.createAttribute(elem, "tile-y", "" + playTurn.tile.getY()));
                }
                if (playTurn.createdHotel != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "created-hotel",
                            playTurn.createdHotel.getName()));
                }
                if (playTurn.mergeSurvivor != null) {
                    elem.add(DocumentHelper.createAttribute(elem, "merge-survivor",
                            playTurn.mergeSurvivor.getName()));
                }
                if (playTurn.getBuy() != null && playTurn.getBuy().size() > 0) {
                    StringBuilder buyStock = new StringBuilder();
                    for (HotelStock stock : playTurn.getBuy())
                        buyStock.append(stock.getChain().getName() + ':' + stock.getNumShares() + ';');
                    elem.add(DocumentHelper.createAttribute(elem, "buy", buyStock.toString()));
                }
                if (playTurn.getTrade() != null && playTurn.getTrade().size() > 0) {
                    StringBuilder tradeStock = new StringBuilder();
                    for (PlayerTurn.TradeStock trade : playTurn.getTrade())
                        tradeStock
                                .append(trade.getTradeIn2().getName() + ':' + trade.getGet1().getName() + ';');
                    elem.add(DocumentHelper.createAttribute(elem, "trade", tradeStock.toString()));
                }
            }
            tcpClient.SendMessage(docQueryCard.asXML());
        }

        else if (rootName.equals("query-merge")) {
            DataObjects dataQueryMerge = xmlToData(xml);

            HotelChain survivor = null;
            for (HotelChain hotel : dataQueryMerge.hotels)
                if (hotel.getName().equals(xml.getRootElement().attribute("survivor").getValue())) {
                    survivor = hotel;
                    break;
                }
            HotelChain defunct = null;
            for (HotelChain hotel : dataQueryMerge.hotels)
                if (hotel.getName().equals(xml.getRootElement().attribute("defunct").getValue())) {
                    defunct = hotel;
                    break;
                }

            PlayerMerge merge = brain.QueryMergeStock(dataQueryMerge.map, dataQueryMerge.me,
                    dataQueryMerge.hotels, dataQueryMerge.players, survivor, defunct);

            // send the selected card back
            Document docQueryMerge = DocumentHelper.createDocument();
            Element elem = DocumentHelper.createElement("reply");
            docQueryMerge.add(elem);
            elem.add(DocumentHelper.createAttribute(elem, "cmd", "query-card"));
            elem.add(DocumentHelper.createAttribute(elem, "msg-id",
                    xml.getRootElement().attribute("msg-id").getValue()));
            if (merge != null) {
                elem.add(DocumentHelper.createAttribute(elem, "keep", "" + merge.getKeep()));
                elem.add(DocumentHelper.createAttribute(elem, "sell", "" + merge.getSell()));
                elem.add(DocumentHelper.createAttribute(elem, "trade", "" + merge.getTrade()));
            }
            tcpClient.SendMessage(docQueryMerge.asXML());
        }

        else if (xml.getRootElement().getName().equals("exit")) {
            System.out.println("Received exit message");
            if (log.isInfoEnabled()) {
                log.info("Received exit message");
            }
            System.exit(0);

        } else {
            String msg = String.format("ERROR: bad message (XML) from server - root node %1$s",
                    xml.getRootElement().getName());
            log.warn(msg);
            //Trace.WriteLine(msg);
        }

        long turnTime = System.currentTimeMillis() - startTime;
        if (turnTime > 800) {
            System.out.println("WARNING - turn took " + turnTime / 1000 + " seconds");

        }
    } catch (RuntimeException ex) {
        System.out.println(String.format("Error on incoming message. Exception: %1$s", ex));
        ex.printStackTrace();
        log.error("Error on incoming message.", ex);
    }
}

From source file:net.windward.Acquire.Framework.java

License:BEER-WARE LICENSE

private void ConnectToServer() throws IOException {
    try {/*from  w  ww. j  a va  2  s.  c  o  m*/
        Document doc = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement("join");
        root.addAttribute("name", brain.getName());
        root.addAttribute("school", MyPlayerBrain.SCHOOL);
        root.addAttribute("language", "Java");

        byte[] data = brain.getAvatar();
        if (data != null) {
            Element avatarElement = DocumentHelper.createElement("avatar");
            BASE64Encoder encoder = new BASE64Encoder();
            avatarElement.setText(encoder.encode(data));
            root.add(avatarElement);
        }

        doc.add(root);

        tcpClient.SendMessage(doc.asXML());
    } catch (Exception e) {
        log.warn("ConnectToServer() threw Exception: " + e.getMessage());
    }
}

From source file:net.windward.Windwardopolis2.Framework.java

License:BEER-WARE LICENSE

private void PlayerOrdersEvent(String order, java.util.ArrayList<Point> path,
        java.util.ArrayList<Passenger> pickUp) {
    try {/*from ww  w  . j a v a  2  s .  c  om*/

        // update our info
        if (path.size() > 0) {
            brain.getMe().getLimo().getPath().clear();
            brain.getMe().getLimo().getPath().addAll(path);
        }
        if (pickUp.size() > 0) {
            brain.getMe().getPickUp().clear();
            brain.getMe().getPickUp().addAll(pickUp);
        }
        Document xml = DocumentHelper.createDocument();
        Element elem = DocumentHelper.createElement(order);
        xml.add(elem);
        if (path.size() > 0) {
            StringBuilder buf = new StringBuilder();
            for (Point ptOn : path) {
                buf.append(String.valueOf(ptOn.x) + ',' + String.valueOf(ptOn.y) + ';');
            }
            Element newElem = DocumentHelper.createElement("path");
            newElem.setText(buf.toString());
            elem.add(newElem);
        }
        if (pickUp.size() > 0) {
            StringBuilder buf = new StringBuilder();
            for (Passenger psngrOn : pickUp) {
                buf.append(psngrOn.getName() + ';');
            }
            Element newElem = DocumentHelper.createElement("pick-up");
            newElem.setText(buf.toString());
            elem.add(newElem);
        }
        try {
            String toSend = xml.asXML();
            tcpClient.SendMessage(toSend);
        } catch (IOException e) {
            System.out.println("bad sent orders event");
            e.printStackTrace();
        }
    } catch (Exception e) {
        log.error("PlayerOrderEvent( " + order + ", ...) threw Exception: " + e.getMessage());
    }
}

From source file:net.windward.Windwardopolis2.Framework.java

License:BEER-WARE LICENSE

private void PlayerPowerSend(PlayerAIBase.CARD_ACTION action, PowerUp powerup) {

    if (log.isInfoEnabled())
        log.info("Request " + action + " " + powerup);

    cardLastPlayed = powerup;//from  ww  w .  ja  va 2s .  co m
    cardLastSendTime = System.currentTimeMillis();

    Document xml = DocumentHelper.createDocument();
    Element elem = DocumentHelper.createElement("order");
    elem.add(DocumentHelper.createAttribute(elem, "action", action.name()));
    Element elemCard = DocumentHelper.createElement("powerup");
    elemCard.add(DocumentHelper.createAttribute(elemCard, "card", powerup.getCard().name()));

    if (powerup.getCompany() != null)
        elemCard.add(DocumentHelper.createAttribute(elemCard, "company", powerup.getCompany().getName()));
    if (powerup.getPassenger() != null)
        elemCard.add(DocumentHelper.createAttribute(elemCard, "passenger", powerup.getPassenger().getName()));
    if (powerup.getPlayer() != null)
        elemCard.add(DocumentHelper.createAttribute(elemCard, "player", powerup.getPlayer().getName()));

    elem.add(elemCard);
    xml.add(elem);
    try {
        String toSend = xml.asXML();
        tcpClient.SendMessage(toSend);
    } catch (IOException e) {
        System.out.println("bad sent orders event");
        e.printStackTrace();
    }
}

From source file:nl.tue.gale.common.XPPEntityReader.java

License:Open Source License

protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = getDocumentFactory();
    Document document = df.createDocument();
    Element parent = null;/*from w  w  w . j a  v a2  s  .c  om*/
    XmlPullParser pp = getXPPParser();
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false);
    defineEntities(pp);

    while (true) {
        int type = pp.nextToken();

        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");

            if (loc >= 0) {
                String target = text.substring(0, loc);
                String txt = text.substring(loc + 1);
                document.addProcessingInstruction(target, txt);
            } else {
                document.addProcessingInstruction(text, "");
            }

            break;
        }

        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }

            break;
        }

        case XmlPullParser.CDSECT: {
            if (parent != null) {
                parent.addCDATA(pp.getText());
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        case XmlPullParser.ENTITY_REF:
            if (parent != null) {
                if (pp.getName().equals("gt")) {
                    parent.addText(">");
                } else if (pp.getName().equals("lt")) {
                    parent.addText("<");
                } else if (pp.getName().equals("amp")) {
                    parent.addText("&");
                } else if (pp.getName().equals("quot")) {
                    parent.addText("\"");
                } else
                    parent.addEntity(pp.getName(), "&" + pp.getName() + ";");
            }
            break;

        case XmlPullParser.END_DOCUMENT:
            return document;

        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = df.createElement(qname);
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());

            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }

            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }

            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }

            parent = newElement;

            break;
        }

        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }

            break;
        }

        case XmlPullParser.TEXT: {
            String text = pp.getText();

            if (parent != null) {
                parent.addText(text);
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        default:
            break;
        }
    }
}