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

The following examples show how to use org.xmpp.packet.IQ#setTo() . 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: OfMeetPlugin.java    From openfire-ofmeet-plugin with Apache License 2.0 6 votes vote down vote up
public void sessionDestroyed(Session session)
{
    Log.debug("OfMeet Plugin -  sessionDestroyed "+ session.getAddress().toString() + "\n" + ((ClientSession) session).getPresence().toXML());

    boolean skypeAvailable = XMPPServer.getInstance().getPluginManager().getPlugin("ofskype") != null;

    if (OfMeetAzure.skypeids.containsKey(session.getAddress().getNode()))
    {
        String sipuri = OfMeetAzure.skypeids.remove(session.getAddress().getNode());

        IQ iq = new IQ(IQ.Type.set);
        iq.setFrom(session.getAddress());
        iq.setTo(XMPPServer.getInstance().getServerInfo().getXMPPDomain());

        Element child = iq.setChildElement("request", "http://igniterealtime.org/protocol/ofskype");
        child.setText("{'action':'stop_skype_user', 'sipuri':'" + sipuri + "'}");
        XMPPServer.getInstance().getIQRouter().route(iq);

        Log.info("OfMeet Plugin - closing skype session " + sipuri);
    }
}
 
Example 2
Source File: ComponentStanzaHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
protected void processIQ(IQ packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        IQ reply = new IQ();
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Keep track of the component that sent an IQ get/set
    if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
        // Handle subsequent bind packets
        LocalComponentSession componentSession = (LocalComponentSession) session;
        // Get the external component of this session
        LocalComponentSession.LocalExternalComponent component =
                (LocalComponentSession.LocalExternalComponent) componentSession.getExternalComponent();
        component.track(packet);
    }
    super.processIQ(packet);
}
 
Example 3
Source File: ClientSessionConnection.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * If the Connection Manager or the Client requested to close the connection then just do
 * nothing. But if the server originated the request to close the connection then we need
 * to send to the Connection Manager a packet letting him know that the Client Session needs
 * to be terminated.
 */
@Override
public void closeVirtualConnection() {
    // Figure out who requested the connection to be closed
    StreamID streamID = session.getStreamID();
    if (multiplexerManager.getClientSession(connectionManagerName, streamID) == null) {
        // Client or Connection manager requested to close the session
        // Do nothing since it has already been removed and closed
    }
    else {
        ConnectionMultiplexerSession multiplexerSession =
                multiplexerManager.getMultiplexerSession(connectionManagerName,streamID);
        if (multiplexerSession != null) {
            // Server requested to close the client session so let the connection manager
            // know that he has to finish the client session
            IQ closeRequest = new IQ(IQ.Type.set);
            closeRequest.setFrom(serverName);
            closeRequest.setTo(connectionManagerName);
            Element child = closeRequest.setChildElement("session",
                    "http://jabber.org/protocol/connectionmanager");
            child.addAttribute("id", streamID.getID());
            child.addElement("close");
            multiplexerSession.process(closeRequest);
        }
    }
}
 
Example 4
Source File: MultiplexerStanzaHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
protected void processIQ(final IQ packet) {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        IQ reply = new IQ();
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Process the packet
    packetHandler.handle(packet);
}
 
Example 5
Source File: XmppPubSubControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private XmppUnsubscribe buildXmppUnsubscribe() {
    IQ iq = new IQ(IQ.Type.set);
    iq.setTo(toJid);
    iq.setFrom(fromJid);
    Element element = new DefaultElement(pubSub, Namespace.get(XmppPubSubConstants.PUBSUB_NAMESPACE));
    Element childElement = new DefaultElement(unsubscribe);
    childElement.addAttribute(node, nodeAttribute);
    element.add(childElement);
    iq.setChildElement(element);
    XmppUnsubscribe xmppUnsubscribe = new XmppUnsubscribe(iq);
    return xmppUnsubscribe;
}
 
Example 6
Source File: XmppPubSubControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private XmppSubscribe buildXmppSubscribe() {
    IQ iq = new IQ(IQ.Type.set);
    iq.setTo(toJid);
    iq.setFrom(fromJid);
    Element element = new DefaultElement(pubSub, Namespace.get(XmppPubSubConstants.PUBSUB_NAMESPACE));
    Element childElement = new DefaultElement(subscribe);
    childElement.addAttribute(node, nodeAttribute);
    element.add(childElement);
    iq.setChildElement(element);
    XmppSubscribe xmppSubscribe = new XmppSubscribe(iq);
    return xmppSubscribe;
}
 
