Example usage for org.dom4j DocumentHelper createElement

List of usage examples for org.dom4j DocumentHelper createElement

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createElement.

Prototype

public static Element createElement(String name) 

Source Link

Usage

From source file:net.sf.kraken.roster.TransportBuddy.java

License:Open Source License

/**
 * Returns the entire vcard element for an avatar.
 *
 * This will return a vCard element, filled in as much as possible, regardless of whether we have
 * real data for the user.  It'll return minimal regardless.
 *
 * @return vCard element//w ww . j a  v  a2s .com
 */
public Element getVCard() {
    Element vcard = DocumentHelper.createElement(QName.get("vCard", NameSpace.VCARD_TEMP));

    vcard.addElement("VERSION").addCDATA("2.0");
    vcard.addElement("JABBERID").addCDATA(getJID().toString());
    vcard.addElement("NICKNAME").addCDATA(getNickname() == null ? getName() : getNickname());

    if (JiveGlobals.getBooleanProperty(
            "plugin.gateway." + getManager().getSession().getTransport().getType() + ".avatars", true)) {
        addVCardPhoto(vcard);
    }

    return vcard;
}

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void addNode(Element source, Element replace, String xpath) {
    List list = replace.selectNodes("value");
    if (list == null)
        return;//from w w w .j  ava2  s  .co  m

    Element newContent = DocumentHelper.createElement("newContent");
    Comment prefixComment = DocumentHelper.createComment(CHANGE_START_COMMENT);
    Comment suffixComment = DocumentHelper.createComment(CHANGE_END_COMMENT);
    newContent.add(prefixComment);
    Iterator itr = list.iterator();
    while (itr.hasNext()) {
        Element value = (Element) itr.next();
        newContent.appendContent(value);
    }
    newContent.add(suffixComment);

    List sourceList = source.selectNodes(xpath);
    if (sourceList == null || sourceList.size() == 0) {
        throw new RuntimeException("xpath expression doesn't resolve to a node: " + xpath);
    }

    System.out.println("Xpath: " + xpath + " resolves to " + sourceList.size() + " nodes.");

    itr = sourceList.iterator();
    while (itr.hasNext()) {
        Element sourceEl = (Element) itr.next();
        System.out.println("Appending to xpath: " + sourceEl.getPath()); // + "newContent:\n" + newContent.asXML());
        sourceEl.appendContent(newContent);
    }
}

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

