org.jivesoftware.smack.tcp.XMPPTCPConnection Java Examples

The following examples show how to use org.jivesoftware.smack.tcp.XMPPTCPConnection. 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: DoX.java    From Smack with Apache License 2.0 7 votes vote down vote up
public static XMPPTCPConnection runDoxResolver(String jid, String password)
        throws XMPPException, SmackException, IOException, InterruptedException {
    XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
            .setXmppAddressAndPassword(jid, password)
            .setResource("dns")
            .setDebuggerFactory(ConsoleDebugger.Factory.INSTANCE)
            .build();
    XMPPTCPConnection connection = new XMPPTCPConnection(config);

    connection.connect().login();

    DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);
    dox.setDnsOverXmppResolver(DnsOverXmppMiniDnsResolver.INSTANCE);

    dox.enable();

    return connection;
}
 
Example #2
Source File: SmackIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@BeforeClass
public static void setup() throws IOException, InterruptedException, XMPPException, SmackException {

    XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword("baeldung","baeldung")
            .setXmppDomain("jabb3r.org")
            .setHost("jabb3r.org")
            .build();

    XMPPTCPConnectionConfiguration config2 = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword("baeldung2","baeldung2")
            .setXmppDomain("jabb3r.org")
            .setHost("jabb3r.org")
            .build();

    connection = new XMPPTCPConnection(config);
    connection.connect();
    connection.login();

}
 
Example #3
Source File: StanzaThread.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void run() {
    XMPPTCPConnectionConfiguration config = null;
    try {
        config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword("baeldung2","baeldung2")
                .setXmppDomain("jabb3r.org")
                .setHost("jabb3r.org")
                .build();

        AbstractXMPPConnection connection = new XMPPTCPConnection(config);
        connection.connect();
        connection.login();

        ChatManager chatManager = ChatManager.getInstanceFor(connection);

        Chat chat = chatManager.chatWith(JidCreate.from("[email protected]").asEntityBareJidOrThrow());

        chat.send("Hello!");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #4
Source File: XmppTools.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static boolean createAccount(DomainBareJid xmppDomain, Localpart username, String password)
        throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
        InterruptedException {
    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
            .setXmppDomain(xmppDomain);
    TLSUtils.acceptAllCertificates(configBuilder);
    XMPPTCPConnectionConfiguration config = configBuilder.build();
    XMPPTCPConnection connection = new XMPPTCPConnection(config);
    connection.connect();
    try {
        if (!supportsIbr(connection))
            return false;

        AccountManager accountManager = AccountManager.getInstance(connection);
        accountManager.createAccount(username, password);
        return true;
    } finally {
        connection.disconnect();
    }
}
 
Example #5
Source File: Omemo.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
private OmemoManager initOMemoManager(XMPPTCPConnection conn, BareJid altUser) {
    BareJid user;

    if (conn.getUser() != null) {
        user = conn.getUser().asBareJid();
    } else {
        user = altUser;
    }

    mOmemoStore = OmemoService.getInstance().getOmemoStoreBackend();
    int defaultDeviceId = mOmemoStore.getDefaultDeviceId(user);

    if (defaultDeviceId < 1) {
        defaultDeviceId = OmemoManager.randomDeviceId();
        mOmemoStore.setDefaultDeviceId(user, defaultDeviceId);
    }

    return OmemoManager.getInstanceFor(conn, defaultDeviceId);
}
 
Example #6
Source File: IoT.java    From Smack with Apache License 2.0 6 votes vote down vote up
private static ThingState actAsDataThing(XMPPTCPConnection connection) throws XMPPException, SmackException, InterruptedException {
    final String key = StringUtils.randomString(12);
    final String sn = StringUtils.randomString(12);
    Thing dataThing = Thing.builder()
                    .setKey(key)
                    .setSerialNumber(sn)
                    .setManufacturer("IgniteRealtime")
                    .setModel("Smack")
                    .setVersion("0.1")
                    .setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
        @Override
        public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
            IoTDataField.IntField field = new IntField("timestamp", (int) (System.currentTimeMillis() / 1000));
            callback.momentaryReadOut(Collections.singletonList(field));
        }
    })
                    .build();
    IoTDiscoveryManager iotDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);
    ThingState state = IoTDiscoveryIntegrationTest.registerThing(iotDiscoveryManager, dataThing);
    printStatus("SUCCESS: Thing registered:" + dataThing);
    return state;
}
 
