Java 类org.jivesoftware.smack.tcp.XMPPTCPConnection 实例源码

项目:android-xmpp-iot-demo    文件:XmppIotDataControl.java   
private void controlNotificationAlarm(boolean torchMode) {
    final XMPPTCPConnection connection = mXmppManager.getXmppConnection();
    final EntityFullJid fullThingJid = mXmppManager.getFullThingJidOrNotify();
    if (fullThingJid == null) return;

    SetBoolData setTorch = new SetBoolData(Constants.NOTIFICATION_ALARM, torchMode);
    IoTControlManager ioTControlManager = IoTControlManager.getInstanceFor(connection);

    LOGGER.info("Trying to control " + fullThingJid + " set torchMode=" + torchMode);

    try {
        final IoTSetResponse ioTSetResponse = ioTControlManager.setUsingIq(fullThingJid, setTorch);
    } catch (SmackException.NoResponseException | XMPPErrorException | SmackException.NotConnectedException | InterruptedException e) {
        mXmppManager.withMainActivity((ma) -> Toast.makeText(mContext, "Could not control thing: " + e, Toast.LENGTH_LONG).show());
        LOGGER.log(Level.SEVERE, "Could not set data", e);
    }
}
项目:communote-server    文件:XMPPConnector.java   
/**
 * The constructor for the XMPP bot.
 *
 * @param host
 *            The server the bot should login.
 * @param port
 *            The hosts port.
 * @param login
 *            The bots login name.
 * @param password
 *            The bots login password.
 * @param resource
 *            The bots resource (i.e. Work or Home). Can be null.
 * @throws IllegalArgumentException
 *             Throws an {@link IllegalArgumentException} if some of the parameters are in an
 *             invalid format.
 */
public XMPPConnector(String host, String port, String login, String password, String resource)
        throws IllegalArgumentException {
    checkParameters(host, port, login, password, resource);
    int numericalPort = port == null ? DEFAULT_XMPP_PORT : Integer.parseInt(port);
    this.sender = login + "@" + host + "/" + resource;
    SmackConfiguration.DEBUG_ENABLED = Boolean.parseBoolean(ApplicationPropertyXmpp.DEBUG
            .getValue());
    ProviderManager.addExtensionProvider(AliasPacketExtension.ALIAS_ELEMENT_NAME,
            AliasPacketExtension.ALIAS_NAMESPACE, AliasPacketExtension.class);
    ConnectionConfiguration config = new ConnectionConfiguration(host, numericalPort);
    connection = new XMPPTCPConnection(config);
    connect(login, password, resource);
    sendPriorityPresence();
    if (connection.isConnected()) {
        LOG.info(ResourceBundleManager.instance().getText("xmpp.connection.started",
                Locale.ENGLISH));
        connection.addConnectionListener(new XMPPConnectionStatusLogger());
    } else {
        LOG.info("The XMPP connection wasn't established.");
    }
}
项目:Intercloud    文件:XmppConnectionManager.java   
@Override
public void connect(XmppURI uri, String password) throws IOException, XMPPException, SmackException {
    this.disconnect();

    XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword(uri.getNode(), password)
            .setServiceName(uri.getDomain())
            .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
            .setDebuggerEnabled(true)
            .build();
    AbstractXMPPConnection connection = new XMPPTCPConnection(configuration);
    connection.connect();
    connection.login();
    // keep connection alive
    // when connection is idle it will run into timeout
    PingManager pingManager = PingManager.getInstanceFor(connection);
    pingManager.setPingInterval(60);
    pingManager.pingMyServer();

    this.connection = connection;
}
项目:Zom-Android    文件:Omemo.java   
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);
}
项目:myrobotlab    文件:Xmpp.java   
public void connect(String hostname, int port, String username, String password) throws Exception {

    purgeTask("reconnect");

    this.hostname = hostname;
    this.serviceName = hostname;
    this.port = port;
    this.username = username;
    this.password = password;

    Builder builder = XMPPTCPConnectionConfiguration.builder();
    builder.setUsernameAndPassword(username, password);
    builder.setServiceName(serviceName);
    builder.setServiceName(hostname);
    builder.setPort(port);
    builder.setSecurityMode(SecurityMode.disabled);
    builder.setDebuggerEnabled(true);

    XMPPTCPConnectionConfiguration config = builder.build();

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

    roster = Roster.getInstanceFor(connection);
    chatManager = ChatManager.getInstanceFor(connection);

    roster.addRosterListener(this);

    isConnected = true;

    // not worth it - always empty right after connect
    // getContactList();

    broadcastState();
  }
