List of usage examples for org.dom4j Element add
void add(Namespace namespace);
Namespace
to this element. From source file:net.windward.Acquire.Framework.java
License:BEER-WARE LICENSE
public final void IncomingMessage(String message) throws DocumentException, IOException { try {//from w w w. j av a2s . c o m 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 {/*ww w .ja v a 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 w ww. j a va2 s . com // 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 .j a v a 2 s . c o 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.ru.cmbi.vase.parse.VASEXMLParser.java
License:Apache License
public static void write(VASEDataObject data, OutputStream xmlOut) throws IOException { DocumentFactory df = DocumentFactory.getInstance(); Document doc = df.createDocument(); Element root = doc.addElement("xml"); if (data.getTitle() != null) { Element title = root.addElement("title"); title.setText(data.getTitle());// w w w . j a v a 2 s . c o m } Element fasta = root.addElement("fasta"); ByteArrayOutputStream fastaStream = new ByteArrayOutputStream(); FastaParser.toFasta(data.getAlignment().getMap(), fastaStream); fasta.add(df.createCDATA(new String(fastaStream.toByteArray(), StandardCharsets.UTF_8))); Element pdb = root.addElement("pdb"); pdb.addAttribute("pdbid", data.getPdbID()); table2xml(data.getTable(), root); if (data.getPlots().size() > 0) { Element plots = root.addElement("plots"); for (PlotDescription pd : data.getPlots()) { Element plot = plots.addElement("plot"); plot.addElement("x").setText(pd.getXAxisColumnID()); plot.addElement("y").setText(pd.getYAxisColumnID()); plot.addAttribute("title", pd.getPlotTitle()); } } XMLWriter writer = new XMLWriter(xmlOut); writer.write(doc); writer.close(); }
From source file:nl.tue.gale.ae.grapple.CourseListService.java
License:Open Source License
private Element createIMSLIP(Concept c) { DocumentFactory df = DocumentFactory.getInstance(); Element sourcedid = df.createElement("sourcedid"); Element result = df.createElement("activity"); Element contentype = result.addElement("contentype"); contentype.addElement("referential").add(sourcedid); sourcedid.addElement("source").addText(galeConfig.getRootGaleUrl() + c.getUriString()); sourcedid.addElement("id").addText(c.getTitle()); String camguid = c.getProperty("cam.model.guid"); if (camguid != null && !"".equals(camguid)) { Element field = contentype.addElement("temporal").addElement("temporalfield"); field.addElement("fieldlabel").addElement("typename").addElement("tyvalue").addText("camguid"); field.addElement("fielddata").addText(camguid); }// w ww. ja v a2s . co m return result; }
From source file:nl.tue.gale.ae.processor.CSSLayoutProcessor.java
License:Open Source License
public void processResource(Resource resource) throws ProcessorException { if (resource.isUsed("xml") || resource.isUsed("response")) return;/*from w w w. java2 s.c o m*/ // skip this processor for objects GaleContext gale = GaleContext.of(resource); if (gale.isObject()) return; String cssLayout = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/presentation#cssLayout", resource); if (cssLayout == null) return; Element xml = gale.xml(); Element body = xml.element("body"); if (body == null) body = xml; Element div = GaleUtil.createHTMLElement("div").addAttribute("id", "gale-content"); @SuppressWarnings("unchecked") List<Node> content = (List<Node>) body.content(); for (Node n : ImmutableList.copyOf(content)) { content.remove(n); div.add(n); } content.add(div); Element cssElement = GaleUtil.parseXML(new StringReader(cssLayout)).getRootElement(); content.add(0, cssElement); resource.put("serialize-xhtml-strict", "true"); }
From source file:nl.tue.gale.ae.processor.FrameLayoutProcessor.java
License:Open Source License
public void processResource(Resource resource) throws ProcessorException { if (resource.isUsed("request")) return;// w w w.j a v a 2 s. c om GaleContext gale = GaleContext.of(resource); // skip this processor for objects if (gale.isObject()) return; // check if this is a call for a frame or the actual content if ("true".equals(gale.req().getParameter("frame"))) { Attribute target = GaleUtil.createHTMLElement("a").addAttribute("target", "_parent") .attribute("target"); resource.put("nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.content", target); resource.put("nl.tue.gale.ae.processor.UpdateProcessor.noUpdate", "true"); return; } // this is a call for the frame Element layoutConfig = (Element) gale.cfgm().getObject("gale://gale.tue.nl/config/presentation#layout", resource); if (layoutConfig == null) return; Element html = GaleUtil.createHTMLElement("html"); Element body = html.addElement("body").addAttribute("style", "margin:0px;padding:0px;"); body.add(layoutConfig); layoutConfig = processLayoutConfig(layoutConfig); String url = GaleUtil.getRequestURL(gale.req()); UrlEncodedQueryString qs = UrlEncodedQueryString.parse(URIs.of(url)); qs.append("frame", "true"); qs.remove("framewait"); Element iframe = GaleUtil.createHTMLElement("iframe").addAttribute("src", qs.apply(URIs.of(url)).toString()); iframe.addAttribute("width", "100%"); iframe.addAttribute("height", "100%"); iframe.addAttribute("frameborder", "0"); Element content = GaleUtil.findElement(layoutConfig, "gale-layoutprocessor-placeholder"); GaleUtil.replaceNode(content, iframe); try { resource.put("url", new URL(url)); } catch (MalformedURLException e) { e.printStackTrace(); } resource.put("original-url", url); resource.put("mime", "text/xhtml"); resource.put("xml", html); resource.put("layout", "true"); try { if (!"true".equals(gale.req().getParameter("no-update"))) gale.em().fireEvent("access", gale.dm().get(gale.conceptUri()), resource); } catch (Exception e) { throw new ProcessorException("unable to update profile for '" + gale.conceptUri() + "'", e); } gale.usedRequest(); }
From source file:nl.tue.gale.ae.processor.FrameLayoutProcessor.java
License:Open Source License
@SuppressWarnings("unchecked") static Element processLayoutConfig(Element layoutConfig) { if (layoutConfig.getName().equals("view")) { layoutConfig.setQName(//from w w w.j a v a 2 s .c o m DocumentFactory.getInstance().createQName("view", "", "http://gale.tue.nl/adaptation")); } else if (layoutConfig.getName().equals("struct")) { Element table = GaleUtil.createHTMLElement("table").addAttribute("cellspacing", "0") .addAttribute("cellpadding", "3").addAttribute("width", "100%").addAttribute("height", "100%") .addAttribute("border", "0"); boolean rows = layoutConfig.attributeValue("rows") != null; String attrname = (rows ? "height" : "width"); String[] sizes = (rows ? layoutConfig.attributeValue("rows").split(";") : layoutConfig.attributeValue("cols").split(";")); Element tr = null; if (!rows) { tr = GaleUtil.createHTMLElement("tr"); table.add(tr); } int i = 0; List<Element> elist = new LinkedList<Element>(); elist.addAll(layoutConfig.elements()); for (Element child : elist) { if (rows) { tr = GaleUtil.createHTMLElement("tr"); table.add(tr); } Element td = GaleUtil.createHTMLElement("td").addAttribute("valign", "top") .addAttribute(attrname, sizes[i]).addAttribute("style", "border-style:none"); tr.add(td); child = processLayoutConfig(child); child.detach(); td.add(child); i++; } return (Element) GaleUtil.replaceNode(layoutConfig, table); } else if (layoutConfig.getName().equals("content")) { layoutConfig.setQName(DocumentFactory.getInstance().createQName("gale-layoutprocessor-placeholder")); } else { for (Element child : (List<Element>) layoutConfig.elements()) processLayoutConfig(child); } return layoutConfig; }
From source file:nl.tue.gale.ae.processor.plugin.CommentsPlugin.java
License:Open Source License
@Override public void doGet(Resource resource) throws ProcessorException { GaleContext gale = GaleContext.of(resource); List<Comment> comments = new ArrayList<Comment>(); for (EntityValue ev : getComments(gale)) { String[] values = (String[]) ev.getValue(); for (String value : values) comments.add(Comment.parse(value)); }//from w ww.ja v a2 s. c o m Collections.sort(comments); String url = GaleUtil.getRequestURL(gale.req()); Element html = GaleUtil.createHTMLElement("html"); Element body = html.addElement("body"); if (gale.userId().equals(gale.concept().getProperty("author"))) body.add(createAuthorOptions(gale)); Element div = body.addElement("div").addAttribute("class", "comment"); Element form = div.addElement("form").addAttribute("method", "POST").addAttribute("action", url) .addAttribute("style", "margin:0").addAttribute("id", "newcomment"); form.addElement("a").addAttribute("href", "#") .addAttribute("onClick", "document.forms['newcomment'].submit(); return false;") .addAttribute("class", "comment-submit good").addText("submit"); form.addElement("span").addAttribute("class", "comment-name").addText(findName(gale, gale.userId())); form.addElement("span").addAttribute("class", "comment-text").addElement("textarea") .addAttribute("name", "comment").addAttribute("rows", "10"); boolean dimComments = (comments.size() > 0 && comments.get(0).getUserId().equals(gale.userId()) ? true : false); for (Comment comment : comments) { Element cdiv = body.addElement("div").addAttribute("class", (dimComments ? "comment comment-read" : "comment")); cdiv.addElement("span").addAttribute("class", "comment-time").addText(comment.getDateString()); cdiv.addElement("span").addAttribute("class", "comment-name") .addText(findName(gale, comment.getUserId())); cdiv.add(createCommentText(comment.getValue())); } resource.put("xml", html); resource.put("mime", "text/xhtml"); resource.put("original-url", gale.conceptUri().toString()); try { resource.put("url", gale.conceptUri().toURL()); } catch (MalformedURLException e) { } gale.usedStream(); }