Example 7
Source File: ClientConnectionHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * In addition to the functionality provided by the parent class, this
 * method will send XMPP ping requests to the remote entity on every first
 * invocation of this method (which will occur after a period of half the
 * allowed connection idle time has passed, without any IO).
 * 
 * XMPP entities must respond with either an IQ result or an IQ error
 * (feature-unavailable) stanza upon receiving the XMPP ping stanza. Both
 * responses will be received by Openfire and will cause the connection idle
 * count to be reset.
 * 
 * Entities that do not respond to the IQ Ping stanzas can be considered
 * dead, and their connection will be closed by the parent class
 * implementation on the second invocation of this method.
 * 
 * Note that whitespace pings that are sent by XMPP entities will also cause
 * the connection idle count to be reset.
 * 
 * @see ConnectionHandler#sessionIdle(IoSession, IdleStatus)
 */
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    super.sessionIdle(session, status);
    
    final boolean doPing = ConnectionSettings.Client.KEEP_ALIVE_PING_PROPERTY.getValue();
    if (doPing && session.getIdleCount(status) == 1) {
        final ClientStanzaHandler handler = (ClientStanzaHandler) session.getAttribute(HANDLER);
        final JID entity = handler.getAddress();
        
        if (entity != null) {
            // Ping the connection to see if it is alive.
            final IQ pingRequest = new IQ(Type.get);
            pingRequest.setChildElement("ping",
                    IQPingHandler.NAMESPACE);
            pingRequest.setFrom( XMPPServer.getInstance().getServerInfo().getXMPPDomain() );
            pingRequest.setTo(entity); 
            
            // Get the connection for this session
            final Connection connection = (Connection) session.getAttribute(CONNECTION);

            if (Log.isDebugEnabled()) {
                Log.debug("ConnectionHandler: Pinging connection that has been idle: " + connection);
            }

            // OF-1497: Ensure that data sent to the client is processed through LocalClientSession, to avoid
            // synchronisation issues with stanza counts related to Stream Management (XEP-0198)!
            LocalClientSession ofSession = (LocalClientSession) SessionManager.getInstance().getSession( entity );
            if (ofSession == null) {
                Log.warn( "Trying to ping a MINA connection that's idle, but has no corresponding Openfire session. MINA Connection: " + connection );
            } else {
                ofSession.deliver( pingRequest );
            }
        }
    }
}
 
Example 8
Source File: InternalComponentManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 *  Send a SoftwareVersion request to the new component. If the component provides information
 *  then it will be added to the  session of current component.
 *
 * @param component the new component that was added to this manager.
 * @param componentJID the XMPP address of the new component.
 */
private void sendSoftwareVersion(Component component, JID componentJID) {
    // Build a "jabber:iq:version" request that will be sent to the component
    IQ iq = new IQ(IQ.Type.get);
    iq.setFrom(getAddress());
    iq.setTo(componentJID);
    iq.setChildElement("query", "jabber:iq:version");
    // Send the "jabber:iq:version" request to the component. The reply (if any) will be processed in
    // #process(Packet) or org.jivesoftware.openfire.net.ComponentStanzaHandler#rocessIQ(Packet)
    //sendPacket(component, iq);
    component.processPacket(iq);
}
 
Example 9
Source File: InternalComponentManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
     *  Send a disco#info request to the new component. If the component provides information
     *  then it will be added to the list of discoverable server items.
     *
     * @param component the new component that was added to this manager.
     * @param componentJID the XMPP address of the new component.
     */
    private void checkDiscoSupport(Component component, JID componentJID) {
        // Build a disco#info request that will be sent to the component
        IQ iq = new IQ(IQ.Type.get);
        iq.setFrom(getAddress());
        iq.setTo(componentJID);
        iq.setChildElement("query", "http://jabber.org/protocol/disco#info");
        // Send the disco#info request to the component. The reply (if any) will be processed in
        // #process(Packet)
//        sendPacket(component, iq);
        component.processPacket(iq);
    }
 
