Search in sources :

Example 31 with XMPPConnection

use of org.jivesoftware.smack.XMPPConnection in project xabber-android by redsolution.

the class MUCManager method requestRoomInfo.

public static void requestRoomInfo(final String account, final String roomJid, final RoomInfoListener listener) {
    final XMPPConnection xmppConnection = AccountManager.getInstance().getAccount(account).getConnectionThread().getXMPPConnection();
    final Thread thread = new Thread("Get room " + roomJid + " info for account " + account) {

        @Override
        public void run() {
            RoomInfo roomInfo = null;
            try {
                LogManager.i(MUCManager.class, "Requesting room info " + roomJid);
                roomInfo = MultiUserChatManager.getInstanceFor(xmppConnection).getRoomInfo(roomJid);
            } catch (SmackException.NoResponseException | XMPPException.XMPPErrorException | SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
            final RoomInfo finalRoomInfo = roomInfo;
            Application.getInstance().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    listener.onRoomInfoReceived(finalRoomInfo);
                }
            });
        }
    };
    thread.start();
}
Also used : RoomInfo(org.jivesoftware.smackx.muc.RoomInfo) XMPPConnection(org.jivesoftware.smack.XMPPConnection) ConnectionThread(com.xabber.android.data.connection.ConnectionThread)

Example 32 with XMPPConnection

use of org.jivesoftware.smack.XMPPConnection in project xabber-android by redsolution.

the class AttentionManager method onSettingsChanged.

public void onSettingsChanged() {
    synchronized (enabledLock) {
        for (String account : AccountManager.getInstance().getAccounts()) {
            ConnectionThread connectionThread = AccountManager.getInstance().getAccount(account).getConnectionThread();
            if (connectionThread == null)
                continue;
            XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
            if (xmppConnection == null)
                continue;
            ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(xmppConnection);
            if (manager == null)
                continue;
            boolean contains = false;
            for (String feature : manager.getFeatures()) {
                if (Attention.NAMESPACE.equals(feature)) {
                    contains = true;
                }
            }
            if (SettingsManager.chatsAttention() == contains)
                continue;
            if (SettingsManager.chatsAttention())
                manager.addFeature(Attention.NAMESPACE);
            else
                manager.removeFeature(Attention.NAMESPACE);
        }
        AccountManager.getInstance().resendPresence();
    }
}
Also used : ConnectionThread(com.xabber.android.data.connection.ConnectionThread) XMPPConnection(org.jivesoftware.smack.XMPPConnection) ServiceDiscoveryManager(org.jivesoftware.smackx.disco.ServiceDiscoveryManager)

Example 33 with XMPPConnection

use of org.jivesoftware.smack.XMPPConnection in project camel by apache.

the class XmppEndpoint method createConnection.

public synchronized XMPPConnection createConnection() throws XMPPException, SmackException, IOException {
    if (connection != null && connection.isConnected()) {
        // use existing working connection
        return connection;
    }
    // prepare for creating new connection
    connection = null;
    LOG.trace("Creating new connection ...");
    XMPPConnection newConnection = createConnectionInternal();
    newConnection.connect();
    newConnection.addPacketListener(new XmppLogger("INBOUND"), new PacketFilter() {

        public boolean accept(Packet packet) {
            return true;
        }
    });
    newConnection.addPacketSendingListener(new XmppLogger("OUTBOUND"), new PacketFilter() {

        public boolean accept(Packet packet) {
            return true;
        }
    });
    if (!newConnection.isAuthenticated()) {
        if (user != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Logging in to XMPP as user: {} on connection: {}", user, getConnectionMessage(newConnection));
            }
            if (password == null) {
                LOG.warn("No password configured for user: {} on connection: {}", user, getConnectionMessage(newConnection));
            }
            if (createAccount) {
                AccountManager accountManager = AccountManager.getInstance(newConnection);
                accountManager.createAccount(user, password);
            }
            if (login) {
                if (resource != null) {
                    newConnection.login(user, password, resource);
                } else {
                    newConnection.login(user, password);
                }
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Logging in anonymously to XMPP on connection: {}", getConnectionMessage(newConnection));
            }
            newConnection.loginAnonymously();
        }
    // presence is not needed to be sent after login
    }
    // okay new connection was created successfully so assign it as the connection
    LOG.debug("Created new connection successfully: {}", newConnection);
    connection = newConnection;
    return connection;
}
Also used : Packet(org.jivesoftware.smack.packet.Packet) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) AccountManager(org.jivesoftware.smack.AccountManager) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Example 34 with XMPPConnection

use of org.jivesoftware.smack.XMPPConnection in project openhab1-addons by openhab.

the class XMPP method sendXMPP.

