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:org.jcommon.com.wechat.data.XmlObject.java

License:Apache License

private void xml2Object() {
    if (this.xml == null)
        return;//ww  w  .  j  a va  2  s.c  o  m
    for (Class<?> clazz = getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
        Field[] fs = clazz.getDeclaredFields();
        Class<?> type = null;
        for (Field f : fs) {
            String name = f.getName();
            Method m = ConfigLoader.getMethod(getClass(), "set" + name);
            if (m == null) {
                m = ConfigLoader.getMethod(getClass(), "is" + name);
            }
            Document document = null;
            Element root = null;
            try {
                document = DocumentHelper.parseText(this.xml);
                root = document.getRootElement();
            } catch (DocumentException e) {
                this.logger.error(this.xml, e);
            }
            if (root == null)
                return;

            if ((m != null) && (root.element(name) != null))
                try {
                    String value = root.element(name).getTextTrim();
                    if (notNull(value)) {
                        type = f.getType();
                        Object args = null;
                        if (String.class == type)
                            args = value;
                        else if ((Integer.class == type) || (Integer.TYPE == type))
                            args = Integer.valueOf(value);
                        else if ((Boolean.class == type) || (Boolean.TYPE == type))
                            args = Boolean.valueOf(Boolean.parseBoolean(value));
                        else if ((Long.class == type) || (Long.TYPE == type))
                            args = Long.valueOf(value);
                        else if ((Float.class == type) || (Float.TYPE == type))
                            args = Float.valueOf(value);
                        try {
                            if (args != null)
                                m.invoke(this, new Object[] { args });
                        } catch (Exception e) {
                            this.logger.warn(e);
                        }
                    }
                } catch (Exception e) {
                    this.logger.error("", e);
                }
        }
    }
}

From source file:org.jcommon.com.wechat.WechatSessionManager.java

License:Apache License

public void onCallback(String encrypt_type, String msg_signature, String signature, String timestamp,
        String nonce, String xml) {
    this.logger.info(xml);
    Document document = null;/*from   w  w  w.  j  ava  2s  . co m*/
    Element root = null;
    boolean done = false;
    String touser = null;
    try {
        document = DocumentHelper.parseText(xml);
        root = document.getRootElement();
    } catch (DocumentException e) {
        this.logger.error(xml, e);
    }
    if (root == null)
        return;

    List<WechatSession> sessions = SessionCache.instance().getAllWechatSession();
    if (root.element("Encrypt") != null) {
        Encrypt encrypt = new Encrypt(encrypt_type, msg_signature, signature, timestamp, nonce, xml);
        touser = encrypt.getToUserName();
        for (WechatSession session : sessions) {
            if ((touser != null && touser.equals(session.getWechatID())) || "*".equals(session.getWechatID())) {
                try {
                    String msg = session.onEncrypt(encrypt);
                    if (msg != null) {
                        onCallback(signature, timestamp, nonce, msg);
                    }
                    done = true;
                } catch (AesException e) {
                    // TODO Auto-generated catch block
                    logger.error("", e);
                }
            }
        }
    }
    if (!done)
        logger.warn("can't find session of " + touser);
}

From source file:org.jcommon.com.wechat.WechatSessionManager.java

License:Apache License

public void onCallback(String signature, String timestamp, String nonce, String xml) {
    this.logger.info(xml);
    Document document = null;/* www . j av a 2  s .c  o  m*/
    Element root = null;
    boolean done = false;
    String touser = null;
    try {
        document = DocumentHelper.parseText(xml);
        root = document.getRootElement();
    } catch (DocumentException e) {
        this.logger.error(xml, e);
    }
    if (root == null)
        return;

    List<WechatSession> sessions = SessionCache.instance().getAllWechatSession();
    if (root.element("Event") != null) {
        Event event = new Event(xml, signature, timestamp, nonce);
        touser = event.getToUserName();
        for (WechatSession session : sessions) {
            if ((touser != null && touser.equals(session.getWechatID())) || "*".equals(session.getWechatID())) {
                session.onEvent(event);
                done = true;
            }
        }
    } else {
        InMessage msg = new InMessage(xml, signature, timestamp, nonce);
        touser = msg.getToUserName();
        for (WechatSession session : sessions) {
            if ((touser != null && touser.equals(session.getWechatID())) || "*".equals(session.getWechatID())) {
                session.onMessage(msg);
                done = true;
            }
        }
    }
    if (!done)
        logger.warn("can't find session of " + touser);
}

From source file:org.jinglenodes.JingleNodesComponent.java

License:Open Source License

