Example usage for org.dom4j Element getNamespaceURI

List of usage examples for org.dom4j Element getNamespaceURI

Introduction

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

Prototype

String getNamespaceURI();

Source Link

Document

Returns the URI mapped to the namespace of this element if one exists otherwise an empty String is returned.

Usage

From source file:org.jitsi.xmpp.util.IQUtils.java

License:Apache License

/**
 * Converts a specific <tt>org.xmpp.packet.iQ</tt> instance into a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance which represents the
 * same stanza.//from  ww  w  .  j  ava 2s. c  o m
 *
 * @param iq the <tt>org.xmpp.packet.IQ</tt> instance to convert to a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance
 * @return a new <tt>org.jivesoftware.smack.packet.IQ</tt> instance which
 * represents the same stanza as the specified <tt>iq</tt>
 * @throws Exception if anything goes wrong during the conversion
 */
// It is safe to cast as ProviderManager verifies classes
// the warning is about cast 'providerOrClass' var to '? extends IQ'
@SuppressWarnings("unchecked")
public static org.jivesoftware.smack.packet.IQ convert(org.xmpp.packet.IQ iq) throws Exception {
    Element element = iq.getChildElement();
    IQProvider iqProvider = null;
    Class<? extends IQ> iqClass = null;

    if (element != null) {
        Object providerOrClass = ProviderManager.getInstance().getIQProvider(element.getName(),
                element.getNamespaceURI());
        if (providerOrClass instanceof IQProvider) {
            iqProvider = (IQProvider) providerOrClass;
        } else {
            // The cast is safe as ProviderManager allows only
            // IQ or IQProvider here
            iqClass = (Class<? extends IQ>) providerOrClass;
        }
    }

    IQ.Type type = iq.getType();
    org.jivesoftware.smack.packet.IQ smackIQ = null;
    org.jivesoftware.smack.packet.XMPPError smackError = null;

    if (iqProvider != null || iqClass != null || iq.getError() != null) {
        XmlPullParserFactory xmlPullParserFactory;

        synchronized (IQUtils.class) {
            if (IQUtils.xmlPullParserFactory == null) {
                IQUtils.xmlPullParserFactory = XmlPullParserFactory.newInstance();
                IQUtils.xmlPullParserFactory.setNamespaceAware(true);
            }
            xmlPullParserFactory = IQUtils.xmlPullParserFactory;
        }

        XmlPullParser parser = xmlPullParserFactory.newPullParser();

        parser.setInput(new StringReader(iq.toXML()));

        int eventType = parser.next();
        // Abort processing if we're not at the beginning of <iq> element
        if (XmlPullParser.START_TAG != eventType) {
            throw new IllegalStateException(Integer.toString(eventType) + " != XmlPullParser.START_TAG");
        }

        String name = parser.getName();
        // Stop processing if the element is not <iq>
        if (!"iq".equals(name)) {
            throw new IllegalStateException(name + " != iq");
        }

        do {
            eventType = parser.next();
            name = parser.getName();
            if (XmlPullParser.START_TAG == eventType) {
                // 7. An IQ stanza of type "error" MAY include the
                // child element contained in the associated "get"
                // or "set" and MUST include an <error/> child.
                if (IQ.Type.error.equals(type) && "error".equals(name)) {
                    smackError = PacketParserUtils.parseError(parser);
                } else if (smackIQ == null && iqProvider != null) {
                    smackIQ = iqProvider.parseIQ(parser);
                } else if (smackIQ == null && iqClass != null) {
                    smackIQ = (org.jivesoftware.smack.packet.IQ) PacketParserUtils.parseWithIntrospection(name,
                            iqClass, parser);
                }
            } else if ((XmlPullParser.END_TAG == eventType && "iq".equals(name))
                    || (smackIQ != null && smackError != null) || XmlPullParser.END_DOCUMENT == eventType) {
                break;
            }
        } while (true);

        // Throw an exception if we have not consumed the whole <iq> element
        eventType = parser.getEventType();
        if (XmlPullParser.END_TAG != eventType) {
            throw new IllegalStateException(Integer.toString(eventType) + " != XmlPullParser.END_TAG");
        }
    }

    // 6. An IQ stanza of type "result" MUST include zero or one child
    // elements.
    // 7. An IQ stanza of type "error" MAY include the child element
    // contained in the associated "get" or "set" and MUST include an
    // <error/> child.
    if (smackIQ == null && (IQ.Type.error.equals(type) || IQ.Type.result.equals(type))) {
        smackIQ = new org.jivesoftware.smack.packet.IQ() {
            @Override
            public String getChildElementXML() {
                return "";
            }
        };
    }

    if (smackIQ != null) {
        // from
        org.xmpp.packet.JID fromJID = iq.getFrom();

        if (fromJID != null)
            smackIQ.setFrom(fromJID.toString());
        // id
        smackIQ.setPacketID(iq.getID());

        // to
        org.xmpp.packet.JID toJID = iq.getTo();

        if (toJID != null)
            smackIQ.setTo(toJID.toString());
        // type
        smackIQ.setType(convert(type));

        if (smackError != null)
            smackIQ.setError(smackError);
    }

    return smackIQ;
}

