Java Code Examples for org.xmpp.packet.IQ#getChildElement()

The following examples show how to use org.xmpp.packet.IQ#getChildElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IQAdminHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the IQ packet sent by an owner or admin of the room. Possible actions are:
 * <ul>
 * <li>Return the list of participants</li>
 * <li>Return the list of moderators</li>
 * <li>Return the list of members</li>
 * <li>Return the list of outcasts</li>
 * <li>Change user's affiliation to member</li>
 * <li>Change user's affiliation to outcast</li>
 * <li>Change user's affiliation to none</li>
 * <li>Change occupant's affiliation to moderator</li>
 * <li>Change occupant's affiliation to participant</li>
 * <li>Change occupant's affiliation to visitor</li>
 * <li>Kick occupants from the room</li>
 * </ul>
 *
 * @param packet the IQ packet sent by an owner or admin of the room.
 * @param role the role of the user that sent the request packet.
 * @throws ForbiddenException If the user is not allowed to perform his request.
 * @throws ConflictException If the desired room nickname is already reserved for the room or
 *                           if the room was going to lose all of its owners.
 * @throws NotAllowedException Thrown if trying to ban an owner or an administrator.
 * @throws CannotBeInvitedException If the user being invited as a result of being added to a members-only room still does not have permission
 */
public void handleIQ(IQ packet, MUCRole role) throws ForbiddenException, ConflictException,
        NotAllowedException, CannotBeInvitedException {
    IQ reply = IQ.createResultIQ(packet);
    Element element = packet.getChildElement();

    // Analyze the action to perform based on the included element
    @SuppressWarnings("unchecked")
    List<Element> itemsList = element.elements("item");
    
    if (!itemsList.isEmpty()) {
        handleItemsElement(role, itemsList, reply);
    }
    else {
        // An unknown and possibly incorrect element was included in the query
        // element so answer a BAD_REQUEST error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.bad_request);
    }
    if (reply.getTo() != null) {
        // Send a reply only if the sender of the original packet was from a real JID. (i.e. not
        // a packet generated locally)
        router.route(reply);
    }
}
 
Example 2
Source File: XmppPubSubControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
public static XmppPubSubConstants.Method getMethod(IQ iq) {
    Element pubsubElement = iq.getChildElement();
    Element methodElement = getChildElement(pubsubElement);
    String name = methodElement.getName();
    switch (name) {
        case "subscribe":
            return XmppPubSubConstants.Method.SUBSCRIBE;
        case "unsubscribe":
            return XmppPubSubConstants.Method.UNSUBSCRIBE;
        case "publish":
            return XmppPubSubConstants.Method.PUBLISH;
        case "retract":
            return XmppPubSubConstants.Method.RETRACT;
        default:
            break;
    }
    return null;
}
 
Example 3
Source File: LocationHandler.java    From openfireLBS with Apache License 2.0 6 votes vote down vote up
private IQ updateLocation(IQ packet) {
	IQ reply = IQ.createResultIQ(packet);

	Element iq = packet.getChildElement();
	JID from = packet.getFrom();
	String username = from.getNode();

	Element item = iq.element("item");
	Double myLon = Double.parseDouble(item.attributeValue("lon"));
	Double myLat = Double.parseDouble(item.attributeValue("lat"));

	boolean f = insertLocation(myLon,myLat,username);
	if (f){
		// reply.setChildElement(iq);
	}else{
		reply.setType(IQ.Type.error);
		reply.setError(PacketError.Condition.internal_server_error);
	}
	
	return reply;
}
 
Example 4
Source File: BookmarkInterceptor.java    From openfire-ofmeet-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * XEP-0048 'Bookmarks' describes a storage element that contains the list of bookmarks that we intend to
 * add to in this method. Such a storage element can be transmitted in a number of different ways, including
 * XEP-0049 "Private XML Storage" and XEP-0223 "Persistent Storage of Private Data via PubSub".
 *
 * @param packet The packet in which to search for a 'storage' element (cannot be null).
 * @return The storage element, or null when no such element was found.
 */
static Element findStorageElement( final Packet packet )
{
    if ( packet instanceof IQ )
    {
        final IQ iq = (IQ) packet;
        final Element childElement = iq.getChildElement();
        if ( childElement == null || iq.getType() != IQ.Type.result )
        {
            return null;
        }

        switch ( childElement.getNamespaceURI() )
        {
            // A "Private XML Storage (XEP-0049) Bookmarks" result stanza.
            case "jabber:iq:private":
                return findStorageElementInPrivateXmlStorage( childElement );

            // a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks result.
            case "http://jabber.org/protocol/pubsub":
                return findStorageElementInPubsub( childElement );

            default:
                return null;
        }
    }

    if ( packet instanceof Message )
    {
        final Message message = (Message) packet;

        // Check for a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks event notification.
        return findStorageElementInPubsub( message.getChildElement( "event", "http://jabber.org/protocol/pubsub#event" ) );
    }

    return null;
}
 