Example 10
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Process an IQ get stanza that was addressed to the service (rather than to a node/user).
 *
 * @param packet The stanza to process.
 * @return A response (can be null).
 */
private IQ handleIQGetToService(IQ packet) {
    final JID senderJID = packet.getFrom();
    final JID bareJidFrom = senderJID.asBareJID();
    packet = packet.createCopy();
    packet.setTo(bareJidFrom);

    final PEPService pepService = pepServiceManager.getPEPService(bareJidFrom);
    pepServiceManager.process(pepService, packet);
    return null;
}
 
Example 11
Source File: XmppPubSubControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private XmppPublish buildXmppPublish() {
    IQ iq = new IQ(IQ.Type.set);
    iq.setTo(toJid);
    iq.setFrom(fromJid);
    Element element = new DefaultElement(pubSub, Namespace.get(XmppPubSubConstants.PUBSUB_NAMESPACE));
    Element publishElement = new DefaultElement(publish).addAttribute(node, nodeAttribute);
    Element itemElement = new DefaultElement(item).addAttribute(id, itemId);
    Element entryElement = new DefaultElement(entry, Namespace.get(testNamespace));
    itemElement.add(entryElement);
    publishElement.add(itemElement);
    element.add(publishElement);
    iq.setChildElement(element);
    XmppPublish xmppPublish = new XmppPublish(iq);
    return xmppPublish;
}
 
Example 12
Source File: IQBlockingHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an IQ-set with the newly blocked JIDs to all resources of the user that have requested the blocklist.
 *
 * @param user      The for which updates are to be broadcasted (cannot be null).
 * @param newBlocks The JIDs for which an update needs to be sent (cannot be null, can be empty).
 */
protected void pushBlocklistUpdates( User user, Collection<JID> newBlocks )
{
    if ( newBlocks.isEmpty() )
    {
        return;
    }

    Log.debug( "Pushing blocklist updates to all resources of user '{}' that have previously requested the blocklist.", user.getUsername() );

    final Collection<ClientSession> sessions = sessionManager.getSessions( user.getUsername() );
    for ( final ClientSession session : sessions )
    {
        if ( session.hasRequestedBlocklist() )
        {
            final IQ iq = new IQ( IQ.Type.set );
            iq.setTo( session.getAddress() );
            final Element block = iq.setChildElement( "unblock", NAMESPACE );
            for ( final JID newBlock : newBlocks )
            {
                block.addElement( "item" ).addAttribute( "jid", newBlock.toString() );
            }

            XMPPServer.getInstance().getPacketRouter().route( iq );
        }
    }
}
 
Example 13
Source File: IQBlockingHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an IQ-set with the newly blocked JIDs to all resources of the user that have requested the blocklist.
 *
 * @param user      The for which updates are to be broadcasted (cannot be null).
 * @param newBlocks The JIDs for which an update needs to be sent (cannot be null, can be empty).
 */
protected void pushBlocklistUpdates( User user, List<JID> newBlocks )
{
    if ( newBlocks.isEmpty() )
    {
        return;
    }

    Log.debug( "Pushing blocklist updates to all resources of user '{}' that have previously requested the blocklist.", user.getUsername() );

    final Collection<ClientSession> sessions = sessionManager.getSessions( user.getUsername() );
    for ( final ClientSession session : sessions )
    {
        if ( session.hasRequestedBlocklist() )
        {
            final IQ iq = new IQ( IQ.Type.set );
            iq.setTo( session.getAddress() );
            final Element block = iq.setChildElement( "block", NAMESPACE );
            for ( final JID newBlock : newBlocks )
            {
                block.addElement( "item" ).addAttribute( "jid", newBlock.toString() );
            }

            XMPPServer.getInstance().getPacketRouter().route( iq );
        }
    }
}
 
Example 14
Source File: SoftwareServerVersionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionCreated(Session session) {
    try {
        IQ versionRequest = new IQ(IQ.Type.get);
        versionRequest.setTo(session.getAddress());
        versionRequest.setFrom(session.getServerName());
        versionRequest.setChildElement("query", "jabber:iq:version");
        session.process(versionRequest);
    } catch (Exception e) {
        Log.error("Exception while trying to query a server for its software version.", e);;
    }
   
}
 
