Java Code Examples for org.jivesoftware.smack.XMPPConnection

The following examples show how to use org.jivesoftware.smack.XMPPConnection. These examples are extracted from open source projects. 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 Project: weixin   Source File: XmppManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 与服务器建立连接
 * 
 * @return
 */
public boolean connectServer() {
	ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppHost, Integer.parseInt(xmppPort));
	//设置安全模式
	connConfig.setSecurityMode(SecurityMode.required);
	//设置SASL认证是否启用
	connConfig.setSASLAuthenticationEnabled(false);
	//设置数据压缩是否启用
	connConfig.setCompressionEnabled(false);
	//是否启用调试模式
	connConfig.setDebuggerEnabled(true);

	/** 创建connection连接 */
	XMPPConnection connection = new XMPPConnection(connConfig);
	this.setConnection(connection);

	try {
		// 连接到服务器
		connection.connect();
		L.i(LOGTAG, "XMPP connected successfully");
		return true;
	} catch (XMPPException e) {
		L.e(LOGTAG, "XMPP connection failed", e);
	}
	return false;
}
 
Example 2
Source Project: Smack   Source File: SLF4JSmackDebugger.java    License: 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 3
Source Project: Smack   Source File: JingleSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Full featured JingleSession constructor.
 *
 * @param conn TODO javadoc me please
 *            the XMPPConnection which is used
 * @param initiator TODO javadoc me please
 *            the initiator JID
 * @param responder TODO javadoc me please
 *            the responder JID
 * @param sessionid TODO javadoc me please
 *            the session ID
 * @param jingleMediaManagers TODO javadoc me please
 *            the jingleMediaManager
 */
public JingleSession(XMPPConnection conn, Jid initiator, Jid responder, String sessionid,
        List<JingleMediaManager> jingleMediaManagers) {
    super();

    this.initiator = initiator;
    this.responder = responder;
    this.sid = sessionid;
    this.jingleMediaManagers = jingleMediaManagers;
    this.setSession(this);
    this.connection = conn;

    // Initially, we don't known the session state.
    setSessionState(JingleSessionStateUnknown.getInstance());

    contentNegotiators = new ArrayList<>();
    mediaSessionMap = new HashMap<>();

    // Add the session to the list and register the listeners
    registerInstance();
    installConnectionListeners(conn);
}
 
Example 4
Source Project: Smack   Source File: MultiUserChatLight.java    License: Apache License 2.0 6 votes vote down vote up
MultiUserChatLight(XMPPConnection connection, EntityJid room) {
    this.connection = connection;
    this.room = room;

    fromRoomFilter = FromMatchesFilter.create(room);
    fromRoomGroupChatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT);

    messageListener = new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) throws NotConnectedException {
            Message message = (Message) packet;
            for (MessageListener listener : messageListeners) {
                listener.processMessage(message);
            }
        }
    };

    connection.addSyncStanzaListener(messageListener, fromRoomGroupChatFilter);
}
 
Example 5
Source Project: Smack   Source File: STUN.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a new STUN Server Address and port from the server.
 * If a error occurs or the server don't support STUN Service, null is returned.
 *
 * @param connection TODO javadoc me please
 * @return the STUN server address
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static STUN getSTUNServer(XMPPConnection connection) throws NotConnectedException, InterruptedException {

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

    STUN stunPacket = new STUN();
    DomainBareJid jid;
    try {
        jid = JidCreate.domainBareFrom(DOMAIN + "." + connection.getXMPPServiceDomain());
    } catch (XmppStringprepException e) {
        throw new AssertionError(e);
    }
    stunPacket.setTo(jid);

    StanzaCollector collector = connection.createStanzaCollectorAndSend(stunPacket);

    STUN response = collector.nextResult();

    // Cancel the collector.
    collector.cancel();

    return response;
}
 
Example 6
Source Project: Smack   Source File: InitiationListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initialize fields used in the tests.
 */
@BeforeEach
public void setup() {

    // mock connection
    connection = mock(XMPPConnection.class);

    // initialize InBandBytestreamManager to get the InitiationListener
    byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);

    // get the InitiationListener from InBandByteStreamManager
    initiationListener = Whitebox.getInternalState(byteStreamManager, "initiationListener", InitiationListener.class);

    // create a In-Band Bytestream open packet
    initBytestream = new Open(sessionID, 4096);
    initBytestream.setFrom(initiatorJID);
    initBytestream.setTo(targetJID);

}
 
