org.jivesoftware.smackx.disco.packet.DiscoverItems Java Examples

The following examples show how to use org.jivesoftware.smackx.disco.packet.DiscoverItems. 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: SipAccountPacket.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Does a service discovery on the server to see if a SIPpark Manager is
 * enabled.
 *
 * @param con the XMPPConnection to use.
 * @return true if SIPpark Manager is available.
 */
public static boolean isSoftPhonePluginInstalled(XMPPConnection con) {
    if (!con.isConnected()) {
        return false;
    }

    ServiceDiscoveryManager disco = ServiceDiscoveryManager
            .getInstanceFor(con);
    try {
        DiscoverItems items = disco.discoverItems(con.getXMPPServiceDomain());
        for ( DiscoverItems.Item item : items.getItems() ) {
            if ("SIP Controller".equals(item.getName())) {
                Log.debug("SIP Controller Found");
                return true;
            }
        }
    }
    catch (XMPPException | SmackException e) {
        Log.error("isSparkPluginInstalled", e);
    }

    return false;

}
 
Example #2
Source File: RoomsListManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
private void findMUCLightName(Chat chat) {
    if (XMPPSession.getInstance().getXMPPConnection().isAuthenticated()) {
        DiscoverItems discoverItems = XMPPSession.getInstance().discoverMUCLightItems();

        if (discoverItems != null) {
            List<DiscoverItems.Item> items = discoverItems.getItems();

            for (DiscoverItems.Item item : items) {

                String itemJid = item.getEntityID().toString();
                if (itemJid.equals(chat.getJid())) {
                    chat.setName(item.getName());
                }
            }

        }

    }
}
 
Example #3
Source File: ConferenceServiceBrowser.java    From Spark with Apache License 2.0 6 votes vote down vote up
public Collection<String> getConferenceServices(String serverString) throws Exception {
    Jid server = JidCreate.from(serverString);
    List<String> answer = new ArrayList<>();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    DiscoverItems items = discoManager.discoverItems(server);
    for (DiscoverItems.Item item : items.getItems() ) {
        if (item.getEntityID().toString().startsWith("conference") || item.getEntityID().toString().startsWith("private")) {
            answer.add(item.getEntityID().toString());
        }
        else {
            try {
                DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
                if (info.containsFeature("http://jabber.org/protocol/muc")) {
                    answer.add(item.getEntityID().toString());
                }
            }
            catch (XMPPException | SmackException e) {
                // Nothing to do
            }
        }
    }
    return answer;
}
 
Example #4
Source File: BookmarksUI.java    From Spark with Apache License 2.0 6 votes vote down vote up
private Collection<DomainBareJid> getConferenceServices(DomainBareJid server) throws Exception {
    List<DomainBareJid> answer = new ArrayList<>();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    DiscoverItems items = discoManager.discoverItems(server);
    for (DiscoverItems.Item item : items.getItems()) {
        DomainBareJid entityID = item.getEntityID().asDomainBareJid();
        // TODO: We should not simply assumet that this is MUC service just because it starts with a given prefix.
        if (entityID.toString().startsWith("conference") || entityID.toString().startsWith("private")) {
            answer.add(entityID);
        }
        else {
            try {
                DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
                if (info.containsFeature("http://jabber.org/protocol/muc")) {
                    answer.add(entityID);
                }
            }
            catch (XMPPException | SmackException e) {
                Log.error("Problem when loading conference service.", e);
            }
        }
    }
    return answer;
}
 
Example #5
Source File: CheckUpdates.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Does a service discvery on the server to see if a Spark Manager
 * is enabled.
 *
 * @param con the XMPPConnection to use.
 * @return true if Spark Manager is available.
 */
public static boolean isSparkPluginInstalled(XMPPConnection con) {
    if (!con.isConnected()) {
        return false;
    }


    try {
        DiscoverItems items = SparkManager.getSessionManager().getDiscoveredItems();
        for (DiscoverItems.Item item : items.getItems() ) {
            if ("Spark Updater".equals(item.getName())) {
                return true;
            }
        }
    }
    catch (Exception e) {
        Log.error(e);
    }

    return false;

}
 
