Java源码示例:org.jivesoftware.smack.AbstractXMPPConnection

示例1
/**
 * Create new SLF4J Smack Debugger instance.
 * @param connection Smack connection to debug
 */
SLF4JSmackDebugger(XMPPConnection connection) {
    super(connection);
    this.writer = new ObservableWriter(writer);
    this.writer.addWriterListener(slf4JRawXmlListener);
    this.reader = new ObservableReader(Validate.notNull(reader));
    this.reader.addReaderListener(slf4JRawXmlListener);

    final SLF4JLoggingConnectionListener loggingConnectionListener = new SLF4JLoggingConnectionListener(connection, logger);
    this.connection.addConnectionListener(loggingConnectionListener);

    if (connection instanceof AbstractXMPPConnection) {
        AbstractXMPPConnection abstractXmppConnection = (AbstractXMPPConnection) connection;
        ReconnectionManager.getInstanceFor(abstractXmppConnection).addReconnectionListener(loggingConnectionListener);
    } else {
        LOGGER.info("The connection instance " + connection
                        + " is not an instance of AbstractXMPPConnection, thus we can not install the ReconnectionListener");
    }
}
 
示例2
void recycle(AbstractXMPPConnection connection) {
    Class<? extends AbstractXMPPConnection> connectionClass = connection.getClass();
    if (!connectionDescriptors.containsKey(connectionClass)) {
        throw new IllegalStateException("Attempt to recycle unknown connection of class '" + connectionClass + "'");
    }

    if (connection.isAuthenticated()) {
        synchronized (connectionPool) {
            connectionPool.put(connectionClass, connection);
        }
    } else {
        connection.disconnect();
    }
    // Note that we do not delete the account of the unauthenticated connection here, as it is done at the end of
    // the test run together with all other dynamically created accounts.
}
 
示例3
@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);
    }
}
 
示例4
/**
 * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and
 * setting the Agent to be offline.
 */
public void shutdown() {
    final XMPPConnection con = SparkManager.getConnection();

    if (con.isConnected()) {
        // Send disconnect.
        ((AbstractXMPPConnection)con).disconnect();
    }

    // Notify all MainWindowListeners
    try {
        fireWindowShutdown();
    }
    catch (Exception ex) {
        Log.error(ex);
    }
    // Close application.
    System.exit(1);

}
 
示例5
/**
 * Closes the current connection and restarts Spark.
 *
 * @param reason the reason for logging out. This can be if user gave no reason.
 */
public void closeConnectionAndInvoke(String reason) {
    final XMPPConnection con = SparkManager.getConnection();
    if (con.isConnected()) {
        if (reason != null) {
            Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
            try
            {
                ((AbstractXMPPConnection)con).disconnect(byePresence);
            }
            catch ( SmackException.NotConnectedException e )
            {
                Log.error( "Unable to sign out with presence.", e);
                ((AbstractXMPPConnection)con).disconnect();
            }
        }
        else {
            ((AbstractXMPPConnection)con).disconnect();
        }
    }
    if (!restartApplicationWithScript()) {
        restartApplicationWithJava();
    }
}
 
示例6
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());
  }
}
 
示例7
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    if (!sampler.getXMPPConnection().isConnected()) {
        return res;
    }
    AbstractXMPPConnection conn = (AbstractXMPPConnection)sampler.getXMPPConnection();
    conn.disconnect();
    if (sampler.getXMPPConnectionConfig() != null)
        sampler.getXMPPConnectionConfig().resetConnection();
    return res;
}
 
示例8
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    AbstractXMPPConnection conn = (AbstractXMPPConnection)sampler.getXMPPConnection();
    conn.connect();
    res.setResponseData(sampler.getXMPPConnection().getConnectionID().getBytes());
    return res;
}
 