License:BEER-WARE LICENSE

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

    try {//from  www. 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.Acquire.Framework.java

License:BEER-WARE LICENSE

private void ConnectToServer() throws IOException {
    try {/*from w  w w  .  ja  v  a 2s. 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 {//w  ww .  j ava2  s  . co m

        // 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;/*  w  w  w .j  ava  2  s .  com*/
    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:org.alfresco.module.vti.web.fp.PropfindMethod.java

License:Open Source License

/**
 * Generates the XML response for a PROPFIND request that asks for all known
 * properties/*from  ww w.  jav  a2 s.  c  o  m*/
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
protected void generateAllPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception {
    // Get the properties for the node

    NodeRef node = nodeInfo.getNodeRef();

    Map<QName, Serializable> props = nodeInfo.getProperties();
    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;

    NodeRef workingCopy = null;
    if (node != null) {
        workingCopy = getDAVHelper().getServiceRegistry().getCheckOutCheckInService().getWorkingCopy(node);
    }

    Map<QName, Serializable> workingCopyProps = null;
    if (workingCopy != null) {
        String workingCopyOwner = getDAVHelper().getNodeService()
                .getProperty(workingCopy, ContentModel.PROP_WORKING_COPY_OWNER).toString();
        if (workingCopyOwner
                .equals(getDAVHelper().getServiceRegistry().getAuthenticationService().getCurrentUserName())) {
            workingCopyProps = getDAVHelper().getNodeService().getProperties(workingCopy);
        }
    }

    // Output the start of the properties element

    Attributes nullAttr = getDAVHelper().getNullAttributes();

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_RESOURCE_TYPE, nullAttr);
    if (isDir) {
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_COLLECTION, WebDAV.XML_COLLECTION, nullAttr);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_COLLECTION, WebDAV.XML_COLLECTION);
    }
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_RESOURCE_TYPE);

    // Get the node name

    Object davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_DISPLAYNAME);

    // Output the node name

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME, nullAttr);
    if (davValue != null) {
        String name = typeConv.convert(String.class, davValue);
        if (name == null || name.length() == 0) {
            logger.error("WebDAV name is null, value=" + davValue.getClass().getName() + ", node=" + node);
        }
        xml.write(name);
    }
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME);

    // Generate a lock status report, if locked
    if (workingCopy != null
            && (VtiUtils.isMacClientRequest(m_request) || VtiUtils.isOffice2010ClientRequest(m_request))) {
        // Office 2008/2011 for Mac assumes that checkouted node is locked node
        generateFakeLockDiscoveryResponseForWorkingCopy(xml, workingCopy, isDir);
    } else {
        generateLockDiscoveryResponse(xml, nodeInfo, isDir);
    }

    // Output the supported lock types

    if (!isDir) {
        writeLockTypes(xml);
    }

    if (isDir) {
        xml.startElement(WebDAV.DAV_NS, "isFolder", WebDAV.DAV_NS + ":isFolder", nullAttr);
        xml.write("t");
        xml.endElement(WebDAV.DAV_NS, "isFolder", WebDAV.DAV_NS + ":isFolder");
        xml.startElement(WebDAV.DAV_NS, "iscollection", WebDAV.DAV_NS + ":iscollection", nullAttr);
        xml.write("1");
        xml.endElement(WebDAV.DAV_NS, "iscollection", WebDAV.DAV_NS + ":iscollection");
        xml.startElement(WebDAV.DAV_NS, "ishidden", WebDAV.DAV_NS + ":ishidden", nullAttr);
        xml.write("0");
        xml.endElement(WebDAV.DAV_NS, "ishidden", WebDAV.DAV_NS + ":ishidden");
        xml.startElement(WebDAV.DAV_NS, "getcontenttype", WebDAV.DAV_NS + ":getcontenttype", nullAttr);
        xml.write("application/octet-stream");
        xml.endElement(WebDAV.DAV_NS, "getcontenttype", WebDAV.DAV_NS + ":getcontenttype");
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH,
                nullAttr);
        xml.write("0");
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);

        // If the node is a folder then return as a collection type

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE, nullAttr);
        if (isDir)
            xml.write(DocumentHelper.createElement(WebDAV.XML_NS_COLLECTION));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE);

        xml.startElement("Repl", "authoritative-directory", "Repl:authoritative-directory", nullAttr);
        xml.write("t");
        xml.endElement("Repl", "authoritative-directory", "Repl:authoritative-directory");
    }

    // Output the source
    //
    // NOTE: source is always a no content element in our implementation

    //xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));        

    // Get the modifed date/time

    if (workingCopyProps != null) {
        davValue = WebDAV.getDAVPropertyValue(workingCopyProps, WebDAV.XML_GET_LAST_MODIFIED);
    } else {
        davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_LAST_MODIFIED);
    }

    Date lastModified = (Date) davValue;

    // Output the last modified date of the node

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED, nullAttr);
    if (davValue != null)
        xml.write(VtiUtils.formatPropfindDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED);

    // Get the creation date
    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_CREATION_DATE);

    // Output the creation date

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE, nullAttr);
    if (davValue != null)
        xml.write(VtiUtils.formatPropfindDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE);

    // For a file node output the content language and content type

    if (isDir == false) {
        long len = 0;

        ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
        if (contentData != null)
            len = contentData.getSize();

        // Output the content length

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH,
                nullAttr);
        xml.write("" + len);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);

    }

    // Print out all the custom properties
    String guid = "";
    if (node != null) {
        guid = node.getId().toUpperCase();
    }

    xml.startElement("Repl", "repl-uid", "Repl:repl-uid", nullAttr);
    if (StringUtils.hasText(guid)) {
        xml.write(VtiUtils.constructRid(guid));
    }
    xml.endElement("Repl", "repl-uid", "Repl:repl-uid");

    xml.startElement("Repl", "resourcetag", "Repl:resourcetag", nullAttr);
    if (lastModified != null) {
        xml.write(VtiUtils.constructResourceTag(guid, lastModified));
    }
    xml.endElement("Repl", "resourcetag", "Repl:resourcetag");

    // Output the etag        
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG, nullAttr);
    if (lastModified != null) {
        xml.write(VtiUtils.constructETag(guid, lastModified));
    }
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG);

    if (!isDir) {
        String modifiedBy = props.get(ContentModel.PROP_MODIFIER).toString();
        xml.startElement("Office", "modifiedby", "Office:modifiedby", nullAttr);
        xml.write(modifiedBy);
        xml.endElement("Office", "modifiedby", "Office:modifiedby");

        // Office 2011 for Mac special property
        xml.startElement(WebDAV.DAV_NS, "getmodifiedby", WebDAV.DAV_NS_PREFIX + "getmodifiedby", nullAttr);
        xml.write(modifiedBy);
        xml.endElement(WebDAV.DAV_NS, "getmodifiedby", WebDAV.DAV_NS_PREFIX + "getmodifiedby");

    }
    // Close off the response

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);
    xml.write("\n");

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
    xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_OK + " " + WebDAV.SC_OK_DESC);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);
    xml.write("\n");

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
    xml.write("\n");
}