Example 7
Source Project: olat   Source File: InstantMessagingClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Close the connection to the server
 */
public void closeConnection(final boolean closeSynchronously) {
    // Set isConnected to false first since connection.close triggers an
    // XMPPConnListener.connectionClosed() event which would result in
    // in a cyclic call of this close method.
    isConnected = false;
    final XMPPConnection connectionToClose = connection;
    final Runnable connectionCloseRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (connectionToClose != null && connectionToClose.isConnected()) {
                    connectionToClose.disconnect();
                }
            } catch (final RuntimeException e) {
                log.warn("Error while trying to close instant messaging connection", e);
            }
        }
    };
    if (closeSynchronously) {
        connectionCloseRunnable.run();
    } else {
        taskExecutorService.runTask(connectionCloseRunnable);
    }
}
 
Example 8
Source Project: Smack   Source File: InBandBytestreamRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Accepts the In-Band Bytestream open request and returns the session to
 * send/receive data.
 *
 * @return the session to send/receive data
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
@Override
public InBandBytestreamSession accept() throws NotConnectedException, InterruptedException {
    XMPPConnection connection = this.manager.getConnection();

    // create In-Band Bytestream session and store it
    InBandBytestreamSession ibbSession = new InBandBytestreamSession(connection,
                    this.byteStreamRequest, this.byteStreamRequest.getFrom());
    this.manager.getSessions().put(this.byteStreamRequest.getSessionID(), ibbSession);

    // acknowledge request
    IQ resultIQ = IQ.createResultIQ(this.byteStreamRequest);
    connection.sendStanza(resultIQ);

    return ibbSession;
}
 
Example 9
Source Project: Smack   Source File: MucEnterConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
Builder(Resourcepart nickname, XMPPConnection connection) {
    this.nickname = Objects.requireNonNull(nickname, "Nickname must not be null");

    timeout = connection.getReplyTimeout();
    timeoutAfter(timeout);

    joinPresenceBuilder = connection.getStanzaFactory().buildPresenceStanza();
}
 
Example 10
public XMPPConnection.FromMode getFromMode() {
    String str = getPropertyAsString(FROM_MODE, XMPPConnection.FromMode.USER.toString());
    if (str.equals(XMPPConnection.FromMode.USER.toString())) {
        return XMPPConnection.FromMode.USER;
    } else if (str.equals(XMPPConnection.FromMode.UNCHANGED.toString())) {
        return XMPPConnection.FromMode.UNCHANGED;
    } else if (str.equals(XMPPConnection.FromMode.OMITTED.toString())) {
        return XMPPConnection.FromMode.OMITTED;
    } else {
        throw new IllegalArgumentException("Unhandled value for fromMode: " + str);
    }
}
 
Example 11
Source Project: Smack   Source File: BoBManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the singleton instance of BoBManager.
 *
 * @param connection TODO javadoc me please
 * @return the instance of BoBManager
 */
public static synchronized BoBManager getInstanceFor(XMPPConnection connection) {
    BoBManager bobManager = INSTANCES.get(connection);
    if (bobManager == null) {
        bobManager = new BoBManager(connection);
        INSTANCES.put(connection, bobManager);
    }

    return bobManager;
}
 