Example #6
Source File: Enterprise.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void populateFeatureSet() {
    final ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    final DiscoverItems items = SparkManager.getSessionManager().getDiscoveredItems();
    for (DiscoverItems.Item item : items.getItems() ) {
        String entity = item.getEntityID().toString();
        if (entity != null) {
            if (entity.startsWith("manager.")) {
                sparkManagerInstalled = true;

                // Populate with feature sets.
                try {
                    featureInfo = disco.discoverInfo(item.getEntityID());
                }
                catch (XMPPException | SmackException | InterruptedException e) {
                    Log.error("Error while retrieving feature list for SparkManager.", e);
                }

            }
        }
    }
}
 
Example #7
Source File: MultiUserChatManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a List of the rooms where the requested user has joined. The Iterator will contain Strings where each
 * String represents a room (e.g. [email protected]).
 *
 * @param user the user to check. A fully qualified xmpp ID, e.g. [email protected].
 * @return a List of the rooms where the requested user has joined.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<EntityBareJid> getJoinedRooms(EntityFullJid user) throws NoResponseException, XMPPErrorException,
                NotConnectedException, InterruptedException {
    // Send the disco packet to the user
    DiscoverItems result = serviceDiscoveryManager.discoverItems(user, DISCO_NODE);
    List<DiscoverItems.Item> items = result.getItems();
    List<EntityBareJid> answer = new ArrayList<>(items.size());
    // Collect the entityID for each returned item
    for (DiscoverItems.Item item : items) {
        EntityBareJid muc = item.getEntityID().asEntityBareJidIfPossible();
        if (muc == null) {
            LOGGER.warning("Not a bare JID: " + item.getEntityID());
            continue;
        }
        answer.add(muc);
    }
    return answer;
}
 
Example #8
Source File: JabberBrowser.java    From Spark with Apache License 2.0 5 votes vote down vote up
public Entity(final DiscoverItems.Item item) {
    this.item = item;
    setVerticalTextPosition(JLabel.BOTTOM);
    setHorizontalTextPosition(JLabel.CENTER);
    setText(item.getName());
    setIcon(SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24));

    addActionListener( e -> browseItem(item) );

}
 
Example #9
Source File: Socks5PacketUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a response to an item discovery request. The stanza doesn't contain any items.
 *
 * @param from the XMPP server
 * @param to the XMPP client
 * @return response to an item discovery request
 */
public static DiscoverItems createDiscoverItems(Jid from, Jid to) {
    DiscoverItems discoverItems = new DiscoverItems();
    discoverItems.setFrom(from);
    discoverItems.setTo(to);
    discoverItems.setType(IQ.Type.result);
    return discoverItems;
}
 
Example #10
Source File: SessionManager.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
public void initializeSession(AbstractXMPPConnection conn) {
	connection = conn;
    personalDataManager = PrivateDataManager.getInstanceFor(conn);

    discoverItems();

    List<DiscoverItems.Item> it = discoverItems.getItems();//

 for (DiscoverItems.Item item : it) {	     	
 	DebugUtil.debug(item.getEntityID()+item.getName());
  }
}
 
Example #11
Source File: STUN.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the server support STUN Service.
 *
 * @param connection the connection
 * @return true if the server support STUN
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static boolean serviceAvailable(XMPPConnection connection) throws XMPPException, SmackException, InterruptedException {

    if (!connection.isConnected()) {
        return false;
    }

    LOGGER.fine("Service listing");

    ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(connection);
    DiscoverItems items = disco.discoverItems(connection.getXMPPServiceDomain());

    for (DiscoverItems.Item item : items.getItems()) {
        DiscoverInfo info = disco.discoverInfo(item.getEntityID());

        for (DiscoverInfo.Identity identity : info.getIdentities()) {
            if (identity.getCategory().equals("proxy") && identity.getType().equals("stun"))
                if (info.containsFeature(NAMESPACE))
                    return true;
        }

        LOGGER.fine(item.getName() + "-" + info.getType());

    }

    return false;
}
 
