Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

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

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

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

License:Open Source License

private void putInQueue(String eventUri, int priority, String presentationUri) {
    logger.debug("putInQueue eventuri = " + eventUri + " priority = " + priority + " presentationuri = "
            + presentationUri);/*from  ww  w.  j  a  va 2  s .  c  o m*/

    /* Loop all collections where presentation is refered and add to queues */
    for (int i = 0; i < referedPresentations.size(); i++) {
        String collectionPresentation = referedPresentations.get(i) == null ? null
                : referedPresentations.get(i);
        if (collectionPresentation != null) {
            //get domain from collection presentation and add to queue in domain
        }

        if (referedPresentations.get(i) != null) {
            domainid = URIParser.getDomainIdFromUri(eventUri);
            queueUri = QUEUE_URI.replace("{domainid}", domainid);

            logger.debug("test");

            boolean jobExists = false;

            /* check if job is already in proper queue */
            for (int j = 0; j < referedJobs.size(); j++) {
                String refer = referedJobs.get(j);
                if (refer != null) {
                    String[] parts = refer.substring(1).split("/");
                    if (parts[1].equals(domainid)) {
                        //select this job to check priority
                        jobExists = true;
                        String job = getSubUri(refer, 8);
                        String jobContent = null;

                        try {
                            jobContent = FSXMLRequestHandler.instance().handleGET(job, null).getText();
                        } catch (IOException e) {
                        }
                        Document jobProperties = null;
                        try {
                            jobProperties = DocumentHelper.parseText(jobContent);
                        } catch (Exception e) {
                        }

                        String jobId = job.substring(job.lastIndexOf("/") + 1);
                        int currentPriority = jobProperties.selectSingleNode("//priority") == null ? 2
                                : Integer.parseInt(jobProperties.selectSingleNode("//priority").getText());
                        logger.debug("current prio " + currentPriority);
                        if (currentPriority > priority) {
                            updatePriority(priority, jobId);
                        }
                    }
                }
            }
            /* Otherwise add as a new job */
            if (!jobExists) {
                logger.debug("call add job");
                addJob(presentationUri, eventUri);
            }

            /* check for double entries */
            getRefers(eventUri);
            int jobCounter = 0;
            for (int k = 0; k < referedJobs.size(); k++) {
                String refer = referedJobs.get(k);
                if (refer != null) {
                    String[] parts = refer.substring(1).split("/");
                    if (parts[1].equals(domainid) && parts[5].equals("presentationindex")
                            && parts[6].equals("job")) {
                        jobCounter++;
                        if (jobCounter > 1) {
                            logger.debug("remove double entry from queue");
                            FSXMLRequestHandler.instance().deleteNodeProperties(refer, false);
                        }
                    }
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * Parses lisa response to fsxml/*www .ja  va  2s . 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();/*from   w ww.java  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"));

        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 ww  w .  j a  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"));

        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.CopyCommand.java

License:Open Source License

/**
 * Copy resource specified by the input parameters.
 * //  ww 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.dynamic.presentation.playout.flash.java

License:Open Source License

public synchronized String run(String uri, String xml) {
    logger.debug("start dynamic/presentation/playout/flash");
    logger.debug("qpr url=" + uri);
    long timer_start = new Date().getTime();
    Document returnXml = DocumentHelper.createDocument();
    Element fsxml = returnXml.addElement("fsxml");
    fsxml.addElement("properties");

    String domain = URIParser.getDomainIdFromUri(uri);
    String user = URIParser.getUserIdFromUri(uri);
    String selectedplaylist = "";
    Element handlerparams = null;

    int pos = xml.indexOf("<virtualpath>");
    if (pos != -1) {
        selectedplaylist = xml.substring(pos + 13 + 14);
        pos = selectedplaylist.indexOf("</virtualpath>");
        if (pos != -1) {
            selectedplaylist = selectedplaylist.substring(0, pos);
            try {
                handlerparams = (Element) DocumentHelper.parseText(xml).getRootElement();
            } catch (Exception docerror) {
                logger.error("invalid parameters in xml");
            }/*from   ww  w.jav a  2 s.  c o  m*/
        } else {
            logger.error("invalid virtual path");
        }
    }

    if (uri.indexOf("/collection/") == -1 || uri.indexOf("/presentation") == -1) {
        return FSXMLBuilder.getErrorMessage("403", "No collection presentation found",
                "You have to supply a valid collection presentation", "http://teamelements.noterik.nl/team");
    }

    config conf = new config(domain, user, selectedplaylist, handlerparams);

    Document presentationProperties = cache.get(uri);
    if (presentationProperties == null) {
        presentationProperties = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
        if (presentationProperties == null) {
            return FSXMLBuilder.getErrorMessage("404", "Presentation not found",
                    "You have to supply an existing presentation", "http://teamelements.noterik.nl/team");
        }
        cache.put(uri, presentationProperties);
    }

    String collection = uri.substring(uri.indexOf("/collection/") + 12, uri.indexOf("/presentation/"));
    conf.setCollection(collection);

    logger.debug("presentation " + uri + " domain " + domain + " user " + user + " collection " + collection);

    Node presentationXml = getPresentation(uri);
    if (presentationXml != null) {
        fsxml.add(presentationXml);
        logger.debug("past presentation xml");
        List<Element> videos = addVideos(presentationXml);
        for (int i = 0; i < videos.size(); i++) {
            fsxml.add(videos.get(i));
        }
        logger.debug("past adding video(s)");
    }
    Node presentationConfig = getPresentationConfig(uri, presentationXml, conf);

    if (presentationConfig != null) {
        fsxml.add(presentationConfig);
        logger.debug("past presentation config");

        List<Element> players = addPlayer(presentationConfig);
        for (int j = 0; j < players.size(); j++) {
            fsxml.add(players.get(j));
        }
    }
    logger.debug("past adding player(s)");

    // moved the remapping of the presentation so we already have the video nodes.
    // Warning: This relies on the corrected presentation config (sponsor/user/collection level
    // don't move before the presentationconfig it's added to the document (dom4j issue)   !!
    presentationXml = dynamicTransform((Element) presentationXml, conf, fsxml);

    Node collectionConfig = getCollectionConfig(uri, conf);
    if (collectionConfig != null) {
        fsxml.add(collectionConfig);
    }

    logger.debug("past collection config");

    logger.debug("end dynamic/presentation/playout/flash");

    long timer_end = new Date().getTime();
    System.out.println("GENTIME=" + (timer_end - timer_start) + " CACHE AT " + cache.getPerformance() + "% req="
            + cache.getTotalRequest() + " size=" + cache.getCacheSize() + " URI=" + uri);
    return fsxml.asXML();
}

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

License:Open Source License

public String execute(String uri, String xml) {
    logger.debug("get streaming server command");

    //get raw id from xml
    try {/*from www .  j av  a  2 s. c o  m*/
        Document properties = DocumentHelper.parseText(xml);
        rawId = properties.selectSingleNode("//properties/raw") == null ? "1"
                : properties.selectSingleNode("//properties/raw").getText();
    } catch (DocumentException e) {
        logger.error("could not parse streaming server command xml :" + xml);
    }

    Pattern collectionPresentationPattern = Pattern.compile(COLLECTION_PRESENTATION);
    Matcher collectionPresentationMatcher = collectionPresentationPattern.matcher(uri);

    if (collectionPresentationMatcher.matches()) {
        logger.debug("collectionpresentation " + uri);
        //get refer presentation
        Document doc = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
        uri = doc.selectSingleNode("//presentation/@referid") == null ? ""
                : doc.selectSingleNode("//presentation/@referid").getText();
    }

    Pattern presentationPattern = Pattern.compile(PRESENTATION);
    Matcher presentationMatcher = presentationPattern.matcher(uri);

    if (presentationMatcher.matches()) {
        logger.debug("presentation " + uri);
        //get refer video
        Document doc = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
        uri = doc.selectSingleNode("//presentation/videoplaylist/video/@referid") == null ? ""
                : doc.selectSingleNode("//presentation/videoplaylist/video/@referid").getText();
    }

    Pattern videoPattern = Pattern.compile(VIDEO);
    Matcher videoMatcher = videoPattern.matcher(uri);

    if (videoMatcher.matches()) {
        logger.debug("video " + uri);
        Document doc = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
        String mount = doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/mount") == null
                ? ""
                : doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/mount").getText();
        String extension = doc
                .selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/extension") == null ? ""
                        : doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/extension")
                                .getText();
        String status = doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/status") == null
                ? ""
                : doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/status").getText();
        String original = doc
                .selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/original") == null ? ""
                        : doc.selectSingleNode("//video/rawvideo[@id='" + rawId + "']/properties/original")
                                .getText();

        logger.debug("mount " + mount);
        logger.debug("extension " + extension);
        logger.debug("status " + status);
        logger.debug("original " + original);

        if (mount != "" && (status.toUpperCase().equals("DONE") || original.toUpperCase().equals("TRUE"))) {
            StringBuffer output = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            output.append("<fsxml><properties/>");

            String[] mounts = mount.split(",");
            logger.debug("number of mounts " + mounts.length);

            for (int i = 0; i < mounts.length; i++) {
                String streamingServer = mounts[i] + ".noterik.com/" + mounts[i];
                String file = uri + "/rawvideo/" + rawId + "/raw." + extension;
                output.append(serverToXml(streamingServer, i + 1, file));
            }
            output.append("</fsxml>");
            return output.toString();
        } else {
            return FSXMLBuilder.getErrorMessage("404", "Video not found", "The specified video was not found",
                    "http://teamelements.noterik.com/team");
        }
    }
    logger.error("Could not convert uri to video " + uri);
    return FSXMLBuilder.getErrorMessage("500", "Could not get stream for this id",
            "Please try with a correct id", "http://teamelements.noterik.com/team");
}

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

License:Open Source License

/**
 * Move resource specified by the input parameters.
 * /*from   w ww  .  j  a  v  a  2  s.  c o  m*/
 * @param input      input parameters
 * @param uri      local directory
 * @return         status/error message
 */
private String move(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);

    // determine optional parameters
    boolean override = false;
    if (params != null) {
        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;

    // 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);

    // 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");
    }

    // check if copy was successful and remove original
    String vError = FSXMLParser.getErrorMessageFromXml(res);
    if (vError != null) {
        logger.error("copy before moving was unsuccessful.");
    } else {
        logger.debug("copy before moving was successful.");
        FSXMLRequestHandler.instance().deleteNodeProperties(sourceUri, true);
    }

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

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

License:Open Source License

private static boolean getPages(String uri) {
    logger.debug("getting pages for project: " + uri);
    uri = getServer() + uri + "?start={start}&limit={limit}";
    int start = 0;
    int limit = 0;
    String baseUrl = uri.replace("{start}", Integer.toString(start)).replace("{limit}",
            Integer.toString(limit));
    try {/*w w w .j  a  v  a 2s .  com*/
        List<Node> nodes = new ArrayList<Node>();
        List<Node> partialNodes;
        String response = HttpHelper.sendRequest("GET", baseUrl, null, null);
        Document doc = DocumentHelper.parseText(response);
        int hits = Integer.parseInt(doc.selectSingleNode("//totalResultsAvailable").getText());

        start = 0;
        limit = 10;
        if (hits > 0) {
            while (start < hits) {
                baseUrl = uri.replace("{start}", Integer.toString(start)).replace("{limit}",
                        Integer.toString(limit));

                logger.error("get pages " + baseUrl);
                response = HttpHelper.sendRequest("GET", baseUrl, null, null);
                doc = DocumentHelper.parseText(response);
                partialNodes = doc.selectNodes("//page");
                start += limit;
                nodes.addAll(partialNodes);
            }

            String id, name, order;
            Element propElem;
            logger.error("nr of nodes found: " + nodes.size());
            for (Iterator<Node> iter = nodes.iterator(); iter.hasNext();) {
                Element elem = (Element) iter.next();
                Properties props = new Properties();
                //props.put("starttime", starttime);
                // get id, name, uri and properties
                id = elem.valueOf("@id");
                name = elem.getName();
                if (!name.equals("page"))
                    continue;

                propElem = (Element) elem.selectSingleNode("properties");
                order = "";
                order = propElem.valueOf("order");
                if (order.equals(""))
                    continue;
                props.put("id", id);
                props.put("order", order);
                map.add(props);
            }
        } else {
            return false;
        }
    } catch (Exception e) {
        logger.error("", e);
        return false;
    }
    return true;
}

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

License:Open Source License

/**
 * Returns a map with the refactorred events
 * /*from   w  w w. j ava  2 s . c o m*/
 * @param currentEvents
 * @param from
 * @param to
 * @param millis
 * @return
 */
private Map<String, String> refactorEvents(Map<String, String> currentEvents, double from, double to,
        double millis) {
    logger.debug("refactoring events");
    Map<String, String> map = new HashMap<String, String>();

    // loop through events
    String uri, properties, starttimeStr;
    Document doc;
    Element propElem;
    double stOld, stNew;
    for (Iterator<String> iter = currentEvents.keySet().iterator(); iter.hasNext();) {
        uri = iter.next();
        properties = currentEvents.get(uri);
        try {
            // parse properties
            doc = DocumentHelper.parseText(properties);
            propElem = doc.getRootElement();

            // starttime
            starttimeStr = propElem.selectSingleNode("starttime").getText();
            stOld = Double.parseDouble(starttimeStr);

            // check if starttime is within boundaries
            if (stOld >= from && stOld <= to) {
                // update starttime
                stNew = stOld + millis;
                propElem.selectSingleNode("starttime").setText(Double.toString(stNew));
                logger.debug("refactor -- uri: " + uri + ", old: " + stOld + ", new: " + stNew);

                // put in map
                map.put(uri, propElem.asXML());
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    return map;
}