Example #7
Source File: LolChat.java    From League-of-Legends-XMPP-Chat-Library with MIT License 6 votes vote down vote up
/**
 * Represents a single connection to a League of Legends chatserver.
 * 
 * @param server
 *            The chatserver of the region you want to connect to
 * @param friendRequestPolicy
 *            Determines how new Friend requests are treated.
 * @param riotApiKey
 *            Your apiKey used to convert summonerId's to name. You can get
 *            your key here <a
 *            href="https://developer.riotgames.com/">developer
 *            .riotgames.com</a>
 * 
 * @see LolChat#setFriendRequestPolicy(FriendRequestPolicy)
 * @see LolChat#setFriendRequestListener(FriendRequestListener)
 */
public LolChat(ChatServer server, FriendRequestPolicy friendRequestPolicy,
		RiotApiKey riotApiKey) {
	this.friendRequestPolicy = friendRequestPolicy;
	this.server = server;
	if (riotApiKey != null && server.api != null) {
		this.riotApi = RiotApi.build(riotApiKey, server);
	}
	Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
	final ConnectionConfiguration config = new ConnectionConfiguration(
			server.host, 5223, "pvp.net");
	config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
	config.setSocketFactory(SSLSocketFactory.getDefault());
	config.setCompressionEnabled(true);
	connection = new XMPPTCPConnection(config);

	addListeners();
}
 
Example #8
Source File: StreamManagementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
public StreamManagementTest(SmackIntegrationTestEnvironment environment) throws Exception {
    super(environment, XMPPTCPConnection.class);
    XMPPTCPConnection connection = getSpecificUnconnectedConnection();
    connection.connect().login();
    if (!connection.isSmAvailable()) {
        throw new TestNotPossibleException("XEP-198: Stream Mangement not supported by service");
    }
}
 
Example #9
Source File: XmppTools.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static boolean supportsIbr(DomainBareJid xmppDomain) throws SmackException, IOException, XMPPException,
        InterruptedException, KeyManagementException, NoSuchAlgorithmException {
    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
            .setXmppDomain(xmppDomain);
    TLSUtils.acceptAllCertificates(configBuilder);
    XMPPTCPConnectionConfiguration config = configBuilder.build();
    XMPPTCPConnection connection = new XMPPTCPConnection(config);
    connection.connect();
    try {
        return supportsIbr(connection);
    } finally {
        connection.disconnect();
    }
}
 
Example #10
Source File: IoT.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void iotScenario(XMPPTCPConnection dataThingConnection, XMPPTCPConnection readingThingConnection) throws TimeoutException, Exception {
    ThingState dataThingState = actAsDataThing(dataThingConnection);

    final SimpleResultSyncPoint syncPoint = new SimpleResultSyncPoint();
    dataThingState.setThingStateChangeListener(new AbstractThingStateChangeListener() {
        @Override
        public void owned(BareJid jid) {
            syncPoint.signal();
        }
    });
    // Wait until the thing is owned.
    syncPoint.waitForResult(TIMEOUT);
    printStatus("OWNED - Thing now owned by " + dataThingState.getOwner());

    // Make sure things are befriended.
    IoTProvisioningManager readingThingProvisioningManager = IoTProvisioningManager.getInstanceFor(readingThingConnection);
    readingThingProvisioningManager.sendFriendshipRequestIfRequired(dataThingConnection.getUser().asBareJid());

    Roster dataThingRoster = Roster.getInstanceFor(dataThingConnection);
    RosterUtil.waitUntilOtherEntityIsSubscribed(dataThingRoster, readingThingConnection.getUser().asBareJid(), TIMEOUT);
    printStatus("FRIENDSHIP ACCEPTED - Trying to read out data");

    IoTDataManager readingThingDataManager = IoTDataManager.getInstanceFor(readingThingConnection);
    List<IoTFieldsExtension> values = readingThingDataManager.requestMomentaryValuesReadOut(dataThingConnection.getUser());
    if (values.size() != 1) {
        throw new IllegalStateException("Unexpected number of values returned: " + values.size());
    }
    IoTFieldsExtension field = values.get(0);
    printStatus("DATA READ-OUT SUCCESS: " + field.toXML());
    printStatus("IoT SCENARIO FINISHED SUCCESSFULLY");
}
 