Example 5
Source File: EntityCapabilitiesManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a list of features from an IQ packet.
 * 
 * @param packet the packet
 * @return a list of features
 */
private static List<String> getFeaturesFrom(IQ packet) {
    List<String> discoFeatures = new ArrayList<>();
    Element query = packet.getChildElement();
    Iterator<Element> featuresIterator = query.elementIterator("feature");
    if (featuresIterator != null) {
        while (featuresIterator.hasNext()) {
            Element featureElement = featuresIterator.next();
            String discoFeature = featureElement.attributeValue("var");

            discoFeatures.add(discoFeature);
        }
    }
    return discoFeatures;
}
 
Example 6
Source File: IQPrivateHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ replyPacket = IQ.createResultIQ(packet);

    Element child = packet.getChildElement();
    Element dataElement = child.elementIterator().next();

    if ( !XMPPServer.getInstance().isLocal( packet.getFrom()) || !UserManager.getInstance().isRegisteredUser( packet.getFrom()) ) {
        replyPacket.setChildElement(packet.getChildElement().createCopy());
        replyPacket.setError(PacketError.Condition.service_unavailable);
        replyPacket.getError().setText( "Service available only to locally registered users." );
        return replyPacket;
    }

    if (dataElement != null) {
        if (IQ.Type.get.equals(packet.getType())) {
            Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
            dataStored.setParent(null);

            child.remove(dataElement);
            child.setParent(null);
            replyPacket.setChildElement(child);
            child.add(dataStored);
        }
        else {
            if (privateStorage.isEnabled()) {
                privateStorage.add(packet.getFrom().getNode(), dataElement);
            } else {
                replyPacket.setChildElement(packet.getChildElement().createCopy());
                replyPacket.setError(PacketError.Condition.service_unavailable);
            }
        }
    }
    else {
        replyPacket.setChildElement("query", "jabber:iq:private");
    }
    return replyPacket;
}
 
Example 7
Source File: DefaultFileTransferManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming,
                            boolean processed)
        throws PacketRejectedException
{
    // We only want packets received by the server
    if (!processed && incoming && packet instanceof IQ) {
        IQ iq = (IQ) packet;
        Element childElement = iq.getChildElement();
        if(childElement == null) {
            return;
        }
        String namespace = childElement.getNamespaceURI();
        String profile = childElement.attributeValue("profile");
        // Check that the SI is about file transfer and try creating a file transfer
        if (NAMESPACE_SI.equals(namespace) && NAMESPACE_SI_FILETRANSFER.equals(profile)) {
            // If this is a set, check the feature offer
            if (iq.getType().equals(IQ.Type.set)) {
                JID from = iq.getFrom();
                JID to = iq.getTo();

                FileTransfer transfer = createFileTransfer(from, to, childElement);

                try {
                    if (transfer == null || !acceptIncomingFileTransferRequest(transfer)) {
                        throw new PacketRejectedException();
                    }
                }
                catch (FileTransferRejectedException e) {
                    throw new PacketRejectedException(e);
                }
            }
        }
    }
}
 
Example 8
Source File: MultiplexerPacketDeliverer.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void handleUnprocessedPacket(Packet packet) {
    if (packet instanceof Message) {
        messageStrategy.storeOffline((Message) packet);
    }
    else if (packet instanceof Presence) {
        // presence packets are dropped silently
        //dropPacket(packet);
    }
    else if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        // Check if we need to unwrap the packet
        Element child = iq.getChildElement();
        if (child != null && "session".equals(child.getName()) &&
                "http://jabber.org/protocol/connectionmanager"
                        .equals(child.getNamespacePrefix())) {
            Element send = child.element("send");
            if (send != null) {
                // Unwrap packet
                Element wrappedElement = (Element) send.elements().get(0);
                if ("message".equals(wrappedElement.getName())) {
                    handleUnprocessedPacket(new Message(wrappedElement));
                }
            }
        }
        else {
            // IQ packets are logged but dropped
            Log.warn(LocaleUtils.getLocalizedString("admin.error.routing") + "\n" +
                    packet.toString());
        }
    }
}
 