Example 15
Source File: XmppPubSubControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private XmppRetract buildXmppRetract() {
    IQ iq = new IQ(IQ.Type.set);
    iq.setTo(toJid);
    iq.setFrom(fromJid);
    Element element = new DefaultElement(pubSub, Namespace.get(XmppPubSubConstants.PUBSUB_NAMESPACE));
    Element retractElement = new DefaultElement(retract).addAttribute(node, nodeAttribute);
    Element itemElement = new DefaultElement(item).addAttribute(id, itemId);
    retractElement.add(itemElement);
    element.add(retractElement);
    iq.setChildElement(element);
    XmppRetract xmppRetract = new XmppRetract(iq);
    return xmppRetract;
}
 
Example 16
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Generates and processes an IQ stanza that subscribes to a PEP service.
 *
 * @param pepService the PEP service of the owner.
 * @param subscriber the JID of the entity that is subscribing to the PEP service.
 * @param owner      the JID of the owner of the PEP service.
 */
private void createSubscriptionToPEPService(PEPService pepService, JID subscriber, JID owner) {
    // If `owner` has a PEP service, generate and process a pubsub subscription packet
    // that is equivalent to: (where 'from' field is JID of subscriber and 'to' field is JID of owner)
    //
    //        <iq type='set'
    //            from='[email protected]/chamber'
    //            to='[email protected]
    //            id='collsub'>
    //          <pubsub xmlns='http://jabber.org/protocol/pubsub'>
    //            <subscribe jid='[email protected]'/>
    //            <options>
    //              <x xmlns='jabber:x:data'>
    //                <field var='FORM_TYPE' type='hidden'>
    //                  <value>http://jabber.org/protocol/pubsub#subscribe_options</value>
    //                </field>
    //                <field var='pubsub#subscription_type'>
    //                  <value>items</value>
    //                </field>
    //                <field var='pubsub#subscription_depth'>
    //                  <value>all</value>
    //                </field>
    //              </x>
    //           </options>
    //         </pubsub>
    //        </iq>

    IQ subscriptionPacket = new IQ(IQ.Type.set);
    subscriptionPacket.setFrom(subscriber);
    subscriptionPacket.setTo(owner.toBareJID());

    Element pubsubElement = subscriptionPacket.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");

    Element subscribeElement = pubsubElement.addElement("subscribe");
    subscribeElement.addAttribute("jid", subscriber.toBareJID());

    Element optionsElement = pubsubElement.addElement("options");
    Element xElement = optionsElement.addElement(QName.get("x", "jabber:x:data"));

    DataForm dataForm = new DataForm(xElement);

    FormField formField = dataForm.addField();
    formField.setVariable("FORM_TYPE");
    formField.setType(FormField.Type.hidden);
    formField.addValue("http://jabber.org/protocol/pubsub#subscribe_options");

    formField = dataForm.addField();
    formField.setVariable("pubsub#subscription_type");
    formField.addValue("items");

    formField = dataForm.addField();
    formField.setVariable("pubsub#subscription_depth");
    formField.addValue("all");

    pepServiceManager.process(pepService, subscriptionPacket);
}
 