项目:League-of-Legends-XMPP-Chat-Library    文件:LolChat.java   
/**
 * 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();
}
项目:SmackPlus    文件:XmppTransceiver.java   
private XmppTransceiver(XMPPTCPConnection connection, PacketFilter messageFilter) {
    this.connection = connection;
    PacketListener observablePacketListener = new PacketListener() {
        @Override
        public void processPacket(Packet packet) throws SmackException.NotConnectedException {
            pw.swordfish.sms.Message sms;
            try {
                sms = xmppToSms(Unsafe.<Message>cast(packet));
            } catch (MalformedSmsAddress ignored) {
                return;
            }
            for (Observer<pw.swordfish.sms.Message> observer : observers)
                observer.onNext(sms);
        }
    };
    this.connection.addPacketListener(observablePacketListener, messageFilter);
}
项目:BizareChat    文件:QuickbloxGroupXmppConnection.java   
private void initGroupConnection() {
    long currentUserId = CurrentUser.getInstance().getCurrentUserId();
    String currentUserPassword = CurrentUser.getInstance().getCurrentPassword();
    String jid = currentUserId + "-" + ApiConstants.APP_ID;
    groupChatConnection = new XMPPTCPConnection(
            jid, currentUserPassword, ApiConstants.MULTI_USERS_CHAT_ENDPOINT);
    groupChatConnection.addConnectionListener(this);
}
项目:BizareChat    文件:QuickbloxPrivateXmppConnection.java   
private void initPrivateConnection() {
    long currentUserId = CurrentUser.getInstance().getCurrentUserId();
    String currentUserPassword = CurrentUser.getInstance().getCurrentPassword();
    String userName = currentUserId + "-" + ApiConstants.APP_ID;
    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
    configBuilder.setUsernameAndPassword(userName, currentUserPassword);
    configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    configBuilder.setServiceName(ApiConstants.CHAT_END_POINT);
    configBuilder.setHost(ApiConstants.CHAT_END_POINT);
    configBuilder.setDebuggerEnabled(true);

    privateChatConnection = new XMPPTCPConnection(configBuilder.build());
    privateChatConnection.addConnectionListener(this);

    ReconnectionManager manager = ReconnectionManager.getInstanceFor(privateChatConnection);
    manager.enableAutomaticReconnection();
    manager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY);
    manager.setFixedDelay(15);

    ProviderManager.addExtensionProvider(Displayed.ELEMENT, Displayed.NAMESPACE, new Displayed.Provider());
    DisplayedManager.getInstanceFor(privateChatConnection).addDisplayedListener(
            (fromJid, toJid, receiptId, receipt) -> {
                messageService.get().processDisplayed(fromJid, toJid, receiptId, receipt);
            });

    ProviderManager.addExtensionProvider(Received.ELEMENT, Received.NAMESPACE, new Received.Provider());
    ReceivedManager.getInstanceFor(privateChatConnection).addReceivedListener(
            (fromJid, toJid, receiptId, receipt) -> {
                messageService.get().processReceived(fromJid, toJid, receiptId, receipt);
            });
}
项目:android-xmpp-iot-demo    文件:AndroidSmackManager.java   
public XMPPTCPConnection createManagedConnection(XMPPTCPConnectionConfiguration configuration) {
    XMPPTCPConnection connection = new XMPPTCPConnection(configuration);
    ManagedXmppConnection managedConnection = new ManagedXmppConnection(connection);

    for (NewManagedConnectionListener newManagedConnectionListener : mNewConnectionListeners) {
        newManagedConnectionListener.newConnection(managedConnection);
    }

    synchronized (managedConnection) {
        mManagedConnections.put(connection, managedConnection);
    }

    return connection;
}
项目:android-xmpp-iot-demo    文件:AndroidSmackManager.java   
void disconnectConnections() {
    forAllManagedConnections(new WithXmppConnection<XMPPTCPConnection>() {
        @Override
        public void withXmppConnection(XMPPTCPConnection connection, ManagedXmppConnection managedXmppConnection) {
            connection.disconnect();
        }
    });
}
项目:android-xmpp-iot-demo    文件:AndroidSmackManager.java   
void forAllManagedConnections(WithXmppConnection<XMPPTCPConnection> withXmppConnection) {
    synchronized (mManagedConnections) {
        for (ManagedXmppConnection<XMPPTCPConnection> managedXmppConnection : mManagedConnections.values()) {
            final XMPPTCPConnection connection = managedXmppConnection.getConnection();
            if (connection == null) {
                mManagedConnections.remove(managedXmppConnection);
                continue;
            }
            withXmppConnection.withXmppConnection(connection, managedXmppConnection);
        }
    }
}
项目:android-xmpp-iot-demo    文件:ClaimThingActivity.java   
private void claimButtonClicked(final Thing thing) {

        final XMPPTCPConnection connection = mXmppManger.getXmppConnection();
        if (connection == null) {
            showInGui("Not connection available");
            return;
        }

        if (!connection.isAuthenticated()) {
            showInGui("Connection not authenticated");
            return;
        }

        IoTDiscoveryManager ioTDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);

        IoTClaimed iotClaimed;
        try {
            iotClaimed = ioTDiscoveryManager.claimThing(mRegistry, thing.getMetaTags(), true);
        } catch (SmackException.NoResponseException | XMPPException.XMPPErrorException | SmackException.NotConnectedException | InterruptedException e) {
            showInGui("Could not claim because " + e);
            LOGGER.log(Level.WARNING, "Could not register", e);
            return;
        }

        EntityBareJid claimedJid = iotClaimed.getJid().asEntityBareJidIfPossible();
        if (claimedJid == null) {
            throw new IllegalStateException();
        }
        Settings settings = Settings.getInstance(this);
        settings.setClaimedJid(claimedJid);

        showInGui("Thing " + claimedJid + " claimed.");
        runOnUiThread(() -> {
            finish();
        });
    }
项目:android-xmpp-iot-demo    文件:XmppIotDataControl.java   
private void performReadOut() {
    XMPPTCPConnection connection = mXmppManager.getXmppConnection();
    EntityFullJid fullThingJid = mXmppManager.getFullThingJidOrNotify();
    if (fullThingJid == null) return;

    LOGGER.info("Requesting read out from " + fullThingJid);

    IoTDataManager iotDataManager = IoTDataManager.getInstanceFor(connection);
    final List<IoTFieldsExtension> res;
    try {
        res = iotDataManager.requestMomentaryValuesReadOut(fullThingJid);
    } catch (SmackException.NoResponseException | XMPPErrorException | SmackException.NotConnectedException |InterruptedException e) {
        mXmppManager.withMainActivity((ma) -> Toast.makeText(mContext, "Could not perform read out: " + e, Toast.LENGTH_LONG).show());
        LOGGER.log(Level.WARNING, "Could not perform read out", e);
        return;
    }

    final List<? extends IoTDataField> dataFields = res.get(0).getNodes().get(0).getTimestampElements().get(0).getDataFields();

    mXmppManager.withMainActivity((ma) -> {
        ma.mIotSensorsLinearLayout.removeAllViews();
        for (IoTDataField field : dataFields) {
            IotSensorView iotSensorView = new IotSensorView(ma, field.getName(), field.getValueString());
            ma.mIotSensorsLinearLayout.addView(iotSensorView);
        }
    });
}
项目:XMPPSample_Studio    文件:XMPP.java   
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);


    }
项目:FlowsManager    文件:XMPPConnectionManager.java   
public static AbstractXMPPConnection getConnection() {

        if ( XMPPConnectionManager.isConfigured == false ) {
            Log.w(LOGTAG, "Instating unconfigured connection" );
            return null;
        }
        if ( XMPPConnectionManager.isConnected == false ) {

            // Send the configuration
            // TODO: Yes I know, this is restrictive, DNS must be working
            XMPPTCPConnectionConfiguration.Builder configBuilder =
                    XMPPTCPConnectionConfiguration.builder();
            configBuilder.setUsernameAndPassword(
                    XMPPConnectionManager.xmppUserName,
                    XMPPConnectionManager.xmppPassword);
            configBuilder.setServiceName( XMPPConnectionManager.xmppUserDomain  );
            configBuilder.setResource( "FlowsManager" );

            XMPPConnectionManager.connection = new XMPPTCPConnection(configBuilder.build());

            try {
                // Create a connection to the XMPP server.
                XMPPConnectionManager.connection.connect();
                // Log into the server
                XMPPConnectionManager.connection.login();
            } catch (Exception ex) {
                Log.w(LOGTAG, "XMPP Connection error " + ex);
                return null ;
            }
            XMPPConnectionManager.isConnected = true ;

        }

        return XMPPConnectionManager.connection ;

    }
项目:xmpp-service    文件:XmppServiceConnection.java   
private void createConnection() {
    Logger.debug(TAG, "creating new connection to " + mAccount.getHost() + ":" + mAccount.getPort());

    XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
            .setServiceName(mAccount.getServiceName())
            .setResource(mAccount.getResourceName())
            .setHost(mAccount.getHost())
            .setPort(mAccount.getPort())
            .setUsernameAndPassword(mAccount.getXmppJid(), mAccount.getPassword())
            .setConnectTimeout(XmppService.CONNECT_TIMEOUT);

    if (XmppService.CUSTOM_SSL_CONTEXT != null) {
        Logger.debug(TAG, "setting custom SSL context");
        builder.setCustomSSLContext(XmppService.CUSTOM_SSL_CONTEXT);
    }

    if (XmppService.CUSTOM_HOSTNAME_VERIFIER != null) {
        Logger.debug(TAG, "setting custom hostname verifier");
        builder.setHostnameVerifier(XmppService.CUSTOM_HOSTNAME_VERIFIER);
    }

    mConnection = new XMPPTCPConnection(builder.build());
    mConnection.setUseStreamManagement(XmppService.USE_STREAM_MANAGEMENT);
    mConnection.setUseStreamManagementResumption(XmppService.USE_STREAM_MANAGEMENT);
    mConnection.setPreferredResumptionTime(XmppService.STREAM_MANAGEMENT_RESUMPTION_TIME);

    mConnection.addConnectionListener(this);
}
项目:Smack    文件:OnceForThisStanza.java   
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");
    }
}
项目:Camel    文件:XmppEndpoint.java   
private XMPPTCPConnection createConnectionInternal() {
    if (connectionConfig != null) {
        return new XMPPTCPConnection(connectionConfig);
    }

    if (port == 0) {
        port = 5222;
    }
    String sName = getServiceName() == null ? host : getServiceName();
    ConnectionConfiguration conf = new ConnectionConfiguration(host, port, sName);
    return new XMPPTCPConnection(conf);
}
项目:MineXMPP    文件:XMPPConnectionHandler.java   
public void setup() {
    this.configBuilder = XMPPTCPConnectionConfiguration.builder();
    this.configBuilder.setUsernameAndPassword(XMPPConnectionHandler.username, XMPPConnectionHandler.password);
    this.configBuilder.setResource(XMPPConnectionHandler.resource);
    this.configBuilder.setServiceName(XMPPConnectionHandler.service);
    this.configBuilder.setHost(XMPPConnectionHandler.host);
    this.configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    this.connection = new XMPPTCPConnection(this.configBuilder.build());
}
项目:openyu-commons    文件:PoolableXmppConnection.java   
public PoolableXmppConnection(XMPPConnection delegate, ObjectPool<XMPPConnection> pool) {
    this.delegate = delegate;
    this.pool = pool;
    //
    if (delegate != null) {
        if (delegate instanceof XMPPTCPConnection) {
            socket = ClassHelper.getDeclaredFieldValue(delegate, "socket");
        }
    }
}
项目:openyu-commons    文件:PoolableXmppConnection.java   
/**
 * 真正關閉連線
 */
