Example usage for org.dom4j Element createCopy

List of usage examples for org.dom4j Element createCopy

Introduction

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

Prototype

Element createCopy();

Source Link

Document

Creates a deep copy of this element The new element is detached from its parent, and getParent() on the clone will return null.

Usage

From source file:org.jivesoftware.multiplexer.net.http.HttpSessionManager.java

License:Open Source License

private String createSessionCreationResponse(HttpSession session) throws DocumentException {
    Element response = DocumentHelper.createElement("body");
    response.addNamespace("", "http://jabber.org/protocol/httpbind");
    response.addNamespace("stream", "http://etherx.jabber.org/streams");
    response.addAttribute("authid", session.getStreamID());
    response.addAttribute("sid", session.getStreamID());
    response.addAttribute("secure", Boolean.TRUE.toString());
    response.addAttribute("requests", String.valueOf(session.getMaxRequests()));
    response.addAttribute("inactivity", String.valueOf(session.getInactivityTimeout()));
    response.addAttribute("polling", String.valueOf(session.getMaxPollingInterval()));
    response.addAttribute("wait", String.valueOf(session.getWait()));
    if (session.getVersion() >= 1.6) {
        response.addAttribute("ver", String.valueOf(session.getVersion()));
    }//from www . j a va2 s  .com

    Element features = response.addElement("stream:features");
    for (Element feature : session.getAvailableStreamFeaturesElements()) {
        features.add(feature.createCopy());
    }

    return response.asXML();
}

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

License:Open Source License

/**
 * Forwards wrapped stanza contained in the <tt>route</tt> element to the specified
 * client. The target client connection is specified in the <tt>route</tt> element by
 * the <tt>streamid</tt> attribute.<p>
 *
 * Wrapped stanzas that failed to be delivered to the target client are returned to
 * the server./*from  w  w w .  jav a2s  . c o  m*/
 *
 * @param route the route element containing the wrapped stanza to send to the target
 *        client.
 */
private void processRoute(Element route) {
    String streamID = route.attributeValue("streamid");
    // Get the wrapped stanza
    Element stanza = (Element) route.elementIterator().next();
    // Get the session that matches the requested stream ID
    Session session = Session.getSession(streamID);
    if (session != null && !session.isClosed()) {
        // Deliver the wrapped stanza to the client
        session.deliver(stanza);
    } else {
        // Inform the server that the wrapped stanza was not delivered
        String tag = stanza.getName();
        if ("message".equals(tag)) {
            connectionManager.getServerSurrogate().deliveryFailed(stanza, streamID);
        } else if ("iq".equals(tag)) {
            String type = stanza.attributeValue("type", "get");
            if ("get".equals(type) || "set".equals(type)) {
                // Build IQ of type ERROR
                Element reply = stanza.createCopy();
                reply.addAttribute("type", "error");
                reply.addAttribute("from", stanza.attributeValue("to"));
                reply.addAttribute("to", stanza.attributeValue("from"));
                Element error = reply.addElement("error");
                error.addAttribute("type", "wait");
                error.addElement("unexpected-request").addAttribute("xmlns",
                        "urn:ietf:params:xml:ns:xmpp-stanzas");
                // Bounce the failed IQ packet
                connectionManager.getServerSurrogate().send(reply.asXML(), streamID);
            }
        }
    }
}

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

License:Open Source License

/**
 * Processes server configuration to use for client connections and store the
 * configuration in {@link ServerSurrogate}.
 *
 * @param stanza stanza sent from the server containing the configuration.
 * @param configuration the configuration element contained in the stanza.
 *//*from w  w w.  j av a 2  s.  c  om*/