示例9
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    XMPPConnection conn = sampler.getXMPPConnection();
    String loginStr = sampler.getPropertyAsString(LOGIN);
    String pwdStr = sampler.getPropertyAsString(PASSWORD);
    String resStr = sampler.getPropertyAsString(RESOURCE);
    res.setSamplerData("Username: " + loginStr + "\nPassword: " + pwdStr + "\nResource: " + resStr);
    AbstractXMPPConnection absConn = (AbstractXMPPConnection) conn;
    if (loginStr.isEmpty()) {
        absConn.loginAnonymously();
    } else {
        absConn.login(loginStr, pwdStr, resStr);
    }
    return res;
}
 
示例10
@SmackIntegrationTest
public void testPresenceEventListenersOffline(final AbstractXMPPConnection conOne,
        final AbstractXMPPConnection conTwo) throws TimeoutException, Exception {
    IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

    final Roster rosterOne = Roster.getInstanceFor(conOne);
    final Roster rosterTwo = Roster.getInstanceFor(conTwo);

    rosterOne.createItem(conTwo.getUser().asBareJid(), "Con Two", null);
    rosterTwo.createItem(conOne.getUser().asBareJid(), "Con One", null);

    IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout);

    final SimpleResultSyncPoint offlineTriggered = new SimpleResultSyncPoint();

    rosterOne.addPresenceEventListener(new AbstractPresenceEventListener() {
        @Override
        public void presenceUnavailable(FullJid jid, Presence presence) {
            if (!jid.equals(conTwo.getUser())) {
                return;
            }
            offlineTriggered.signal();
        }
    });

    // Disconnect conTwo, this should cause an 'unavailable' presence to be send from conTwo to
    // conOne.
    conTwo.disconnect();

    Boolean result = offlineTriggered.waitForResult(timeout);
    if (!result) {
        throw new Exception("presenceUnavailable() was not called");
    }
}
 
示例11
public MultiUserChatLowLevelIntegrationTest(SmackIntegrationTestEnvironment environment) throws Exception {
    super(environment);
    AbstractXMPPConnection connection = getConnectedConnection();
    try {
        if (MultiUserChatManager.getInstanceFor(connection).getMucServiceDomains().isEmpty()) {
            throw new TestNotPossibleException("MUC component not offered by service");
        }
    } finally {
        recycle(connection);
    }
}
 
示例12
@SmackIntegrationTest
public void testMucBookmarksAutojoin(AbstractXMPPConnection connection) throws InterruptedException,
                TestNotPossibleException, XMPPException, SmackException, IOException {
    final BookmarkManager bookmarkManager = BookmarkManager.getBookmarkManager(connection);
    if (!bookmarkManager.isSupported()) {
        throw new TestNotPossibleException("Private data storage not supported");
    }
    final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
    final Resourcepart mucNickname = Resourcepart.from("Nick-" + StringUtils.randomString(6));
    final String randomMucName = StringUtils.randomString(6);
    final DomainBareJid mucComponent = multiUserChatManager.getMucServiceDomains().get(0);
    final MultiUserChat muc = multiUserChatManager.getMultiUserChat(JidCreate.entityBareFrom(
                    Localpart.from(randomMucName), mucComponent));

    MucCreateConfigFormHandle handle = muc.createOrJoin(mucNickname);
    if (handle != null) {
        handle.makeInstant();
    }
    muc.leave();

    bookmarkManager.addBookmarkedConference("Smack Inttest: " + testRunId, muc.getRoom(), true,
                    mucNickname, null);

    connection.disconnect();
    connection.connect().login();

    // MucBookmarkAutojoinManager is also able to do its task automatically
    // after every login, it's not deterministic when this will be finished.
    // So we trigger it manually here.
    MucBookmarkAutojoinManager.getInstanceFor(connection).autojoinBookmarkedConferences();

   assertTrue(muc.isJoined());

   // If the test went well, leave the MUC
   muc.leave();
}
 
示例13
protected List<AbstractXMPPConnection> getUnconnectedConnections(int count)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    List<AbstractXMPPConnection> connections = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {
        AbstractXMPPConnection connection = getUnconnectedConnection();
        connections.add(connection);
    }
    return connections;
}
 
