Search in sources :

Example 1 with ConnectionConfiguration

use of org.jivesoftware.smack.ConnectionConfiguration 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 2 with ConnectionConfiguration

use of org.jivesoftware.smack.ConnectionConfiguration in project SmartMesh_Android by SmartMeshFoundation.

the class XmppUtils method createConnection.

/**
 * Create a XMPP connection instance
 * @return
 * @throws org.jivesoftware.smack.XMPPException
 */
public void createConnection() throws XMPPException {
    // Open the DEBUG mode
    XMPPConnection.DEBUG_ENABLED = true;
    // Configure the connection
    ConnectionConfiguration config = new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVER_NAME);
    config.setReconnectionAllowed(true);
    config.setSASLAuthenticationEnabled(true);
    // Don't send the online status
    config.setSendPresence(false);
    conn = null;
    conn = new XMPPConnection(config);
    // To connect to the server
    conn.connect();
    // Configuration of the Provider if not configured Will be unable to parse the data
    SERVER_NAME = conn.getServiceName();
    conn.addConnectionListener(this);
    configureConnection(ProviderManager.getInstance());
}
Also used : ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Example 3 with ConnectionConfiguration

use of org.jivesoftware.smack.ConnectionConfiguration in project wildfly-camel by wildfly-extras.

the class XMPPIntegrationTest method setUp.

@Before
public void setUp() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(XMPPIntegrationTest.class.getResourceAsStream("/server.jks"), "secret".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
    String port = AvailablePortFinder.readServerData("xmpp-port");
    ConnectionConfiguration connectionConfig = XMPPTCPConnectionConfiguration.builder().setXmppDomain(JidCreate.domainBareFrom("apache.camel")).setHostAddress(InetAddress.getLocalHost()).setPort(Integer.parseInt(port)).setCustomSSLContext(sslContext).setHostnameVerifier((hostname, session) -> true).build();
    context.bind("customConnectionConfig", connectionConfig);
}
Also used : ServerSetupTask(org.jboss.as.arquillian.api.ServerSetupTask) SSLContext(javax.net.ssl.SSLContext) Arquillian(org.jboss.arquillian.junit.Arquillian) ServerSetup(org.jboss.as.arquillian.api.ServerSetup) RunWith(org.junit.runner.RunWith) NamingException(javax.naming.NamingException) EmbeddedXMPPServer(org.wildfly.camel.test.xmpp.subA.EmbeddedXMPPServer) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) InetAddress(java.net.InetAddress) SecureRandom(java.security.SecureRandom) XMPPTCPConnectionConfiguration(org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration) CamelAware(org.wildfly.extension.camel.CamelAware) After(org.junit.After) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) ProducerTemplate(org.apache.camel.ProducerTemplate) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Before(org.junit.Before) InitialContext(javax.naming.InitialContext) CamelContext(org.apache.camel.CamelContext) ShrinkWrap(org.jboss.shrinkwrap.api.ShrinkWrap) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) KeyStore(java.security.KeyStore) Test(org.junit.Test) AvailablePortFinder(org.wildfly.camel.test.common.utils.AvailablePortFinder) JidCreate(org.jxmpp.jid.impl.JidCreate) RouteBuilder(org.apache.camel.builder.RouteBuilder) Deployment(org.jboss.arquillian.container.test.api.Deployment) JavaArchive(org.jboss.shrinkwrap.api.spec.JavaArchive) ManagementClient(org.jboss.as.arquillian.container.ManagementClient) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) XMPPTCPConnectionConfiguration(org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Before(org.junit.Before)

Example 4 with ConnectionConfiguration

use of org.jivesoftware.smack.ConnectionConfiguration in project ecf by eclipse.

the class ECFConnection method connect.

public synchronized Object connect(ID remote, Object data, int timeout) throws ECFException {
    if (connection != null)
        throw new ECFException("already connected");
    if (timeout > 0)
        SmackConfiguration.setPacketReplyTimeout(timeout);
    Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
    final XMPPID jabberURI = getXMPPID(remote);
    String username = jabberURI.getNodename();
    String hostname = jabberURI.getHostname();
    String hostnameOverride = null;
    // Check for the URI form of "joe@bloggs.org;talk.google.com", which
    // would at this point would have
    // - username = "joe"
    // - hostname = "blogs.org;talk.google.com"
    // - hostnameOverride = null
    // 
    // We need to turn this into:
    // - username = "joe"
    // - hostname = "bloggs.org"
    // - hostnameOverride = "talk.google.com"
    int semiColonIdx = hostname.lastIndexOf(';');
    if (semiColonIdx != -1) {
        hostnameOverride = hostname.substring(semiColonIdx + 1);
        hostname = hostname.substring(0, semiColonIdx);
    }
    if (google && hostnameOverride == null) {
        hostnameOverride = GOOGLE_TALK_HOST;
    }
    final String serviceName = hostname;
    serverPort = jabberURI.getPort();
    serverResource = jabberURI.getResourceName();
    if (serverResource == null || serverResource.equals(XMPPID.PATH_DELIMITER)) {
        serverResource = getClientIdentifier();
        jabberURI.setResourceName(serverResource);
    }
    try {
        ConnectionConfiguration config;
        if (hostnameOverride != null) {
            config = new ConnectionConfiguration(hostnameOverride, XMPP_DEFAULT_PORT, serviceName);
        } else if (serverPort == -1) {
            config = new ConnectionConfiguration(serviceName);
        } else {
            config = new ConnectionConfiguration(serviceName, serverPort);
        }
        config.setSendPresence(true);
        // authentication; handler should provide keystore password:
        if (callbackHandler instanceof javax.security.auth.callback.CallbackHandler) {
            config.setCallbackHandler((javax.security.auth.callback.CallbackHandler) callbackHandler);
        }
        connection = new XMPPConnection(config);
        connection.connect();
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        if (google || GOOGLE_TALK_HOST.equals(hostnameOverride)) {
            username = username + "@" + serviceName;
        }
        connection.addPacketListener(packetListener, null);
        connection.addConnectionListener(connectionListener);
        // Login
        connection.login(username, (String) data, serverResource);
        waitForBindResult();
    } catch (final XMPPException e) {
        throw new ContainerConnectException("Login attempt failed", e);
    }
    return jid;
}
Also used : CallbackHandler(org.eclipse.ecf.core.security.CallbackHandler) XMPPConnection(org.jivesoftware.smack.XMPPConnection) ECFException(org.eclipse.ecf.core.util.ECFException) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) ContainerConnectException(org.eclipse.ecf.core.ContainerConnectException) XMPPException(org.jivesoftware.smack.XMPPException) XMPPID(org.eclipse.ecf.provider.xmpp.identity.XMPPID)