private void obtainClientOptions(Element stanza, Element configuration) {
    ServerSurrogate serverSurrogate = connectionManager.getServerSurrogate();
    // Check if TLS is avaiable (and if it is required)
    Element startTLS = configuration.element("starttls");
    if (startTLS != null) {
        if (startTLS.element("required") != null) {
            serverSurrogate.setTlsPolicy(Connection.TLSPolicy.required);
        } else {
            serverSurrogate.setTlsPolicy(Connection.TLSPolicy.optional);
        }
    } else {
        serverSurrogate.setTlsPolicy(Connection.TLSPolicy.disabled);
    }
    // Check if compression is available
    Element compression = configuration.element("compression");
    if (compression != null) {
        serverSurrogate.setCompressionPolicy(Connection.CompressionPolicy.optional);
    } else {
        serverSurrogate.setCompressionPolicy(Connection.CompressionPolicy.disabled);
    }
    // Cache supported SASL mechanisms for client authentication
    Element mechanisms = configuration.element("mechanisms");
    if (mechanisms != null) {
        serverSurrogate.setSASLMechanisms(mechanisms);
    }
    // Check if anonymous login is supported
    serverSurrogate.setNonSASLAuthEnabled(configuration.element("auth") != null);
    // Check if in-band registration is supported
    serverSurrogate.setInbandRegEnabled(configuration.element("register") != null);

    // Send ACK to the server
    Element reply = stanza.createCopy();
    reply.addAttribute("type", "result");
    reply.addAttribute("to", connectionManager.getServerName());
    reply.addAttribute("from", jidAddress);
    connection.deliver(reply.asXML());
}

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

License:Open Source License

/**
 * Returns the SASL mechanisms supported by the server for client authentication.
 *
 * @param mechanisms the SASL mechanisms supported by the server for client authentication.
 *//*from w ww  . ja va2 s  .c  om*/
public void setSASLMechanisms(Element mechanisms) {
    saslMechanisms = mechanisms.createCopy();
}

From source file:org.jivesoftware.multiplexer.spi.ClientFailoverDeliverer.java

License:Open Source License

public void deliver(Element stanza) {
    // Inform the server that the wrapped stanza was not delivered
    String tag = stanza.getName();
    if ("message".equals(tag)) {
        serverSurrogate.deliveryFailed(stanza, streamID);
    } else if ("iq".equals(tag)) {
        String type = stanza.attributeValue("type", "get");
        if ("get".equals(type) || "set".equals(type)) {
            // Build IQ of type ERROR
            Element reply = stanza.createCopy();
            reply.addAttribute("type", "error");
            reply.addAttribute("from", stanza.attributeValue("to"));
            reply.addAttribute("to", stanza.attributeValue("from"));
            Element error = reply.addElement("error");
            error.addAttribute("type", "wait");
            error.addElement("unexpected-request").addAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
            // Bounce the failed IQ packet
            serverSurrogate.send(reply.asXML(), streamID);
        }//  www . ja v a2  s.c o  m
    }
}

From source file:org.jivesoftware.multiplexer.spi.ServerFailoverDeliverer.java

License:Open Source License

public void deliver(Element stanza) {
    if ("route".equals(stanza.getName())) {
        // Inform the client that the stanza was not delivered to the server
        // Get the stream id that identifies the client that sent the stanza
        String streamID = stanza.attributeValue("streamid");
        // Get the wrapped stanza
        Element wrapped = (Element) stanza.elementIterator().next();
        String tag = wrapped.getName();
        if ("message".equals(tag) || "iq".equals(tag) || "presence".equals(tag)) {
            // Build ERROR bouncing packet
            Element reply = wrapped.createCopy();
            reply.addAttribute("type", "error");
            reply.addAttribute("from", wrapped.attributeValue("to"));
            reply.addAttribute("to", wrapped.attributeValue("from"));
            Element error = reply.addElement("error");
            error.addAttribute("type", "wait");
            error.addElement("internal-server-error").addAttribute("xmlns",
                    "urn:ietf:params:xml:ns:xmpp-stanzas");
            // Get the session that matches the specified stream ID
            Session session = Session.getSession(streamID);
            if (session != null) {
                // Bounce the failed packet
                session.deliver(reply);/*from w  w w  .j a  v a  2s  . co m*/
            }
        }
    }
}