@Override
protected IQ handleIQGet(IQ iq) throws Exception {
    final IQ reply = IQ.createResultIQ(iq);

    final Element element = iq.getChildElement();
    final String namespace = element.getNamespaceURI();

    if (JingleChannelIQ.NAME.equals(element.getName()) && JingleChannelIQ.NAMESPACE.equals(namespace)
            && UDP.equals(element.attributeValue(PROTOCOL))) {
        final Element childElement = iq.getChildElement().createCopy();
        final RelayChannel channel = plugin.createRelayChannel();

        if (channel != null) {

            childElement.addAttribute(HOST, plugin.getPublicIP());
            childElement.addAttribute(LOCAL_PORT, Integer.toString(channel.getPortA()));
            childElement.addAttribute(REMOTE_PORT, Integer.toString(channel.getPortB()));

            reply.setChildElement(childElement);

            Log.debug("Created relay channel {}:{}, {}:{}, {}:{}",
                    new Object[] { HOST, plugin.getPublicIP(), LOCAL_PORT, Integer.toString(channel.getPortA()),
                            REMOTE_PORT, Integer.toString(channel.getPortB()) });

        } else {/*from  w  w  w .  ja  va  2s. c  o  m*/
            reply.setError(PacketError.Condition.internal_server_error);
        }
        return reply;
    } else if (JingleTrackerIQ.NAME.equals(element.getName()) && JingleTrackerIQ.NAMESPACE.equals(namespace)) {

        final List<TrackerEntry> entries = new ArrayList<TrackerEntry>();
        entries.add(new TrackerEntry(TrackerEntry.Type.relay, TrackerEntry.Policy._roster,
                plugin.getServiceName() + "." + getDomain(), UDP));

        final String elements = getChildElementXML(entries);

        final Element e = DocumentHelper.parseText(elements).getRootElement();

        reply.setChildElement(e);

        return reply;
    }

    return null; // feature not implemented.
}

From source file:org.jitsi.jigasi.xmpp.CallControlComponent.java

License:Apache License

protected void sendPacketXml(String xmlToSend) {
    try {/*w  w w  .  j  a v a  2  s .com*/
        Document doc = DocumentHelper.parseText(xmlToSend);

        org.xmpp.packet.Message toSend = new Message(doc.getRootElement());

        send(toSend);
    } catch (DocumentException e) {
        logger.error(e, e);
    }
}

From source file:org.jivesoftware.admin.LdapUserProfile.java

License:Open Source License

/**
 * Returns true if the vCard mappings where successfully loaded from the XML/DB
 * properties./*from ww  w .  ja  va  2s. c  om*/
 *
 * @return true if mappings where loaded from saved property.
 */
public boolean loadFromProperties() {
    String xmlProperty = JiveGlobals.getProperty("ldap.vcard-mapping");
    if (xmlProperty == null || xmlProperty.trim().length() == 0) {
        return false;
    }

    try {
        // Remove CDATA wrapping element
        if (xmlProperty.startsWith("<![CDATA[")) {
            xmlProperty = xmlProperty.substring(9, xmlProperty.length() - 3);
        }
        // Parse XML
        Document document = DocumentHelper.parseText(xmlProperty);
        Element vCard = document.getRootElement();

        Element element = vCard.element("N");
        if (element != null) {
            name = element.elementTextTrim("GIVEN");
        }
        element = vCard.element("EMAIL");
        if (element != null) {
            email = element.elementTextTrim("USERID");
        }
        element = vCard.element("FN");
        if (element != null) {
            fullName = element.getTextTrim();
        }
        element = vCard.element("NICKNAME");
        if (element != null) {
            nickname = element.getTextTrim();
        }
        element = vCard.element("BDAY");
        if (element != null) {
            birthday = element.getTextTrim();
        }
        // Parse addresses
        Iterator addresses = vCard.elementIterator("ADR");
        while (addresses.hasNext()) {
            element = (Element) addresses.next();
            if (element.element("HOME") != null) {
                if (element.element("STREET") != null) {
                    homeStreet = element.elementTextTrim("STREET");
                }
                if (element.element("LOCALITY") != null) {
                    homeCity = element.elementTextTrim("LOCALITY");
                }
                if (element.element("REGION") != null) {
                    homeState = element.elementTextTrim("REGION");
                }
                if (element.element("PCODE") != null) {
                    homeZip = element.elementTextTrim("PCODE");
                }
                if (element.element("CTRY") != null) {
                    homeCountry = element.elementTextTrim("CTRY");
                }
            } else if (element.element("WORK") != null) {
                if (element.element("STREET") != null) {
                    businessStreet = element.elementTextTrim("STREET");
                }
                if (element.element("LOCALITY") != null) {
                    businessCity = element.elementTextTrim("LOCALITY");
                }
                if (element.element("REGION") != null) {
                    businessState = element.elementTextTrim("REGION");
                }
                if (element.element("PCODE") != null) {
                    businessZip = element.elementTextTrim("PCODE");
                }
                if (element.element("CTRY") != null) {
                    businessCountry = element.elementTextTrim("CTRY");
                }
            }
        }
        // Parse telephones
        Iterator telephones = vCard.elementIterator("TEL");
        while (telephones.hasNext()) {
            element = (Element) telephones.next();
            if (element.element("HOME") != null) {
                if (element.element("VOICE") != null) {
                    homePhone = element.elementTextTrim("NUMBER");
                } else if (element.element("CELL") != null) {
                    homeMobile = element.elementTextTrim("NUMBER");
                } else if (element.element("FAX") != null) {
                    homeFax = element.elementTextTrim("NUMBER");
                } else if (element.element("PAGER") != null) {
                    homePager = element.elementTextTrim("NUMBER");
                }
            } else if (element.element("WORK") != null) {
                if (element.element("VOICE") != null) {
                    businessPhone = element.elementTextTrim("NUMBER");
                } else if (element.element("CELL") != null) {
                    businessMobile = element.elementTextTrim("NUMBER");
                } else if (element.element("FAX") != null) {
                    businessFax = element.elementTextTrim("NUMBER");
                } else if (element.element("PAGER") != null) {
                    businessPager = element.elementTextTrim("NUMBER");
                }
            }
        }
        element = vCard.element("TITLE");
        if (element != null) {
            businessJobTitle = element.getTextTrim();
        }
        element = vCard.element("ORG");
        if (element != null) {
            if (element.element("ORGUNIT") != null) {
                businessDepartment = element.elementTextTrim("ORGUNIT");
            }
        }
        avatarStoredInDB = JiveGlobals.getBooleanProperty("ldap.override.avatar", false);
    } catch (DocumentException e) {
        Log.error("Error loading vcard mappings from property", e);
        return false;
    }

    return true;
}