Example 12
Source Project: Smack   Source File: IoTDataManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Try to read out a things momentary values.
 *
 * @param jid the full JID of the thing to read data from.
 * @return a list with the read out data.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<IoTFieldsExtension> requestMomentaryValuesReadOut(EntityFullJid jid)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final XMPPConnection connection = connection();
    final int seqNr = nextSeqNr.incrementAndGet();
    IoTDataRequest iotDataRequest = new IoTDataRequest(seqNr, true);
    iotDataRequest.setTo(jid);

    StanzaFilter doneFilter = new IoTFieldsExtensionFilter(seqNr, true);
    StanzaFilter dataFilter = new IoTFieldsExtensionFilter(seqNr, false);

    // Setup the IoTFieldsExtension message collectors before sending the IQ to avoid a data race.
    StanzaCollector doneCollector = connection.createStanzaCollector(doneFilter);

    StanzaCollector.Configuration dataCollectorConfiguration = StanzaCollector.newConfiguration().setStanzaFilter(
                    dataFilter).setCollectorToReset(doneCollector);
    StanzaCollector dataCollector = connection.createStanzaCollector(dataCollectorConfiguration);

    try {
        connection.createStanzaCollectorAndSend(iotDataRequest).nextResultOrThrow();
        // Wait until a message with an IoTFieldsExtension and the done flag comes in.
        doneCollector.nextResult();
    }
    finally {
        // Canceling dataCollector will also cancel the doneCollector since it is configured as dataCollector's
        // collector to reset.
        dataCollector.cancel();
    }

    int collectedCount = dataCollector.getCollectedCount();
    List<IoTFieldsExtension> res = new ArrayList<>(collectedCount);
    for (int i = 0; i < collectedCount; i++) {
        Message message = dataCollector.pollResult();
        IoTFieldsExtension iotFieldsExtension = IoTFieldsExtension.from(message);
        res.add(iotFieldsExtension);
    }

    return res;
}
 
Example 13
Source Project: Smack   Source File: SpoilerManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the connections instance of the SpoilerManager.
 *
 * @param connection xmpp connection
 * @return SpoilerManager TODO javadoc me please
 */
public static synchronized SpoilerManager getInstanceFor(XMPPConnection connection) {
    SpoilerManager manager = INSTANCES.get(connection);
    if (manager == null) {
        manager = new SpoilerManager(connection);
        INSTANCES.put(connection, manager);
    }
    return manager;
}
 
Example 14
Source Project: Smack   Source File: RosterExchangeManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends a roster entry to userID.
 *
 * @param rosterEntry the roster entry to send
 * @param targetUserID the user that will receive the roster entries
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void send(RosterEntry rosterEntry, Jid targetUserID) throws NotConnectedException, InterruptedException {
    XMPPConnection connection = weakRefConnection.get();

    // Create a new message to send the roster
    MessageBuilder messageBuilder = connection.getStanzaFactory().buildMessageStanza().to(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange();
    rosterExchange.addRosterEntry(rosterEntry);
    messageBuilder.addExtension(rosterExchange);

    // Send the message that contains the roster
    connection.sendStanza(messageBuilder.build());
}
 
Example 15
Source Project: Smack   Source File: JingleIBBTransportManager.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized JingleIBBTransportManager getInstanceFor(XMPPConnection connection) {
    JingleIBBTransportManager manager = INSTANCES.get(connection);
    if (manager == null) {
        manager = new JingleIBBTransportManager(connection);
        INSTANCES.put(connection, manager);
    }
    return manager;
}
 
Example 16
Source Project: jmeter-bzm-plugins   Source File: JMeterXMPPSamplerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessageFrom() throws Exception {
    JMeterXMPPSampler obj = getjMeterXMPPSampler();
    obj.getXMPPConnection().setFromMode(XMPPConnection.FromMode.USER);

    obj.setProperty(SendMessage.RECIPIENT, "[email protected]");
    obj.setProperty(SendMessage.BODY, "body");
    SampleResult res = doAction(obj, SendMessage.class);
    assertTrue(res.getSamplerData().contains("from"));
}
 
Example 17
Source Project: Smack   Source File: CloseListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If a close request to an unknown session is received it should be replied
 * with an &lt;item-not-found/&gt; error.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldReplyErrorIfSessionIsUnknown() throws Exception {

    // mock connection
    XMPPConnection connection = mock(XMPPConnection.class);

    // initialize InBandBytestreamManager to get the CloseListener
    InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);

    // get the CloseListener from InBandByteStreamManager
    CloseListener closeListener = Whitebox.getInternalState(byteStreamManager, "closeListener",
                    CloseListener.class);

    Close close = new Close("unknownSessionId");
    close.setFrom(initiatorJID);
    close.setTo(targetJID);

    closeListener.handleIQRequest(close);

    // wait because packet is processed in an extra thread
    Thread.sleep(200);

    // capture reply to the In-Band Bytestream close request
    ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
    verify(connection).sendStanza(argument.capture());

    // assert that reply is the correct error packet
    assertEquals(initiatorJID, argument.getValue().getTo());
    assertEquals(IQ.Type.error, argument.getValue().getType());
    assertEquals(StanzaError.Condition.item_not_found,
                    argument.getValue().getError().getCondition());

}
 