From source file:org.jivesoftware.openfire.commands.AdHocCommandManager.java

License:Open Source License

public IQ process(IQ packet) {
    IQ reply = IQ.createResultIQ(packet);
    Element iqCommand = packet.getChildElement();

    // Only packets of type SET can be processed
    if (!IQ.Type.set.equals(packet.getType())) {
        // Answer a bad_request error
        reply.setChildElement(iqCommand.createCopy());
        reply.setError(PacketError.Condition.bad_request);
        return reply;
    }/* w w w  .ja va 2  s .c om*/

    String sessionid = iqCommand.attributeValue("sessionid");
    String commandCode = iqCommand.attributeValue("node");
    String from = packet.getFrom().toString();
    AdHocCommand command = commands.get(commandCode);
    if (sessionid == null) {
        // A new execution request has been received. Check that the command exists
        if (command == null) {
            // Requested command does not exist so return item_not_found error.
            reply.setChildElement(iqCommand.createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        } else {
            // Check that the requester has enough permission. Answer forbidden error if
            // requester permissions are not enough to execute the requested command
            if (!command.hasPermission(packet.getFrom())) {
                reply.setChildElement(iqCommand.createCopy());
                reply.setError(PacketError.Condition.forbidden);
                return reply;
            }

            // Create new session ID
            sessionid = StringUtils.randomString(15);

            Element childElement = reply.setChildElement("command", NAMESPACE);

            if (command.getMaxStages(null) == 0) {
                // The command does not require any user interaction (returns results only)
                // Execute the command and return the execution result which may be a
                // data form (i.e. report data) or a note element
                command.execute(null, childElement);
                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.completed.name());
            } else {
                // The command requires user interactions (ie. has stages)
                // Check that the user has not excedded the limit of allowed simultaneous
                // command sessions.
                AtomicInteger counter = sessionsCounter.get(from);
                if (counter == null) {
                    synchronized (from.intern()) {
                        counter = sessionsCounter.get(from);
                        if (counter == null) {
                            counter = new AtomicInteger(0);
                            sessionsCounter.put(from, counter);
                        }
                    }
                }
                int limit = JiveGlobals.getIntProperty("xmpp.command.limit", 100);
                if (counter.incrementAndGet() > limit) {
                    counter.decrementAndGet();
                    // Answer a not_allowed error since the user has exceeded limit. This
                    // checking prevents bad users from consuming all the system memory by not
                    // allowing them to create infinite simultaneous command sessions.
                    reply.setChildElement(iqCommand.createCopy());
                    reply.setError(PacketError.Condition.not_allowed);
                    return reply;
                }
                // Originate a new command session.
                SessionData session = new SessionData(sessionid, packet.getFrom());
                sessions.put(sessionid, session);

                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.executing.name());

                // Add to the child element the data form the user must complete and
                // the allowed actions
                command.addNextStageInformation(session, childElement);
            }
        }

    } else {
        // An execution session already exists and the user has requested to perform a
        // certain action.
        String action = iqCommand.attributeValue("action");
        SessionData session = sessions.get(sessionid);
        // Check that a Session exists for the specified sessionID
        if (session == null) {
            // Answer a bad_request error (bad-sessionid)
            reply.setChildElement(iqCommand.createCopy());
            reply.setError(PacketError.Condition.bad_request);
            return reply;
        }

        // Check if the Session data has expired (default is 10 minutes)
        int timeout = JiveGlobals.getIntProperty("xmpp.command.timeout", 10 * 60 * 1000);
        if (System.currentTimeMillis() - session.getCreationStamp() > timeout) {
            // TODO Check all sessions that might have timed out (use another thread?)
            // Remove the old session
            removeSessionData(sessionid, from);
            // Answer a not_allowed error (session-expired)
            reply.setChildElement(iqCommand.createCopy());
            reply.setError(PacketError.Condition.not_allowed);
            return reply;
        }

        synchronized (sessionid.intern()) {
            // Check if the user is requesting to cancel the command
            if (AdHocCommand.Action.cancel.name().equals(action)) {
                // User requested to cancel command execution so remove the session data
                removeSessionData(sessionid, from);
                // Generate a canceled confirmation response
                Element childElement = reply.setChildElement("command", NAMESPACE);
                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.canceled.name());
            }

            // If the user didn't specify an action then follow the default execute action
            if (action == null || AdHocCommand.Action.execute.name().equals(action)) {
                action = session.getExecuteAction().name();
            }

            // Check that the specified action was previously offered
            if (!session.isValidAction(action)) {
                // Answer a bad_request error (bad-action)
                reply.setChildElement(iqCommand.createCopy());
                reply.setError(PacketError.Condition.bad_request);
                return reply;
            } else if (AdHocCommand.Action.prev.name().equals(action)) {
                // Move to the previous stage and add to the child element the data form
                // the user must complete and the allowed actions of the previous stage
                Element childElement = reply.setChildElement("command", NAMESPACE);
                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.executing.name());
                command.addPreviousStageInformation(session, childElement);
            } else if (AdHocCommand.Action.next.name().equals(action)) {
                // Store the completed form in the session data
                saveCompletedForm(iqCommand, session);
                // Move to the next stage and add to the child element the new data form
                // the user must complete and the new allowed actions
                Element childElement = reply.setChildElement("command", NAMESPACE);
                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.executing.name());
                command.addNextStageInformation(session, childElement);
            } else if (AdHocCommand.Action.complete.name().equals(action)) {
                // Store the completed form in the session data
                saveCompletedForm(iqCommand, session);
                // Execute the command and return the execution result which may be a
                // data form (i.e. report data) or a note element
                Element childElement = reply.setChildElement("command", NAMESPACE);
                command.execute(session, childElement);
                childElement.addAttribute("sessionid", sessionid);
                childElement.addAttribute("node", commandCode);
                childElement.addAttribute("status", AdHocCommand.Status.completed.name());

                // Command has been executed so remove the session data
                removeSessionData(sessionid, from);
            }
        }
    }
    return reply;
}

