Example usage for org.dom4j Element elementText

List of usage examples for org.dom4j Element elementText

Introduction

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

Prototype

String elementText(QName qname);

Source Link

Usage

From source file:com.rowtheboat.input.VariableSplitInput.java

License:Open Source License

/**
 * Construct the variable split class/*from   w  w  w .jav a  2  s .co  m*/
 * 
 * @param   file   the file from which to pull the xml workout data
 */
public VariableSplitInput(File file) throws MalformedURLException, DocumentException {

    /* Initialise the arrays */
    times = new float[10];
    timeIndexes = new int[10];

    /* Create the reader */
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);

    /* Get the root element */
    root = document.getRootElement();

    /* Create the rower */
    for (Iterator i = root.elementIterator("Rower"); i.hasNext();) {

        Element rowerElement = (Element) i.next();
        ComputerRower rower = new ComputerRower(ComputerRower.VARIABLE_SPLIT);
        rower.setName(rowerElement.elementText("Name"));
    }

    /* Create the workout */
    for (Iterator i = root.elementIterator("Details"); i.hasNext();) {

        Element wElement = (Element) i.next();
        Workout workout = new Workout(Integer.parseInt(wElement.elementText("Type")));
        workout.setDate(wElement.elementText("Date"));
        if (workout.getType() == Workout.DISTANCE_WORKOUT) {
            workout.setDistance(Integer.parseInt(wElement.elementText("Distance")));
        } else {
            workout.setTime(Integer.parseInt(wElement.elementText("Time")));
        }
    }

    /* Populate the stroke times and time index arrays */
    int arrayIndex = 0;
    for (int i = 0, size = root.nodeCount(); i < size; i++) {
        Node node = root.node(i);
        if (node instanceof Element && node.getName().equals("Stroke")) {
            Element el = (Element) node;
            times[arrayIndex] = Float.parseFloat(el.elementText("Time"));
            timeIndexes[arrayIndex] = i;
            arrayIndex++;
            if (arrayIndex == times.length) {
                increaseArraySizes();
            }
        }
    }
}

From source file:com.rowtheboat.input.VariableSplitInput.java

License:Open Source License

public StrokeData retrieveStrokeData(float time) throws Exception {

    boolean nextStrokeExists = true;

    while (true) {
        if (lastStrokeIndex != 0 && times[lastStrokeIndex] == 0.0) {
            /* If this isn't the first stroke index and the distance is 0.0 then the last
             * distance was the final one because any uninitialised floats are 0.0  Thus
             * decrease the index and break */
            lastStrokeIndex--;/*w w w  .  ja v a  2s  . co  m*/
            nextStrokeExists = false;
            break;
        }
        if (time >= times[lastStrokeIndex]) {
            /* If the time required is greater or equal than the stroke then proceed  */

            if (lastStrokeIndex < times.length - 1) {
                /* If the last stroke index is less than the length - 1 then proceed and test
                 * whether the time required is less than the next stroke.  If so break as we
                 * have the correct stroke index.  Otherwise fall out of if statements,
                 * increase index and try again. */
                if (time < times[lastStrokeIndex + 1]) {
                    break;
                }
            }

            /* Increment the index if not broken out already (i.e. found the required stroke
             * index) */
            lastStrokeIndex++;
        }
    }

    /* Create the stroke */
    StrokeData stroke = new StrokeData();
    Element strokeEl = (Element) root.node(timeIndexes[lastStrokeIndex]);

    /* If there's another stroke available create more accurate distances and times */
    if (nextStrokeExists) {
        float time1 = times[lastStrokeIndex];
        float time2 = times[lastStrokeIndex + 1];
        float dist1 = Float.parseFloat(strokeEl.elementText("Distance"));
        Element e = (Element) root.node(timeIndexes[lastStrokeIndex + 1]);
        float dist2 = Float.parseFloat(e.elementText("Distance"));
        double mPerS = (dist2 - dist1) / (time2 - time1);
        stroke.setDistance((float) (((time - time1) * mPerS) + dist1));
        stroke.setTime(time);
    } else {
        stroke.setDistance(Float.parseFloat(strokeEl.elementText("Distance")));
        stroke.setTime(times[lastStrokeIndex]);
    }

    /* Check to see whether full stroke information is available */
    double split = Double.parseDouble(strokeEl.elementText("Split"));
    if (split != 0.0) {
        /* Full stroke data was switched on */
        stroke.setPower(Double.parseDouble(strokeEl.elementText("Power")));
        stroke.setStrokeRate(Integer.parseInt(strokeEl.elementText("SPM")));
        stroke.setHeartRate(Float.parseFloat(strokeEl.elementText("HR")));
    }

    /* Return the stroke */
    return stroke;
}

From source file:com.safi.workshop.sqlexplorer.dbproduct.AliasManager.java

License:Open Source License

/**
 * Upgrades a v3 definition (java beans style) to v3.5.0beta2 and onwards
 * /*from ww w.  j  a  v a 2s . c  o m*/
 * @param beans
 * @return
 */