From source file:org.jivesoftware.multiplexer.StreamError.java

License:Open Source License

/**
 * Returns the error condition./*from   w w w .j a v  a 2s  .c o  m*/
 *
 * @return the error condition.
 * @see Condition
 */
public Condition getCondition() {
    for (Iterator i = element.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.getNamespaceURI().equals(ERROR_NAMESPACE) && !el.getName().equals("text")) {
            return Condition.fromXMPP(el.getName());
        }
    }
    return null;
}

From source file:org.jivesoftware.multiplexer.StreamError.java

License:Open Source License

/**
 * Sets the error condition.//from  www.j  ava2 s  . c  o m
 *
 * @param condition the error condition.
 * @see Condition
 */
public void setCondition(Condition condition) {
    if (condition == null) {
        throw new NullPointerException("Condition cannot be null");
    }
    Element conditionElement = null;
    for (Iterator i = element.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.getNamespaceURI().equals(ERROR_NAMESPACE) && !el.getName().equals("text")) {
            conditionElement = el;
        }
    }
    if (conditionElement != null) {
        element.remove(conditionElement);
    }

    conditionElement = docFactory.createElement(condition.toXMPP(), ERROR_NAMESPACE);
    element.add(conditionElement);
}

From source file:org.jivesoftware.openfire.component.InternalComponentManager.java

License:Open Source License

/**
 * Processes packets that were sent to this service. Currently only packets that were sent from
 * registered components are being processed. In the future, we may also process packet of
 * trusted clients. Trusted clients may be able to execute ad-hoc commands such as adding or
 * removing components./* ww w .  jav  a  2 s.c o m*/
 *
 * @param packet the packet to process.
 */
public void process(Packet packet) throws PacketException {
    List<Component> components = getComponents(packet.getFrom());
    // Only process packets that were sent by registered components
    if (!components.isEmpty()) {
        if (packet instanceof IQ && IQ.Type.result == ((IQ) packet).getType()) {
            IQ iq = (IQ) packet;
            Element childElement = iq.getChildElement();
            if (childElement != null) {
                String namespace = childElement.getNamespaceURI();
                if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
                    // Add a disco item to the server for the component that supports disco
                    Element identity = childElement.element("identity");
                    if (identity == null) {
                        // Do nothing since there are no identities in the disco#info packet
                        return;
                    }
                    try {
                        XMPPServer.getInstance().getIQDiscoItemsHandler().addComponentItem(
                                packet.getFrom().toBareJID(), identity.attributeValue("name"));
                        for (Component component : components) {
                            if (component instanceof ComponentSession.ExternalComponent) {
                                ComponentSession.ExternalComponent externalComponent = (ComponentSession.ExternalComponent) component;
                                externalComponent.setName(identity.attributeValue("name"));
                                externalComponent.setType(identity.attributeValue("type"));
                                externalComponent.setCategory(identity.attributeValue("category"));
                            }
                        }
                    } catch (Exception e) {
                        Log.error("Error processing disco packet of components: " + components + " - "
                                + packet.toXML(), e);
                    }
                    // Store the IQ disco#info returned by the component
                    addComponentInfo(iq);
                    // Notify listeners that a component answered the disco#info request
                    notifyComponentInfo(iq);
                    // Alert other cluster nodes
                    CacheFactory.doClusterTask(new NotifyComponentInfo(iq));
                }
            }
        }
    }
}

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.
 *//*from   ww  w.ja  va2 s. co 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  av  a  2  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