public synchronized void reallyClose() {
    try {
        if (delegate != null) {
            if (delegate instanceof XMPPTCPConnection) {
                XMPPTCPConnection conn = (XMPPTCPConnection) delegate;
                conn.disconnect();
                // 移除所有的listener
                removeAllListeners(conn);
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:openyu-commons    文件:XmppFactoryImplTest.java   
@Test
@BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 0, concurrency = 10)
// round: 0.40 [+- 0.00], round.block: 0.05 [+- 0.01], round.gc: 0.00 [+-
// 0.00], GC.calls: 1, GC.time: 0.01, time.total: 0.41, time.warmup: 0.00,
// time.bench: 0.41
public void createXMPPConnection() throws Exception {
    XMPPConnection result = null;
    result = factory.createXMPPConnection();
    System.out.println(result);
    assertNotNull(result);
    //
    XMPPTCPConnection conn = (XMPPTCPConnection) result;
    conn.disconnect();
}
项目:jabbot    文件:XmppBinding.java   
@Override
public boolean connect(){
    connection = new XMPPTCPConnection(newConnectionConfiguration(getConfiguration()));
       privilegeMapper = new PrivilegeMapper(connection);
    try {
        connection.connect();
        connection.login();
        PingManager.getInstanceFor(connection).setPingInterval(pingInterval);
        this.initListeners(getConfiguration().getCommandPrefix(),connection);
        super.dispatchEvent(new ConnectedEvent(this));
        return connection.isConnected();
    } catch (XMPPException | SmackException | IOException e) {
        throw new ConnectionException(e);
    }
}
项目:graylog-plugin-jabber    文件:JabberAlarmCallback.java   
private XMPPConnection login(final Configuration config) throws IOException, XMPPException, SmackException, KeyManagementException, NoSuchAlgorithmException {
    final String serviceName = isNullOrEmpty(config.getString(CK_SERVICE_NAME))
            ? config.getString(CK_HOSTNAME) : config.getString(CK_SERVICE_NAME);

    final XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
            .setHost(config.getString(CK_HOSTNAME))
            .setPort(config.getInt(CK_PORT))
            .setServiceName(serviceName)
            .setSendPresence(false);

    if (config.getBoolean(CK_ACCEPT_SELFSIGNED)) {
        TLSUtils.acceptAllCertificates(configBuilder);
    }

    final boolean requireSecurity = config.getBoolean(CK_REQUIRE_SECURITY);
    configBuilder.setSecurityMode(requireSecurity ?
            ConnectionConfiguration.SecurityMode.required : ConnectionConfiguration.SecurityMode.ifpossible);

    final XMPPTCPConnectionConfiguration connectionConfiguration = configBuilder.build();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Supported SASL authentications: {}", SASLAuthentication.getRegisterdSASLMechanisms());
        LOG.debug("require_security: {}", requireSecurity);
        LOG.debug("Security mode: {}", connectionConfiguration.getSecurityMode());
        LOG.debug("Socket factory: {}", connectionConfiguration.getSocketFactory());
        LOG.debug("Keystore: {}", connectionConfiguration.getKeystorePath());
        LOG.debug("Keystore type: {}", connectionConfiguration.getKeystoreType());
    }

    final XMPPTCPConnection xmppConnection = new XMPPTCPConnection(connectionConfiguration);

    xmppConnection.connect();
    xmppConnection.login(config.getString(CK_USERNAME), config.getString(CK_PASSWORD));

    return xmppConnection;
}
项目:LOL-Chat    文件:LolChat.java   
/**
 * 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,
               String riotApiKey) {
    this.friendRequestPolicy = friendRequestPolicy;
    if (riotApiKey != null && server.api != null) {
        this.riotApi = new JRiot(riotApiKey, server.name().toLowerCase());
    }
    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);

    try {
        connection.connect();
    } catch (Exception e) {
        System.err.println("Failed to connect to " + server.host);
        return;
    }
    addListeners();
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (!stop) {
                try {
                    Thread.sleep(500);//NOT SURE ABOUT THIS, TODO:REVIST
                } catch (final InterruptedException ignored) {
                }
            }
        }
    }).start();
}
项目:SmackDemo    文件:XMPPManager.java   
private XMPPManager() {
    config = new ConnectionConfiguration(serverAddress, 5222, serverName);
    config.setReconnectionAllowed(true);
    config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    connection = new XMPPTCPConnection(config);
    connection.addConnectionListener(new XMPPConnectionListener());
}
项目:SmackPlus    文件:XMPPClient.java   
public static XMPPClient connect(String serviceName, String username, String password) throws XMPPException.ConnectException {
    XMPPConnection connection = new XMPPTCPConnection(serviceName);
    try {
        connection.connect();
        connection.login(username, password, "Android");
    } catch (org.jivesoftware.smack.XMPPException | IOException | SmackException e) {
        throw new XMPPException.ConnectException(e);
    }
    return new XMPPClient(connection);
}
项目:SmackPlus    文件:XmppTransceiver.java   
public static XmppTransceiver connect(String serviceName, String username, String password, PacketFilter messageFilter) throws ConnectException {
    XMPPTCPConnection connection = new XMPPTCPConnection(serviceName);
    try {
        connection.connect();
        connection.login(username, password, "Android");
    } catch (org.jivesoftware.smack.XMPPException | SmackException | IOException e) {
        throw new ConnectException(e);
    }
    return new XmppTransceiver(connection, messageFilter);
}
项目:android-xmpp-iot-demo    文件:AndroidSmackManager.java   
public ManagedXmppConnection<XMPPTCPConnection> getManagedXmppConnectionFor(XMPPTCPConnection connection) {
    synchronized (mManagedConnections) {
        return mManagedConnections.get(connection);
    }
}
项目:android-xmpp-iot-demo    文件:AndroidSmackManager.java   
public void disconnectAndUnmanage(XMPPTCPConnection connection) {
    connection.disconnect();
    synchronized (mManagedConnections) {
        mManagedConnections.remove(connection);
    }
}
项目:android-xmpp-iot-demo    文件:XmppManager.java   
boolean isConnectionUseable() {
    final XMPPTCPConnection connection = xmppConnection;
    return connection != null && connection.isAuthenticated();
}
项目:android-xmpp-iot-demo    文件:XmppManager.java   
XMPPTCPConnection getXmppConnection() {
    return xmppConnection;
}
项目:android-xmpp-iot-demo    文件:XmppManager.java   
XmppConnectionState getConnectionState() {
    final ManagedXmppConnection<XMPPTCPConnection> managedXmppConnection = mManagedXmppConnection;
    if (managedXmppConnection == null) return XmppConnectionState.Disconnected;
    return managedXmppConnection.getState();
}
项目:mangosta-android    文件:RoomManager.java   
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();
                }

            }
        }
    }
项目:mangosta-android    文件:XMPPSession.java   
public XMPPTCPConnection getXMPPConnection() {
    return mXMPPConnection;
}
项目:lider    文件:OnlineRosterListener.java   
public OnlineRosterListener(XMPPTCPConnection connection) {
    this.connection = connection;
    getInitialOnlineUsers();
}
项目:Smack    文件:OnceForThisStanza.java   
public static void setup(XMPPTCPConnection connection, Stanza packet) {
    StanzaFilter packetFilter = new OnceForThisStanza(connection, packet);
    connection.addRequestAckPredicate(packetFilter);
}
项目:openyu-commons    文件:PoolableXmppConnection.java   
@SuppressWarnings("unchecked")
protected void removeAllListeners(XMPPTCPConnection conn) {

    // addAsyncStanzaListener(packetListener, packetFilter)
    @SuppressWarnings("rawtypes")
    Map asyncRecvListeners = ClassHelper.getDeclaredFieldValue(conn, "asyncRecvListeners");
    if (CollectionHelper.notEmpty(asyncRecvListeners)) {
        asyncRecvListeners.clear();
    }
    // addConnectionListener(connectionListener)
    Set<ConnectionListener> connectionListeners = ClassHelper.getDeclaredFieldValue(conn, "connectionListeners");
    if (CollectionHelper.notEmpty(connectionListeners)) {
        connectionListeners.clear();
    }

    // addPacketInterceptor(packetInterceptor, packetFilter)
    @SuppressWarnings("rawtypes")
    Map interceptors = ClassHelper.getDeclaredFieldValue(conn, "interceptors");
    if (CollectionHelper.notEmpty(interceptors)) {
        interceptors.clear();
    }

    // addPacketSendingListener(packetListener, packetFilter)
    @SuppressWarnings("rawtypes")
    Map sendListeners = ClassHelper.getDeclaredFieldValue(conn, "sendListeners");
    if (CollectionHelper.notEmpty(sendListeners)) {
        sendListeners.clear();
    }

    // addSyncStanzaListener(packetListener, packetFilter)
    @SuppressWarnings("rawtypes")
    Map syncRecvListeners = ClassHelper.getDeclaredFieldValue(conn, "syncRecvListeners");
    if (CollectionHelper.notEmpty(syncRecvListeners)) {
        syncRecvListeners.clear();
    }

    // registerIQRequestHandler(final IQRequestHandler iqRequestHandler)
    @SuppressWarnings("rawtypes")
    Map setIqRequestHandler = ClassHelper.getDeclaredFieldValue(conn, "setIqRequestHandler");
    if (CollectionHelper.notEmpty(setIqRequestHandler)) {
        setIqRequestHandler.clear();
    }
    @SuppressWarnings("rawtypes")
    Map getIqRequestHandler = ClassHelper.getDeclaredFieldValue(conn, "getIqRequestHandler");
    if (CollectionHelper.notEmpty(getIqRequestHandler)) {
        getIqRequestHandler.clear();
    }
    //
    conn.removeAllRequestAckPredicates();
    conn.removeAllStanzaAcknowledgedListeners();
    conn.removeAllStanzaIdAcknowledgedListeners();
}
项目:Zom-Android    文件:XmppStreamHandler.java   
public XmppStreamHandler(XMPPTCPConnection connection, ConnectionListener connectionListener) {
    mConnection = connection;
    mConnectionListener = connectionListener;
    startListening();
}