Example 5 with ConnectionConfiguration

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

the class MultiUserChatTest method testManyResources.

public void testManyResources() throws Exception {
    // Create 5 more connections for user2
    XMPPTCPConnection[] conns = new XMPPConnection[5];
    for (int i = 0; i < conns.length; i++) {
        ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration(getHost(), getPort(), getXMPPServiceDomain());
        connectionConfiguration.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        conns[i] = new XMPPTCPConnection(connectionConfiguration);
        conns[i].connect();
        conns[i].login(getUsername(1), getPassword(1), "resource-" + i);
        Thread.sleep(20);
    }
    // Join the 5 connections to the same room
    MultiUserChat[] mucs = new MultiUserChat[5];
    for (int i = 0; i < mucs.length; i++) {
        mucs[i] = new MultiUserChat(conns[i], room);
        mucs[i].join("resource-" + i);
    }
    Thread.sleep(200);
    // Each connection has something to say
    for (int i = 0; i < mucs.length; i++) {
        mucs[i].sendMessage("I'm resource-" + i);
    }
    Thread.sleep(200);
    // Each connection leaves the room and closes the connection
    for (MultiUserChat muc1 : mucs) {
        muc1.leave();
    }
    Thread.sleep(200);
    for (int i = 0; i < mucs.length; i++) {
        conns[i].disconnect();
    }
}
Also used : ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Aggregations

ConnectionConfiguration (org.jivesoftware.smack.ConnectionConfiguration)14 XMPPConnection (org.jivesoftware.smack.XMPPConnection)9 XMPPException (org.jivesoftware.smack.XMPPException)6 Message (org.jivesoftware.smack.packet.Message)3 SSLContext (javax.net.ssl.SSLContext)2 AxisFault (org.apache.axis2.AxisFault)2 ConnectionListener (org.jivesoftware.smack.ConnectionListener)2 FromContainsFilter (org.jivesoftware.smack.filter.FromContainsFilter)2 ToContainsFilter (org.jivesoftware.smack.filter.ToContainsFilter)2 XMPPTCPConnection (org.jivesoftware.smack.tcp.XMPPTCPConnection)2 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)1 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)1 PerunNotifMessageDto (cz.metacentrum.perun.notif.dto.PerunNotifMessageDto)1 PoolMessage (cz.metacentrum.perun.notif.dto.PoolMessage)1 PerunNotifReceiver (cz.metacentrum.perun.notif.entities.PerunNotifReceiver)1 InetAddress (java.net.InetAddress)1 KeyManagementException (java.security.KeyManagementException)1 KeyStore (java.security.KeyStore)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SecureRandom (java.security.SecureRandom)1