protected Element convertToV350(Element beans) {
    Element result = new DefaultElement(Alias.ALIASES);
    for (Object o : beans.elements("Bean")) {
        Element bean = (Element) o;
        Element alias = result.addElement(Alias.ALIAS);
        alias.addAttribute(Alias.AUTO_LOGON,
                Boolean.toString(getBoolean(bean.elementText("autoLogon"), false)));
        alias.addAttribute(Alias.CONNECT_AT_STARTUP,
                Boolean.toString(getBoolean(bean.elementText("connectAtStartup"), false)));
        alias.addAttribute(Alias.DRIVER_ID, bean.element("driverIdentifier").elementText("string"));
        alias.addElement(Alias.NAME).setText(bean.elementText("name"));
        Element userElem = alias.addElement(Alias.USERS).addElement(User.USER);
        userElem.addElement(User.USER_NAME).setText(bean.elementText("userName"));
        userElem.addElement(User.PASSWORD).setText(bean.elementText("password"));
        alias.addElement(Alias.URL).setText(bean.elementText("url"));
        alias.addElement(Alias.FOLDER_FILTER_EXPRESSION).setText(bean.elementText("folderFilterExpression"));
        alias.addElement(Alias.NAME_FILTER_EXPRESSION).setText(bean.elementText("nameFilterExpression"));
        alias.addElement(Alias.SCHEMA_FILTER_EXPRESSION).setText(bean.elementText("schemaFilterExpression"));
    }

    return result;
}

From source file:com.safi.workshop.sqlexplorer.dbproduct.DriverManager.java

License:Open Source License

/**
 * Converts from the old v3 format (which is a JavaBean encoding)
 * /*  w ww .  j av a2 s  .c  om*/
 * @param root
 * @return
 */
protected Element convertFromV3(Element root) {
    Element result = new DefaultElement(DRIVERS);
    for (Object o : root.elements("Bean")) {
        Element elem = (Element) o;
        String str;
        Element driver = result.addElement(DRIVER);

        try {
            str = elem.element("identifier").elementText("string");
            driver.addAttribute(ID, str);

            str = elem.elementText("driverClass");
            if (str != null)
                driver.addElement(DRIVER_CLASS).setText(str);

            str = elem.elementText("name");
            driver.addElement(NAME).setText(str);

            str = elem.elementText("url");
            driver.addElement(URL).setText(str);

            Element jars = driver.addElement(JARS);
            Element jarFileNames = elem.element("jarFileNames");
            for (Object o2 : jarFileNames.elements("Bean")) {
                Element jarBeanElem = (Element) o2;
                str = jarBeanElem.elementText("string");
                if (str != null && str.trim().length() > 0)
                    jars.addElement(JAR).setText(str);
            }
        } catch (IllegalArgumentException e) {
            SQLExplorerPlugin.error("Error loading v3 driver " + driver.attributeValue(ID), e);
            throw e;
        }
    }

    return result;
}

From source file:com.safi.workshop.sqlexplorer.dbproduct.User.java

License:Open Source License

/**
 * Constructs a User, from a definition previously recorded by describeAsXml()
 * /*w w  w. jav  a 2s  .co  m*/
 * @param root
 */
public User(Element root) {
    super();
    this.userName = root.elementText(USER_NAME);
    this.password = root.elementText(PASSWORD);
    autoCommit = getBoolean(root.attributeValue(AUTO_COMMIT), true);
    commitOnClose = getBoolean(root.attributeValue(COMMIT_ON_CLOSE), true);
}

From source file:com.sdk.msg.InMsgParaser.java

License:Apache License

@SuppressWarnings("unused")
public static void main(String[] args) throws DocumentException {
    String xml = "<xml>\n" + "<ToUserName><![CDATA[James]]></ToUserName>\n"
            + "<FromUserName><![CDATA[JFinal]]></FromUserName>\n" + "<CreateTime>1348831860</CreateTime>\n"
            + "<MsgType><![CDATA[text]]></MsgType>\n" + "<Content><![CDATA[this is a test]]></Content>\n"
            + "<MsgId>1234567890123456</MsgId>\n" + "</xml>";

    //      InTextMsg msg = (InTextMsg)parse(xml);
    //      System.out.println(msg.getToUserName());
    //      System.out.println(msg.getFromUserName());
    //      System.out.println(msg.getContent());

    String xml_2 = "<xml>\n" + "<ToUserName>o_p8Lt5PM0jHki-RJ7i4aNYqYO4s</ToUserName>\n"
            + "<FromUserName>gh_b662f7a195f4</FromUserName>\n" + "<CreateTime>1348831860</CreateTime>\n"
            + "<MsgType><![CDATA[text]]></MsgType>\n" + "<Content><![CDATA[this is a test]]></Content>\n"
            + "<MsgId>1234567890123456</MsgId>\n" + "</xml>";

    Document doc = DocumentHelper.parseText(xml_2);
    Element root = doc.getRootElement();
    String value = root.elementText("abc");
    System.out.println(value);//from w w w .j a  va  2s  .  c o  m
}