From source file:org.alfresco.module.vti.web.fp.PropfindMethod.java

License:Open Source License

/**
 * Generates the XML response snippet showing the fake lock information for the given path
 * //  www.j a v  a  2  s  .co m
 * @param xml XMLWriter
 * @param node NodeRef
 * @param isDir boolean
 */
protected void generateFakeLockDiscoveryResponseForWorkingCopy(XMLWriter xml, NodeRef node, boolean isDir)
        throws Exception {

    Attributes nullAttr = getDAVHelper().getNullAttributes();
    String ns = WebDAV.DAV_NS;
    if (node != null) {
        String owner = (String) getNodeService().getProperty(node, ContentModel.PROP_WORKING_COPY_OWNER);
        String lockTocken = WebDAV.makeLockToken(node, owner);
        // Output the XML response

        xml.startElement(ns, WebDAV.XML_LOCK_DISCOVERY, WebDAV.XML_NS_LOCK_DISCOVERY, nullAttr);
        xml.startElement(ns, WebDAV.XML_ACTIVE_LOCK, WebDAV.XML_NS_ACTIVE_LOCK, nullAttr);

        xml.startElement(ns, WebDAV.XML_LOCK_TYPE, WebDAV.XML_NS_LOCK_TYPE, nullAttr);
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_WRITE));
        xml.endElement(ns, WebDAV.XML_LOCK_TYPE, WebDAV.XML_NS_LOCK_TYPE);

        xml.startElement(ns, WebDAV.XML_LOCK_SCOPE, WebDAV.XML_NS_LOCK_SCOPE, nullAttr);
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_EXCLUSIVE));
        xml.endElement(ns, WebDAV.XML_LOCK_SCOPE, WebDAV.XML_NS_LOCK_SCOPE);

        // NOTE: We only support one level of lock at the moment

        xml.startElement(ns, WebDAV.XML_DEPTH, WebDAV.XML_NS_DEPTH, nullAttr);
        xml.write("0");
        xml.endElement(ns, WebDAV.XML_DEPTH, WebDAV.XML_NS_DEPTH);

        xml.startElement(ns, WebDAV.XML_OWNER, WebDAV.XML_NS_OWNER, nullAttr);
        xml.write(owner);
        xml.endElement(ns, WebDAV.XML_OWNER, WebDAV.XML_NS_OWNER);

        xml.startElement(ns, WebDAV.XML_TIMEOUT, WebDAV.XML_NS_TIMEOUT, nullAttr);

        xml.write(WebDAV.SECOND + "604800");

        xml.endElement(ns, WebDAV.XML_TIMEOUT, WebDAV.XML_NS_TIMEOUT);

        xml.startElement(ns, WebDAV.XML_LOCK_TOKEN, WebDAV.XML_NS_LOCK_TOKEN, nullAttr);
        xml.startElement(ns, WebDAV.XML_HREF, WebDAV.XML_NS_HREF, nullAttr);

        xml.write(lockTocken);

        xml.endElement(ns, WebDAV.XML_HREF, WebDAV.XML_NS_HREF);
        xml.endElement(ns, WebDAV.XML_LOCK_TOKEN, WebDAV.XML_NS_LOCK_TOKEN);

        xml.endElement(ns, WebDAV.XML_ACTIVE_LOCK, WebDAV.XML_NS_ACTIVE_LOCK);
        xml.endElement(ns, WebDAV.XML_LOCK_DISCOVERY, WebDAV.XML_NS_LOCK_DISCOVERY);
    }
}