Example 18
Source Project: Smack   Source File: IoTProvisioningManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the manger instance responsible for the given connection.
 *
 * @param connection the XMPP connection.
 * @return a manager instance.
 */
public static synchronized IoTProvisioningManager getInstanceFor(XMPPConnection connection) {
    IoTProvisioningManager manager = INSTANCES.get(connection);
    if (manager == null) {
        manager = new IoTProvisioningManager(connection);
        INSTANCES.put(connection, manager);
    }
    return manager;
}
 
Example 19
Source Project: Yahala-Messenger   Source File: XMPPManager.java    License: MIT License 5 votes vote down vote up
public ConnectionCreationListener createConnectionListener() {
    connectionCreationListener = new ConnectionCreationListener() {
        @Override
        public void connectionCreated(XMPPConnection xmppConnection) {
            FileLog.e("Test", "Connection created: Successful!");
        }
    };

    return connectionCreationListener;
}
 
Example 20
Source Project: Smack   Source File: PushNotificationsManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the singleton instance of PushNotificationsManager.
 *
 * @param connection TODO javadoc me please
 * @return the instance of PushNotificationsManager
 */
public static synchronized PushNotificationsManager getInstanceFor(XMPPConnection connection) {
    PushNotificationsManager pushNotificationsManager = INSTANCES.get(connection);

    if (pushNotificationsManager == null) {
        pushNotificationsManager = new PushNotificationsManager(connection);
        INSTANCES.put(connection, pushNotificationsManager);
    }

    return pushNotificationsManager;
}
 
Example 21
Source Project: Smack   Source File: OmemoService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the bundle of a contact and build a fresh OMEMO session with the contacts device.
 * Note that this builds a fresh session, regardless if we have had a session before or not.
 *
 * @param connection authenticated XMPP connection
 * @param userDevice our OmemoDevice
 * @param contactsDevice OmemoDevice of a contact.
 *
 * @throws CannotEstablishOmemoSessionException if we cannot establish a session (because of missing bundle etc.)
 * @throws SmackException.NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException.NoResponseException if there was no response from the remote entity.
 * @throws CorruptedOmemoKeyException if our IdentityKeyPair is corrupted.
 */
void buildFreshSessionWithDevice(XMPPConnection connection, OmemoDevice userDevice, OmemoDevice contactsDevice)
        throws CannotEstablishOmemoSessionException, SmackException.NotConnectedException, InterruptedException,
        SmackException.NoResponseException, CorruptedOmemoKeyException {

    if (contactsDevice.equals(userDevice)) {
        // Do not build a session with yourself.
        return;
    }

    OmemoBundleElement bundleElement;
    try {
        bundleElement = fetchBundle(connection, contactsDevice);
    } catch (XMPPException.XMPPErrorException | PubSubException.NotALeafNodeException |
            PubSubException.NotAPubSubNodeException e) {
        throw new CannotEstablishOmemoSessionException(contactsDevice, e);
    }

    // Select random Bundle
    HashMap<Integer, T_Bundle> bundlesList = getOmemoStoreBackend().keyUtil().BUNDLE.bundles(bundleElement, contactsDevice);
    int randomIndex = new Random().nextInt(bundlesList.size());
    T_Bundle randomPreKeyBundle = new ArrayList<>(bundlesList.values()).get(randomIndex);

    // build the session
    OmemoManager omemoManager = OmemoManager.getInstanceFor(connection, userDevice.getDeviceId());
    processBundle(omemoManager, randomPreKeyBundle, contactsDevice);
}
 
Example 22
Source Project: carbon-identity   Source File: MPAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a connection to the XMPP server with the available configuration details given in
 * the identity.xml
 *
 * @return XMPPConnection
 */
private XMPPConnection createConnection() {
    String xmppServer = IdentityUtil.getProperty(IdentityConstants.ServerConfig.XMPP_SETTINGS_SERVER);
    int xmppPort = Integer.parseInt(IdentityUtil.getProperty(IdentityConstants.ServerConfig.XMPP_SETTINGS_PORT));
    String xmppExt = IdentityUtil.getProperty(IdentityConstants.ServerConfig.XMPP_SETTINGS_EXT);

    ConnectionConfiguration config = new ConnectionConfiguration(xmppServer, xmppPort, xmppExt);
    config.setSASLAuthenticationEnabled(true);
    return new XMPPConnection(config);
}
 