/**
 * Stores private data. If the name and namespace of the element matches another
 * stored private data XML document, then replace it with the new one.
 *
 * @param data     the data to store (XML element)
 * @param workgroupName the name of the workgroup where the data should be stored.
 *//* w  w  w .  j  a  va2s .  co m*/
public void add(String workgroupName, Element data) {
    Connection con = null;
    PreparedStatement pstmt = null;
    try {
        StringWriter writer = new StringWriter();
        data.write(writer);
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(LOAD_SETTINGS);
        pstmt.setString(1, workgroupName);
        pstmt.setString(2, data.getNamespaceURI());
        ResultSet rs = pstmt.executeQuery();
        boolean update = false;
        if (rs.next()) {
            update = true;
        }
        rs.close();
        pstmt.close();

        if (update) {
            pstmt = con.prepareStatement(UPDATE_SETTINGS);
        } else {
            pstmt = con.prepareStatement(INSERT_SETTINGS);
        }

        DbConnectionManager.setLargeTextField(pstmt, 1, writer.toString());
        pstmt.setString(2, data.getName());
        pstmt.setString(3, workgroupName);
        pstmt.setString(4, data.getNamespaceURI());
        pstmt.executeUpdate();
    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
        DbConnectionManager.closeConnection(pstmt, con);
    }
}

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>
 * //w  ww .j a v  a2 s .c  om
 * 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.filetransfer.DefaultFileTransferManager.java

License:Open Source License

protected static Element getChildElement(Element element, String namespace) {
    //noinspection unchecked
    List<Element> elements = element.elements();
    if (elements.isEmpty()) {
        return null;
    }/*  www.j a v a 2  s .  c  o m*/
    for (Element childElement : elements) {
        String childNamespace = childElement.getNamespaceURI();
        if (namespace.equals(childNamespace)) {
            return childElement;
        }
    }

    return null;
}

From source file:org.jivesoftware.openfire.filetransfer.proxy.FileTransferProxy.java

License:Open Source License

public boolean handleIQ(IQ packet) throws UnauthorizedException {
    Element childElement = packet.getChildElement();
    String namespace = null;//from   w  w  w  . java 2 s  . co m

    // ignore errors
    if (packet.getType() == IQ.Type.error) {
        return true;
    }
    if (childElement != null) {
        namespace = childElement.getNamespaceURI();
    }

    if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
        IQ reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(packet);
        router.route(reply);
        return true;
    } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
        // a component
        IQ reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(packet);
        router.route(reply);
        return true;
    } else if (FileTransferManager.NAMESPACE_BYTESTREAMS.equals(namespace)) {
        if (packet.getType() == IQ.Type.get) {
            IQ reply = IQ.createResultIQ(packet);
            Element newChild = reply.setChildElement("query", FileTransferManager.NAMESPACE_BYTESTREAMS);
            Element response = newChild.addElement("streamhost");
            response.addAttribute("jid", getServiceDomain());
            response.addAttribute("host", proxyIP);
            response.addAttribute("port", String.valueOf(connectionManager.getProxyPort()));
            router.route(reply);
            return true;
        } else if (packet.getType() == IQ.Type.set && childElement != null) {
            String sid = childElement.attributeValue("sid");
            JID from = packet.getFrom();
            JID to = new JID(childElement.elementTextTrim("activate"));

            IQ reply = IQ.createResultIQ(packet);
            try {
                connectionManager.activate(from, to, sid);
            } catch (IllegalArgumentException ie) {
                Log.error("Error activating connection", ie);
                reply.setType(IQ.Type.error);
                reply.setError(new PacketError(PacketError.Condition.not_allowed));
            }

            router.route(reply);
            return true;
        }
    }
    return false;
}