示例14
private static void verifyLowLevelTestMethod(Method method,
                Class<? extends AbstractXMPPConnection> connectionClass) {
    if (!testMethodParametersIsListOfConnections(method, connectionClass)
                    && !testMethodParametersVarargsConnections(method, connectionClass)) {
        throw new IllegalArgumentException(method + " is not a valid low level test method");
    }
}
 
示例15
private static <C extends AbstractXMPPConnection> void invokeSpecificLowLevel(LowLevelTestMethod testMethod,
        AbstractSmackSpecificLowLevelIntegrationTest<C> test)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InterruptedException,
        SmackException, IOException, XMPPException {
    if (testMethod.smackIntegrationTestAnnotation.onlyDefaultConnectionType()) {
        throw new IllegalArgumentException("SpecificLowLevelTests must not have set onlyDefaultConnectionType");
    }
    Class<C> connectionClass = test.getConnectionClass();
    testMethod.invoke(test, connectionClass);
}
 
示例16
private void invoke(AbstractSmackLowLevelIntegrationTest test,
                Class<? extends AbstractXMPPConnection> connectionClass)
                throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
                InterruptedException, SmackException, IOException, XMPPException {
    final int connectionCount;
    if (parameterListOfConnections) {
        connectionCount = smackIntegrationTestAnnotation.connectionCount();
        if (connectionCount < 1) {
            throw new IllegalArgumentException(testMethod + " is annotated to use less than one connection ('"
                            + connectionCount + ')');
        }
    } else {
        connectionCount = testMethod.getParameterCount();
    }

    List<? extends AbstractXMPPConnection> connections = connectionManager.constructConnectedConnections(
                    connectionClass, connectionCount);

    if (parameterListOfConnections) {
        testMethod.invoke(test, connections);
    } else {
        Object[] connectionsArray = new Object[connectionCount];
        for (int i = 0; i < connectionsArray.length; i++) {
            connectionsArray[i] = connections.remove(0);
        }
        testMethod.invoke(test, connectionsArray);
    }

    connectionManager.recycle(connections);
}
 
示例17
static boolean testMethodParametersIsListOfConnections(Method testMethod, Class<? extends AbstractXMPPConnection> connectionClass) {
    Type[] parameterTypes = testMethod.getGenericParameterTypes();
    if (parameterTypes.length != 1) {
        return false;
    }
    Class<?> soleParameter = testMethod.getParameterTypes()[0];
    if (!Collection.class.isAssignableFrom(soleParameter)) {
        return false;
    }

    ParameterizedType soleParameterizedType = (ParameterizedType) parameterTypes[0];
    Type[] actualTypeArguments = soleParameterizedType.getActualTypeArguments();
    if (actualTypeArguments.length != 1) {
        return false;
    }

    Type soleActualTypeArgument = actualTypeArguments[0];
    if (!(soleActualTypeArgument instanceof Class<?>)) {
        return false;
    }
    Class<?> soleActualTypeArgumentAsClass = (Class<?>) soleActualTypeArgument;
    if (!connectionClass.isAssignableFrom(soleActualTypeArgumentAsClass)) {
        return false;
    }

    return true;
}
 
示例18
static boolean testMethodParametersVarargsConnections(Method testMethod, Class<? extends AbstractXMPPConnection> connectionClass) {
    Class<?>[] parameterTypes = testMethod.getParameterTypes();
    for (Class<?> parameterType : parameterTypes) {
        if (!parameterType.isAssignableFrom(connectionClass)) {
            return false;
        }
    }

    return true;
}
 
示例19
SmackIntegrationTestEnvironment(AbstractXMPPConnection conOne, AbstractXMPPConnection conTwo, AbstractXMPPConnection conThree, String testRunId,
                Configuration configuration, XmppConnectionManager connectionManager) {
    this.conOne = conOne;
    this.conTwo = conTwo;
    this.conThree = conThree;
    this.testRunId = testRunId;
    this.configuration = configuration;
    this.connectionManager = connectionManager;
}
 
