Java Code Examples for com.rabbitmq.client.ConnectionFactory#setUsername()

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setUsername() . 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 File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 8 votes vote down vote up
@Bean
@DependsOn("amqpBroker")
CachingConnectionFactory connectionFactory() {
    log.info("Creating connection factory for MQ broker...");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(hostname);
    cf.setPort(port);
    cf.setUsername(userName);
    cf.setPassword(password);
    cf.setVirtualHost(virtualHost);
    cf.setAutomaticRecoveryEnabled(false);
    if (useSSL) {
        try {
            cf.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            //TODO don't throw raw exceptions
            throw new RuntimeException(e);
        }
    }

    log.info("Connection factory created.");
    return new CachingConnectionFactory(cf);
}
 
Example 2
Source File: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 6 votes vote down vote up
private void publishAgentAction(String routingKey, byte[] data, BasicProperties props)
		throws TimeoutException, IOException {
	String exchangeName = ApplicationConfigProvider.getInstance().getAgentDetails().getAgentExchange();
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(ApplicationConfigProvider.getInstance().getMessageQueue().getHost());
	factory.setUsername(ApplicationConfigProvider.getInstance().getMessageQueue().getUser());
	factory.setPassword(ApplicationConfigProvider.getInstance().getMessageQueue().getPassword());
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();
	channel.exchangeDeclare(exchangeName, MessageConstants.EXCHANGE_TYPE, true);
	channel.queueDeclare(routingKey, true, false, false, null);
	channel.queueBind(routingKey, exchangeName, routingKey);
	channel.basicPublish(exchangeName, routingKey, props, data);
	channel.close();
	connection.close();
}
 
Example 3
Source File: RabbitQueueFactory.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Connection getConnection() throws IOException {
    if (this.connection != null && this.connection.isOpen()) return this.connection;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setHost(this.server);
    if (this.port > 0) factory.setPort(this.port);
    if (this.username != null && this.username.length() > 0) factory.setUsername(this.username);
    if (this.password != null && this.password.length() > 0) factory.setPassword(this.password);
    try {
        this.connection = factory.newConnection();
        //Map<String, Object> map = this.connection.getServerProperties();
        if (!this.connection.isOpen()) throw new IOException("no connection");
        return this.connection;
    } catch (TimeoutException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 4
Source File: CacheInvalidationSubscriber.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}
 
Example 5
Source File: ManSender.java    From demo_springboot_rabbitmq with Apache License 2.0 6 votes vote down vote up
public ManSender(String queueName) throws Exception {
    this.queueName = queueName;
    // 创建链接工厂
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setVirtualHost(virtualHost);
    factory.setUsername(userName);
    factory.setPassword(password);
    // 创建链接
    connection = factory.newConnection();

    // 创建消息信道
    channel = connection.createChannel();

    // 生命消息队列
    channel.queueDeclare(queueName, true, false, false, null);
}
 
Example 6
Source File: RabbitMqConnFactoryUtil.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * 获取rabbit连接
 */
public static Connection getRabbitConn() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setVirtualHost("/");
    factory.setHost("192.168.242.131");
    factory.setPort(5672);
    Connection conn = factory.newConnection();

    //高级连接使用线程池
    // ExecutorService es = Executors.newFixedThreadPool(20);
    // Connection conn = factory.newConnection(es);

    return conn;
}
 
Example 7
Source File: Registration.java    From NFVO with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a deregistration message to the NFVO
 *
 * @param brokerIp the rabbitmq broker ip
 * @param port the port of rabbitmq
 * @param username the username to connect with
 * @param password the password to connect with
 * @param virtualHost the virtualHost
 * @param managerCredentialUsername the username to remove
 * @param managerCredentialPassword the password to remove
 * @throws IOException In case of InterruptedException
 * @throws TimeoutException in case of TimeoutException
 */
public void deregisterPluginFromNfvo(
    String brokerIp,
    int port,
    String username,
    String password,
    String virtualHost,
    String managerCredentialUsername,
    String managerCredentialPassword)
    throws IOException, TimeoutException {
  String message =
      "{'username':'"
          + managerCredentialUsername
          + "','action':'deregister','password':'"
          + managerCredentialPassword
          + "'}";
  ConnectionFactory factory = new ConnectionFactory();
  factory.setHost(brokerIp);
  factory.setPort(port);
  factory.setUsername(username);
  factory.setPassword(password);
  factory.setVirtualHost(virtualHost);
  Connection connection = factory.newConnection();
  Channel channel = connection.createChannel();

  // check if exchange and queue exist
  channel.exchangeDeclarePassive("openbaton-exchange");
  channel.queueDeclarePassive("nfvo.manager.handling");
  channel.basicQos(1);

  AMQP.BasicProperties props =
      new AMQP.BasicProperties.Builder().contentType("text/plain").build();

  channel.basicPublish("openbaton-exchange", "nfvo.manager.handling", props, message.getBytes());
  channel.close();
  connection.close();
}
 