From source file:org.jivesoftware.openfire.fastpath.history.ChatTranscriptManager.java

License:Open Source License

/**
 * Return the plain text version of a chat transcript.
 *
 * @param sessionID the sessionID of the <code>ChatSession</code>
 * @return the plain text version of a chat transcript.
 *//*  ww w . j  av  a  2 s.  c  o  m*/
public static String getTextTranscriptFromSessionID(String sessionID) {
    String transcript = null;

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(GET_SESSION_TRANSCRIPT);
        pstmt.setString(1, sessionID);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            transcript = DbConnectionManager.getLargeTextField(rs, 1);
        }
    } catch (Exception ex) {
        Log.error(ex.getMessage(), ex);
    } finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }

    if (transcript == null || "".equals(transcript)) {
        return "";
    }

    // Define time zone used in the transcript.
    SimpleDateFormat UTC_FORMAT = new SimpleDateFormat(JiveConstants.XMPP_DELAY_DATETIME_FORMAT);
    UTC_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));

    final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");

    Document element = null;
    try {
        element = DocumentHelper.parseText(transcript);
    } catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }

    StringBuilder buf = new StringBuilder();

    // Add the Messages and Presences contained in the retrieved transcript element
    for (Iterator<Element> it = element.getRootElement().elementIterator(); it.hasNext();) {
        Element packet = it.next();
        String name = packet.getName();

        String message = "";
        String from = "";
        if ("presence".equals(name)) {
            String type = packet.attributeValue("type");
            from = new JID(packet.attributeValue("from")).getResource();
            if (type == null) {
                message = from + " has joined the room";
            } else {
                message = from + " has left the room";
            }
        } else if ("message".equals(name)) {
            from = new JID(packet.attributeValue("from")).getResource();
            message = packet.elementText("body");
            message = StringUtils.escapeHTMLTags(message);
        }

        List<Element> el = packet.elements("x");
        for (Element ele : el) {
            if ("jabber:x:delay".equals(ele.getNamespaceURI())) {
                String stamp = ele.attributeValue("stamp");
                try {
                    String formattedDate;
                    synchronized (UTC_FORMAT) {
                        Date d = UTC_FORMAT.parse(stamp);
                        formattedDate = formatter.format(d);
                    }

                    if ("presence".equals(name)) {
                        buf.append("[").append(formattedDate).append("] ").append(message).append("\n");
                    } else {
                        buf.append("[").append(formattedDate).append("] ").append(from).append(": ")
                                .append(message).append("\n");
                    }
                } catch (ParseException e) {
                    Log.error(e.getMessage(), e);
                }
            }
        }
    }

    return buf.toString();
}

