Example usage for org.dom4j Element elementIterator

List of usage examples for org.dom4j Element elementIterator

Introduction

In this page you can find the example usage for org.dom4j Element elementIterator.

Prototype

Iterator<Element> elementIterator();

Source Link

Document

Returns an iterator over all this elements child elements.

Usage

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

License:Open Source License

/**
 * Splits the videoplaylist at a given number of milliseconds.
 * Finds which video clip is running at the given time and splits it  
 * /*  www . ja  v  a2s.  c  o m*/
 * @param input
 * @param uri
 * @return
 */
private String split(Properties input, String uri) {
    // parse parameters
    double time;
    String timeStr;
    totalPrevDuration = 0d;
    int new_position = 0;
    map_joined.clear();
    map_joined = null;
    map_joined = new ArrayList<Properties>();

    try {

        time = Double.parseDouble(input.getProperty("time"));
        timeStr = Double.toString(time);
    } catch (Exception e) {
        logger.error("Parameters could not be parsed", e);
        return FSXMLBuilder.getErrorMessage("500", "Parameters could not be parsed",
                "Please call this command as follows: split AT MILLIS", "http://teamelements.noterik.com/team");
    }

    // check uri
    if (!URIParser.getParentUriPart(uri).equals("videoplaylist")) {
        return FSXMLBuilder.getErrorMessage("500", "Incorrect uri, should be a videoplaylist uri",
                "Please call this command as follows: split AT MILLIS", "http://teamelements.noterik.com/team");
    }

    // get all clips from the given uri
    ArrayList<Properties> currentClips = getClips(uri);
    //Get the clip that needs to be splitted in the videoplaylist
    String clipURI = getVideoClip(currentClips, time);
    if (clipURI == null) {
        return FSXMLBuilder.getErrorMessage("500", "Clip to split not found!",
                "Please call this command as follows: split AT MILLIS", "http://teamelements.noterik.com/team");
    }
    logger.debug("Clip to split" + clipURI);

    Document doc = FSXMLRequestHandler.instance().getNodeProperties(clipURI, false);
    //Get the referif
    Element videoElem = (Element) doc.selectSingleNode("//video");
    String referid = videoElem.valueOf("@referid");

    //Get the video duration from the original video
    double originalDuration = getOriginalDuration(referid);

    logger.debug("Original duration" + Double.toString(originalDuration));

    Element propElem = (Element) doc.selectSingleNode("//properties");
    Element elem;
    String key, src_properties, trg_properties;

    double src_duration = time - totalPrevDuration;
    trg_properties = "<properties>";
    src_properties = "<properties>";
    boolean foundStart = false, foundDuration = false;
    for (Iterator<Element> iter = propElem.elementIterator(); iter.hasNext();) {
        try {
            // get element
            elem = iter.next();
            key = elem.getName();
            logger.debug("Element: " + key);
            if (key == "starttime") {
                foundStart = true;
                logger.debug("FOUND starttime!!!");
                src_properties += elem.asXML();
                double starttime = Double.parseDouble(elem.getTextTrim());
                elem.setText(Double.toString(starttime + src_duration));
                trg_properties += elem.asXML();
            }

            if (key == "duration") {
                foundDuration = true;
                logger.debug("FOUND duration!!!");
                src_properties += "<duration>" + Double.toString(src_duration) + "</duration>";
                double trg_duration = Double.parseDouble(elem.getTextTrim());
                logger.debug("Setting target duration: " + Double.toString(trg_duration - src_duration));
                elem.setText(Double.toString(trg_duration - src_duration));
                trg_properties += elem.asXML();
            }

            if (key == "position") {
                src_properties += elem.asXML();
                int position = Integer.parseInt(elem.getTextTrim());
                position++;
                new_position = position;
                logger.debug("FOUND position!!!" + Integer.toString(new_position));
                trg_properties += "<position>" + Integer.toString(position) + "</position>";
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    if (!foundStart) {
        logger.debug("NOT FOUND starttime!!!");
        src_properties += "<starttime>0</starttime>";
        trg_properties += "<starttime>" + timeStr + "</starttime>";
    }

    if (!foundDuration) {
        logger.debug("NOT FOUND duration!!!");
        src_properties += "<duration>" + Double.toString(src_duration) + "</duration>";
        trg_properties += "<duration>" + Double.toString(originalDuration - src_duration) + "</duration>";
        logger.debug("Setting target duration: " + Double.toString(originalDuration - src_duration));
    }

    src_properties += "</properties>";
    trg_properties += "</properties>";
    logger.debug("Source video prop XML: " + src_properties);
    logger.debug("Target video prop XML:: " + trg_properties);
    // process splitting
    boolean success = FSXMLRequestHandler.instance().saveFsXml(clipURI + "/properties",
            "<fsxml>" + src_properties + "</fsxml>", "PUT", true);
    if (success) {
        String attributes = "<attributes><referid>" + referid + "</referid></attributes>";
        String response = FSXMLRequestHandler.instance().handlePOST(uri + "/video",
                "<fsxml>" + attributes + "</fsxml>");
        if (FSXMLParser.getErrorMessageFromXml(response) != null) {
            return FSXMLBuilder.getErrorMessage("500", "Failed to duplicate video in playlist ",
                    "Please call this command as follows: split AT MILLIS",
                    "http://teamelements.noterik.com/team");
        }

        fixPositions(uri, new_position);

        Document resDoc = XMLHelper.asDocument(response);
        Element resElem = (Element) resDoc.selectSingleNode("//uri");
        String new_video_uri = resElem.getTextTrim();
        response = FSXMLRequestHandler.instance().handlePUT(new_video_uri + "/properties",
                "<fsxml>" + trg_properties + "</fsxml>");
        if (FSXMLParser.getErrorMessageFromXml(response) != null) {
            return FSXMLBuilder.getErrorMessage("500", "Failed to update properties of " + new_video_uri,
                    "Please call this command as follows: split AT MILLIS",
                    "http://teamelements.noterik.com/team");
        }
    } else {
        return FSXMLBuilder.getErrorMessage("500", "Failed to update properties of " + clipURI,
                "Please call this command as follows: split AT MILLIS", "http://teamelements.noterik.com/team");
    }

    logger.debug("*********** END OF PROCESS **********");
    return FSXMLBuilder.getStatusMessage("Successfully updated events", "Successfully updated events", clipURI);
}

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

License:Open Source License

private ArrayList<Properties> getClips(String uri) {
    logger.debug("getting clips for videoplaylist: " + uri);
    ArrayList<Properties> map = new ArrayList<Properties>();
    SortedMap map_positioned = new TreeMap();
    Document doc = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
    try {//from  w w w  .  java 2s  .c  o  m
        // get videoplaylist
        Element videoplaylist = (Element) doc.selectSingleNode("//videoplaylist[@id='1']");

        // get all child nodes
        Element elem, propElem;
        String id, name, eUri, properties, starttime, duration, referid, position;
        for (Iterator<Element> iter = videoplaylist.elementIterator(); iter.hasNext();) {
            try {
                // get element
                elem = iter.next();

                // get id, name, uri and properties
                id = elem.valueOf("@id");
                name = elem.getName();
                if (!name.equals("video"))
                    continue;

                referid = elem.valueOf("@referid");

                Properties props = new Properties();
                propElem = (Element) elem.selectSingleNode("properties");
                starttime = propElem.valueOf("starttime");
                starttime = starttime != "" ? starttime : "0";
                props.put("starttime", starttime);
                duration = propElem.valueOf("duration");
                if (duration == null || duration == "") {
                    Document refDoc = FSXMLRequestHandler.instance().getNodeProperties(referid, false);
                    // get original video
                    Element origVideoProps = (Element) refDoc.selectSingleNode("//rawvideo[@id='1']")
                            .selectSingleNode("properties");
                    if (origVideoProps == null) {
                        origVideoProps = (Element) refDoc.selectSingleNode("//rawvideo[@id='2']")
                                .selectSingleNode("properties");
                    }
                    duration = origVideoProps.valueOf("duration");
                    //Convert to milliseconds
                    double dur = Double.parseDouble(duration);
                    dur = dur * 1000;
                    duration = Double.toString(dur);
                }
                props.put("duration", duration);
                position = propElem.valueOf("position");
                if (position != null && position != "") {
                    props.put("position", position);
                }
                logger.debug(name + "/" + id + " starttime: " + starttime);
                logger.debug(name + "/" + id + " duration: " + duration);
                properties = propElem != null ? propElem.asXML() : null;
                eUri = uri + "/" + name + "/" + id;
                logger.debug("id: " + id + ", name: " + name + ", eventUri: " + eUri + ", properties: "
                        + properties);
                props.put("uri", eUri);
                // add to map

                if (position != null && position != "") {
                    map_positioned.put(Integer.parseInt(position), props);
                } else {
                    map.add(props);
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    } catch (Exception e) {
        logger.error("", e);
    }

    map_joined.addAll(map);
    map_joined.addAll(map_positioned.values());
    int count = 0;
    for (Iterator<Properties> iter = map_joined.iterator(); iter.hasNext();) {
        count++;
        Properties cur_map = iter.next();
        String map_uri = cur_map.getProperty("uri");
        String map_starttime = cur_map.getProperty("starttime");
        String map_duration = cur_map.getProperty("duration");
        String position = "<properties><position>" + Integer.toString(count) + "</position><starttime>"
                + map_starttime + "</starttime><duration>" + map_duration + "</duration></properties>";
        logger.debug("Joining maps uri: " + map_uri);
        logger.debug("Joining maps properties: " + position);
        String response = FSXMLRequestHandler.instance().handlePUT(map_uri + "/properties",
                "<fsxml>" + position + "</fsxml>");
    }

    return map_joined;
}

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

License:Open Source License

private void fixPositions(String uri, int position) {
    logger.debug("fix positions for: " + uri);
    int current_position = position;
    Document doc = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
    try {/*from   w  w  w.j  a  v a 2  s .c  om*/
        // get videoplaylist
        Element videoplaylist = (Element) doc.selectSingleNode("//videoplaylist[@id='1']");

        // get all child nodes
        Element elem, propElem;
        String id, name;
        for (Iterator<Element> iter = videoplaylist.elementIterator(); iter.hasNext();) {
            try {
                // get element
                elem = iter.next();

                // get id, name, uri and properties
                id = elem.valueOf("@id");
                name = elem.getName();
                if (!name.equals("video"))
                    continue;
                String properties = "<properties>";
                propElem = (Element) elem.selectSingleNode("properties");

                for (Iterator<Element> iter2 = propElem.elementIterator(); iter2.hasNext();) {
                    try {
                        // get element
                        Element videoElem = iter2.next();
                        String property = videoElem.getName();
                        String value = videoElem.getTextTrim();
                        if (property != "starttime" && property != "duration" && property != "position")
                            continue;
                        if (property == "position") {
                            int posvalue = (value != "" ? Integer.parseInt(value) : 0);
                            logger.debug("OLD Position is: " + Integer.toString(posvalue));
                            if (posvalue >= current_position) {
                                posvalue++;
                                logger.debug("NEW Position is: " + Integer.toString(posvalue));
                                properties += "<position>" + Integer.toString(posvalue) + "</position>";
                            } else {
                                properties += videoElem.asXML();
                            }
                        } else {
                            properties += videoElem.asXML();
                        }

                    } catch (Exception e) {
                        logger.error("", e);
                    }
                }
                properties += "</properties>";
                logger.debug("Fix position of: " + uri + "/video/" + id);
                logger.debug("Properties are: " + properties);
                String response = FSXMLRequestHandler.instance().handlePUT(uri + "/video/" + id + "/properties",
                        "<fsxml>" + properties + "</fsxml>");
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:com.noterik.bart.fs.legacy.tools.FlandersHelper.java

License:Open Source License

private static String processXml(String original, String flanders) {
    String xml = "";

    Map<String, String> values = new HashMap<String, String>();

    Document origdoc = null;/* www .  j a  va 2  s  .  co  m*/
    Document flandoc = null;

    try {
        origdoc = DocumentHelper.parseText(original);
        flandoc = DocumentHelper.parseText(flanders);
    } catch (DocumentException e) {
        LOG.error("", e);
    }

    Element origProp = (Element) origdoc.selectSingleNode("//properties");
    Iterator i = origProp.elementIterator();

    while (i.hasNext()) {
        Element prop = (Element) i.next();
        String name = prop.getName();
        String value = prop.getText();
        values.put(name, value);
    }

    LOG.debug("\n flandProp = " + flandoc.asXML());

    Element flandProp = (Element) flandoc.selectSingleNode("/meta-data");
    Iterator j = flandProp.elementIterator();

    while (j.hasNext()) {
        Element prop = (Element) j.next();
        String name = prop.getName();
        String value = prop.getText();
        values.put(name, value);
    }

    Element finalEl = DocumentHelper.createElement("fsxml");
    Element propsEl = finalEl.addElement("properties");

    Iterator<String> it = values.keySet().iterator();
    while (it.hasNext()) {
        String name = it.next();
        String value = values.get(name);
        propsEl.addElement(name).addText(value);
    }

    xml = finalEl.asXML();

    return xml;
}

From source file:com.openedit.users.filesystem.MapPropertyContainer.java

License:Open Source License

/**
 * Load the properties from the given element.
 *
 * @param inPropertiesElement The element (hopefully created via
 *         <code>createPropertiesElement</code>) from which to load the properties
 *//*from www  .ja v  a 2 s  . c om*/
protected void loadProperties(Element inPropertiesElement) {
    Map properties = new HashMap();

    if (inPropertiesElement != null) {
        for (Iterator iter = inPropertiesElement.elementIterator(); iter.hasNext();) {
            Element elem = (Element) iter.next();

            if (elem.getName().equals("property")) {
                String name = elem.attributeValue("name");
                String value = elem.attributeValue("value");

                if ((name != null) && (value != null)) {
                    properties.put(name, value);
                }
            }
        }
    }

    fieldProperties = properties;
}

From source file:com.openkm.openmeetings.service.RestService.java

License:Open Source License

/**
 * call/* ww  w. java 2  s  .  c o m*/
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static Map<String, Element> callMap(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    Map<String, Element> elementMap = new LinkedHashMap<String, Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        String nodeVal = item.getName();
        elementMap.put(nodeVal, item);
    }

    return elementMap;
}

From source file:com.openkm.openmeetings.service.RestService.java

License:Open Source License

/**
 * call//from  w  ww .  j  a  va 2 s .c om
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static List<Element> callList(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    List<Element> elementList = new ArrayList<Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        elementList.add(item);
    }

    return elementList;
}

From source file:com.prj.utils.UfdmXmlUtil.java

/**
 * ??: ??XML//from w w w .  j  a v a2s . c  om
 * @auther 
 * @date 2014-11-28 
 * @param element
 * @param map
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map readXml(Element element, Map map) {
    try {
        if (map == null) {
            map = new HashMap();
        }
        Iterator iter = element.elementIterator();
        while (iter.hasNext()) {
            Element ele = (Element) iter.next();
            map.put(ele.getName(), ele.getText().trim());
            if (ele.elements().size() != 0) {
                readXml(ele, map);
            }
        }
        return map;
    } catch (Exception er) {
        er.printStackTrace();
        return null;
    }
}

From source file:com.pureinfo.srm.config.affirm.model.Affirm.java

License:Open Source License

/**
 * @see com.pureinfo.force.xml.IXMLSupporter#fromXML(org.dom4j.Element)
 *///www .  jav a 2 s .  c o  m
public void fromXML(Element _element) throws PureException {
    m_affirms = new HashMap();
    for (Iterator iter = _element.elementIterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        String sName = XMLUtil.getRequiredAttributeValue(element, ATTRIBUTE_NAME);
        String sDay = XMLUtil.getRequiredAttributeValue(element, ATTRIBUTE_DAY);
        m_affirms.put(sName, sDay);
    }
}

From source file:com.pureinfo.srm.report.report.digital.parser.DisplayParser.java

License:Open Source License

private static LineGroup parseLineGroup(Element _sItem) {
    LineGroup group = new LineGroup();
    group.setGrouper(_sItem.attributeValue("grouper"));
    group.setId(_sItem.attributeValue("id"));
    group.setOther(_sItem.attributeValue("auto"));
    group.setTotal(_sItem.attributeValue("total"));
    for (Iterator iter = _sItem.elementIterator(); iter.hasNext();) {
        Element xItem = (Element) iter.next();
        DisplayItem item = parseItem(xItem);
        if (item != null) {
            group.addItem(item);/* www .j a va 2 s. c  om*/
        }
    }
    return group;
}