Example #12
Source File: DiscoverItemsProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public DiscoverItems parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
                throws XmlPullParserException, IOException {
    DiscoverItems discoverItems = new DiscoverItems();
    boolean done = false;
    DiscoverItems.Item item;
    Jid jid = null;
    String name = "";
    String action = "";
    String node = "";
    discoverItems.setNode(parser.getAttributeValue("", "node"));
    while (!done) {
        XmlPullParser.Event eventType = parser.next();

        if (eventType == XmlPullParser.Event.START_ELEMENT && "item".equals(parser.getName())) {
            // Initialize the variables from the parsed XML
            jid = ParserUtils.getJidAttribute(parser);
            name = parser.getAttributeValue("", "name");
            node = parser.getAttributeValue("", "node");
            action = parser.getAttributeValue("", "action");
        }
        else if (eventType == XmlPullParser.Event.END_ELEMENT && "item".equals(parser.getName())) {
            // Create a new Item and add it to DiscoverItems.
            item = new DiscoverItems.Item(jid);
            item.setName(name);
            item.setNode(node);
            item.setAction(action);
            discoverItems.addItem(item);
        }
        else if (eventType == XmlPullParser.Event.END_ELEMENT && "query".equals(parser.getName())) {
            done = true;
        }
    }

    return discoverItems;
}
 
Example #13
Source File: RoomBrowser.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void displayRoomInformation(final EntityBareJid roomJID) {
     SwingWorker worker = new SwingWorker() {
         RoomInfo roomInfo = null;
         DiscoverItems items = null;

         @Override
public Object construct() {
             try {
                 roomInfo = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getRoomInfo( roomJID );


                 ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
                 items = manager.discoverItems(roomJID);
             }
             catch (XMPPException | SmackException | InterruptedException e) {
                 Log.error(e);
             }
             return "ok";
         }

         @Override
public void finished() {
             setupRoomInformationUI(roomJID, roomInfo, items);
         }
     };

     worker.start();
 }
 
Example #14
Source File: Socks5BytestreamManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of JIDs of SOCKS5 proxies by querying the XMPP server. The SOCKS5 proxies are
 * in the same order as returned by the XMPP server.
 *
 * @return list of JIDs of SOCKS5 proxies
 * @throws XMPPErrorException if there was an error querying the XMPP server for SOCKS5 proxies
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<Jid> determineProxies() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    XMPPConnection connection = connection();
    ServiceDiscoveryManager serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);

    List<Jid> proxies = new ArrayList<>();

    // get all items from XMPP server
    DiscoverItems discoverItems = serviceDiscoveryManager.discoverItems(connection.getXMPPServiceDomain());

    // query all items if they are SOCKS5 proxies
    for (Item item : discoverItems.getItems()) {
        // skip blacklisted servers
        if (this.proxyBlacklist.contains(item.getEntityID())) {
            continue;
        }

        DiscoverInfo proxyInfo;
        try {
            proxyInfo = serviceDiscoveryManager.discoverInfo(item.getEntityID());
        }
        catch (NoResponseException | XMPPErrorException e) {
            // blacklist errornous server
            proxyBlacklist.add(item.getEntityID());
            continue;
        }

        if (proxyInfo.hasIdentity("proxy", "bytestreams")) {
            proxies.add(item.getEntityID());
        } else {
            /*
             * server is not a SOCKS5 proxy, blacklist server to skip next time a Socks5
             * bytestream should be established
             */
            this.proxyBlacklist.add(item.getEntityID());
        }
    }

    return proxies;
}
 
Example #15
Source File: JabberBrowser.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void browseItem(DiscoverItems.Item discoveredItem) {
    addAddress(discoveredItem.getEntityID().toString());
    browsePanel.removeAll();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(con);
    DiscoverItems result;
    try {
        result = discoManager.discoverItems(discoveredItem.getEntityID());
    }
    catch (XMPPException | SmackException | InterruptedException e) {
        browsePanel.invalidate();
        browsePanel.validate();
        browsePanel.repaint();
        return;
    }

    List<Entity> list = new ArrayList<>();
    for (DiscoverItems.Item item : result.getItems() ) {
        Entity entity = new Entity(item);
        browsePanel.add(entity);
        list.add(entity);
    }

    GraphicUtils.makeSameSize((JComponent[])list.toArray(new JComponent[list.size()]));

    browsePanel.invalidate();
    browsePanel.validate();
    browsePanel.repaint();
}
 
