List of usage examples for org.dom4j DocumentHelper createAttribute
public static Attribute createAttribute(Element owner, String name, String value)
From source file:net.windward.Acquire.Framework.java
License:BEER-WARE LICENSE
public final void IncomingMessage(String message) throws DocumentException, IOException { try {//from w ww . j av a 2 s .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.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 ava 2s.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:nz.co.senanque.schemaparser.SchemaVisitorDom4j.java
License:Apache License
@Override public void initialize(String xsdpackageName, String targetNamespace) { Element root = document.addElement(rootName); Namespace xsi = DocumentHelper.createNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); root.add(xsi);//from w ww . j a v a2s . co m if (targetNamespace != null) { Namespace tns = DocumentHelper.createNamespace("tns", targetNamespace); root.add(tns); QName schemaLocation = DocumentHelper.createQName("schemaLocation", xsi); Attribute attribute = DocumentHelper.createAttribute(root, schemaLocation, targetNamespace + " " + location + " " + rootName.getNamespaceURI() + " " + rootLocation); root.add(attribute); } elements.push(root); }
From source file:org.craftercms.core.processors.impl.AttributeAddingProcessor.java
License:Open Source License
protected void addAttribute(Map.Entry<String, String> attribute, Element element) { String name = attribute.getKey(); String value = attribute.getValue(); if (logger.isDebugEnabled()) { logger.debug("Adding attribute " + name + "=" + value + " to element " + element.getUniquePath()); }// ww w .j ava2 s. c om element.add(DocumentHelper.createAttribute(element, name, value)); }
From source file:org.neuclear.asset.orders.TransferGlobals.java
License:Open Source License
public static Attribute createAttribute(final Element elem, final String name, final String value) { return DocumentHelper.createAttribute(elem, createQName(name), value); }
From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java
License:Open Source License
private Object modify(Node node, Attribute attribute) { Object old = null;/*from w ww. j a va 2s .c o m*/ if (node instanceof Element) { //Set or replace value of attribute on Element Element element = (Element) node; String attrName = attribute.getName(); Attribute existing = element.attribute(attrName); if (existing != null) { element.remove(existing); old = existing; } element.add(attribute); } else if (node instanceof Attribute) { //Modify the value of the existing attribute. Attribute existing = (Attribute) node; old = DocumentHelper.createAttribute(null, existing.getName(), existing.getValue()); existing.setValue(attribute.getValue()); } else { throw new RecordException( "Target of put(x,Attribute) must be empty or an existing Element or Attribute. Got: " + node); } return old; }
From source file:org.openadaptor.util.XmlUtils.java
License:Open Source License
public static org.dom4j.Node create(String xpath, org.dom4j.Document document) { org.dom4j.Node result = null; LocationPath lp = getLocationPath(xpath); if (lp != null) { List steps = lp.getSteps(); Step lastStep = removeLeaf(steps); String parentXpath = toXPath(steps, lp.isAbsolute()); //log.debug("Parent XPath: "+parentXpath); org.dom4j.Node parent = document.selectSingleNode(parentXpath); if (parent == null) { //log.debug("Parent does not exist, need to recursively create "); parent = create(parentXpath, document); }/*from w w w . ja v a 2 s. co m*/ if (parent == null) { //Have to give up. throw new RuntimeException("Failed to create node for xpath: " + xpath); } else { //log.debug("Parent exists. Now need to add the last bit:" +lastStep.getText()); //log.debug("Axis is: "+Axis.lookup(lastStep.getAxis())); String txt = lastStep.getText(); String name = txt.substring(txt.indexOf("::") + "::".length()); //+1 since "::" is two chars long. if (parent instanceof Element) { Element parentElement = (Element) parent; switch (lastStep.getAxis()) { case Axis.ATTRIBUTE: Attribute newAttribute = DocumentHelper.createAttribute(null, name, ""); parentElement.add(newAttribute); result = newAttribute; break; default: Element element = DocumentHelper.createElement(name); parentElement.add(element); result = element; break; } } else { throw new RuntimeException("Cannot create child of non-Element parent. XPath was: " + xpath); } } } else { throw new RuntimeException("Failed to resolve XPath String: " + xpath); } return result; }
From source file:org.pentaho.platform.plugin.adhoc.AdhocWebServiceInteractXml.java
License:Open Source License
public static Document convertXml(final Document reportXml) { // get the list of headers List<String> headerList = new ArrayList<String>(); List<?> nodes = reportXml.selectNodes("/report/groupheader/@name"); //$NON-NLS-1$ // find all the unique group header names Iterator<?> it = nodes.iterator(); Attribute attr;/* w w w. jav a2 s . c om*/ String name; while (it.hasNext()) { // we only need to go until we get the first duplicate attr = (Attribute) it.next(); name = attr.getText(); if (!"dummy".equals(name)) { //$NON-NLS-1$ if (!headerList.contains(name)) { headerList.add(name); System.out.println(name); } else { break; } } } String headerNames[] = new String[headerList.size()]; String headerValues[] = new String[headerList.size()]; Element headerNodes[] = new Element[headerList.size()]; String columnHeaders[] = new String[0]; Element columnHeaderNodes[] = new Element[0]; headerList.toArray(headerNames); for (int idx = 0; idx < headerValues.length; idx++) { headerValues[idx] = ""; //$NON-NLS-1$ } Document reportDoc = DocumentHelper.createDocument(); Element reportNode = DocumentHelper.createElement("report"); //$NON-NLS-1$ reportDoc.setRootElement(reportNode); // process the top-level nodes nodes = reportXml.selectNodes("/report/*"); //$NON-NLS-1$ Node node; // go thru all the nodes it = nodes.iterator(); while (it.hasNext()) { node = (Node) it.next(); name = node.getName(); if ("groupheader".equals(name)) { //$NON-NLS-1$ // process the group headers // get the group header name String headerName = node.selectSingleNode("@name").getText(); //$NON-NLS-1$ if (!"dummy".equals(headerName)) { //$NON-NLS-1$ // find the header index String headerValue = node.selectSingleNode("element[1]").getText();//$NON-NLS-1$ int headerIdx = -1; for (int idx = 0; idx < headerNames.length; idx++) { if (headerNames[idx].equals(headerName)) { headerIdx = idx; break; } } if (!headerValues[headerIdx].equals(headerValue)) { // this is a new header value headerValues[headerIdx] = headerValue; // find the parent node Element parentNode; if (headerIdx == 0) { parentNode = reportNode; } else { parentNode = headerNodes[headerIdx - 1]; } // create a group header node for this Element headerNode = DocumentHelper.createElement("groupheader");//$NON-NLS-1$ parentNode.add(headerNode); headerNodes[headerIdx] = headerNode; // create the name attribute attr = DocumentHelper.createAttribute(headerNode, "name", headerName);//$NON-NLS-1$ headerNode.add(attr); // create the value node Element elementNode = DocumentHelper.createElement("element");//$NON-NLS-1$ headerNode.add(elementNode); attr = DocumentHelper.createAttribute(elementNode, "name", headerName);//$NON-NLS-1$ elementNode.add(attr); elementNode.setText(headerValue); } } // see if there are any column headers List<?> elements = node.selectNodes("element");//$NON-NLS-1$ if (elements.size() == 0) { elements = node.selectNodes("band/element");//$NON-NLS-1$ } if (elements.size() > 1) { // there are column headers here, get them and store them for the next set of rows columnHeaders = new String[elements.size() - 1]; columnHeaderNodes = new Element[elements.size() - 1]; for (int idx = 1; idx < elements.size(); idx++) { columnHeaders[idx - 1] = ((Element) elements.get(idx)).getText(); } } } else if ("items".equals(name)) {//$NON-NLS-1$ // process items (rows) // get the parent node, this should always be the last one on the list Element parentNode; if (headerNodes.length == 0) { parentNode = reportNode; } else { parentNode = headerNodes[headerNodes.length - 1]; } // create the items node Element itemsNode = DocumentHelper.createElement("items");//$NON-NLS-1$ parentNode.add(itemsNode); // create the headers node Element headersNode = DocumentHelper.createElement("headers");//$NON-NLS-1$ itemsNode.add(headersNode); // create the rows node Element itemBandsNode = DocumentHelper.createElement("itembands");//$NON-NLS-1$ itemsNode.add(itemBandsNode); for (int idx = 0; idx < columnHeaders.length; idx++) { Element headerNode = DocumentHelper.createElement("header");//$NON-NLS-1$ headerNode.setText(columnHeaders[idx]); headersNode.add(headerNode); columnHeaderNodes[idx] = headerNode; } // now copy the item bands over List<?> itembands = node.selectNodes("itemband");//$NON-NLS-1$ Iterator<?> bands = itembands.iterator(); boolean first = true; while (bands.hasNext()) { Element itemband = (Element) bands.next(); Element itemBandNode = DocumentHelper.createElement("itemband");//$NON-NLS-1$ itemBandsNode.add(itemBandNode); List<?> elementList = itemband.selectNodes("element");//$NON-NLS-1$ Iterator<?> elements = elementList.iterator(); int idx = 0; while (elements.hasNext()) { Element element = (Element) elements.next(); Element elementNode = DocumentHelper.createElement("element");//$NON-NLS-1$ itemBandNode.add(elementNode); elementNode.setText(element.getText()); name = element.selectSingleNode("@name").getText();//$NON-NLS-1$ if (name.endsWith("Element")) {//$NON-NLS-1$ name = name.substring(0, name.length() - "Element".length());//$NON-NLS-1$ } attr = DocumentHelper.createAttribute(elementNode, "name", name);//$NON-NLS-1$ elementNode.add(attr); if (first) { // copy the item name over to the column header attr = DocumentHelper.createAttribute(columnHeaderNodes[idx], "name", name);//$NON-NLS-1$ columnHeaderNodes[idx].add(attr); } idx++; } first = false; } } } return reportDoc; }