Search in sources :

Example 21 with XMPPException

use of org.jivesoftware.smack.XMPPException 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 22 with XMPPException

use of org.jivesoftware.smack.XMPPException 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)

Example 23 with XMPPException

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

the class XmppPubSubProducer method process.

public void process(Exchange exchange) throws Exception {
    try {
        if (connection == null) {
            connection = endpoint.createConnection();
        }
        // make sure we are connected
        if (!connection.isConnected()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Reconnecting to: " + XmppEndpoint.getConnectionMessage(connection));
            }
            connection.connect();
        }
    } catch (XMPPException e) {
        throw new RuntimeExchangeException("Cannot connect to XMPP Server: " + ((connection != null) ? XmppEndpoint.getConnectionMessage(connection) : endpoint.getHost()), exchange, e);
    }
    try {
        Object body = exchange.getIn().getBody(Object.class);
        if (body instanceof PubSub) {
            PubSub pubsubpacket = (PubSub) body;
            endpoint.getBinding().populateXmppPacket(pubsubpacket, exchange);
            exchange.getIn().setHeader(XmppConstants.DOC_HEADER, pubsubpacket);
            connection.sendPacket(pubsubpacket);
        } else {
            throw new Exception("Message does not contain a pubsub packet");
        }
    } catch (XMPPException xmppe) {
        throw new RuntimeExchangeException("Cannot send XMPP pubsub: from " + endpoint.getUser() + " to: " + XmppEndpoint.getConnectionMessage(connection), exchange, xmppe);
    } catch (Exception e) {
        throw new RuntimeExchangeException("Cannot send XMPP pubsub: from " + endpoint.getUser() + " to: " + XmppEndpoint.getConnectionMessage(connection), exchange, e);
    }
}
Also used : PubSub(org.jivesoftware.smackx.pubsub.packet.PubSub) RuntimeExchangeException(org.apache.camel.RuntimeExchangeException) XMPPException(org.jivesoftware.smack.XMPPException) RuntimeExchangeException(org.apache.camel.RuntimeExchangeException) XMPPException(org.jivesoftware.smack.XMPPException)

Example 24 with XMPPException

use of org.jivesoftware.smack.XMPPException in project Smack by igniterealtime.

the class FileTransferTest method testFileTransfer.

public void testFileTransfer() throws Exception {
    final byte[] testTransfer = "This is a test transfer".getBytes();
    final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
    FileTransferManager manager1 = new FileTransferManager(getConnection(0));
    manager1.addFileTransferListener(new FileTransferListener() {

        public void fileTransferRequest(final FileTransferRequest request) {
            new Thread(new Runnable() {

                public void run() {
                    IncomingFileTransfer transfer = request.accept();
                    InputStream stream;
                    try {
                        stream = transfer.recieveFile();
                    } catch (XMPPException e) {
                        exception = e;
                        return;
                    }
                    byte[] testRecieve = new byte[testTransfer.length];
                    int receiveCount = 0;
                    try {
                        while (receiveCount != -1) {
                            receiveCount = stream.read(testRecieve);
                        }
                    } catch (IOException e) {
                        exception = e;
                    } finally {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        queue.put(testRecieve);
                    } catch (InterruptedException e) {
                        exception = e;
                    }
                }
            }).start();
        }
    });
    // Send the file from user1 to user0
    FileTransferManager manager2 = new FileTransferManager(getConnection(1));
    OutgoingFileTransfer outgoing = manager2.createOutgoingFileTransfer(getFullJID(0));
    OutputStream stream = outgoing.sendFile("test.txt", testTransfer.length, "The great work of robin hood");
    stream.write(testTransfer);
    stream.flush();
    stream.close();
    if (exception != null) {
        exception.printStackTrace();
        fail();
    }
    byte[] array = queue.take();
    assertEquals("Recieved file not equal to sent file.", testTransfer, array);
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) SynchronousQueue(java.util.concurrent.SynchronousQueue) XMPPException(org.jivesoftware.smack.XMPPException)

Example 25 with XMPPException

use of org.jivesoftware.smack.XMPPException in project Smack by igniterealtime.

the class LastActivityManagerTest method testOnlinePermisionDenied.

/**
	 * This is a test to check if a denied LastActivity response is handled correctly.
	 */
public void testOnlinePermisionDenied() {
    TCPConnection conn0 = getConnection(0);
    TCPConnection conn2 = getConnection(2);
    // Send a message as the last activity action from connection 2 to
    // connection 0
    conn2.sendStanza(new Message(getBareJID(0)));
    // Wait 1 seconds to have some idle time
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail("Thread sleep interrupted");
    }
    try {
        LastActivityManager.getLastActivity(conn0, getFullJID(2));
        fail("No error was received from the server. User was able to get info of other user not in his roster.");
    } catch (XMPPException e) {
        assertNotNull("No error was returned from the server", e.getXMPPError());
        assertEquals("Forbidden error was not returned from the server", 403, e.getXMPPError().getCode());
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) TCPConnection(org.jivesoftware.smack.TCPConnection) XMPPException(org.jivesoftware.smack.XMPPException)

Aggregations

XMPPException (org.jivesoftware.smack.XMPPException)52 ArrayList (java.util.ArrayList)15 JingleSessionRequestListener (org.jivesoftware.smackx.jingle.listeners.JingleSessionRequestListener)13 JingleMediaManager (org.jivesoftware.smackx.jingle.media.JingleMediaManager)13 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)9 IOException (java.io.IOException)8 SmackException (org.jivesoftware.smack.SmackException)7 PayloadType (org.jivesoftware.smackx.jingle.media.PayloadType)6 NoResponseException (org.jivesoftware.smack.SmackException.NoResponseException)5 Message (org.jivesoftware.smack.packet.Message)5 FixedResolver (org.jivesoftware.smackx.jingle.nat.FixedResolver)5 FixedTransportManager (org.jivesoftware.smackx.jingle.nat.FixedTransportManager)5 TransportCandidate (org.jivesoftware.smackx.jingle.nat.TransportCandidate)5 TCPConnection (org.jivesoftware.smack.TCPConnection)4 XMPPConnection (org.jivesoftware.smack.XMPPConnection)4 Form (org.jivesoftware.smackx.Form)4 JingleSessionListener (org.jivesoftware.smackx.jingle.listeners.JingleSessionListener)4 JmfMediaManager (org.jivesoftware.smackx.jingle.mediaimpl.jmf.JmfMediaManager)4 ICETransportManager (org.jivesoftware.smackx.jingle.nat.ICETransportManager)4 SocketException (java.net.SocketException)3