Example 23
Source Project: Smack   Source File: DnsOverXmppManager.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void enable() {
    if (enabled) return;

    if (resolver == null) {
        throw new IllegalStateException("No DnsOverXmppResolver configured");
    }

    XMPPConnection connection = connection();
    if (connection == null) return;

    connection.registerIQRequestHandler(dnsIqRequestHandler);
    serviceDiscoveryManager.addFeature(NAMESPACE);
}
 
Example 24
Source Project: Smack   Source File: HashManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor of the HashManager.
 *
 * @param connection connection
 */
private HashManager(XMPPConnection connection) {
    super(connection);
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
    sdm.addFeature(NAMESPACE.V2.toString());
    addAlgorithmsToFeatures(RECOMMENDED);
}
 
Example 25
Source Project: olat   Source File: IMAppender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Options are activated and become effective only after calling this method.
 */
@Override
public void activateOptions() {
    try {
        cb = new CyclicBuffer(bufferSize);

        // Create a connection to the XMPP server
        LogLog.debug("Stablishing connection with XMPP server");
        con = new XMPPConnection(InstantMessagingModule.getConnectionConfiguration());
        // Most servers require you to login before performing other tasks
        LogLog.debug("About to login as [" + username + "/" + password + "]");
        con.connect();
        con.login(username, password);

        // Start a conversation with IMAddress
        if (chatroom) {
            LogLog.debug("About to create ChatGroup");
            groupchat = new MultiUserChat(con, (String) recipientsList.get(0));
            LogLog.debug("About to join room");
            groupchat.join(nickname != null ? nickname : username);
        } else {
            final Iterator iter = recipientsList.iterator();
            while (iter.hasNext()) {
                chats.add(con.getChatManager().createChat((String) iter.next(), null));
            }
            // chat = con.createChat(recipients);
        }

    } catch (final XMPPException xe) {
        errorHandler.error("Error while activating options for appender named [" + name + "] Could not connect to instant messaging server with user: "
                + getUsername(), xe, ErrorCode.GENERIC_FAILURE);
    } catch (final Exception e) {
        errorHandler.error("Error while activating options for appender named [" + name + "]", e, ErrorCode.GENERIC_FAILURE);
    }
}
 
Example 26
Source Project: olat   Source File: GroupChatJoinTask.java    License: Apache License 2.0 5 votes vote down vote up
public GroupChatJoinTask(final OLATResourceable ores, final MultiUserChat muc, final XMPPConnection connection, final String roomJID, final String nickname,
        final String roomName, final GenericEventListener listeningController) {
    this.ores = ores;
    this.muc = muc;
    this.connection = connection;
    this.roomJID = roomJID;
    this.roomName = roomName;
    this.nickname = nickname;
    this.listeningController = listeningController;
}
 
