Example usage for org.dom4j Node asXML

List of usage examples for org.dom4j Node asXML

Introduction

In this page you can find the example usage for org.dom4j Node asXML.

Prototype

String asXML();

Source Link

Document

asXML returns the textual XML representation of this node.

Usage

From source file:com.globalsight.terminology.EntryUtils.java

License:Apache License

/**
 * Returns the HTML representation of an element's text. This is
 * like getInnerXml() but doesn't encode apostrophes.
 *//*from  www .  j  av a 2 s .  c o  m*/
static public String getInnerHtml(Element p_node) {
    StringBuffer result = new StringBuffer();

    List content = p_node.content();

    for (int i = 0, max = content.size(); i < max; i++) {
        Node node = (Node) content.get(i);

        // Work around a specific behaviour of DOM4J text nodes:
        // The text node asXML() returns the plain Unicode string,
        // so we need to encode entities manually.
        if (node.getNodeType() == Node.TEXT_NODE) {
            result.append(EditUtil.encodeHtmlEntities(node.getText()));
        } else {
            // Element nodes write their text nodes correctly.
            result.append(node.asXML());
        }
    }

    return result.toString();
}

From source file:com.googlecode.fascinator.redbox.sru.SRUClient.java

License:Open Source License

/**
 * <p>/*from w ww  .j  a  v  a  2s  . c  om*/
 * Search for a record from the National Library of Australia with the provided identifier. If multiple records match this identifier only the
 * first will be returned.
 * </p>
 * 
 * @param id The identifier to search for
 * @return String The record matching this identifier. Null if not found
 */
public String nlaGetRecordById(String id) {
    Node node = nlaGetRecordNodeById(id);

    if (node == null) {
        return null;
    }

    if ("xml".equals(responsePacking)) {
        return node.asXML();
    } else {
        return node.getText();
    }
}

From source file:com.noterik.bart.fs.action.SearchAction.java

License:Open Source License

/**
 * Parses lisa response to fsxml//from   w  w w . j a  v a2  s.c  o  m
 * @param xml
 * @return
 */
private static String parse2fsxml(String xml) {
    String fsxml = "";

    // start with empty properties
    fsxml += "<properties />";

    try {
        // parse xml (only add result elements)
        Document doc = DocumentHelper.parseText(xml);
        List<Node> nList = doc.selectNodes("//result");
        Node node;
        for (Iterator<Node> iter = nList.iterator(); iter.hasNext();) {
            node = iter.next();
            if (node instanceof Element) {
                fsxml += node.asXML();
            }
        }
    } catch (Exception e) {
        logger.error("SearchAction: error parsing response from lisa", e);
    }

    // add fsxml
    fsxml = "<fsxml>" + fsxml + "</fsxml>";

    return fsxml;
}

From source file:com.noterik.bart.fs.action.SetRedoScreensAction.java

License:Open Source License