Example 8
Source File: ClientHelper.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
public static Connection getAmqpConnection(String userName, String password, String brokerHost, String port)
        throws IOException, TimeoutException {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(userName);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost("carbon");
    connectionFactory.setHost(brokerHost);
    connectionFactory.setPort(Integer.valueOf(port));
    return connectionFactory.newConnection();
}
 
Example 9
Source File: RabbitMQTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Before
public void before(final MockTracer tracer) throws IOException, TimeoutException {
  tracer.reset();
  final ConnectionFactory factory = new ConnectionFactory();
  factory.setUsername("guest");
  factory.setPassword("guest");
  factory.setHost("localhost");
  factory.setPort(embeddedAMQPBroker.getBrokerPort());
  connection = factory.newConnection();
  channel = connection.createChannel();
}
 
Example 10
Source File: RabbitMQAbstractConfig.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public ConnectionFactory createConnectionFactory() {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost(this.host);
    connectionFactory.setUsername(this.username);
    connectionFactory.setPassword(this.password);
    connectionFactory.setVirtualHost(this.virtualHost);
    connectionFactory.setRequestedChannelMax(this.requestedChannelMax);
    connectionFactory.setRequestedFrameMax(this.requestedFrameMax);
    connectionFactory.setConnectionTimeout(this.connectionTimeout);
    connectionFactory.setHandshakeTimeout(this.handshakeTimeout);
    connectionFactory.setRequestedHeartbeat(this.requestedHeartbeat);
    connectionFactory.setPort(this.port);
    return connectionFactory;
}
 
Example 11
Source File: RabbitMqTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    EmbeddedRabbitMqConfig configuration = new EmbeddedRabbitMqConfig.Builder()
            // 时间过短会启动失败
            .rabbitMqServerInitializationTimeoutInMillis(60000)
            // 时间过短会停止失败
            .defaultRabbitMqCtlTimeoutInMillis(60000)

            .build();
    EmbeddedRabbitMq rabbitMq = new EmbeddedRabbitMq(configuration);
    try {
        rabbitMq.start();

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        Connection connection = connectionFactory.newConnection();
        Assert.assertTrue(connection.isOpen());
        Channel channel = connection.createChannel();
        Assert.assertTrue(channel.isOpen());
        channel.close();
        Assert.assertFalse(channel.isOpen());
        connection.close();
        Assert.assertFalse(connection.isOpen());
    } finally {
        rabbitMq.stop();
    }
}
 
Example 12
Source File: RabbitMqIngressSpringConfig.java    From pitchfork with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "close")
public Connection rabbitMqConnection(RabbitMqIngressConfigProperties properties) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(properties.getUser());
    factory.setPassword(properties.getPassword());
    factory.setVirtualHost(properties.getVirtualHost());
    factory.setHost(properties.getHost());
    factory.setPort(properties.getPort());

    return factory.newConnection();
}
 
Example 13
Source File: MQConfig.java    From jseckill with Apache License 2.0 5 votes vote down vote up
@Bean("mqConnectionReceive")
public Connection mqConnectionReceive(@Autowired MQConfigBean mqConfigBean) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    //用户名
    factory.setUsername(username);
    //密码
    factory.setPassword(password);
    //虚拟主机路径(相当于数据库名)
    factory.setVirtualHost(virtualHost);
    //返回连接
    return factory.newConnection(mqConfigBean.getAddressList());
}
 
Example 14
Source File: RabbitMqConnectionFactoy.java    From util4j with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection() throws IOException, TimeoutException {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost("127.0.0.1");
	factory.setPort(5672);
	factory.setVirtualHost("/");
	factory.setUsername("guest");
	factory.setPassword("guest");
	return factory.newConnection();
}
 
Example 15
Source File: RabbitMQProducerClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public RabbitMQProducerClient(String host, int port, String username, String password) {
    factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setUsername(username);
    factory.setPassword(password);
}
 