Example 9
Source File: EntityCapabilitiesManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts a list of identities from an IQ packet.
 * 
 * @param packet the packet
 * @return a list of identities
 */
private static List<String> getIdentitiesFrom(IQ packet) {
    List<String> discoIdentities = new ArrayList<>();
    Element query = packet.getChildElement();
    if (query == null) {
        return discoIdentities;
    }
    Iterator<Element> identitiesIterator = query.elementIterator("identity");
    if (identitiesIterator != null) {
        while (identitiesIterator.hasNext()) {
            Element identityElement = identitiesIterator.next();

            StringBuilder discoIdentity = new StringBuilder();

            String cat = identityElement.attributeValue("category");
            String type = identityElement.attributeValue("type");
            String lang = identityElement.attributeValue("xml:lang");
            String name = identityElement.attributeValue("name");

            if (cat != null) {
                discoIdentity.append(cat);
            }
            discoIdentity.append('/');

            if (type != null) {
                discoIdentity.append(type);
            }
            discoIdentity.append('/');

            if (lang != null) {
                discoIdentity.append(lang);
            }
            discoIdentity.append('/');

            if (name != null) {
                discoIdentity.append(name);
            }

            discoIdentities.add(discoIdentity.toString());
        }
    }
    return discoIdentities;
}
 
Example 10
Source File: IQOfflineMessagesHandler.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ reply = IQ.createResultIQ(packet);
    Element offlineRequest = packet.getChildElement();

    JID from = packet.getFrom();
    if (offlineRequest.element("purge") != null) {
        // User requested to delete all offline messages
        messageStore.deleteMessages(from.getNode());
    }
    else if (offlineRequest.element("fetch") != null) {
        // Mark that offline messages shouldn't be sent when the user becomes available
        stopOfflineFlooding(from);
        // User requested to receive all offline messages
        for (OfflineMessage offlineMessage : messageStore.getMessages(from.getNode(), false)) {
            sendOfflineMessage(from, offlineMessage);
        }
    }
    else {
        for (Iterator it = offlineRequest.elementIterator("item"); it.hasNext();) {
            Element item = (Element) it.next();
            Date creationDate = null;
            try {
                creationDate = xmppDateTime.parseString(item.attributeValue("node"));
            } catch (ParseException e) {
                Log.error("Error parsing date", e);
            }
            if ("view".equals(item.attributeValue("action"))) {
                // User requested to receive specific message
                OfflineMessage offlineMsg = messageStore.getMessage(from.getNode(), creationDate);
                if (offlineMsg != null) {
                    sendOfflineMessage(from, offlineMsg);
                }
            }
            else if ("remove".equals(item.attributeValue("action"))) {
                // User requested to delete specific message
                if (messageStore.getMessage(from.getNode(), creationDate) != null) {
                    messageStore.deleteMessage(from.getNode(), creationDate);
                } else {
                    // If the requester is authorized but the node does not exist, the server MUST return a <item-not-found/> error.
                    reply.setError(PacketError.Condition.item_not_found);
                }
            }
        }
    }
    return reply;
}
 
Example 11
Source File: LocationHandler.java    From openfireLBS with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * 
 * @param packet
 * @return
 */
private IQ getUsersNearme(IQ packet) {

	IQ reply = IQ.createResultIQ(packet);
	
	JID from = packet.getFrom();
	
	Element iq = packet.getChildElement();
	Element item = iq.element("item");
	Double myLon = Double.parseDouble(item.attributeValue("lon"));
	Double myLat = Double.parseDouble(item.attributeValue("lat"));
	
	// XXX: update user location firstly 
	insertLocation(myLon,myLat,from.getNode());
	
	// find users near me 
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	try {
		pstmt = openfireConn.prepareStatement(SQL_USERS_NEARME);
		pstmt.setDouble(1, myLon);
		pstmt.setDouble(2, myLon);
		pstmt.setDouble(3, myLat);
		pstmt.setDouble(4, myLat);
		rs = pstmt.executeQuery();
		String username = null;
		double nearLon = 0;
		double nearLat = 0;
		while (rs.next()) {  
			username = rs.getString("username");
			nearLon = rs.getDouble("lon");
			nearLat = rs.getDouble("lat");
			Element e = iq.addElement("item");
			e.addAttribute("user", username);
			e.addAttribute("lon", Double.toString(nearLon));
			e.addAttribute("lat", Double.toString(nearLat));
		}
		reply.setChildElement(iq);
	} catch (SQLException e1) {
		reply.setType(IQ.Type.error);
		reply.setError(PacketError.Condition.internal_server_error);
		e1.printStackTrace();
	}
	return reply;
}