Example #11
Source File: IoT.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void iotScenario(String dataThingJidString, String dataThingPassword, String readingThingJidString,
        String readingThingPassword, IotScenario scenario) throws Exception {
    final EntityBareJid dataThingJid = JidCreate.entityBareFrom(dataThingJidString);
    final EntityBareJid readingThingJid = JidCreate.entityBareFrom(readingThingJidString);

    final XMPPTCPConnectionConfiguration dataThingConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword(dataThingJid.getLocalpart(), dataThingPassword)
            .setXmppDomain(dataThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();
    final XMPPTCPConnectionConfiguration readingThingConnectionConfiguration = XMPPTCPConnectionConfiguration
            .builder().setUsernameAndPassword(readingThingJid.getLocalpart(), readingThingPassword)
            .setXmppDomain(readingThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();

    final XMPPTCPConnection dataThingConnection = new XMPPTCPConnection(dataThingConnectionConfiguration);
    final XMPPTCPConnection readingThingConnection = new XMPPTCPConnection(readingThingConnectionConfiguration);

    dataThingConnection.setReplyTimeout(TIMEOUT);
    readingThingConnection.setReplyTimeout(TIMEOUT);

    dataThingConnection.setUseStreamManagement(false);
    readingThingConnection.setUseStreamManagement(false);

    try {
        dataThingConnection.connect().login();
        readingThingConnection.connect().login();
        scenario.iotScenario(dataThingConnection, readingThingConnection);
    } finally {
        dataThingConnection.disconnect();
        readingThingConnection.disconnect();
    }
}
 
Example #12
Source File: StreamManagementTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testStreamManagement(XMPPTCPConnection conOne, XMPPTCPConnection conTwo) throws InterruptedException,
                SmackException, IOException, XMPPException {
    final String body1 = "Hi, what's up? " + testRunId;
    final String body2 = "Hi, what's up? I've been just instantly shutdown" + testRunId;
    final String body3 = "Hi, what's up? I've been just resumed" + testRunId;

    final StanzaCollector collector = conTwo.createStanzaCollector(new AndFilter(
                    MessageWithBodiesFilter.INSTANCE,
                    FromMatchesFilter.createFull(conOne.getUser())));

    try {
        send(body1, conOne, conTwo);
        assertMessageWithBodyReceived(body1, collector);

        conOne.instantShutdown();

        send(body2, conOne, conTwo);

        // Reconnect with xep198
        conOne.connect().login();
        assertMessageWithBodyReceived(body2, collector);

        send(body3, conOne, conTwo);
        assertMessageWithBodyReceived(body3, collector);
    }
    finally {
        collector.cancel();
    }
}
 
Example #13
Source File: SmackGcmSenderChannel.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @param senderId
 *            Your GCM project number
 * @param apiKey
 *            API Key of your project
 */
protected void connect(long senderId, String apiKey, int keepAliveInterval) throws XMPPException, IOException, SmackException {

    // Configure connection
    ConnectionConfiguration config = new ConnectionConfiguration(GcmServiceConstants.GCM_SERVER, GcmServiceConstants.GCM_PORT);
    config.setSecurityMode(SecurityMode.enabled);
    config.setReconnectionAllowed(true);
    config.setRosterLoadedAtLogin(false);
    config.setSendPresence(false);
    config.setSocketFactory(SSLSocketFactory.getDefault());

    // Create connection object and initiate connection
    connection = new XMPPTCPConnection(config);
    pingManager = PingManager.getInstanceFor(connection);
    pingManager.setPingInterval(keepAliveInterval);
    pingManager.registerPingFailedListener(this);
    connection.connect();

    // Register listener to log connection state events
    connection.addConnectionListener(new SmackLoggingConnectionListener());

    // Handle incoming messages (delivery receipts and Google control messages)
    connection.addPacketListener(upstreamListener, new PacketTypeFilter(Message.class));

    // Log in...
    connection.login(senderId + "@" + GcmServiceConstants.GCM_SERVER, apiKey);
}
 
Example #14
Source File: OnceForThisStanza.java    From Smack with Apache License 2.0 5 votes vote down vote up
private OnceForThisStanza(XMPPTCPConnection connection, Stanza packet) {
    this.connection = connection;
    this.id = packet.getStanzaId();
    if (StringUtils.isNullOrEmpty(id)) {
        throw new IllegalArgumentException("Stanza ID must be set");
    }
}
 
Example #15
Source File: XMPP.java    From XMPPSample_Studio with Apache License 2.0 5 votes vote down vote up
public void login(String user, String pass, StatusItem status, String username)
            throws XMPPException, SmackException, IOException, InterruptedException {
        Log.i(TAG, "inside XMPP getlogin Method");
        long l = System.currentTimeMillis();
        XMPPTCPConnection connect = connect();
        if (connect.isAuthenticated()) {
            Log.i(TAG, "User already logged in");
            return;
        }

        Log.i(TAG, "Time taken to connect: " + (System.currentTimeMillis() - l));

        l = System.currentTimeMillis();
        connect.login(user, pass);
        Log.i(TAG, "Time taken to login: " + (System.currentTimeMillis() - l));

        Log.i(TAG, "login step passed");

        Presence p = new Presence(Presence.Type.available);
        p.setMode(Presence.Mode.available);
        p.setPriority(24);
        p.setFrom(connect.getUser());
        if (status != null) {
            p.setStatus(status.toJSON());
        } else {
            p.setStatus(new StatusItem().toJSON());
        }
//        p.setTo("");
        VCard ownVCard = new VCard();
        ownVCard.load(connect);
        ownVCard.setNickName(username);
        ownVCard.save(connect);

        PingManager pingManager = PingManager.getInstanceFor(connect);
        pingManager.setPingInterval(150000);
        connect.sendPacket(p);


    }
 
Example #16
Source File: OnceForThisStanza.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void setup(XMPPTCPConnection connection, Stanza packet) {
    StanzaFilter packetFilter = new OnceForThisStanza(connection, packet);
    connection.addRequestAckPredicate(packetFilter);
}
 
Example #17
Source File: DoX.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws XMPPException, SmackException, IOException, InterruptedException {
    SmackConfiguration.DEBUG = true;

    XMPPTCPConnection connection = new XMPPTCPConnection(args[0], args[1]);
    connection.setReplyTimeout(60000);

    connection.connect().login();

    DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);

    Jid target = JidCreate.from("[email protected]/listener");
    Question question = new Question("geekplace.eu", Record.TYPE.A);

    DnsMessage response = dox.query(target, question);

    // CHECKSTYLE:OFF
    System.out.println(response);
    // CHECKSTYLE:ON

    connection.disconnect();
}
 
Example #18
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 4 votes vote down vote up
public XMPPTCPConnection getXMPPConnection() {
    return mXMPPConnection;
}
 
Example #19
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();
                }

            }
        }
    }
 
