List of usage examples for com.rabbitmq.client ConnectionFactory setVirtualHost
public void setVirtualHost(String virtualHost)
From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java
License:Apache License
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());/*www. j a v a 2 s . c om*/ optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments formatter.setOptionComparator((o1, o2) -> { // I know this isn't fast, but who cares! The list is short. //noinspection SuspiciousMethodCalls return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2)); }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = ThreadLocalRandom.current(); Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line)); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java
License:Apache License
/** * * @return Connection Factory for RMQ//from w ww. ja v a 2s .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; }
From source file:org.apache.flume.amqp.AmqpSource.java
License:Apache License
@VisibleForTesting static ConnectionFactory createConnectionFactoryFrom(Context context) { String host = context.getString(AmqpSourceConfigurationConstants.HOST, Constants.Defaults.HOST); int port = context.getInteger(AmqpSourceConfigurationConstants.PORT, Constants.Defaults.PORT); String virtualHost = context.getString(AmqpSourceConfigurationConstants.VIRTUAL_HOST, Constants.Defaults.VIRTUAL_HOST); String userName = context.getString(AmqpSourceConfigurationConstants.USER_NAME, Constants.Defaults.USER_NAME); String password = context.getString(AmqpSourceConfigurationConstants.PASSWORD, Constants.Defaults.PASSWORD); int connectionTimeout = context.getInteger(AmqpSourceConfigurationConstants.CONNECTION_TIMEOUT, Constants.Defaults.CONNECTION_TIMEOUT); int requestHeartbeat = context.getInteger(AmqpSourceConfigurationConstants.REQUEST_HEARTBEAT, Constants.Defaults.REQUESTED_HEARTBEAT); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(host);/* ww w. j a va 2s . c o m*/ connectionFactory.setPort(port); connectionFactory.setVirtualHost(virtualHost); connectionFactory.setUsername(userName); connectionFactory.setPassword(password); connectionFactory.setConnectionTimeout(connectionTimeout); connectionFactory.setRequestedHeartbeat(requestHeartbeat); return connectionFactory; }
From source file:org.apache.flume.RabbitMQUtil.java
License:Apache License
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);/*from w ww.j av a2 s. c o m*/ 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; }
From source file:org.apache.nifi.amqp.processors.AbstractAMQPProcessor.java
License:Apache License
/** * Creates {@link Connection} to AMQP system. *///from ww w. ja v a 2 s. c o m private Connection createConnection(ProcessContext context) { ConnectionFactory cf = new ConnectionFactory(); cf.setHost(context.getProperty(HOST).getValue()); cf.setPort(Integer.parseInt(context.getProperty(PORT).getValue())); cf.setUsername(context.getProperty(USER).getValue()); cf.setPassword(context.getProperty(PASSWORD).getValue()); String vHost = context.getProperty(V_HOST).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 ProviderCreationException("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 SSLContextService.ClientAuth clientAuth; if (StringUtils.isBlank(rawClientAuth)) { clientAuth = SSLContextService.ClientAuth.REQUIRED; } else { try { clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException( 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); } }
From source file:org.apache.nutch.fetcher.RabbitmqProxy.java
License:Apache License
private RabbitmqProxy(Configuration configuration) { try {/*from w w w . j a v a 2 s . c o m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(configuration.get("rabbitmq.ip")); factory.setUsername(configuration.get("rabbitmq.username")); factory.setPassword(configuration.get("rabbitmq.password")); factory.setVirtualHost(configuration.get("rabbitmq.virtualhost")); connection = factory.newConnection(); channel = connection.createChannel(); exchange_name = configuration.get("rabbitmq.exchange"); channel.exchangeDeclare(exchange_name, "fanout"); } catch (java.io.IOException e) { LOG.fatal(e); } }
From source file:org.apache.nutch.indexwriter.rabbit.RabbitIndexWriter.java
License:Apache License
@Override public void open(JobConf JobConf, String name) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(serverHost);//from ww w . j a v a 2 s.co m factory.setPort(serverPort); if (serverVirtualHost != null) { factory.setVirtualHost(serverVirtualHost); } factory.setUsername(serverUsername); factory.setPassword(serverPassword); try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(exchangeServer, exchangeType, true); channel.queueDeclare(queueName, queueDurable, false, false, null); channel.queueBind(queueName, exchangeServer, queueRoutingKey); } catch (TimeoutException | IOException ex) { throw makeIOException(ex); } }
From source file:org.apache.nutch.publisher.rabbitmq.RabbitMQPublisherImpl.java
License:Apache License
@Override public boolean setConfig(Configuration conf) { try {/*from w ww . j a v a 2 s .com*/ EXCHANGE_SERVER = conf.get("rabbitmq.exchange.server", "fetcher_log"); EXCHANGE_TYPE = conf.get("rabbitmq.exchange.type", "fanout"); HOST = conf.get("rabbitmq.host", "localhost"); PORT = conf.getInt("rabbitmq.port", 5672); VIRTUAL_HOST = conf.get("rabbitmq.virtualhost", null); USERNAME = conf.get("rabbitmq.username", null); PASSWORD = conf.get("rabbitmq.password", null); QUEUE_NAME = conf.get("rabbitmq.queue.name", "fanout.queue"); QUEUE_DURABLE = conf.getBoolean("rabbitmq.queue.durable", true); QUEUE_ROUTING_KEY = conf.get("rabbitmq.queue.routingkey", "fanout.key"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST); factory.setPort(PORT); if (VIRTUAL_HOST != null) { factory.setVirtualHost(VIRTUAL_HOST); } if (USERNAME != null) { factory.setUsername(USERNAME); factory.setPassword(PASSWORD); } Connection connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_SERVER, EXCHANGE_TYPE); channel.queueDeclare(QUEUE_NAME, QUEUE_DURABLE, false, false, null); channel.queueBind(QUEUE_NAME, EXCHANGE_SERVER, QUEUE_ROUTING_KEY); LOG.info("Configured RabbitMQ publisher"); return true; } catch (Exception e) { LOG.error("Could not initialize RabbitMQ publisher - {}", StringUtils.stringifyException(e)); return false; } }
From source file:org.apache.nutch.rabbitmq.RabbitMQClient.java
License:Apache License
/** * Builds a new instance of {@link RabbitMQClient} * * @param serverHost The server host. * @param serverPort The server port. * @param serverVirtualHost The virtual host into the RabbitMQ server. * @param serverUsername The username to access the server. * @param serverPassword The password to access the server. * @throws IOException It is thrown if there is some issue during the connection creation. *///from w ww . ja v a 2 s . c o m public RabbitMQClient(String serverHost, int serverPort, String serverVirtualHost, String serverUsername, String serverPassword) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(getValue(serverHost, "localhost")); factory.setPort(getValue(serverPort, 5672)); factory.setVirtualHost(getValue(serverVirtualHost, "/")); factory.setUsername(getValue(serverUsername, "guest")); factory.setPassword(getValue(serverPassword, "guest")); try { connection = factory.newConnection(); } catch (TimeoutException e) { throw makeIOException(e); } }
From source file:org.belio.mq.RabbitConsumer.java
@Override public void open() throws IOException { try {//from w ww.j av a2 s.co m com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); factory.setHost(mqproperties.getProperty("host")); factory.setVirtualHost(mqproperties.getProperty("vhost")); factory.setUsername(mqproperties.getProperty("username")); factory.setPassword(mqproperties.getProperty("password")); factory.setPort(Integer.parseInt(mqproperties.getProperty("port"))); factory.setAutomaticRecoveryEnabled(true); factory.setNetworkRecoveryInterval(1); // Create a new connection to MQ connection = factory.newConnection(); // Create a new channel and declare it's type and exhange as well //Create a new rabbit publisher executor = Executors.newScheduledThreadPool( Integer.parseInt(threadproperties.getProperty(queueType.name().toLowerCase()).split(",")[0])); } catch (IOException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } catch (ShutdownSignalException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } catch (ConsumerCancelledException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } }