org.jivesoftware.smack.AbstractXMPPConnection Java Examples

The following examples show how to use org.jivesoftware.smack.AbstractXMPPConnection. 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: MainWindow.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #2
Source File: MainWindow.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * 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);

}
 
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: XmppConnectionManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
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.
}
 
Example #5
Source File: SLF4JSmackDebugger.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #6
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #7
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #8
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #9
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
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);
}
 
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: SmackIntegrationTestEnvironment.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #12
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #15
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example #17
Source File: AbstractSmackLowLevelIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: Connect.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #19
Source File: Login.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: LowLevelRosterIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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");
    }
}
 
Example #21
Source File: MultiUserChatLowLevelIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #22
Source File: MultiUserChatLowLevelIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #23
Source File: Disconnect.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #24
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidLowLevelVarargs() {
    Method testMethod = getTestMethod(ValidLowLevelVarargs.class);
    assertTrue(SmackIntegrationTestFramework.testMethodParametersVarargsConnections(testMethod,
                    AbstractXMPPConnection.class));
}
 
Example #25
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testInvalidLowLevelVargs() {
    Method testMethod = getTestMethod(InvalidLowLevelVarargs.class);
    assertFalse(SmackIntegrationTestFramework.testMethodParametersVarargsConnections(testMethod,
                    AbstractXMPPConnection.class));
}
 
Example #26
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testInvalidLowLevelList() {
    Method testMethod = getTestMethod(InvalidLowLevelList.class);
    assertFalse(SmackIntegrationTestFramework.testMethodParametersIsListOfConnections(testMethod,
                    AbstractXMPPConnection.class));
}
 
Example #27
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidLowLevelList() {
    Method testMethod = getTestMethod(ValidLowLevelList.class);
    assertTrue(SmackIntegrationTestFramework.testMethodParametersIsListOfConnections(testMethod,
                    AbstractXMPPConnection.class));
}
 
Example #28
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
public void test(AbstractXMPPConnection connectionOne, Integer invalid, AbstractXMPPConnection connectionTwo,
                AbstractXMPPConnection connectionThree) {
}
 
Example #29
Source File: SmackIntegrationTestFrameWorkTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
public void test(AbstractXMPPConnection connectionOne, AbstractXMPPConnection connectionTwo,
                AbstractXMPPConnection connectionThree) {
}
 
Example #30
Source File: SessionManager.java    From xyTalk-pc with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setConnection(AbstractXMPPConnection connection) {
	this.connection = connection;
}