Example #16
Source File: MamManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
public RemoteCommand getAdvancedConfigurationCommand() throws InterruptedException, XMPPException, SmackException {
    DiscoverItems discoverItems = adHocCommandManager.discoverCommands(archiveAddress);
    for (DiscoverItems.Item item : discoverItems.getItems()) {
        if (item.getNode().equals(ADVANCED_CONFIG_NODE))
            return adHocCommandManager.getRemoteCommand(archiveAddress, item.getNode());
    }
    throw new SmackException.FeatureNotSupportedException(ADVANCED_CONFIG_NODE, archiveAddress);
}
 
Example #17
Source File: MamManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
public boolean isAdvancedConfigurationSupported() throws InterruptedException, XMPPException, SmackException {
    DiscoverItems discoverItems = adHocCommandManager.discoverCommands(archiveAddress);
    for (DiscoverItems.Item item : discoverItems.getItems()) {
        if (item.getNode().equals(ADVANCED_CONFIG_NODE)) {
            return true;
        }
    }
    return false;
}
 
Example #18
Source File: MultiUserChatLightManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of the rooms the user occupies.
 *
 * @param mucLightService TODO javadoc me please
 * @return a List of the rooms the user occupies.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<Jid> getOccupiedRooms(DomainBareJid mucLightService)
        throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    DiscoverItems result = ServiceDiscoveryManager.getInstanceFor(connection()).discoverItems(mucLightService);
    List<DiscoverItems.Item> items = result.getItems();
    List<Jid> answer = new ArrayList<>(items.size());

    for (DiscoverItems.Item item : items) {
        Jid mucLight = item.getEntityID();
        answer.add(mucLight);
    }

    return answer;
}
 
Example #19
Source File: FeatureDiscovery.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private EnumMap<Feature, JID> discover(JID entity, boolean withItems) {
    // NOTE: smack automatically creates instances of SDM and CapsM and connects them
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(mConn);

    // 1. get features from server
    EnumMap<Feature, JID> features = discover(discoManager, entity);
    if (features == null)
        return new EnumMap<>(FeatureDiscovery.Feature.class);

    if (!withItems)
        return features;

    // 2. get server items
    DiscoverItems items;
    try {
        items = discoManager.discoverItems(entity.toBareSmack());
    } catch (SmackException.NoResponseException |
            XMPPException.XMPPErrorException |
            SmackException.NotConnectedException |
            InterruptedException ex) {
        LOGGER.log(Level.WARNING, "can't get service discovery items", ex);
        return features;
    }

    // 3. get features from server items
    for (DiscoverItems.Item item: items.getItems()) {
        EnumMap<Feature, JID> itemFeatures = discover(discoManager, JID.fromSmack(item.getEntityID()));
        if (itemFeatures != null)
            features.putAll(itemFeatures);
    }

    LOGGER.info("supported server features: "+features);
    return features;
}
 
