Example usage for com.rabbitmq.client ConnectionFactory setConnectionTimeout

List of usage examples for com.rabbitmq.client ConnectionFactory setConnectionTimeout

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory setConnectionTimeout.

Prototype

public void setConnectionTimeout(int timeout) 

Source Link

Document

Set the TCP connection timeout.

Usage

From source file:TestUfms.java

public static void main(String[] args) throws Exception {
    // AMQP//from  w w w  .j  a v a2 s . c  om

    //      UfmsProto.RegCompany.Builder builderRegCompany = UfmsProto.RegCompany.newBuilder();
    //      builderRegCompany.setAddress("11-chaulong");
    //      builderRegCompany.setCompany("CPR_0101885631");
    //      builderRegCompany.setName("cadpro");
    //      builderRegCompany.setTel("0437152984");      
    //      UfmsProto.RegCompany rc = builderRegCompany.build();
    //      UfmsProto.BaseMessage rcMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegCompany).setExtension(UfmsProto.RegCompany.msg, rc).build();      
    //      byte[] rcData = rcMsg.toByteArray();
    //      System.out.println(rcMsg.toString());
    //      
    //      
    //      UfmsProto.RegDriver.Builder builderRegDriver = UfmsProto.RegDriver.newBuilder();
    //      builderRegDriver.setDatetimeExpire(1981979234);
    //      builderRegDriver.setDatetimeIssue(1095379200);
    //      builderRegDriver.setDriver("CPR_010099045659");
    //      builderRegDriver.setLicense("B2");
    //      builderRegDriver.setName("Dao Duy Hung");
    //      builderRegDriver.setRegPlace("Ha Noi");
    //      UfmsProto.RegDriver rd = builderRegDriver.build();
    //      UfmsProto.BaseMessage rdMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegDriver).setExtension(UfmsProto.RegDriver.msg, rd).build();      
    //      byte[] rdData = rdMsg.toByteArray();
    //      System.out.println(rdMsg.toString());
    //      
    //      UfmsProto.RegVehicle.Builder builderRegVehicle = UfmsProto.RegVehicle.newBuilder();
    //      builderRegVehicle.setCompany("CPR_0101885631");
    //      builderRegVehicle.setDatetime(1481979234);
    //      builderRegVehicle.setDeviceId("CPR_01");
    //      builderRegVehicle.setDeviceModel("CPR_Model_1");
    //      builderRegVehicle.setDeviceModelNo(1);
    //      builderRegVehicle.setDriver("CPR_010099045659");
    //      builderRegVehicle.setSim("0966871864");
    //      builderRegVehicle.setVehicle("29A1511");
    //      builderRegVehicle.setVehicleType(VehicleType.HopDong);
    //      builderRegVehicle.setVin("01");
    //      UfmsProto.RegVehicle rv = builderRegVehicle.build();
    //      UfmsProto.BaseMessage rvMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegVehicle).setExtension(UfmsProto.RegVehicle.msg, rv).build();      
    //      byte[] rvData = rvMsg.toByteArray();
    //      System.out.println(rvMsg.toString());

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("27.118.27.118");
    factory.setUsername("ctchaulong");
    factory.setPassword("EHjt81_FI");
    factory.setPort(5673);

    factory.setConnectionTimeout(600);

    Connection connection = factory.newConnection();
    System.out.println("creat connection done!");
    Channel channel = connection.createChannel();
    System.out.println("creat channel done!");

    int i = 0;
    // build WayPoint message 
    boolean a = true;
    while (a) {
        i++;

        UfmsProto.WayPoint.Builder builder = UfmsProto.WayPoint.newBuilder();
        int now = (int) (System.currentTimeMillis() / 1000);
        builder.setDatetime(now);
        builder.setDoor(true);
        builder.setDriver("010099045659");
        builder.setHeading(90);
        builder.setIgnition(true);
        builder.setSpeed(0); //<200
        //builder.setVehicle("29A1511");
        builder.setVehicle("29A1516");
        //builder.setVehicle("29K-8942");
        builder.setX(105.8445795); //> 0
        builder.setY(21.0306089); //>0
        //         builder.setX(021.0306089); //>0
        //         builder.setY(105.8445795); //> 0         
        builder.setZ(20); //>0            21.0306089,105.8445795,16z

        UfmsProto.WayPoint wp = builder.build();
        UfmsProto.BaseMessage msg = UfmsProto.BaseMessage.newBuilder()
                .setMsgType(UfmsProto.BaseMessage.MsgType.WayPoint).setExtension(UfmsProto.WayPoint.msg, wp)
                .build();
        byte[] data = msg.toByteArray();
        System.out.println(msg.toString());

        // send to server
        //channel.basicPublish("ufms.all", "", null, data);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rcData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rdData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rvData);   

        channel.basicPublish("tracking.ctchaulong", "track1", null, data);
        try {
            System.out.println("Send [" + i + "] time(s)! sleep in 1s...");
            Thread.sleep(1000); //1000 milliseconds is one second.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }
    // clean up
    channel.close();
    connection.close();
    //      System.out.println("send done! ");
}

From source file:com.hp.ov.sdk.messaging.msmb.services.MsmbConnectionManager.java

License:Apache License

public void startMsmb(final RestParams params) {
    Connection conn = null;//from w w w. j a va2 s .co  m
    Channel channel = null;
    // validate args
    if (null == params) {
        throw new SDKInvalidArgumentException(SDKErrorEnum.invalidArgument, null, null, null,
                SdkConstants.APPLIANCE, null);
    }
    // check if connection object already exists in the map
    // msmbConnection = map.get(params.getHostname());
    if (!map.containsKey(params.getHostname())) {
        // get client cert
        final RabbitMqClientCert mqClientCert = messagingCertificate
                .getRabbitMqClientCertificateKeyPair(params);
        // get CA cert
        CaCert caCert = messagingCertificate.getCACertificate(params);
        // get SSLContext
        SSLContext sslContext = CertificateStoreManager.getSslContext(mqClientCert, caCert);
        ConnectionFactory connectionFactory = RabbitMqClientConnectionFactory.getConnectionFactory(sslContext,
                params);
        connectionFactory.setConnectionTimeout(1000);

        try {
            conn = connectionFactory.newConnection();
            channel = conn.createChannel();
        } catch (final IOException e) {
            throw new SDKResourceNotFoundException(SDKErrorEnum.resourceNotFound, null, null, null,
                    SdkConstants.APPLIANCE, null);
        }
        // put into map
        map.putIfAbsent(params.getHostname(), new MsmbConnection(conn, channel, MsmbState.START));
    }

}

From source file:com.hp.ov.sdk.messaging.scmb.services.ScmbConnectionManager.java

License:Apache License

public void startScmb(final RestParams params) {
    Connection conn = null;// w  w  w . j  a  v  a 2 s  .  c o m
    Channel channel = null;
    // validate args
    if (null == params) {
        throw new SDKInvalidArgumentException(SDKErrorEnum.invalidArgument, null, null, null,
                SdkConstants.APPLIANCE, null);
    }
    final String sessionId = params.getSessionId();
    // check if connection object already exists in the map
    // scmbConnection = map.get(params.getHostname());
    if (!map.containsKey(params.getHostname())) {
        // get client cert
        final RabbitMqClientCert mqClientCert = messagingCertificate
                .getRabbitMqClientCertificateKeyPair(params);
        // get CA cert
        CaCert caCert = messagingCertificate.getCACertificate(params);
        // get SSLContext
        SSLContext sslContext = CertificateStoreManager.getSslContext(mqClientCert, caCert);
        ConnectionFactory connectionFactory = RabbitMqClientConnectionFactory.getConnectionFactory(sslContext,
                params);
        connectionFactory.setConnectionTimeout(1000);
        try {
            conn = connectionFactory.newConnection();
            channel = conn.createChannel();

        } catch (final IOException e) {
            LOGGER.error("ScmbConnectionManager : startScmb: IOException");
            throw new SDKScmbConnectionNotFoundException(SDKErrorEnum.scmbConnectionNotFound, null, null, null,
                    SdkConstants.SCMB_CONNECTION, null);
        }

        // put into map
        map.putIfAbsent(params.getHostname(), new ScmbConnection(conn, channel, ScmbState.START));
    }

}

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

private ConnectionFactory getOrCreateConnectionFactory() {
    if (connectionFactory == null) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(getUsername());
        factory.setPassword(getPassword());
        factory.setVirtualHost(getVhost());
        factory.setHost(getHostname());/*from  w  w w  . j  ava 2s  .  c  om*/
        factory.setPort(getPortNumber());
        if (getClientProperties() != null) {
            factory.setClientProperties(getClientProperties());
        }
        factory.setConnectionTimeout(getConnectionTimeout());
        factory.setRequestedChannelMax(getRequestedChannelMax());
        factory.setRequestedFrameMax(getRequestedFrameMax());
        factory.setRequestedHeartbeat(getRequestedHeartbeat());
        if (getSslProtocol() != null) {
            try {
                if (getSslProtocol().equals("true")) {
                    factory.useSslProtocol();
                } else if (getTrustManager() == null) {
                    factory.useSslProtocol(getSslProtocol());
                } else {
                    factory.useSslProtocol(getSslProtocol(), getTrustManager());
                }
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                throw new IllegalArgumentException("Invalid sslProtocol " + sslProtocol, e);
            }
        }
        if (getAutomaticRecoveryEnabled() != null) {
            factory.setAutomaticRecoveryEnabled(getAutomaticRecoveryEnabled());
        }
        if (getNetworkRecoveryInterval() != null) {
            factory.setNetworkRecoveryInterval(getNetworkRecoveryInterval());
        }
        if (getTopologyRecoveryEnabled() != null) {
            factory.setTopologyRecoveryEnabled(getTopologyRecoveryEnabled());
        }
        connectionFactory = factory;
    }
    return connectionFactory;
}

From source file:com.paxxis.cornerstone.messaging.service.amqp.AMQPServiceBusConnector.java

License:Apache License

protected void initConnection() {
    try {/*ww  w . j  a  v  a  2 s . co  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(port);
        factory.setAutomaticRecoveryEnabled(autoRecover);
        factory.setConnectionTimeout(timeout);
        factory.setNetworkRecoveryInterval(recoveryInterval);
        factory.setRequestedHeartbeat(heartbeat);
        factory.setTopologyRecoveryEnabled(autoTopologyRecover);
        factory.setExceptionHandler(exceptionHandler);

        connection = factory.newConnection();
        session = (AMQPSession) createSession();
    } catch (IOException e) {
        logger.error(e);
        throw new RuntimeException(e);
    }
}

From source file:com.simple.sftpfetch.publish.RabbitClient.java

License:Apache License

/**
 * Initialize the RabbitClient, establish a connection and declare the exchange
 *
 * @param factory the RabbitMQ ConnectionFactory
 * @param connectionInfo a bean containing the necessary connection information
 *
 * @throws NoSuchAlgorithmException/* www. j  a  v  a 2s .c  o m*/
 * @throws KeyManagementException
 * @throws URISyntaxException
 * @throws IOException
 */
public RabbitClient(ConnectionFactory factory, RabbitConnectionInfo connectionInfo)
        throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException {
    factory.setHost(connectionInfo.getHostname());
    factory.setPort(connectionInfo.getPort());
    factory.setUsername(connectionInfo.getUsername());
    factory.setPassword(connectionInfo.getPassword());
    factory.setVirtualHost(connectionInfo.getVhost());
    factory.setConnectionTimeout(connectionInfo.getTimeout());
    Connection conn = factory.newConnection();
    exchange = connectionInfo.getExchange();
    channel = conn.createChannel();
    channel.exchangeDeclare(exchange, EXCHANGE_TYPE, true);
    this.amqpProperties = new AMQP.BasicProperties.Builder().contentType(CONTENT_TYPE).deliveryMode(2).build();
}

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance.//from   w  w w .j  ava2s. com
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:io.bootique.rabbitmq.client.connection.ConnectionConfig.java

License:Apache License

public Connection createConnection(String connectionName) {
    com.rabbitmq.client.ConnectionFactory factory = createConnectionFactory();

    factory.setRequestedChannelMax(requestedChannelMax);
    factory.setRequestedFrameMax(requestedFrameMax);
    factory.setRequestedHeartbeat(requestedHeartbeat);
    factory.setConnectionTimeout(connectionTimeout);
    factory.setHandshakeTimeout(handshakeTimeout);
    factory.setShutdownTimeout(shutdownTimeout);
    factory.setAutomaticRecoveryEnabled(automaticRecoveryEnabled);
    factory.setTopologyRecoveryEnabled(topologyRecovery);
    factory.setNetworkRecoveryInterval(networkRecoveryInterval);

    LOGGER.info("Creating RabbitMQ connection.");
    try {/* www  .j  a  v  a2 s .c om*/
        return factory.newConnection();
    } catch (IOException | TimeoutException e) {
        throw new RuntimeException(String.format("Can't create connection \"%s\".", connectionName), e);
    }
}

From source file:net.roboconf.messaging.rabbitmq.internal.utils.RabbitMqUtils.java

License:Apache License

/**
 * Configures the connection factory with the right settings.
 * @param factory the connection factory
 * @param configuration the messaging configuration
 * @throws IOException if something went wrong
 * @see RabbitMqConstants/*from  ww w. j av a  2s  .  c  om*/
 */
public static void configureFactory(ConnectionFactory factory, Map<String, String> configuration)
        throws IOException {

    final Logger logger = Logger.getLogger(RabbitMqUtils.class.getName());
    logger.fine("Configuring a connection factory for RabbitMQ.");

    String messageServerIp = configuration.get(RABBITMQ_SERVER_IP);
    if (messageServerIp != null) {
        Map.Entry<String, Integer> entry = Utils.findUrlAndPort(messageServerIp);
        factory.setHost(entry.getKey());
        if (entry.getValue() > 0)
            factory.setPort(entry.getValue());
    }

    factory.setUsername(configuration.get(RABBITMQ_SERVER_USERNAME));
    factory.setPassword(configuration.get(RABBITMQ_SERVER_PASSWORD));

    // Timeout for connection establishment: 5s
    factory.setConnectionTimeout(5000);

    // Configure automatic reconnection
    factory.setAutomaticRecoveryEnabled(true);

    // Recovery interval: 10s
    factory.setNetworkRecoveryInterval(10000);

    // Exchanges and so on should be redeclared if necessary
    factory.setTopologyRecoveryEnabled(true);

    // SSL
    if (Boolean.parseBoolean(configuration.get(RABBITMQ_USE_SSL))) {
        logger.fine("Connection factory for RabbitMQ: SSL is used.");

        InputStream clientIS = null;
        InputStream storeIS = null;
        try {
            clientIS = new FileInputStream(configuration.get(RABBITMQ_SSL_KEY_STORE_PATH));
            storeIS = new FileInputStream(configuration.get(RABBITMQ_SSL_TRUST_STORE_PATH));

            char[] keyStorePassphrase = configuration.get(RABBITMQ_SSL_KEY_STORE_PASSPHRASE).toCharArray();
            KeyStore ks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_KEY_STORE_TYPE, DEFAULT_SSL_KEY_STORE_TYPE));
            ks.load(clientIS, keyStorePassphrase);

            String value = getValue(configuration, RABBITMQ_SSL_KEY_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(value);
            kmf.init(ks, keyStorePassphrase);

            char[] trustStorePassphrase = configuration.get(RABBITMQ_SSL_TRUST_STORE_PASSPHRASE).toCharArray();
            KeyStore tks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_TRUST_STORE_TYPE, DEFAULT_SSL_TRUST_STORE_TYPE));
            tks.load(storeIS, trustStorePassphrase);

            value = getValue(configuration, RABBITMQ_SSL_TRUST_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(value);
            tmf.init(tks);

            SSLContext c = SSLContext
                    .getInstance(getValue(configuration, RABBITMQ_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL));
            c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            factory.useSslProtocol(c);

        } catch (GeneralSecurityException e) {
            throw new IOException("SSL configuration for the RabbitMQ factory failed.", e);

        } finally {
            Utils.closeQuietly(storeIS);
            Utils.closeQuietly(clientIS);
        }
    }
}

From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java

License:Apache License

/**
 *
 * @return Connection Factory for RMQ// ww w . j a v  a  2  s  .c  om
 * @throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException if Malformed URI has been passed
 */
public ConnectionFactory getConnectionFactory()
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
    ConnectionFactory factory = new ConnectionFactory();
    if (this.uri != null && !this.uri.isEmpty()) {
        try {
            factory.setUri(this.uri);
        } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException e) {
            LOG.error("Failed to parse uri", e);
            throw e;
        }
    } else {
        factory.setHost(this.host);
        factory.setPort(this.port);
        factory.setVirtualHost(this.virtualHost);
        factory.setUsername(this.username);
        factory.setPassword(this.password);
    }

    if (this.automaticRecovery != null) {
        factory.setAutomaticRecoveryEnabled(this.automaticRecovery);
    }
    if (this.connectionTimeout != null) {
        factory.setConnectionTimeout(this.connectionTimeout);
    }
    if (this.networkRecoveryInterval != null) {
        factory.setNetworkRecoveryInterval(this.networkRecoveryInterval);
    }
    if (this.requestedHeartbeat != null) {
        factory.setRequestedHeartbeat(this.requestedHeartbeat);
    }
    if (this.topologyRecovery != null) {
        factory.setTopologyRecoveryEnabled(this.topologyRecovery);
    }
    if (this.requestedChannelMax != null) {
        factory.setRequestedChannelMax(this.requestedChannelMax);
    }
    if (this.requestedFrameMax != null) {
        factory.setRequestedFrameMax(this.requestedFrameMax);
    }

    return factory;
}