Example 27
Source Project: Smack   Source File: MultipleRecipientManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends the specified stanza to the collection of specified recipients using the specified
 * connection. If the server has support for XEP-33 then only one stanza is going to be sent to
 * the server with the multiple recipient instructions. However, if XEP-33 is not supported by
 * the server then the client is going to send the stanza to each recipient.
 *
 * @param connection the connection to use to send the packet.
 * @param packet the stanza to send to the list of recipients.
 * @param to the collection of JIDs to include in the TO list or <code>null</code> if no TO list exists.
 * @param cc the collection of JIDs to include in the CC list or <code>null</code> if no CC list exists.
 * @param bcc the collection of JIDs to include in the BCC list or <code>null</code> if no BCC list
 *        exists.
 * @param replyTo address to which all replies are requested to be sent or <code>null</code>
 *        indicating that they can reply to any address.
 * @param replyRoom JID of a MUC room to which responses should be sent or <code>null</code>
 *        indicating that they can reply to any address.
 * @param noReply true means that receivers should not reply to the message.
 * @throws XMPPErrorException if server does not support XEP-33: Extended Stanza Addressing and
 *         some XEP-33 specific features were requested.
 * @throws NoResponseException if there was no response from the server.
 * @throws FeatureNotSupportedException if special XEP-33 features where requested, but the
 *         server does not support them.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static void send(XMPPConnection connection, Stanza packet, Collection<? extends Jid> to, Collection<? extends Jid> cc, Collection<? extends Jid> bcc,
        Jid replyTo, Jid replyRoom, boolean noReply) throws NoResponseException, XMPPErrorException, FeatureNotSupportedException, NotConnectedException, InterruptedException {
    // Check if *only* 'to' is set and contains just *one* entry, in this case extended stanzas addressing is not
    // required at all and we can send it just as normal stanza without needing to add the extension element
    if (to != null && to.size() == 1 && (cc == null || cc.isEmpty()) && (bcc == null || bcc.isEmpty()) && !noReply
                    && StringUtils.isNullOrEmpty(replyTo) && StringUtils.isNullOrEmpty(replyRoom)) {
        Jid toJid = to.iterator().next();
        packet.setTo(toJid);
        connection.sendStanza(packet);
        return;
    }
    DomainBareJid serviceAddress = getMultipleRecipientServiceAddress(connection);
    if (serviceAddress != null) {
        // Send packet to target users using multiple recipient service provided by the server
        sendThroughService(connection, packet, to, cc, bcc, replyTo, replyRoom, noReply,
                serviceAddress);
    }
    else {
        // Server does not support XEP-33 so try to send the packet to each recipient
        if (noReply || replyTo != null ||
                replyRoom != null) {
            // Some specified XEP-33 features were requested so throw an exception alerting
            // the user that this features are not available
            throw new FeatureNotSupportedException("Extended Stanza Addressing");
        }
        // Send the packet to each individual recipient
        sendToIndividualRecipients(connection, packet, to, cc, bcc);
    }
}
 
Example 28
Source Project: Smack   Source File: ServiceAdministrationManager.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized ServiceAdministrationManager getInstanceFor(XMPPConnection connection) {
    ServiceAdministrationManager serviceAdministrationManager = INSTANCES.get(connection);
    if (serviceAdministrationManager == null) {
        serviceAdministrationManager = new ServiceAdministrationManager(connection);
        INSTANCES.put(connection, serviceAdministrationManager);
    }
    return serviceAdministrationManager;
}
 
Example 29
Source Project: Spark   Source File: Tasks.java    License: Apache License 2.0 5 votes vote down vote up
public static void saveTasks(Tasks tasks, XMPPConnection con) {
    PrivateDataManager manager = PrivateDataManager.getInstanceFor( con );

    PrivateDataManager.addPrivateDataProvider("scratchpad", "scratchpad:tasks", new Tasks.Provider());
    try {
        manager.setPrivateData(tasks);
    }
    catch (XMPPException | SmackException | InterruptedException e) {
        Log.error(e);
    }
}
 
Example 30
Source Project: Smack   Source File: Socks5ByteStreamRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Target should not not blacklist any SOCKS5 proxies regardless of failing connections.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotBlacklistInvalidProxy() throws Exception {
    final Protocol protocol = new Protocol();
    final XMPPConnection connection = ConnectionUtils.createMockedConnection(protocol, targetJID);

    // build SOCKS5 Bytestream initialization request
    Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
                    initiatorJID, targetJID, sessionID);
    bytestreamInitialization.addStreamHost(JidCreate.from("invalid." + proxyJID), "127.0.0.2", 7778);

    // get SOCKS5 Bytestream manager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);

    // try to connect several times
    for (int i = 0; i < 10; i++) {
        assertThrows(Socks5Exception.CouldNotConnectToAnyProvidedSocks5Host.class, () -> {
            // build SOCKS5 Bytestream request with the bytestream initialization
            Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
                            byteStreamManager, bytestreamInitialization);

            // set timeouts
            byteStreamRequest.setTotalConnectTimeout(600);
            byteStreamRequest.setMinimumConnectTimeout(300);
            byteStreamRequest.setConnectFailureThreshold(0);

            // accept the stream (this is the call that is tested here)
            byteStreamRequest.accept();
        });

        // verify targets response
        assertEquals(1, protocol.getRequests().size());
        Stanza targetResponse = protocol.getRequests().remove(0);
        assertTrue(IQ.class.isInstance(targetResponse));
        assertEquals(initiatorJID, targetResponse.getTo());
        assertEquals(IQ.Type.error, ((IQ) targetResponse).getType());
        assertEquals(StanzaError.Condition.item_not_found,
                        targetResponse.getError().getCondition());
    }
}