Example 16
Source File: RabbitMQUtil.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
public static ConnectionFactory getFactory(Context context){
        Preconditions.checkArgument(context!=null, "context cannot be null.");
        ConnectionFactory factory = new ConnectionFactory();
        
        String hostname = context.getString("hostname");
        Preconditions.checkArgument(hostname!=null, "No hostname specified.");
        factory.setHost(hostname);
        
        int port = context.getInteger(RabbitMQConstants.CONFIG_PORT, -1);
        
        if(-1!=port){
            factory.setPort(port);
        }
        
        String username = context.getString(RabbitMQConstants.CONFIG_USERNAME);
        
        if(null==username){
            factory.setUsername(ConnectionFactory.DEFAULT_USER);
        } else {
            factory.setUsername(username);
        }
        
        String password = context.getString(RabbitMQConstants.CONFIG_PASSWORD);
        
        if(null==password){
            factory.setPassword(ConnectionFactory.DEFAULT_PASS);
        } else {
            factory.setPassword(password);
        }
        
        String virtualHost = context.getString(RabbitMQConstants.CONFIG_VIRTUALHOST);
        
        if(null!=virtualHost){
            factory.setVirtualHost(virtualHost);
        }
        
        int connectionTimeout = context.getInteger(RabbitMQConstants.CONFIG_CONNECTIONTIMEOUT, -1);
        
        if(connectionTimeout>-1){
           factory.setConnectionTimeout(connectionTimeout); 
        }
        
        
        
//        boolean useSSL = context.getBoolean("usessl", false);
//        if(useSSL){
//            factory.useSslProtocol();
//        }
        
        
        return factory;
    }
 
Example 17
Source File: AbstractAMQPProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Connection createConnection(ProcessContext context) {
    final ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(context.getProperty(HOST).evaluateAttributeExpressions().getValue());
    cf.setPort(Integer.parseInt(context.getProperty(PORT).evaluateAttributeExpressions().getValue()));
    cf.setUsername(context.getProperty(USER).evaluateAttributeExpressions().getValue());
    cf.setPassword(context.getProperty(PASSWORD).getValue());

    final String vHost = context.getProperty(V_HOST).evaluateAttributeExpressions().getValue();
    if (vHost != null) {
        cf.setVirtualHost(vHost);
    }

    // handles TLS/SSL aspects
    final Boolean useCertAuthentication = context.getProperty(USE_CERT_AUTHENTICATION).asBoolean();
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    // if the property to use cert authentication is set but the SSL service hasn't been configured, throw an exception.
    if (useCertAuthentication && sslService == null) {
        throw new IllegalStateException("This processor is configured to use cert authentication, " +
                "but the SSL Context Service hasn't been configured. You need to configure the SSL Context Service.");
    }
    final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();

    if (sslService != null) {
        final SslContextFactory.ClientAuth clientAuth;
        if (StringUtils.isBlank(rawClientAuth)) {
            clientAuth = SslContextFactory.ClientAuth.REQUIRED;
        } else {
            try {
                clientAuth = SslContextFactory.ClientAuth.valueOf(rawClientAuth);
            } catch (final IllegalArgumentException iae) {
                throw new IllegalStateException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                        rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
            }
        }
        final SSLContext sslContext = sslService.createSSLContext(clientAuth);
        cf.useSslProtocol(sslContext);

        if (useCertAuthentication) {
            // this tells the factory to use the cert common name for authentication and not user name and password
            // REF: https://github.com/rabbitmq/rabbitmq-auth-mechanism-ssl
            cf.setSaslConfig(DefaultSaslConfig.EXTERNAL);
        }
    }

    try {
        Connection connection = cf.newConnection();
        return connection;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to establish connection with AMQP Broker: " + cf.toString(), e);
    }
}
 