From source file:org.jivesoftware.openfire.disco.IQDiscoInfoHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested info to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // Look for a DiscoInfoProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // DiscoInfoProvider responsibility to provide information about the JID's name together 
    // with any possible requested node.  
    DiscoInfoProvider infoProvider = getProvider(
            packet.getTo() == null ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (infoProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;/*from   www .  j av  a2s  . c o m*/
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");
        //String node = metaData.getProperty("query:node");

        // Check if we have information about the requested name and node
        if (infoProvider.hasInfo(name, node, packet.getFrom())) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // Add to the reply all the identities provided by the DiscoInfoProvider
            Element identity;
            Iterator<Element> identities = infoProvider.getIdentities(name, node, packet.getFrom());
            while (identities.hasNext()) {
                identity = identities.next();
                identity.setQName(new QName(identity.getName(), queryElement.getNamespace()));
                queryElement.add((Element) identity.clone());
            }

            // Add to the reply all the features provided by the DiscoInfoProvider
            Iterator<String> features = infoProvider.getFeatures(name, node, packet.getFrom());
            boolean hasDiscoInfoFeature = false;
            boolean hasDiscoItemsFeature = false;
            boolean hasResultSetManagementFeature = false;

            while (features.hasNext()) {
                final String feature = features.next();
                queryElement.addElement("feature").addAttribute("var", feature);
                if (feature.equals(NAMESPACE_DISCO_INFO)) {
                    hasDiscoInfoFeature = true;
                } else if (feature.equals("http://jabber.org/protocol/disco#items")) {
                    hasDiscoItemsFeature = true;
                } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
                    hasResultSetManagementFeature = true;
                }
            }

            if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
                // IQDiscoItemsHandler provides result set management
                // support.
                queryElement.addElement("feature").addAttribute("var",
                        ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
            }

            if (!hasDiscoInfoFeature) {
                // XEP-0030 requires that every entity that supports service
                // discovery broadcasts the disco#info feature.
                queryElement.addElement("feature").addAttribute("var", NAMESPACE_DISCO_INFO);
            }

            // Add to the reply the extended info (XDataForm) provided by the DiscoInfoProvider
            DataForm dataForm = infoProvider.getExtendedInfo(name, node, packet.getFrom());
            if (dataForm != null) {
                queryElement.add(dataForm.getElement());
            }
        } else {
            // If the DiscoInfoProvider has no information for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a DiscoInfoProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.jivesoftware.openfire.disco.IQDiscoItemsHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested items to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // TODO Implement publishing client items
    if (IQ.Type.set == packet.getType()) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.feature_not_implemented);
        return reply;
    }//from w w w.  j a  v  a  2  s  .co  m

    // Look for a DiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // DiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    DiscoItemsProvider itemsProvider = getProvider(
            packet.getTo() == null ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (itemsProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");

        // Check if we have items associated with the requested name and node
        Iterator<DiscoItem> itemsItr = itemsProvider.getItems(name, node, packet.getFrom());
        if (itemsItr != null) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // See if the requesting entity would like to apply 'result set
            // management'
            final Element rsmElement = packet.getChildElement()
                    .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

            // apply RSM only if the element exists, and the (total) results
            // set is not empty.
            final boolean applyRSM = rsmElement != null && itemsItr.hasNext();

            if (applyRSM) {
                if (!ResultSet.isValidRSMRequest(rsmElement)) {
                    reply.setError(PacketError.Condition.bad_request);
                    return reply;
                }

                // Calculate which results to include.
                final List<DiscoItem> rsmResults;
                final List<DiscoItem> allItems = new ArrayList<DiscoItem>();
                while (itemsItr.hasNext()) {
                    allItems.add(itemsItr.next());
                }
                final ResultSet<DiscoItem> rs = new ResultSetImpl<DiscoItem>(allItems);
                try {
                    rsmResults = rs.applyRSMDirectives(rsmElement);
                } catch (NullPointerException e) {
                    final IQ itemNotFound = IQ.createResultIQ(packet);
                    itemNotFound.setError(PacketError.Condition.item_not_found);
                    return itemNotFound;
                }

                // add the applicable results to the IQ-result
                for (DiscoItem item : rsmResults) {
                    final Element resultElement = item.getElement();
                    resultElement.setQName(new QName(resultElement.getName(), queryElement.getNamespace()));
                    queryElement.add(resultElement.createCopy());
                }

                // overwrite the 'set' element.
                queryElement.remove(
                        queryElement.element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)));
                queryElement.add(rs.generateSetElementFromResults(rsmResults));
            } else {
                // don't apply RSM:
                // Add to the reply all the items provided by the DiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the DiscoItemsProvider has no items for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a DiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.jivesoftware.openfire.fastpath.dataforms.WorkgroupFormProvider.java

License:Open Source License

public void executeGet(IQ packet, Workgroup workgroup) {
    IQ reply = IQ.createResultIQ(packet);
    FormManager formManager = FormManager.getInstance();
    DataForm dataForm = formManager.getDataForm(workgroup);
    if (dataForm == null) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(new PacketError(PacketError.Condition.item_not_found));
        workgroup.send(reply);// w ww. ja  v  a 2s.  com
        return;
    }

    Element iq = packet.getChildElement();

    if (iq.elements().isEmpty()) {
        reply.setChildElement(iq.createCopy());
        // Send the data form to the requestor

        reply.addExtension(dataForm.createCopy());
        workgroup.send(reply);
    }
}