Example #20
Source File: SmackConnection.java    From SmackAndroidDemo with Apache License 2.0 3 votes vote down vote up
public void connect() throws IOException, XMPPException, SmackException {
    Log.i(TAG, "connect()");

    XMPPTCPConnectionConfiguration.XMPPTCPConnectionConfigurationBuilder builder = XMPPTCPConnectionConfiguration.builder();
    builder.setServiceName(mServiceName);
    builder.setResource("SmackAndroidTestClient");
    builder.setUsernameAndPassword(mUsername, mPassword);
    builder.setRosterLoadedAtLogin(true);


    mConnection = new XMPPTCPConnection(builder.build());

    //Set ConnectionListener here to catch initial connect();
    mConnection.addConnectionListener(this);

    mConnection.connect();
    mConnection.login();

    PingManager.setDefaultPingInterval(600); //Ping every 10 minutes
    PingManager pingManager = PingManager.getInstanceFor(mConnection);
    pingManager.registerPingFailedListener(this);

    setupSendMessageReceiver();

    ChatManager.getInstanceFor(mConnection).addChatListener(this);
    mConnection.getRoster().addRosterListener(this);

}
 
Example #21
Source File: Omemo.java    From Zom-Android-XMPP with GNU General Public License v3.0 3 votes vote down vote up
public Omemo (XMPPTCPConnection connection, BareJid user) {

        oneTimeSetup();

        mOmemoManager = this.initOMemoManager(connection, user);

    }
 
Example #22
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 3 votes vote down vote up
public XmppConnection(Context context) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    super(context);

    synchronized (XmppConnection.class) {
        mGlobalId = mGlobalCount++;
    }

    Debug.onConnectionStart();

    SmackConfiguration.setDefaultPacketReplyTimeout(PACKET_REPLY_TIMEOUT);

    XMPPTCPConnection.setUseStreamManagementDefault(true);
    XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);

    // Create a single threaded executor.  This will serialize actions on the underlying connection.
    createExecutor();

    addProviderManagerExtensions();

    //XmppStreamHandler.addExtensionProviders();

    mChatGroupManager = new XmppChatGroupManager();

    mSessionManager = new XmppChatSessionManager();

    mContactListManager = new XmppContactListManager();


}
 
Example #23
Source File: IoT.java    From Smack with Apache License 2.0 votes vote down vote up
void iotScenario(XMPPTCPConnection dataThingConnection, XMPPTCPConnection readingThingConnection) throws Exception;