示例20
public static boolean addConnectionDescriptor(
                XmppConnectionDescriptor<? extends AbstractXMPPConnection, ? extends ConnectionConfiguration, ? extends ConnectionConfiguration.Builder<?, ?>> connectionDescriptor) {
    String nickname = connectionDescriptor.getNickname();
    Class<? extends AbstractXMPPConnection> connectionClass = connectionDescriptor.getConnectionClass();

    boolean alreadyExisted;
    synchronized (CONNECTION_DESCRIPTORS) {
        alreadyExisted = removeConnectionDescriptor(nickname);

        CONNECTION_DESCRIPTORS.put(connectionClass, connectionDescriptor);
        NICKNAME_CONNECTION_DESCRIPTORS.put(connectionDescriptor.getNickname(), connectionDescriptor);
    }
    return alreadyExisted;
}
 
示例21
private void prepareMainConnections() throws KeyManagementException, NoSuchAlgorithmException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, SmackException, IOException,
        XMPPException, InterruptedException {
    final int mainAccountCount = AccountNum.values().length;
    List<AbstractXMPPConnection> connections = new ArrayList<>(mainAccountCount);
    for (AccountNum mainAccountNum : AccountNum.values()) {
        AbstractXMPPConnection mainConnection = getConnectedMainConnectionFor(mainAccountNum);
        connections.add(mainConnection);
    }
    conOne = connections.get(0);
    conTwo = connections.get(1);
    conThree = connections.get(2);
}
 
示例22
private <C extends AbstractXMPPConnection> C constructConnectedConnection(
                XmppConnectionDescriptor<C, ? extends ConnectionConfiguration, ? extends ConnectionConfiguration.Builder<?, ?>> connectionDescriptor)
                throws InterruptedException, SmackException, IOException, XMPPException {
    C connection = constructConnection(connectionDescriptor, null);

    connection.connect();
    connection.login();

    return connection;
}
 
示例23
private <C extends AbstractXMPPConnection> C constructConnection(
        XmppConnectionDescriptor<C, ? extends ConnectionConfiguration, ? extends ConnectionConfiguration.Builder<?, ?>> connectionDescriptor,
        Collection<ConnectionConfigurationBuilderApplier> customConnectionConfigurationAppliers)
        throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    String username = "sinttest-" + testRunId + '-' + (connections.size() + 1);
    String password = StringUtils.randomString(24);

    return constructConnection(username, password, connectionDescriptor, customConnectionConfigurationAppliers);
}
 
示例24
public AbstractXMPPConnection getConnection() {
	return connection;
}
 
示例25
public void setConnection(AbstractXMPPConnection connection) {
	this.connection = connection;
}
 
示例26
public static <C extends AbstractXMPPConnection, CC extends ConnectionConfiguration, CCB extends ConnectionConfiguration.Builder<?, CC>>
        Builder<C, CC, CCB> buildWith(Class<C> connectionClass, Class<CC> connectionConfigurationClass) {
    return buildWith(connectionClass, connectionConfigurationClass, null);
}
 
示例27
public static <C extends AbstractXMPPConnection, CC extends ConnectionConfiguration, CCB extends ConnectionConfiguration.Builder<?, CC>>
        Builder<C, CC, CCB> buildWith(Class<C> connectionClass, Class<CC> connectionConfigurationClass, Class<CCB> connectionConfigurationBuilderClass) {
    return new Builder<>(connectionClass, connectionConfigurationClass, connectionConfigurationBuilderClass);
}
 
示例28
protected AbstractXMPPConnection getConnectedConnection() throws InterruptedException, XMPPException, SmackException, IOException {
    AbstractXMPPConnection connection = getUnconnectedConnection();
    connection.connect().login();
    return connection;
}
 
示例29
protected AbstractXMPPConnection getUnconnectedConnection()
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    return environment.connectionManager.constructConnection();
}
 
示例30
protected void recycle(AbstractXMPPConnection connection) {
    environment.connectionManager.recycle(connection);
}