Example 18
Source File: EmbeddedRabbitMqTest.java    From embedded-rabbitmq with Apache License 2.0 4 votes vote down vote up
@Test
  public void start() throws Exception {
    File configFile = temporaryFolder.newFile("rabbitmq.conf");
    PrintWriter writer = new PrintWriter(configFile, "UTF-8");
    writer.println("log.connection.level = debug");
    writer.println("log.channel.level = debug");
    writer.close();

    EmbeddedRabbitMqConfig config = new EmbeddedRabbitMqConfig.Builder()
//        .version(PredefinedVersion.V3_8_0)
        .version(new BaseVersion("3.8.1"))
        .randomPort()
        .downloadFrom(OfficialArtifactRepository.GITHUB)
//        .downloadFrom(new URL("https://github.com/rabbitmq/rabbitmq-server/releases/download/rabbitmq_v3_6_6_milestone1/rabbitmq-server-mac-standalone-3.6.5.901.tar.xz"), "rabbitmq_server-3.6.5.901")
//        .envVar(RabbitMqEnvVar.NODE_PORT, String.valueOf(PORT))
        .envVar(RabbitMqEnvVar.CONFIG_FILE, configFile.toString().replace(".conf", ""))
        .extractionFolder(temporaryFolder.newFolder("extracted"))
        .rabbitMqServerInitializationTimeoutInMillis(TimeUnit.SECONDS.toMillis(20))
        .defaultRabbitMqCtlTimeoutInMillis(TimeUnit.SECONDS.toMillis(20))
        .erlangCheckTimeoutInMillis(TimeUnit.SECONDS.toMillis(10))
//        .useCachedDownload(false)
        .build();

    rabbitMq = new EmbeddedRabbitMq(config);
    rabbitMq.start();
    LOGGER.info("Back in the test!");

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setPort(config.getRabbitMqPort());
    connectionFactory.setVirtualHost("/");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");

    Connection connection = connectionFactory.newConnection();
    assertThat(connection.isOpen(), equalTo(true));
    Channel channel = connection.createChannel();
    assertThat(channel.isOpen(), equalTo(true));

    ProcessResult listUsersResult = new RabbitMqCtl(config, Collections.singletonMap("TEST_ENV_VAR", "FooBar"))
        .execute("list_users")
        .get();

    assertThat(listUsersResult.getExitValue(), is(0));
    assertThat(listUsersResult.getOutput().getString(), containsString("guest"));

    RabbitMqPlugins rabbitMqPlugins = new RabbitMqPlugins(config);
    Map<Plugin.State, Set<Plugin>> groupedPlugins = rabbitMqPlugins.groupedList();
    assertThat(groupedPlugins.get(Plugin.State.ENABLED_EXPLICITLY).size(), equalTo(0));

    rabbitMqPlugins.enable("rabbitmq_management");

    Plugin plugin = rabbitMqPlugins.list().get("rabbitmq_management");
    assertThat(plugin, is(notNullValue()));
    assertThat(plugin.getState(),
        hasItems(Plugin.State.ENABLED_EXPLICITLY, Plugin.State.RUNNING));

    HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:15672").openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    assertThat(urlConnection.getResponseCode(), equalTo(200));
    urlConnection.disconnect();

    rabbitMqPlugins.disable("rabbitmq_management");

    channel.close();
    connection.close();
  }
 
Example 19
Source File: SharedRabbitMQResource.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doInitialize(
    final ResourceSpecifier aSpecifier, final Map<String, Object> aAdditionalParams)
    throws ResourceInitializationException {
  try {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);
    factory.setHost(host);
    factory.setPort(port);

    if (useHttps) {
      if (trustAll) {
        factory.useSslProtocol();
      } else {

        try (FileInputStream keystoreStream = new FileInputStream(keystorePath);
            FileInputStream trustStoreStream = new FileInputStream(truststorePath); ) {

          KeyStore ks = KeyStore.getInstance("PKCS12");
          ks.load(keystoreStream, keystorePass.toCharArray());

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          kmf.init(ks, keystorePass.toCharArray());

          KeyStore tks = KeyStore.getInstance("JKS");
          tks.load(trustStoreStream, truststorePass.toCharArray());

          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
          tmf.init(tks);

          SSLContext c = SSLContext.getInstance(sslProtocol);
          c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

          factory.useSslProtocol(c);
        }
      }
    }

    connection = factory.newConnection();
  } catch (final Exception e) {
    throw new ResourceInitializationException(
        new BaleenException("Error connecting to RabbitMQ", e));
  }

  getMonitor().info("Initialised shared RabbitMQ resource");
  return true;
}
 
Example 20
Source File: EndPoint.java    From flink-learning with Apache License 2.0 4 votes vote down vote up
public EndPoint(String endpointName) throws Exception {
    this.endPointName = endpointName;

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("127.0.0.1");
    factory.setUsername("admin");
    factory.setPassword("admin");
    factory.setPort(5672);

    connection = factory.newConnection();


    channel = connection.createChannel();

    channel.queueDeclare(endpointName, false, false, false, null);
}