From source file:org.alfresco.module.vti.web.fp.PropfindMethod.java

License:Open Source License

/**
 * Output the supported lock types XML element
 * /*from w  ww. j  a v a  2  s  .  co m*/
 * @param xml XMLWriter
 */
protected void writeLockTypes(XMLWriter xml) {
    try {
        AttributesImpl nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK, nullAttr);

        xml.startElement(WebDAV.DAV_NS, "lockentry", "D:lockentry", nullAttr);

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_LOCK_SCOPE, WebDAV.XML_NS_LOCK_SCOPE, nullAttr);
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_EXCLUSIVE));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_LOCK_SCOPE, WebDAV.XML_NS_LOCK_SCOPE);

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_LOCK_TYPE, WebDAV.XML_NS_LOCK_TYPE, nullAttr);
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_WRITE));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_LOCK_TYPE, WebDAV.XML_NS_LOCK_TYPE);

        xml.endElement(WebDAV.DAV_NS, "lockentry", "D:lockentry");

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK);
    } catch (Exception ex) {
        throw new AlfrescoRuntimeException("XML write error", ex);
    }
}

From source file:org.alfresco.repo.webdav.PropFindMethod.java

License:Open Source License

/**
 * Generates the XML response for a PROPFIND request that asks for a
 * specific set of properties/*  w  ww.  j a v  a 2s .  c om*/
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
private void generateNamedPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception {
    // Get the properties for the node
    Map<QName, Serializable> props = nodeInfo.getProperties();
    Map<QName, String> deadProperties = null;

    // Output the start of the properties element
    Attributes nullAttr = getDAVHelper().getNullAttributes();

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

    ArrayList<WebDAVProperty> propertiesNotFound = new ArrayList<WebDAVProperty>();

    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;

    // Loop through the requested property list
    for (WebDAVProperty property : m_properties) {
        // Get the requested property details

        String propName = property.getName();
        String propNamespaceUri = property.getNamespaceUri();

        // Check if the property is a standard WebDAV property

        Object davValue = null;

        if (WebDAV.DEFAULT_NAMESPACE_URI.equals(propNamespaceUri)) {
            // Check if the client is requesting lock information
            if (propName.equals(WebDAV.XML_LOCK_DISCOVERY)) // && metaData.isLocked())
            {
                generateLockDiscoveryResponse(xml, nodeInfo, isDir);
            } else if (propName.equals(WebDAV.XML_SUPPORTED_LOCK)) {
                // Output the supported lock types
                writeLockTypes(xml);
            }

            // Check if the client is requesting the resource type

            else if (propName.equals(WebDAV.XML_RESOURCE_TYPE)) {
                // If the node is a folder then return as a collection type

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE,
                        nullAttr);
                if (isDir) {
                    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_COLLECTION));
                }
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE);
            } else if (propName.equals(WebDAV.XML_DISPLAYNAME)) {
                // Get the node name
                if (getRootNodeRef().equals(nodeInfo.getNodeRef())) {
                    // Output an empty name for the root node
                    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));
                } else {
                    // Get the node name
                    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_DISPLAYNAME);

                    // Output the node name
                    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME,
                            nullAttr);
                    if (davValue != null) {
                        String name = typeConv.convert(String.class, davValue);
                        if (name == null || name.length() == 0) {
                            logger.error("WebDAV name is null, value=" + davValue.getClass().getName()
                                    + ", node=" + nodeInfo.getNodeRef());
                        }
                        xml.write(name);
                    }
                    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME);
                }
            } else if (propName.equals(WebDAV.XML_SOURCE)) {
                // NOTE: source is always a no content element in our
                // implementation

                xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));
            } else if (propName.equals(WebDAV.XML_GET_LAST_MODIFIED)) {
                // Get the modifed date/time

                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_LAST_MODIFIED);

                // Output the last modified date of the node

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED,
                        nullAttr);
                if (davValue != null)
                    xml.write(WebDAV.formatModifiedDate(typeConv.convert(Date.class, davValue)));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_LANGUAGE) && !isDir) {
                // Get the content language
                // TODO:
                // Output the content language
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE,
                        WebDAV.XML_NS_GET_CONTENT_LANGUAGE, nullAttr);
                // TODO:
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE,
                        WebDAV.XML_NS_GET_CONTENT_LANGUAGE);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_TYPE) && !isDir) {
                // Get the content type
                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_CONTENT_TYPE);

                // Output the content type
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE,
                        nullAttr);
                if (davValue != null)
                    xml.write(typeConv.convert(String.class, davValue));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE);
            } else if (propName.equals(WebDAV.XML_GET_ETAG) && !isDir) {
                // Output the etag

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG, nullAttr);
                xml.write(getDAVHelper().makeETag(nodeInfo));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_LENGTH)) {
                // Get the content length, if it's not a folder
                long len = 0;

                if (!isDir) {
                    ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
                    if (contentData != null)
                        len = contentData.getSize();
                }

                // Output the content length
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH,
                        nullAttr);
                xml.write("" + len);
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);
            } else if (propName.equals(WebDAV.XML_CREATION_DATE)) {
                // Get the creation date
                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_CREATION_DATE);

                // Output the creation date
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE,
                        nullAttr);
                if (davValue != null)
                    xml.write(WebDAV.formatCreationDate(typeConv.convert(Date.class, davValue)));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE);
            } else if (propName.equals(WebDAV.XML_ALF_AUTHTICKET)) {
                // Get the users authentication ticket

                SessionUser davUser = (SessionUser) m_request.getSession()
                        .getAttribute(AuthenticationFilter.AUTHENTICATION_USER);

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET,
                        nullAttr);
                if (davUser != null)
                    xml.write(davUser.getTicket());
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET);
            } else {
                // Could not map the requested property to an Alfresco property
                if (property.getName().equals(WebDAV.XML_HREF) == false)
                    propertiesNotFound.add(property);
            }
        } else {
            // Look in the custom properties

            //                String qualifiedName = propNamespaceUri + WebDAV.NAMESPACE_SEPARATOR + propName;

            String value = (String) nodeInfo.getProperties().get(property.createQName());
            if (value == null) {
                if (deadProperties == null) {
                    deadProperties = loadDeadProperties(nodeInfo.getNodeRef());
                }
                value = deadProperties.get(property.createQName());
            }

            if (value == null) {
                propertiesNotFound.add(property);
            } else {
                if (property.hasNamespaceName()) {
                    xml.startElement(property.getNamespaceName(), property.getName(),
                            property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName(),
                            nullAttr);
                    xml.write(value);
                    xml.endElement(property.getNamespaceName(), property.getName(),
                            property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName());
                } else {
                    xml.startElement("", property.getName(), property.getName(), nullAttr);
                    xml.write(value);
                    xml.endElement("", property.getName(), property.getName());
                }
            }

        }
    }

    // Close off the successful part of the response

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
    xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_OK + " " + WebDAV.SC_OK_DESC);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);

    // If some of the requested properties were not found return another
    // status section

    if (propertiesNotFound.size() > 0) {
        // Start the second status section

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

        // Loop through the list of properties that were not found

        for (WebDAVProperty property : propertiesNotFound) {
            // Output the property not found status block

            String propName = property.getName();
            String propNamespaceName = property.getNamespaceName();
            String propQName = propName;
            if (propNamespaceName != null && propNamespaceName.length() > 0)
                propQName = propNamespaceName + ":" + propName;

            xml.write(DocumentHelper.createElement(propQName));
        }

        // Close the unsuccessful part of the response

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
        xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_NOT_FOUND + " " + WebDAV.SC_NOT_FOUND_DESC);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
    }
}