Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

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

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:com.liferay.util.xml.ElementComparator.java

License:Open Source License

public int compare(Object obj1, Object obj2) {
    Element el1 = (Element) obj1;
    Element el2 = (Element) obj2;

    String el1Name = el1.getName();
    String el2Name = el2.getName();

    if (!el1Name.equals(el2Name)) {
        return el1Name.compareTo(el2Name);
    }/*from w  ww .  j  a  va  2s .com*/

    String el1Text = el1.getTextTrim();
    String el2Text = el2.getTextTrim();

    if (!el1Text.equals(el2Text)) {
        return el1Text.compareTo(el2Text);
    }

    List el1Attrs = el1.attributes();
    List el2Attrs = el2.attributes();

    if (el1Attrs.size() < el2Attrs.size()) {
        return -1;
    } else if (el1Attrs.size() > el2Attrs.size()) {
        return 1;
    }

    for (int i = 0; i < el1Attrs.size(); i++) {
        Attribute attr = (Attribute) el1Attrs.get(i);

        int value = _compare(el2Attrs, attr, new AttributeComparator());

        if (value != 0) {
            return value;
        }
    }

    List el1Elements = el1.elements();
    List el2Elements = el2.elements();

    if (el1Elements.size() < el2Elements.size()) {
        return -1;
    } else if (el1Elements.size() > el2Elements.size()) {
        return 1;
    }

    for (int i = 0; i < el1Elements.size(); i++) {
        Element el = (Element) el1Elements.get(i);

        int value = _compare(el2Elements, el, new ElementComparator());

        if (value != 0) {
            return value;
        }
    }

    return 0;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.context.GeoEventDispatcher.java

License:Apache License

static Message buildGeoMessageFromPubSubIQ(final IQ geoIQ) {
    Message geoMessage = null;/*from  ww  w. j a v  a2 s. c o m*/
    if (IQ.Type.set == geoIQ.getType() && geoIQ.getTo().toString().startsWith("pubsub")) {
        // find 'geoloc'
        Element element = geoIQ.getChildElement();
        Element action = element.element("publish");
        if (action != null) {
            String nodeID = action.attributeValue("node");
            if (nodeID != null && nodeID.endsWith(TopicHelper.TOPIC_GEOLOC)) {
                // Entity publishes an item
                geoMessage = new Message();
                geoMessage.setType(Message.Type.chat);
                Map<String, String> geoValues = new HashMap<String, String>();
                JID from = geoIQ.getFrom();
                String appId = JIDUtil.getAppId(from);
                geoValues.put(APP_ID, appId);

                String userId = JIDUtil.getUserId(from);
                geoValues.put(USER_ID, userId);

                String deviceId = JIDUtil.getResource(from.toString());
                geoValues.put(DEVICE_ID, deviceId);

                Iterator<Element> items = action.elementIterator("item");
                if (items != null) {
                    while (items.hasNext()) {
                        Element item = (Element) items.next();
                        Element mmx = item.element(Constants.MMX_ELEMENT);
                        if (mmx == null)
                            continue;
                        Element payload = mmx.element(Constants.MMX_PAYLOAD);
                        if (payload == null)
                            return null; // not a valid MMX payload, ignore it
                        Attribute timestamp = payload.attribute(Constants.MMX_ATTR_STAMP);
                        if (timestamp != null) {
                            geoValues.put(Constants.MMX_ATTR_STAMP, timestamp.getValue());
                        }
                        String geoData = payload.getTextTrim();
                        GeoLoc geoLoc = GsonData.getGson().fromJson(geoData, GeoLoc.class);
                        if (geoLoc.getAccuracy() != null) {
                            geoValues.put(ACCURACY, geoLoc.getAccuracy().toString());
                        }
                        if (geoLoc.getLng() != null && geoLoc.getLat() != null) {
                            geoValues.put(LONG, geoLoc.getLng().toString());
                            geoValues.put(LAT, geoLoc.getLat().toString());
                            // calculate geohash
                            GeoPoint point = new GeoPointDefaultImpl(geoLoc.getLat(), geoLoc.getLng());
                            geoValues.put(GEOHASH, localGeoEndocoder.get().encodePoint(point));
                        }
                        if (geoLoc.getAlt() != null) {
                            geoValues.put(ALTITUDE, Integer.toString((int) geoLoc.getAlt().floatValue()));
                        }
                        Element geoElement = geoMessage.addChildElement(Constants.MMX_ELEMENT,
                                Constants.MMX_NS_CONTEXT);
                        geoElement.addAttribute(Constants.MMX_ATTR_MTYPE, Constants.MMX_MTYPE_GEOLOC);
                        JSONObject geoJson = new JSONObject(geoValues);
                        geoElement.setText(geoJson.toString());
                        geoMessage.setBody(geoJson.toString());

                        return geoMessage;

                    }
                }
            }
        }
    }
    return null;
}

From source file:com.mgmtp.perfload.core.common.config.XmlConfigReader.java

License:Apache License

private List<TestJar> readTestJars(final Element testplan) throws IOException {
    File jarDir = new File(baseDir, "test-lib");
    @SuppressWarnings("unchecked")
    List<Element> jarElems = testplan.element("testJars").elements();
    List<TestJar> result = newArrayListWithCapacity(jarElems.size());
    for (Element jarElem : jarElems) {
        String fileName = jarElem.getTextTrim();
        byte[] jarBytes = toByteArray(new File(jarDir, fileName));
        result.add(new TestJar(fileName, jarBytes));
    }//from w w w .ja v a2 s. c  om
    return ImmutableList.copyOf(result);
}

From source file:com.mgmtp.perfload.core.common.config.XmlConfigReader.java

License:Apache License

private List<String> readJvmArgs(final Element testplan) {
    List<String> result = newArrayListWithExpectedSize(2);
    Element element = testplan.element("jvmargs");
    if (element != null) {
        @SuppressWarnings("unchecked")
        List<Element> propsElems = element.elements();
        for (Element propsElem : propsElems) {
            result.add(propsElem.getTextTrim());
        }/*from  ww  w .  j  a v a  2 s. c  o  m*/
    }
    return ImmutableList.copyOf(result);
}

From source file:com.mothsoft.alexis.engine.textual.ParseResponseMessageListener.java

License:Apache License

@SuppressWarnings("unchecked")
private ParsedContent readResponse(final String xml) throws IOException {
    // turn the content into a ParsedContent complex object
    final Map<Term, Integer> termCountMap = new HashMap<Term, Integer>();
    final Map<String, DocumentAssociation> associationCountMap = new HashMap<String, DocumentAssociation>();
    final List<DocumentNamedEntity> entities = new ArrayList<DocumentNamedEntity>();

    final List<Node> sentenceNodes = new ArrayList<Node>();

    final SAXReader saxReader = new SAXReader();

    org.dom4j.Document document;/*from w  w w. jav  a2 s.  c  o m*/
    try {
        document = saxReader.read(new StringReader(xml));
    } catch (DocumentException e) {
        throw new IOException(e);
    }

    sentenceNodes.addAll(document.selectNodes("/document/sentences/s"));

    int sentencePosition = 1;

    for (final Node ith : sentenceNodes) {
        parseSentence(sentencePosition++, (Element) ith, termCountMap, associationCountMap);
    }
    sentenceNodes.clear();

    final List<Node> nameNodes = new ArrayList<Node>();
    nameNodes.addAll(document.selectNodes("/document/names/name"));
    for (final Node node : nameNodes) {
        final Element element = (Element) node;
        final String countString = element.attributeValue("count");
        final Integer count = (countString == null ? 0 : Integer.valueOf(countString));
        final String name = element.getTextTrim();
        entities.add(new DocumentNamedEntity(name, count));
    }

    // count up all the terms in the document
    Integer documentTermCount = 0;
    for (final Term ith : termCountMap.keySet()) {
        documentTermCount += (termCountMap.get(ith));
    }

    // individual term count
    final List<DocumentTerm> documentTerms = new ArrayList<DocumentTerm>();
    for (final Term term : termCountMap.keySet()) {
        final Integer count = termCountMap.get(term);
        documentTerms.add(new DocumentTerm(term, count));
    }

    // sort the named entities by count
    Collections.sort(entities, new Comparator<DocumentNamedEntity>() {
        @Override
        public int compare(final DocumentNamedEntity e1, DocumentNamedEntity e2) {
            return -1 * e1.getCount().compareTo(e2.getCount());
        }
    });

    return new ParsedContent(associationCountMap.values(), documentTerms, entities, documentTermCount);
}

From source file:com.mpaike.core.config.xml.elementreader.GenericElementReader.java

License:Open Source License

/**
 * Creates a ConfigElementImpl object from the given element.
 * /*from ww w .j a  v a  2s.com*/
 * @param element The element to parse
 * @return The GenericConfigElement representation of the given element
 */
@SuppressWarnings("unchecked")
private GenericConfigElement createConfigElement(Element element) {
    // get the name and value of the given element
    String name = element.getName();

    // create the config element object and populate with value
    // and attributes
    GenericConfigElement configElement = new GenericConfigElement(name);
    if ((element.hasContent()) && (element.hasMixedContent() == false)) {
        String value = element.getTextTrim();
        if (value != null && value.length() > 0) {
            if (propertyConfigurer != null) {
                value = propertyConfigurer.resolveValue(value);
            }
            configElement.setValue(value);
        }
    }

    Iterator<Attribute> attrs = element.attributeIterator();
    while (attrs.hasNext()) {
        Attribute attr = attrs.next();
        String attrName = attr.getName();
        String attrValue = attr.getValue();

        if (propertyConfigurer != null) {
            attrValue = propertyConfigurer.resolveValue(attrValue);
        }

        configElement.addAttribute(attrName, attrValue);
    }

    return configElement;
}

From source file:com.nokia.helium.diamonds.XMLMerger.java

License:Open Source License

/**
 * Compare two elements name and attributes. Returns true if name and all
 * attributes are matching, false otherwise.
 * /*from w ww .ja  va  2 s.co  m*/
 * @param a
 * @param b
 * @return boolean
 */
@SuppressWarnings("unchecked")
protected boolean areSame(Element a, Element b) {
    log.debug("areSame:" + a + " <=> " + b);
    if (!a.getName().equals(b.getName())) {
        return false;
    }
    log.debug("same attribute list size?");
    if (a.attributes().size() != b.attributes().size()) {
        return false;
    }
    log.debug("same attribute list?");
    for (Iterator<Attribute> at = a.attributes().iterator(); at.hasNext();) {
        Attribute attra = at.next();
        Attribute attrb = b.attribute(attra.getName());
        if (attrb == null || !attra.getValue().equals(attrb.getValue())) {
            return false;
        }
    }
    if (!a.getTextTrim().equals(b.getTextTrim())) {
        return false;
    }
    return true;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private static IndexConfig loadIndexConfig(String configUri) {
    IndexConfig iConfig = new IndexConfig();
    String domain = URIParser.getDomainIdFromUri(configUri);
    String user = URIParser.getUserIdFromUri(configUri);
    Document cDoc = FSXMLRequestHandler.instance().getNodeProperties(configUri, false);
    if (cDoc == null) {
        // load default index configuration
        LOG.debug("Could not load config from " + configUri + " ... loading default");
        String indexType = DEFAULT_INDEX_TYPE;
        String indexUri = DEFAULT_INDEX_URI.replace("{domainid}", domain).replace("{user}", user);
        iConfig.setIndexType(indexType);
        iConfig.setIndexUri(indexUri);//w  w  w .j a  v a  2 s  . c  o m
        iConfig.setDefaultQueue(true);
    } else {
        // load config from filesystem
        LOG.debug("loaded config for " + configUri);
        List<Node> properties = cDoc.selectNodes("//properties/*");
        for (Iterator<Node> i = properties.iterator(); i.hasNext();) {
            Element property = (Element) i.next();
            String propertyName = property.getName();
            String propertyValue = property.getTextTrim();
            LOG.debug("config property: " + property);
            if (propertyName.equals("indextype")) {
                iConfig.setIndexType(propertyValue);
            } else if (property.getName().equals("indexuri")) {
                String inderUri = propertyValue.replace("{domainid}", domain).replace("{user}", user);
                iConfig.setIndexUri(inderUri);
            } else if (property.getName().equals("indexobject")) {
                iConfig.setIndexObject(propertyValue);
            } else if (property.getName().equals("presentationdate")) {
                iConfig.setProperty(propertyName, propertyValue);
            } else {
                iConfig.setProperty(propertyName, "enabled");
            }
        }
    }
    return iConfig;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private static IndexConfig loadIndexConfig(String configUri) {
    IndexConfig iConfig = new IndexConfig();
    String domain = URIParser.getDomainIdFromUri(configUri);
    String user = URIParser.getUserIdFromUri(configUri);
    Document cDoc = FSXMLRequestHandler.instance().getNodeProperties(configUri, false);
    if (cDoc == null) {
        // load default index configuration
        LOG.debug("Could not load config from " + configUri + " ... loading default");
        String indexType = DEFAULT_INDEX_TYPE;
        String indexUri = DEFAULT_INDEX_URI.replace("{domainid}", domain).replace("{user}", user);
        iConfig.setIndexType(indexType);
        iConfig.setIndexUri(indexUri);/* w  ww  . j av  a2 s .  co  m*/
        iConfig.setDefaultQueue(true);
    } else {
        // load config from filesystem
        LOG.debug("loaded config for " + configUri);
        List<Node> properties = cDoc.selectNodes("//properties/*");
        for (Iterator<Node> i = properties.iterator(); i.hasNext();) {
            Element property = (Element) i.next();
            String propertyName = property.getName();
            String propertyValue = property.getTextTrim();
            LOG.debug("config property: " + property);
            if (propertyName.equals("indextype")) {
                iConfig.setIndexType(propertyValue);
            } else if (property.getName().equals("indexuri")) {
                String inderUri = propertyValue.replace("{domainid}", domain).replace("{user}", user);
                iConfig.setIndexUri(inderUri);
            } else if (property.getName().equals("presentationdate")) {
                iConfig.setProperty(propertyName, propertyValue);
            } else {
                iConfig.setProperty(propertyName, "enabled");
            }
        }
    }
    return iConfig;
}

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  
 * /*  w ww .  ja v a 2  s  .  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);
}