Example #20
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public DiscoverItems discoverMUCLightItems() {
    DiscoverItems discoverItems = null;
    try {
        discoverItems = ServiceDiscoveryManager.getInstanceFor(mXMPPConnection).discoverItems(JidCreate.from(MUC_LIGHT_SERVICE_NAME));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return discoverItems;
}
 
Example #21
Source File: OfflineMessageHeader.java    From Smack with Apache License 2.0 4 votes vote down vote up
public OfflineMessageHeader(DiscoverItems.Item item) {
    super();
    user = item.getEntityID();
    jid = item.getName();
    stamp = item.getNode();
}
 
Example #22
Source File: JabberBrowser.java    From Spark with Apache License 2.0 4 votes vote down vote up
public DiscoverItems.Item getItem() {
    return item;
}
 
Example #23
Source File: GatewayPlugin.java    From Spark with Apache License 2.0 4 votes vote down vote up
private void populateTransports() throws Exception {
    DiscoverItems discoItems = SparkManager.getSessionManager().getDiscoveredItems();

    for (DiscoverItems.Item item : discoItems.getItems() ) {

        String entityName = item.getEntityID().toString();
        if (entityName != null) {
    	if (entityName.startsWith("aim.")) {
                AIMTransport aim = new AIMTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), aim);
            }
            else if (entityName.startsWith("msn.")) {
                MSNTransport msn = new MSNTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), msn);
            }
            else if (entityName.startsWith("yahoo.")) {
                YahooTransport yahoo = new YahooTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), yahoo);
            }
            else if (entityName.startsWith("icq.")) {
                ICQTransport icq = new ICQTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), icq);
            }
            else if (entityName.startsWith("gtalk.")) {
                GTalkTransport gtalk = new GTalkTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), gtalk);
            }
            else if (entityName.startsWith("xmpp.")) {
                XMPPTransport xmppTransport = new XMPPTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), xmppTransport);
            }
            else if (entityName.startsWith("irc.")) {
                IRCTransport ircTransport = new IRCTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), ircTransport);
            }
            else if (entityName.startsWith("sip.") || entityName.startsWith("simple.")) {
                SimpleTransport simpleTransport = new SimpleTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), simpleTransport);
            }
            else if (entityName.startsWith("gadugadu.")) {
                GaduGaduTransport gadugaduTransport = new GaduGaduTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), gadugaduTransport);
            }
            else if (entityName.startsWith("qq.")) {
                QQTransport qqTransport = new QQTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), qqTransport);
            }
            else if (entityName.startsWith("sametime.")) {
            	SametimeTransport sametimeTransport = new SametimeTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), sametimeTransport);
            }
            else if (entityName.startsWith("facebook.")) {
            	FacebookTransport facebookTransport = new FacebookTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), facebookTransport);
            }
            else if (entityName.startsWith("myspace.") || entityName.startsWith("myspaceim.")) {
            	MySpaceTransport myspaceTransport = new MySpaceTransport(item.getEntityID().asDomainBareJid());
                TransportUtils.addTransport(item.getEntityID().asDomainBareJid(), myspaceTransport);
            }                
        }
    }

}
 
Example #24
Source File: FastpathPlugin.java    From Spark with Apache License 2.0 4 votes vote down vote up
public void initialize() {

        new WorkgroupInitializer().initialize();

        EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				  container = new FastpathContainer();
				  workgroupLabel = new JLabel(FpRes.getString("workgroup"));
				  comboBox = new JComboBox();
				  joinButton = new JButton(FpRes.getString("join"), null);
				  logoutButton = new RolloverButton(FpRes.getString("logout"), null);
		        // Initialize tab handler for Fastpath chats.
		        fastpathTabHandler = new FastpathTabHandler();
		        mainPanel = new BackgroundPane();
			}
   		 
   	 });
   	 




			
			
        try {
            DiscoverItems items = SparkManager.getSessionManager().getDiscoveredItems();
            for (DiscoverItems.Item item : items.getItems() ) {
                String entityID = item.getEntityID() != null ? item.getEntityID().toString() : "";
                if (entityID.startsWith("workgroup")) {
                    // Log into workgroup
                    final DomainBareJid workgroupService = JidCreate.domainBareFromOrThrowUnchecked("workgroup." + SparkManager.getSessionManager().getServerAddress());
                    final EntityFullJid jid = SparkManager.getSessionManager().getJID();


                    SwingWorker worker = new SwingWorker() {
                        public Object construct() {
                            try {
                                return Agent.getWorkgroups(workgroupService, jid, SparkManager.getConnection());
                            }
                            catch (XMPPException | SmackException | InterruptedException e1) {
                                return Collections.emptyList();
                            }
                        }

                        public void finished() {
                            Collection<String> agents = (Collection<String>)get();
                            if (agents.size() == 0) {
                                return;
                            }
                            showSelection(agents);
                        }
                    };

                    worker.start();

                }

            }
        }
        catch (Exception e) {
            Log.error(e);
        }

        SparkManager.getConnection().addConnectionListener(this);
    }
 