Example 17
Source File: EntityCapabilitiesManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public void process(Presence packet) {
    if (Presence.Type.unavailable == packet.getType()) {
        if (packet.getFrom() != null ) {
            this.capabilitiesBeingUpdated.remove( packet.getFrom() );
            final String oldVer = this.entityCapabilitiesUserMap.remove( packet.getFrom() );
            if ( oldVer != null ) {
                checkObsolete( oldVer );
            }
        }
        return;
    }

    // Examine the packet and check if it has caps info,
    // if not -- do nothing by returning.
    Element capsElement = packet.getChildElement("c", "http://jabber.org/protocol/caps");
    if (capsElement == null) {
        return;
    }

    // Examine the packet and check if it's in legacy format (pre version 1.4
    // of XEP-0115). If so, do nothing by returning.
    // TODO: if this packet is in legacy format, we SHOULD check the 'node',
    // 'ver', and 'ext' combinations as specified in the archived version
    // 1.3 of the specification, and cache the results. See JM-1447
    final String hashAttribute = capsElement.attributeValue("hash");
    if (hashAttribute == null || hashAttribute.trim().length() == 0) {
        return;
    }
    
    // Examine the packet and check if it has and a 'ver' hash
    // if not -- do nothing by returning.
    final String newVerAttribute = capsElement.attributeValue("ver");
    if (newVerAttribute == null || newVerAttribute.trim().length() == 0) {
        return;
    }

    // Check to see if the 'ver' hash is already in our cache.
    EntityCapabilities caps;
    if ((caps = entityCapabilitiesMap.get(newVerAttribute)) != null) {
        // The 'ver' hash is in the cache already, so let's update the
        // entityCapabilitiesUserMap for the user that sent the caps
        // packet.
        Log.trace( "Registering 'ver' (for recognized caps) for {}", packet.getFrom() );
        registerCapabilities( packet.getFrom(), caps );
    }
    else {
        // If this entity previously had another registration, that now no longer is valid.
        final String ver = entityCapabilitiesUserMap.remove(packet.getFrom());
        if ( ver != null ) {
            capabilitiesBeingUpdated.put( packet.getFrom(), ver );
        }

        // The 'ver' hash is not in the cache so send out a disco#info query
        // so that we may begin recognizing this 'ver' hash.
        IQ iq = new IQ(IQ.Type.get);
        iq.setTo(packet.getFrom());

        String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
        iq.setFrom(serverName);

        iq.setChildElement("query", "http://jabber.org/protocol/disco#info");

        String packetId = iq.getID();
        
        caps = new EntityCapabilities();
        caps.setHashAttribute(hashAttribute);
        caps.setVerAttribute(newVerAttribute);
        Log.trace( "Querying 'ver' for unrecognized caps. Querying: {}", packet.getFrom() );
        verAttributes.put(packetId, caps);

        final IQRouter iqRouter = XMPPServer.getInstance().getIQRouter();
        iqRouter.addIQResultListener(packetId, this);
        iqRouter.route(iq);
    }
}
 
Example 18
Source File: S2STestService.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Run a test against the domain.
 * @return K-V pairs of debug information.
 * @throws Exception On error.
 */
public Map<String, String> run() throws Exception {
    waitUntil = new Semaphore(0);
    Map<String, String> results = new HashMap<>();
    final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain);

    // Tear down existing routes.
    final SessionManager sessionManager = SessionManager.getInstance();
    for (final Session incomingServerSession : sessionManager.getIncomingServerSessions( domain ) )
    {
        incomingServerSession.close();
    }

    final Session outgoingServerSession = sessionManager.getOutgoingServerSession( pair );
    if ( outgoingServerSession != null )
    {
        outgoingServerSession.close();
    }

    final IQ pingRequest = new IQ( Type.get );
    pingRequest.setChildElement( "ping", IQPingHandler.NAMESPACE );
    pingRequest.setFrom( pair.getLocal() );
    pingRequest.setTo( domain );

    // Intercept logging.
    final Writer logs = new StringWriter();
    final String appenderName = addAppender( logs );

    // Intercept packets.
    final PacketInterceptor interceptor = new S2SInterceptor( pingRequest );
    InterceptorManager.getInstance().addInterceptor(interceptor);

    // Send ping.
    try
    {
        Log.info( "Sending server to server ping request to " + domain );
        XMPPServer.getInstance().getIQRouter().route( pingRequest );

        // Wait for success or exceed socket timeout.
        waitUntil.tryAcquire( RemoteServerManager.getSocketTimeout(), TimeUnit.MILLISECONDS );

        // Check on the connection status.
        logSessionStatus();

        // Prepare response.
        results.put( "certs", getCertificates() );
        results.put( "stanzas", interceptor.toString() );
        results.put( "logs", logs.toString() );

        return results;
    }
    finally
    {
        // Cleanup
        InterceptorManager.getInstance().removeInterceptor( interceptor );
        removeAppender( appenderName );
    }
}
 
Example 19
Source File: EntityCapabilitiesManagerTest.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the CAPS verification string generation based on the
 * "Simple Generation Example" provided in section 5.2 of XEP-0115 (version
 * 1.4 and later).
 */