@Override
public String run() {

    logger.debug("**************************** starting SetRedoScreensAction ************************");
    String requestBody = event.getRequestData();
    String uri = event.getUri();/* w  ww.ja va  2s .co m*/
    String domain = URIParser.getDomainFromUri(uri);

    logger.debug("request body: " + requestBody);
    logger.debug("uri: " + uri);

    try {
        Document doc = DocumentHelper.parseText(requestBody);
        Node mtNode = doc.selectSingleNode("//properties/mount");

        if (mtNode == null) {
            logger.debug("Mounts are not set, redo will not be set to true");
            return null;
        }

        // get uri and properties of video
        String vidUri = uri.substring(0, uri.lastIndexOf("/rawvideo"));

        String transcoder = doc.selectSingleNode("//properties/transcoder") == null ? ""
                : doc.selectSingleNode("//properties/transcoder").getText();

        // work around so we don't need to fix APU
        if (!transcoder.equals("apu")) {
            // check is screens are already done
            Document vidDoc = FSXMLRequestHandler.instance().getNodeProperties(vidUri, false);
            boolean hasScreens = vidDoc.selectSingleNode(".//screens") != null;
            if (hasScreens) {
                logger.debug("Screens are already present. No need to set redo to true.");
                return null;
            }
        }

        logger.debug("Screens properties will be created");
        // get uri of redo tag
        String screensUri = vidUri + "/screens/1/properties";
        logger.debug("screensUri: " + screensUri);

        // check for domain preferences
        String screenProperties = DEFAULT_SCREENS_PROPERTIES;
        String configURI = SCREENS_CONFIG_URI.replace("{domain}", domain);
        Document configDoc = FSXMLRequestHandler.instance().getNodeProperties(configURI, false);
        if (configDoc != null) {
            logger.debug("Custom screenshots profile");
            Node configProperties = configDoc.selectSingleNode("//screensprofile/properties");
            screenProperties = "<fsxml>" + configProperties.asXML() + "</fsxml>";
        }

        //if apu most likely only 1 raw available, always use raw 1 otherwise job might never get executed
        if (transcoder.equals("apu")) {
            Document sProperties = XMLHelper.asDocument(screenProperties);
            Node useraw = sProperties.selectSingleNode("//useraw");
            if (useraw != null) {
                sProperties.selectSingleNode("//useraw").setText("1");
            }
            screenProperties = sProperties.asXML();
        }

        logger.debug("redo properties: " + screenProperties);
        if (!FSXMLRequestHandler.instance().saveFsXml(screensUri, screenProperties, "PUT", true)) {
            throw new ActionException("Screens properties could not be set");
        } else {
            logger.debug("screens properties were created successfully");
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return null;
}

From source file:com.noterik.bart.fs.action.SetRedoScreensMjpegAction.java

License:Open Source License

@Override
public String run() {
    logger.debug("**************************** starting SetRedoScreensMjpegAction ************************");
    String requestBody = event.getRequestData();
    String uri = event.getUri();//from  w  w w  . j  a  v a 2  s . c om
    String domain = URIParser.getDomainFromUri(uri);

    logger.debug("request body: " + requestBody);
    logger.debug("uri: " + uri);

    try {
        Document doc = DocumentHelper.parseText(requestBody);
        Node mtNode = doc.selectSingleNode("//properties/mount");

        if (mtNode == null) {
            logger.debug("Mounts are not set, redo will not be set to true");
            return null;
        }

        // get uri and properties of video
        String vidUri = uri.substring(0, uri.lastIndexOf("/rawvideo"));

        Document vidDoc = FSXMLRequestHandler.instance().getNodeProperties(vidUri, false);

        boolean hasScreens = vidDoc.selectSingleNode(".//screens") != null;
        if (hasScreens) {
            logger.debug("Screens are already present. No need to set redo to true.");
            return null;
        }

        logger.debug("Screens properties will be created");
        // get uri of redo tag
        String screensUri = vidUri + "/screens/1/properties";
        logger.debug("screensUri: " + screensUri);

        // check for domain preferences
        String screenProperties = DEFAULT_SCREENS_PROPERTIES;
        String configURI = SCREENS_CONFIG_URI.replace("{domain}", domain);
        Document configDoc = FSXMLRequestHandler.instance().getNodeProperties(configURI, false);
        if (configDoc != null) {
            logger.debug("Custom screens profile");
            Node configProperties = configDoc.selectSingleNode("//screensprofile/properties");
            screenProperties = "<fsxml>" + configProperties.asXML() + "</fsxml>";
        }

        logger.debug("redo properties: " + screenProperties);
        if (!FSXMLRequestHandler.instance().saveFsXml(screensUri, screenProperties, "PUT", true)) {
            throw new ActionException("Screens properties could not be set");
        } else {
            logger.debug("screens properties were created successfully");
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return null;
}

From source file:com.noterik.bart.fs.fscommand.AddEventCommand.java

License:Open Source License

public String execute(String uri, String xml) {
    logger.debug("Add event of presentation " + uri);
    logger.debug("Add event xml " + xml);

    Document doc = XMLHelper.asDocument(xml);
    List<Node> events;
    String ticket = "";
    String user = "";

    if (doc == null) {
        logger.error("Could not parse xml");
        return FSXMLBuilder.getErrorMessage("500", "No xml found", "Please provide xml", "");
    } else {//w w  w . j a  va2s.c o  m
        events = doc.selectNodes("/fsxml/*");
        user = doc.selectSingleNode("//properties/user") == null ? ""
                : doc.selectSingleNode("//properties/user").getText();
        user = user.toLowerCase();
        ticket = doc.selectSingleNode("//properties/ticket") == null ? ""
                : doc.selectSingleNode("//properties/ticket").getText();
    }

    //TODO: validate ticket

    // create playlist if it does not exist
    createPlaylistIfNotExists(uri);

    for (Iterator<Node> it = events.iterator(); it.hasNext();) {
        Node event = it.next();

        if (!event.getName().equals("properties")) {
            logger.debug("received " + event.asXML());

            String starttime = event.selectSingleNode("properties/starttime") == null ? ""
                    : event.selectSingleNode("properties/starttime").getText();
            String duration = event.selectSingleNode("properties/duration") == null ? ""
                    : event.selectSingleNode("properties/duration").getText();
            String reason = event.selectSingleNode("properties/reason") == null ? ""
                    : event.selectSingleNode("properties/reason").getText();

            logger.debug("starttime = " + starttime + " duration = " + duration + " reason = " + reason);

            // determine starttime relative to beginning of video
            long stSpringfield = determineCorrectStarttime(uri, starttime);

            if (starttime.equals("") || duration.equals("") || reason.equals("")) {
                logger.error("Not all mandatory fields where provided");
                return FSXMLBuilder.getErrorMessage("500", "No all mandatory fields available",
                        "Please provide all mandatory fields in your request", "");
            }

            // create new 'bookmark'
            StringBuffer bmXml = new StringBuffer();
            bmXml.append("<fsxml>");
            bmXml.append("<properties>");
            bmXml.append("<title><![CDATA[");
            bmXml.append(reason);
            bmXml.append("]]></title>");
            bmXml.append("<description><![CDATA[");
            bmXml.append(reason);
            bmXml.append("]]></description>");
            bmXml.append("<starttime>");
            bmXml.append(stSpringfield);
            bmXml.append("</starttime>");
            bmXml.append("<duration>");
            bmXml.append(duration);
            bmXml.append("</duration>");
            bmXml.append("<creator>");
            bmXml.append(user);
            bmXml.append("</creator>");
            bmXml.append("<changedby>");
            bmXml.append(user);
            bmXml.append("</changedby>");
            bmXml.append("<lastupdate>");
            bmXml.append(LASTUPDATE_FORMAT.format(new Date()));
            bmXml.append("</lastupdate>");
            bmXml.append("</properties>");
            bmXml.append("</fsxml>");
            String bmUri = uri + "/videoplaylist/1/bookmark";
            String resp = FSXMLRequestHandler.instance().handlePOST(bmUri, bmXml.toString());
            logger.debug(resp);
        }
    }

    return FSXMLBuilder.getFSXMLStatusMessage("The properties where successfully added", "", "");
}

From source file:com.noterik.bart.fs.fscommand.CopyCommand.java

License:Open Source License

/**
 * Copy resource specified by the input parameters.
 * /*  w w w  . ja  va 2 s .co  m*/
 * @param input      input parameters
 * @param uri      local directory
 * @return         status/error message
 */
private String copy(Properties input, String uri) {
    String res = null;

    // get input parameters
    String source = input.getProperty("source");
    String destination = input.getProperty("destination");
    String params = input.getProperty("params");
    logger.debug("source: " + source + ", destination: " + destination + ", params: " + params);
    //System.out.println("source: "+source+", destination: "+destination+", params: "+params);   

    // determine optional parameters
    boolean recursive = false, override = false;
    if (params != null) {
        recursive = params.contains("-r");
        override = params.contains("-o");
    }

    // check input parameters
    if (source == null || destination == null) {
        return FSXMLBuilder.getErrorMessage("500", "No source or destination",
                "Please provide the SOURCE and DESTINATION input parameters",
                "http://teamelements.noterik.com/team");
    }

    // resolve uris
    String sourceUri = URIParser.resolveLocalUri(source, uri);
    if (sourceUri.lastIndexOf("/") == sourceUri.length() - 1) {
        sourceUri = sourceUri.substring(0, sourceUri.lastIndexOf("/"));
    }
    String destinationUri = URIParser.resolveLocalUri(destination, uri);
    if (destinationUri.lastIndexOf("/") == destinationUri.length() - 1) {
        destinationUri = destinationUri.substring(0, destinationUri.lastIndexOf("/"));
    }
    logger.debug("ABSOLUTE URIS -- source: " + sourceUri + ", destination: " + destinationUri);

    // check if uri is an uri of type id
    String typeSource = URIParser.getResourceTypeFromUri(sourceUri);
    String cpDest = URIParser.getCurrentUriPart(destinationUri);
    if (!URIParser.isResourceId(sourceUri)) {
        return FSXMLBuilder.getErrorMessage("500", "Invalid source specified, only id nodes permitted.",
                "Invalid source specified, only id nodes permitted.", "http://teamelements.noterik.com/team");
    }

    String docStr = null;
    String refer = null;
    if (recursive) {
        // get properties of source   
        Document doc = getPropertiesOfUri(sourceUri, -1);
        logger.debug("document being created: " + doc.asXML());

        // exception for first node
        Element root = doc.getRootElement();
        Node first = root.selectSingleNode("//" + typeSource);
        refer = first.valueOf("@referid");
        List<Node> children = first.selectNodes("child::*");
        for (Iterator<Node> iter = children.iterator(); iter.hasNext();) {
            Node node = iter.next();
            docStr += node.asXML();
        }
        docStr = "<fsxml>" + docStr + "</fsxml>";
        logger.debug("document being created after first node exception: " + docStr);
    } else {
        // get properties of source   
        Document doc = getPropertiesOfUri(sourceUri, 0);
        logger.debug("document being created: " + doc.asXML());

        // exception for first node
        Element root = doc.getRootElement();
        Node first = root.selectSingleNode("//" + typeSource);
        Node properties = first.selectSingleNode("properties");
        refer = first.valueOf("@referid");
        docStr = "<fsxml>" + properties.asXML() + "</fsxml>";
        logger.debug("document being created after first node exception: " + docStr);
    }

    // check if dest ends with 'properties'
    String newResourceUri = null;
    if (cpDest.equals(FSXMLHelper.XML_PROPERTIES)) {
        logger.debug("putting to " + destinationUri);
        res = rHandler.handlePUT(destinationUri, docStr);
        newResourceUri = URIParser.getParentUri(destinationUri);
    } else if (URIParser.isResourceId(destinationUri)) {
        destinationUri += "/" + FSXMLHelper.XML_PROPERTIES;
        logger.debug("putting to " + destinationUri);
        res = rHandler.handlePUT(destinationUri, docStr);
        newResourceUri = URIParser.getParentUri(destinationUri);
    } else {
        logger.debug("posting to " + destinationUri);
        res = rHandler.handlePOST(destinationUri, docStr);
        try {
            if (FSXMLParser.getErrorMessageFromXml(res) == null) {
                Document respDoc = DocumentHelper.parseText(res);
                newResourceUri = respDoc.valueOf("//uri");
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    // add refer of first node
    if (refer != null && !refer.equals("")) {
        logger.debug("adding refer for first node (" + refer + ")");
        boolean ok = rHandler.saveAttributes(newResourceUri,
                "<fsxml><attributes><referid>" + refer + "</referid></attributes></fsxml>", "PUT");
        logger.debug("attributes added: " + ok);
    } else {
        logger.debug("not need for adding refer id");
    }

    logger.debug("response: " + res);
    return res;
}

From source file:com.noterik.bart.fs.fscommand.CopyCommand.java

License:Open Source License

/**
 * //from www.  j  ava2  s .c om
 * @param uri
 * @return
 */
private Document getPropertiesOfUri(String uri, int depth) {
    // refactor uri
    String cp = URIParser.getCurrentUriPart(uri);
    if (cp.equals(FSXMLHelper.XML_PROPERTIES)) {
        uri = URIParser.getParentUri(uri);
    }

    // get complete
    Document pDoc = null;
    if (depth == -1) {
        pDoc = rHandler.getNodeProperties(uri, true);
    } else {
        pDoc = rHandler.getNodeProperties(uri, depth, true);
    }

    // loop through xml and check referid's
    List<Node> rNodes = pDoc.selectNodes("//@referid");
    logger.debug("rNodes: " + rNodes);
    for (Iterator<Node> iter = rNodes.iterator(); iter.hasNext();) {
        // get referid attribute and parent node
        Node node = iter.next();
        String referid = node.getText();
        Element parent = node.getParent();
        logger.debug("parent: " + parent.asXML() + ", refer: " + referid);

        // get properties of referid
        Document rDoc = rHandler.getNodeProperties(referid, 0, false);
        logger.debug("rDoc: " + rDoc.asXML());
        Node properties = rDoc.selectSingleNode("//properties");
        List<Node> pNodes = properties.selectNodes("child::*");
        logger.debug("pNodes: " + pNodes);
        for (Iterator<Node> iter2 = pNodes.iterator(); iter2.hasNext();) {
            // select the same property elements that are in parent element and refer properties
            Node prop = iter2.next();
            List<Node> parentPNodes = parent.selectNodes("properties/child::*");
            for (Node parentPropNode : parentPNodes) {
                if (parentPropNode.getName().equals(prop.getName())
                        && parentPropNode.getText().equals(prop.getText())) {
                    logger.debug("removing: " + parentPropNode.asXML());
                    parentPropNode.detach();
                }
            }
        }
    }

    return pDoc;
}

From source file:com.noterik.bart.fs.fscommand.CreatePresentationFromBookmark.java

License:Open Source License

private String handlePresentation() {
    //get collection where to put presentation in
    Document config = XMLHelper.asDocument(xml);
    String collectionUri = config.selectSingleNode("//collection") == null ? ""
            : config.selectSingleNode("//collection").getText();

    if (collectionUri.equals("")) {
        logger.error("no collection supplied");
        return FSXMLBuilder.getErrorMessage("500", "No collection supplied", "Please provide a collection",
                "http://teamelements.noterik.com/team");
    }//from   ww  w  .  ja  v a  2  s  . c o m

    domainid = URIParser.getDomainIdFromUri(collectionUri);
    user = URIParser.getUserIdFromUri(collectionUri);

    if (domainid.equals("")) {
        logger.error("got no domain from uri");
        return FSXMLBuilder.getErrorMessage("500", "No domain found", "Please provide a collection with domain",
                "http://teamelements.noterik.com/team");
    }
    if (user.equals("")) {
        logger.error("got no user from uri");
        return FSXMLBuilder.getErrorMessage("500", "No user found", "Please provide a collection with user",
                "http://teamelements.noterik.com/team");
    }

    //get collection presentation
    Document collectionPresentation = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
    String presentationUri = collectionPresentation.selectSingleNode("//presentation/@referid") == null ? ""
            : collectionPresentation.selectSingleNode("//presentation/@referid").getText();

    if (presentationUri.equals("")) {
        logger.error("no presentation refered");
        return FSXMLBuilder.getErrorMessage("500", "No presentation refered", "",
                "http://teamelements.noterik.com/team");
    }

    Document presentation = FSXMLRequestHandler.instance().getNodeProperties(presentationUri, false);

    //remove statistics from original presentation
    Element statistics = (Element) presentation.selectSingleNode("//statistics");
    if (statistics != null) {
        statistics.detach();
    }

    StringBuffer presentationXml = new StringBuffer();

    // exception for first node
    Element root = presentation.getRootElement();
    Node first = root.selectSingleNode("//presentation");
    List<Node> children = first.selectNodes("child::*");
    for (Iterator<Node> iter = children.iterator(); iter.hasNext();) {
        Node node = iter.next();
        presentationXml.append(node.asXML());
    }
    String pXml = "<fsxml>" + presentationXml.toString() + "</fsxml>";
    String response = FSXMLRequestHandler.instance()
            .handlePOST("/domain/" + domainid + "/user/" + user + "/presentation", pXml);

    //response contains new presentation uri we have to refer to in collection
    Document resp = XMLHelper.asDocument(response);

    logger.debug("response = " + resp.asXML());
    String newPresentationUri = resp.selectSingleNode("//status[@id='400']/properties/uri") == null ? ""
            : resp.selectSingleNode("//status[@id='400']/properties/uri").getText();

    if (newPresentationUri.equals("")) {
        logger.error("could not create presentation");
        return FSXMLBuilder.getErrorMessage("500", "Could not create presentation", "Try again later",
                "http://teamelements.noterik.com/team");
    }

    //refer new presentation in the collection
    String response2 = FSXMLRequestHandler.instance().handlePOST(collectionUri + "/presentation",
            "<fsxml><attributes><referid>" + newPresentationUri + "</referid></attributes></fsxml>");

    Document resp2 = XMLHelper.asDocument(response2);
    logger.debug("response 2 = " + resp2.asXML());

    String newCollectionPresentationUri = resp2.selectSingleNode("//status[@id='400']/properties/uri") == null
            ? ""
            : resp2.selectSingleNode("//status[@id='400']/properties/uri").getText();

    if (newCollectionPresentationUri.equals("")) {
        logger.error("could not create refer presentation in collection");
        return FSXMLBuilder.getErrorMessage("500", "Could not create presentation in collection",
                "Try again later", "http://teamelements.noterik.com/team");
    }

    return resp2.asXML();
}

From source file:com.noterik.bart.fs.fscommand.dynamic.collection.config.wizard.java

License:Open Source License

public String run(String uri, String xml) {
    logger.debug("start dynamic/collection/config/wizard");

    Document doc = XMLHelper.asDocument(xml);

    if (doc == null) {
        return FSXMLBuilder.getErrorMessage("403", "The value you sent is not valid",
                "You have to POST a valid command XML", "http://teamelements.noterik.nl/team");
    }/*from   w  w  w.j av a2  s .  co  m*/

    String user = doc.selectSingleNode("//properties/user") == null ? ""
            : doc.selectSingleNode("//properties/user").getText();
    String ticket = doc.selectSingleNode("//properties/ticket") == null ? ""
            : doc.selectSingleNode("//properties/ticket").getText();

    //TODO: validate user/ticket

    //get collection
    Document collection = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
    logger.debug(collection.asXML());

    //get roles
    Element wizard;
    List<Node> wizards = collection.selectNodes("//config[@id='1']/wizard");
    Node userRole = collection
            .selectSingleNode("//config[@id='roles']/user[@id='" + user + "']/properties/wizard");

    if (userRole == null) {
        logger.debug("user not found --> default wizard");
        // Loop all wizards
        for (Iterator<Node> iter = wizards.iterator(); iter.hasNext();) {
            wizard = (Element) iter.next();

            String wizardId = wizard.attribute("id") == null ? "" : wizard.attribute("id").getText();
            if (!wizardId.equals("1")) {
                logger.debug("detach wizard with id " + wizardId);
                wizard.detach();
            }
        }
    } else {
        logger.debug("user found " + userRole.asXML());
        String roles = userRole.getText();
        String[] results = roles.split(",");

        // Loop all wizards
        for (Iterator<Node> iter = wizards.iterator(); iter.hasNext();) {
            wizard = (Element) iter.next();

            String wizardId = wizard.attribute("id") == null ? "" : wizard.attribute("id").getText();
            if (!inArray(results, wizardId)) {
                logger.debug("detach wizard with id " + wizardId);
                wizard.detach();
            }
        }
    }

    //detach config roles
    Node configRoles = collection.selectSingleNode("//config[@id='roles']");
    configRoles.detach();

    return collection.asXML();
}