Example #25
Source File: Socks5ByteStreamManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
private static void createResponses(Protocol protocol, String sessionID,
                Verification<Bytestream, Bytestream> streamHostUsedVerification, Socks5TestProxy socks5TestProxy)
                throws XmppStringprepException {
    // build discover info that supports the SOCKS5 feature
    DiscoverInfoBuilder discoverInfo = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfo.addFeature(Bytestream.NAMESPACE);

    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer,
                    initiatorJID);
    discoverItems.addItem(new Item(JidCreate.from("proxy2.xmpp-server")));
    discoverItems.addItem(new Item(proxyJID));

    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    /*
     * build discover info for proxy "proxy2.xmpp-server" containing information about being a
     * SOCKS5 proxy
     */
    DiscoverInfoBuilder proxyInfo1 = Socks5PacketUtils.createDiscoverInfo(JidCreate.from("proxy2.xmpp-server"),
                    initiatorJID);
    Identity identity1 = new Identity("proxy", "proxy2.xmpp-server", "bytestreams");
    proxyInfo1.addIdentity(identity1);

    // return the SOCKS5 bytestream proxy identity if proxy is queried
    protocol.addResponse(proxyInfo1.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover info for proxy containing information about being a SOCKS5 proxy
    DiscoverInfoBuilder proxyInfo2 = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity2 = new Identity("proxy", proxyJID.toString(), "bytestreams");
    proxyInfo2.addIdentity(identity2);

    // return the SOCKS5 bytestream proxy identity if proxy is queried
    protocol.addResponse(proxyInfo2.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    /*
     * build a SOCKS5 stream host info for "proxy2.xmpp-server" containing the address and the
     * port of the proxy
     */
    Bytestream streamHostInfo1 = Socks5PacketUtils.createBytestreamResponse(
                    JidCreate.from("proxy2.xmpp-server"), initiatorJID);
    streamHostInfo1.addStreamHost(JidCreate.from("proxy2.xmpp-server"), proxyAddress, socks5TestProxy.getPort());

    // return stream host info if it is queried
    protocol.addResponse(streamHostInfo1, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build a SOCKS5 stream host info containing the address and the port of the proxy
    Bytestream streamHostInfo2 = Socks5PacketUtils.createBytestreamResponse(proxyJID,
                    initiatorJID);
    streamHostInfo2.addStreamHost(proxyJID, proxyAddress, socks5TestProxy.getPort());

    // return stream host info if it is queried
    protocol.addResponse(streamHostInfo2, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build used stream host response
    Bytestream streamHostUsedPacket = Socks5PacketUtils.createBytestreamResponse(targetJID,
                    initiatorJID);
    streamHostUsedPacket.setSessionID(sessionID);
    streamHostUsedPacket.setUsedHost(proxyJID);

    // return used stream host info as response to the bytestream initiation
    protocol.addResponse(streamHostUsedPacket, streamHostUsedVerification,
                    Verification.correspondingSenderReceiver, Verification.requestTypeSET);

    // build response to proxy activation
    IQ activationResponse = Socks5PacketUtils.createActivationConfirmation(proxyJID,
                    initiatorJID);

    // return proxy activation response if proxy should be activated
    protocol.addResponse(activationResponse, new Verification<Bytestream, IQ>() {

        @Override
        public void verify(Bytestream request, IQ response) {
            assertEquals(targetJID, request.getToActivate().getTarget());
        }

    }, Verification.correspondingSenderReceiver, Verification.requestTypeSET);
}
 
Example #26
Source File: Socks5ByteStreamManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if
 * initiator can not connect to the SOCKS5 proxy used by target.
 *
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws XmppStringprepException if the provided string is invalid.
 */
@Test
public void shouldFailIfInitiatorCannotConnectToSocks5Proxy()
                throws SmackException, InterruptedException, XMPPException, XmppStringprepException {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);
    final String sessionID = "session_id_shouldFailIfInitiatorCannotConnectToSocks5Proxy";

    // TODO: The following two variables should be named initatorProxyJid and initiatorProxyAddress.
    final DomainBareJid proxyJID = JidCreate.domainBareFrom("s5b-proxy.initiator.org");
    // Use an TEST-NET-1 address from RFC 5737 to act as black hole.
    final String proxyAddress = "192.0.2.1";

    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    byteStreamManager.setAnnounceLocalStreamHost(false);
    byteStreamManager.setProxyConnectionTimeout(3000);

    /**
     * create responses in the order they should be queried specified by the XEP-0065
     * specification
     */

    // build discover info that supports the SOCKS5 feature
    DiscoverInfoBuilder discoverInfoBuilder = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfoBuilder.addFeature(Bytestream.NAMESPACE);

    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfoBuilder.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer,
                    initiatorJID);
    Item item = new Item(proxyJID);
    discoverItems.addItem(item);

    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover info for proxy containing information about being a SOCKS5 proxy
    DiscoverInfoBuilder proxyInfo = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity = new Identity("proxy", proxyJID.toString(), "bytestreams");
    proxyInfo.addIdentity(identity);

    // return the socks5 bytestream proxy identity if proxy is queried
    protocol.addResponse(proxyInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build a socks5 stream host info containing the address and the port of the
    // proxy
    Bytestream streamHostInfo = Socks5PacketUtils.createBytestreamResponse(proxyJID,
                    initiatorJID);
    streamHostInfo.addStreamHost(proxyJID, proxyAddress, 7778);

    // return stream host info if it is queried
    protocol.addResponse(streamHostInfo, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build used stream host response
    Bytestream streamHostUsedPacket = Socks5PacketUtils.createBytestreamResponse(targetJID,
                    initiatorJID);
    streamHostUsedPacket.setSessionID(sessionID);
    streamHostUsedPacket.setUsedHost(proxyJID);

    // return used stream host info as response to the bytestream initiation
    protocol.addResponse(streamHostUsedPacket, new Verification<Bytestream, Bytestream>() {

        @Override
        public void verify(Bytestream request, Bytestream response) {
            // verify SOCKS5 Bytestream request
            assertEquals(response.getSessionID(), request.getSessionID());
            assertEquals(1, request.getStreamHosts().size());
            StreamHost streamHost = (StreamHost) request.getStreamHosts().toArray()[0];
            assertEquals(response.getUsedHost().getJID(), streamHost.getJID());
        }

    }, Verification.correspondingSenderReceiver, Verification.requestTypeSET);

    IOException e = assertThrows(IOException.class, () -> {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
    });

    // initiator can't connect to proxy because it is not running
    protocol.verifyAll();
    Throwable actualCause = e.getCause();
    assertEquals(TimeoutException.class, actualCause.getClass(), "Unexpected throwable: " + actualCause + '.' + ExceptionUtil.getStackTrace(actualCause));
}
 
Example #27
Source File: Socks5ByteStreamManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if the
 * proxy used by target is invalid.
 *
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws IOException if an I/O error occurred.
 */
@Test
public void shouldFailIfTargetUsesInvalidSocks5Proxy()
                throws SmackException, InterruptedException, IOException, XMPPException {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);
    final String sessionID = "session_id_shouldFailIfTargetUsesInvalidSocks5Proxy";

    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    // TODO: It appears that it is not required to disable the local stream host for this unit test.
    byteStreamManager.setAnnounceLocalStreamHost(false);

    /**
     * create responses in the order they should be queried specified by the XEP-0065
     * specification
     */

    // build discover info that supports the SOCKS5 feature
    DiscoverInfoBuilder discoverInfo = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfo.addFeature(Bytestream.NAMESPACE);

    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer,
                    initiatorJID);
    Item item = new Item(proxyJID);
    discoverItems.addItem(item);

    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover info for proxy containing information about being a SOCKS5 proxy
    DiscoverInfoBuilder proxyInfo = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity = new Identity("proxy", proxyJID.toString(), "bytestreams");
    proxyInfo.addIdentity(identity);

    // return the socks5 bytestream proxy identity if proxy is queried
    protocol.addResponse(proxyInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build a socks5 stream host info containing the address and the port of the
    // proxy
    Bytestream streamHostInfo = Socks5PacketUtils.createBytestreamResponse(proxyJID,
                    initiatorJID);
    streamHostInfo.addStreamHost(proxyJID, proxyAddress, 7778);

    // return stream host info if it is queried
    protocol.addResponse(streamHostInfo, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build used stream host response with unknown proxy
    Bytestream streamHostUsedPacket = Socks5PacketUtils.createBytestreamResponse(targetJID,
                    initiatorJID);
    streamHostUsedPacket.setSessionID(sessionID);
    streamHostUsedPacket.setUsedHost(JidCreate.from("invalid.proxy"));

    // return used stream host info as response to the bytestream initiation
    protocol.addResponse(streamHostUsedPacket, Verification.correspondingSenderReceiver,
                    Verification.requestTypeSET);

    SmackException e = assertThrows(SmackException.class, () -> {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
    });

    protocol.verifyAll();
    assertTrue(e.getMessage().contains("Remote user responded with unknown host"));
}
 
Example #28
Source File: Socks5ByteStreamManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if no
 * SOCKS5 proxy can be found. If it turns out that a proxy is not a SOCKS5 proxy it should not
 * be queried again.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws IOException if an I/O error occurred.
 */
@Test
public void shouldBlacklistNonSocks5Proxies() throws SmackException, InterruptedException, IOException, XMPPException {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID);
    final String sessionID = "session_id_shouldBlacklistNonSocks5Proxies";

    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    byteStreamManager.setAnnounceLocalStreamHost(false);

    /**
     * create responses in the order they should be queried specified by the XEP-0065
     * specification
     */

    // build discover info that supports the SOCKS5 feature
    DiscoverInfoBuilder discoverInfoBuilder = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfoBuilder.addFeature(Bytestream.NAMESPACE);

    DiscoverInfo discoverInfo = discoverInfoBuilder.build();
    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer,
                    initiatorJID);
    Item item = new Item(proxyJID);
    discoverItems.addItem(item);

    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    // build discover info for proxy containing information about NOT being a Socks5
    // proxy
    DiscoverInfoBuilder proxyInfo = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity = new Identity("noproxy", proxyJID.toString(), "bytestreams");
    proxyInfo.addIdentity(identity);

    // return the proxy identity if proxy is queried
    protocol.addResponse(proxyInfo.build(), Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    SmackException e = assertThrows(SmackException.class, () -> {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);

        fail("exception should be thrown");
    });

    protocol.verifyAll();
    assertTrue(e.getMessage().contains("no SOCKS5 proxies available"));

    /* retry to establish SOCKS5 Bytestream */

    // add responses for service discovery again
    protocol.addResponse(discoverInfo, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver,
                    Verification.requestTypeGET);

    e = assertThrows(SmackException.class, () -> {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
    });
    /*
     * #verifyAll() tests if the number of requests and responses corresponds and should
     * fail if the invalid proxy is queried again
     */
    protocol.verifyAll();
    assertTrue(e.getMessage().contains("no SOCKS5 proxies available"));
}
 
Example #29
Source File: SessionManager.java    From xyTalk-pc with GNU Affero General Public License v3.0 4 votes vote down vote up
public DiscoverItems getDiscoveredItems() {
    return discoverItems;
}
 
Example #30
Source File: RoomManager.java    From mangosta-android with Apache License 2.0 4 votes vote down vote up
public void loadMUCLightRooms() {

        final XMPPTCPConnection connection = XMPPSession.getInstance().getXMPPConnection();

        if (connection.isAuthenticated()) {

            DiscoverItems discoverItems = XMPPSession.getInstance().discoverMUCLightItems();

            if (discoverItems != null) {
                RealmManager.getInstance().hideAllMUCLightChats();
                List<DiscoverItems.Item> items = discoverItems.getItems();
                Realm realm = RealmManager.getInstance().getRealm();

                try {
                    for (DiscoverItems.Item item : items) {
                        String itemJid = item.getEntityID().toString();

                        if (itemJid.contains(XMPPSession.MUC_LIGHT_SERVICE_NAME)) {

                            Chat chatRoom = realm.where(Chat.class).equalTo("jid", itemJid).findFirst();

                            if (chatRoom == null) {
                                chatRoom = new Chat();
                                chatRoom.setJid(item.getEntityID().toString());
                                chatRoom.setType(Chat.TYPE_MUC_LIGHT);
                                getSubject(chatRoom);
                            }

                            realm.beginTransaction();
                            chatRoom.setShow(true);
                            chatRoom.setName(item.getName());
                            realm.copyToRealmOrUpdate(chatRoom);
                            realm.commitTransaction();

                            // set last retrieved from MAM
                            ChatMessage chatMessage = RealmManager.getInstance().getFirstMessageForChat(chatRoom.getJid());
                            if (chatMessage != null) {
                                realm.beginTransaction();
                                chatRoom.setLastRetrievedFromMAM(chatMessage.getMessageId());
                                realm.copyToRealmOrUpdate(chatRoom);
                                realm.commitTransaction();
                            }

                        }
                    }

                } finally {
                    realm.close();
                    mListener.onRoomsLoaded();
                }

            }
        }
    }