From source file:com.surevine.chat.openfire.audit.AuditMessageFactory.java

License:Open Source License

/**
 * Creates an {@link AuditMessage} from an XMPP {@link Message} packet. This method only
 * supports the creation of <code>AuditMessage</code> objects from <code>Message</code> objects
 * of the type {@link Message.Type.normal} , {@link Message.Type.chat} and
 * {@link Message.Type.groupchat}./*  ww w  .jav a2  s  . com*/
 * 
 * @param message
 *            The XMPP Message packet.
 * @return The <code>AuditMessage</code> for the provided <code>Message</code> or an
 *         <code>AuditException</code> if the <code>Message</code> is <code>null</code> or an
 *         unsupported type.
 */
public AuditMessage createAuditMessage(final Message message) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating an audit message from a message packet: " + message);
    }
    if (message == null) {
        throw new AuditException("Unable to create an audit message from a null message packet");
    }

    /*
     * We are only interested in the message types for normal, chat or groupchat. If we receive
     * any other types then an error has occurred with the packet filtering.
     */
    AuditEvent event = null;
    final Message.Type messageType = message.getType();
    if (messageType == Message.Type.normal) {
        event = AuditEvent.INVITATION;
    } else if (messageType == Message.Type.chat) {
        event = AuditEvent.CHAT_MSG;
    } else if (messageType == Message.Type.groupchat) {
        event = AuditEvent.GROUP_CHAT_MSG;
    } else {
        throw new AuditException("Unsupported message type found when creating an audit message");
    }

    String sender = message.getFrom().toString();
    String receiver = message.getTo().toString();
    Date eventTime = new Date();
    String content = message.getBody();
    String securityLabel = "";

    try {
        Element element = message.getExtension(IXmppSecurityLabelExtension.XEP_0258_XML_ELEMENT,
                IXmppSecurityLabelExtension.XEP_0258_XML_NAMESPACE).getElement();
        securityLabel = element.elementText(DISPLAY_MARKING);
    } catch (NullPointerException npe) {
        LOG.info("No SecurityLabelExtension for groupChat");
    }

    return new AuditMessage(event, sender, receiver, eventTime, content, securityLabel);
}

From source file:com.taobao.osceola.demo.acount.persist.service.impl.AccountPersistServiceImpl.java

License:Open Source License

@Override
public Account readAccount(String id) throws AccountPersistException {
    Document doc = readDocument();

    Element accountsEle = doc.getRootElement().element(ELEMENT_ACCOUNTS);

    for (Element accountEle : accountsEle.elements()) {
        if (accountEle.elementText(ELEMENT_ACCOUNT_ID).equals(id)) {
            return buildAccount(accountEle);
        }//from www  . j av a  2 s  . com
    }
    return null;
}

From source file:com.taobao.osceola.demo.acount.persist.service.impl.AccountPersistServiceImpl.java

License:Open Source License

/**
 * @param accountEle//from   w  w  w.j a  v  a2 s. co  m
 * @return
 */
private Account buildAccount(Element element) {
    Account account = new Account();

    account.setId(element.elementText(ELEMENT_ACCOUNT_ID));
    account.setName(element.elementText(ELE_ACCOUNT_NAME));
    account.setEmail(element.elementText(ELE_ACCOUNT_EMAIL));
    account.setPassword(element.elementText(ELEMENT_ACCOUNT_PASSWORD));
    account.setActivated(element.elementText(ELEMENT_ACCOUNT_ACTIVATED).equals("true"));

    return account;
}

From source file:com.tchepannou.sms.dynamark.DynamarkGateway.java

License:Apache License

public SMSResponse process(SMSRequest request) throws IOException {
    String user = _properties.getProperty(PROPERTY_USER);
    String password = _properties.getProperty(PROPERTY_PASSWORD);

    HttpClient client = new HttpClient();

    /* posting */
    String url = "http://services.dynmark.com/HttpServices/SendMessage.ashx";
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
    NameValuePair[] data = { new NameValuePair("user", user), new NameValuePair("password", password),
            new NameValuePair("to", request.getTo()), new NameValuePair("text", request.getBody()) };

    post.setRequestBody(data);/* w w  w .  j av a2 s.c  om*/
    client.executeMethod(post);
    //String response = post.getResponseBodyAsString();

    SMSResponse resp = new SMSResponse();
    SAXReader reader = new SAXReader();
    try {
        Document doc = reader.read(post.getResponseBodyAsStream());
        Element root = doc.getRootElement();
        String status = root.attributeValue("status");
        if ("failed".equals(status)) {
            resp.setSuccess(false);
            resp.setStatus(status);
            resp.setStatusText(root.elementText("failureDescription"));
        } else {
            Element r = root.element("Response");
            resp.setSuccess(true);
            resp.setTransactionId(r.attributeValue("TransactionID"));
        }

        return resp;
    } catch (DocumentException e) {
        throw new IOException("Document error", e);
    }
}