// provide public static methods here
/**
     * Sends a message to an XMPP user.
     * 
     * @param to the XMPP address to send the message to
     * @param message the message to send
     * 
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a message to an XMPP user.")
public static boolean sendXMPP(@ParamDoc(name = "to") String to, @ParamDoc(name = "message") String message) {
    boolean success = false;
    try {
        XMPPConnection conn = XMPPConnect.getConnection();
        ChatManager chatmanager = ChatManager.getInstanceFor(conn);
        Chat newChat = chatmanager.createChat(to, null);
        try {
            while (message.length() >= 2000) {
                newChat.sendMessage(message.substring(0, 2000));
                message = message.substring(2000);
            }
            newChat.sendMessage(message);
            logger.debug("Sent message '{}' to '{}'.", message, to);
            success = true;
        } catch (XMPPException e) {
            logger.warn("Error Delivering block", e);
        } catch (NotConnectedException e) {
            logger.warn("Error Delivering block", e);
        }
    } catch (NotInitializedException e) {
        logger.warn("Could not send XMPP message as connection is not correctly initialized!");
    }
    return success;
}
Also used : NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) Chat(org.jivesoftware.smack.Chat) XMPPConnection(org.jivesoftware.smack.XMPPConnection) XMPPException(org.jivesoftware.smack.XMPPException) ChatManager(org.jivesoftware.smack.ChatManager) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 35 with XMPPConnection

use of org.jivesoftware.smack.XMPPConnection in project perun by CESNET.

the class PerunNotifJabberSender method send.

@Override
public Set<Integer> send(List<PerunNotifMessageDto> dtosToSend) {
    Set<Integer> usedPools = new HashSet<Integer>();
    try {
        ConnectionConfiguration config = new ConnectionConfiguration(jabberServer, port, serviceName);
        XMPPConnection connection = new XMPPConnection(config);
        connection.connect();
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        connection.login(username, password);
        for (PerunNotifMessageDto messageDto : dtosToSend) {
            PerunNotifReceiver receiver = messageDto.getReceiver();
            PoolMessage dto = messageDto.getPoolMessage();
            Message message = new Message();
            message.setSubject(messageDto.getSubject());
            message.setBody(messageDto.getMessageToSend());
            message.setType(Message.Type.headline);
            String myReceiverId = dto.getKeyAttributes().get(receiver.getTarget());
            if (myReceiverId == null || myReceiverId.isEmpty()) {
                //Can be set one static account
                message.setTo(receiver.getTarget());
            } else {
                //We try to resolve id
                Integer id = null;
                try {
                    id = Integer.valueOf(myReceiverId);
                } catch (NumberFormatException ex) {
                    logger.error("Cannot resolve id: {}, error: {}", Arrays.asList(id, ex.getMessage()));
                    logger.debug("ST:", ex);
                }
                if (id != null) {
                    try {
                        User user = perun.getUsersManagerBl().getUserById(session, id);
                        Attribute emailAttribute = perun.getAttributesManagerBl().getAttribute(session, user, "urn:perun:user:attribute-def:def:jabber");
                        if (emailAttribute != null && StringUtils.hasText(emailAttribute.toString())) {
                            message.setTo((String) emailAttribute.getValue());
                        }
                    } catch (UserNotExistsException ex) {
                        logger.error("Cannot found user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (AttributeNotExistsException ex) {
                        logger.warn("Cannot found email for user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (Exception ex) {
                        logger.error("Error during user email recognition, ex: {}", ex.getMessage());
                        logger.debug("ST:", ex);
                    }
                }
            }
            connection.sendPacket(message);
            usedPools.addAll(messageDto.getUsedPoolIds());
        }
        connection.disconnect();
    } catch (XMPPException ex) {
        logger.error("Error during jabber establish connection.", ex);
    }
    return null;
}
Also used : PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) Message(org.jivesoftware.smack.packet.Message) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) PerunNotifReceiver(cz.metacentrum.perun.notif.entities.PerunNotifReceiver) XMPPConnection(org.jivesoftware.smack.XMPPConnection) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) XMPPException(org.jivesoftware.smack.XMPPException)

Aggregations

XMPPConnection (org.jivesoftware.smack.XMPPConnection)64 XMPPException (org.jivesoftware.smack.XMPPException)14 Message (org.jivesoftware.smack.packet.Message)9 SmackException (org.jivesoftware.smack.SmackException)7 IQ (org.jivesoftware.smack.packet.IQ)7 InputStream (java.io.InputStream)6 OutputStream (java.io.OutputStream)6 ArrayList (java.util.ArrayList)6 SynchronousQueue (java.util.concurrent.SynchronousQueue)6 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)6 ServiceDiscoveryManager (org.jivesoftware.smackx.disco.ServiceDiscoveryManager)6 TimeoutException (java.util.concurrent.TimeoutException)5 StanzaCollector (org.jivesoftware.smack.StanzaCollector)5 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)5 DiscoverInfo (org.jivesoftware.smackx.disco.packet.DiscoverInfo)5 ConnectionThread (com.xabber.android.data.connection.ConnectionThread)4 ConnectionConfiguration (org.jivesoftware.smack.ConnectionConfiguration)4 NoResponseException (org.jivesoftware.smack.SmackException.NoResponseException)4 Packet (org.jivesoftware.smack.packet.Packet)4 Jid (org.jxmpp.jid.Jid)4