From source file:org.jivesoftware.openfire.fastpath.history.ChatTranscriptManager.java

License:Open Source License

/**
 * Formats a given XML Chat Transcript./*from www.j  a v a2  s  .  co  m*/
 *
 * @param transcript the XMP ChatTranscript.
 * @return the pretty-version of a transcript.
 */
public static String formatTranscript(String transcript) {
    if (transcript == null || "".equals(transcript)) {
        return "";
    }
    final SimpleDateFormat UTC_FORMAT = new SimpleDateFormat(JiveConstants.XMPP_DELAY_DATETIME_FORMAT);
    UTC_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));

    final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");

    Document element = null;
    try {
        element = DocumentHelper.parseText(transcript);
    } catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }

    StringBuilder buf = new StringBuilder();
    String conv1 = null;

    // Add the Messages and Presences contained in the retrieved transcript element
    for (Iterator<Element> it = element.getRootElement().elementIterator(); it.hasNext();) {
        Element packet = it.next();
        String name = packet.getName();

        String message = "";
        String from = "";
        if ("presence".equals(name)) {
            String type = packet.attributeValue("type");
            from = new JID(packet.attributeValue("from")).getResource();
            if (type == null) {
                message = from + " has joined the room";
            } else {
                message = from + " has left the room";
            }
        } else if ("message".equals(name)) {
            from = new JID(packet.attributeValue("from")).getResource();
            message = packet.elementText("body");
            message = StringUtils.escapeHTMLTags(message);
            if (conv1 == null) {
                conv1 = from;
            }
        }

        List<Element> el = packet.elements("x");
        for (Element ele : el) {
            if ("jabber:x:delay".equals(ele.getNamespaceURI())) {
                String stamp = ele.attributeValue("stamp");
                try {
                    String formattedDate;
                    synchronized (UTC_FORMAT) {
                        Date d = UTC_FORMAT.parse(stamp);
                        formattedDate = formatter.format(d);
                    }

                    if ("presence".equals(name)) {
                        buf.append("<tr valign=\"top\"><td class=\"notification-label\" colspan=2 nowrap>[")
                                .append(formattedDate).append("] ").append(message).append("</td></tr>");
                    } else {
                        String cssClass = conv1.equals(from) ? "conversation-label1" : "conversation-label2";
                        buf.append("<tr valign=\"top\"><td width=1% class=\"" + cssClass + "\" nowrap>[")
                                .append(formattedDate).append("] ").append(from)
                                .append(":</td><td class=\"conversation-body\">").append(message)
                                .append("</td></tr>");
                    }
                } catch (ParseException e) {
                    Log.error(e.getMessage(), e);
                }
            }
        }
    }

    return buf.toString();
}

From source file:org.jivesoftware.openfire.fastpath.WorkgroupSettings.java

License:Open Source License

/**
 * Returns the data stored under a key corresponding to the name and namespace
 * of the given element. The Element must be in the form:<p>
 *
 * <code>&lt;name xmlns='namespace'/&gt;</code><p>
 * /*from  w  ww  . ja va2s  .c o m*/
 * If no data is currently stored under the given key, an empty element will be
 * returned.
 *
 * @param data an XML document who's element name and namespace is used to
 *      match previously stored private data.
 * @param workgroupName the name of the workgroup who's data is to be stored.
 * @return the data stored under the given key or the data element.
 */
public Element get(String workgroupName, Element data) {
    data.clearContent();
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(LOAD_SETTINGS);
        pstmt.setString(1, workgroupName);
        pstmt.setString(2, data.getNamespaceURI());
        rs = pstmt.executeQuery();
        if (rs.next()) {
            Document document = DocumentHelper.parseText(rs.getString(1).trim());
            data = document.getRootElement();
        }
    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return data;
}

From source file:org.jivesoftware.openfire.ldap.LdapVCardProvider.java

License:Open Source License

/**
 * Initializes the VCard template as set by the administrator.
 *///from  www . j  av a2  s .  co m
private void initTemplate() {
    String property = JiveGlobals.getProperty("ldap.vcard-mapping");
    Log.debug("LdapVCardProvider: Found vcard mapping: '" + property);
    try {
        // Remove CDATA wrapping element
        if (property.startsWith("<![CDATA[")) {
            property = property.substring(9, property.length() - 3);
        }
        Document document = DocumentHelper.parseText(property);
        template = new VCardTemplate(document);
    } catch (Exception e) {
        Log.error("Error loading vcard mapping: " + e.getMessage());
    }

    Log.debug("LdapVCardProvider: attributes size==" + template.getAttributes().length);
}