@Test
public void testSimpleGenerationExample() throws Exception {
    // formulate the result stanza
    final IQ iq = new IQ(IQ.Type.result);
    iq.setFrom("[email protected]/chamber");
    iq.setTo("[email protected]");
    iq.setID("simpleexample1");

    final Element query = iq.setChildElement("query",
            "http://jabber.org/protocol/disco#info");

    // Consider an entity whose category is "client", whose service
    // discovery type is "pc", service discovery name is "Exodus 0.9.1"
    // (...)
    final Element identity = query.addElement("identity");
    identity.addAttribute("category", "client");
    identity.addAttribute("type", "pc");
    identity.addAttribute("name", "Exodus 0.9.1");

    // (...) and whose supported features are
    // "http://jabber.org/protocol/disco#info",
    // "http://jabber.org/protocol/disco#items",
    // "http://jabber.org/protocol/muc" and
    // "http://jabber.org/protocol/caps"
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/disco#info");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/disco#items");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/muc");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/caps");

    // Using the SHA-1 algorithm (...)
    final String verification = EntityCapabilitiesManager.generateVerHash(
            iq, "sha-1");

    // the verification string result must be QgayPKawpkPSDYmwT/WM94uAlu0=
    assertEquals("QgayPKawpkPSDYmwT/WM94uAlu0=", verification);
}
 
Example 20
Source File: EntityCapabilitiesManagerTest.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the CAPS verification string generation based on the
 * "Complex Generation Example" provided in section 5.3 of XEP-0115 (version
 * 1.4 and later).
 */
@Test
public void testComplexGenerationExample() throws Exception {
    // formulate the result stanza
    final IQ iq = new IQ(IQ.Type.result);
    iq.setFrom("[email protected]/chamber");
    iq.setTo("[email protected]");
    iq.setID("simpleexample1");

    final Element query = iq.setChildElement("query",
            "http://jabber.org/protocol/disco#info");
    query.addAttribute("node",
            "http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w=");

    // Two identities: "client/pc/Psi" and "client/pc/"
    final Element identityA = query.addElement("identity");
    identityA.addAttribute("category", "client");
    identityA.addAttribute("type", "pc");
    identityA.addAttribute("name", "Psi 0.11");
    identityA.addAttribute("xml:lang", "en");

    final Element identityB = query.addElement("identity");
    identityB.addAttribute("category", "client");
    identityB.addAttribute("type", "pc");
    identityB.addAttribute("name", "\u03a8 0.11");
    identityB.addAttribute("xml:lang", "el");

    // the features: "http://jabber.org/protocol/caps",
    // http://jabber.org/protocol/disco#info",
    // "http://jabber.org/protocol/disco#items",
    // "http://jabber.org/protocol/muc".
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/disco#info");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/disco#items");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/muc");
    query.addElement("feature").addAttribute("var",
            "http://jabber.org/protocol/caps");

    // extended service discovery forms
    final Element ext = query.addElement(QName.get("x", "jabber:x:data"));
    ext.addAttribute("type", "result");

    final Element formField = ext.addElement("field");
    formField.addAttribute("var", "FORM_TYPE");
    formField.addAttribute("type", "hidden");
    formField.addElement("value")
            .setText("urn:xmpp:dataforms:softwareinfo");

    final Element ipField = ext.addElement("field");
    ipField.addAttribute("var", "ip_version");
    ipField.addElement("value").setText("ipv4");
    ipField.addElement("value").setText("ipv6");

    final Element osField = ext.addElement("field");
    osField.addAttribute("var", "os");
    osField.addElement("value").setText("Mac");

    final Element osvField = ext.addElement("field");
    osvField.addAttribute("var", "os_version");
    osvField.addElement("value").setText("10.5.1");

    final Element softwareField = ext.addElement("field");
    softwareField.addAttribute("var", "software");
    softwareField.addElement("value").setText("Psi");

    final Element softwarevField = ext.addElement("field");
    softwarevField.addAttribute("var", "software_version");
    softwarevField.addElement("value").setText("0.11");

    // Using the SHA-1 algorithm (...)
    final String verification = EntityCapabilitiesManager.generateVerHash(
            iq, "SHA-1");

    // the verification string result must be q07IKJEyjvHSyhy//CH0CxmKi8w=
    assertEquals("q07IKJEyjvHSyhy//CH0CxmKi8w=", verification);
}