List of usage examples for com.rabbitmq.client Channel exchangeDeclare
Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type) throws IOException;
From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.channel.ARabbitChannel.java
License:Apache License
protected Channel getChannel() throws ChannelException { try {//from w w w .j a v a 2s .c o m synchronized (connectionFactory) { if (connection == null) { try { String host = discovery.discoverHost(); if (host == null || host.isEmpty()) { throw new ChannelException(String.format("Discovery returned invalid host: %s", host)); } connectionFactory.setHost(host); connection = connectionFactory.newConnection(); } catch (IOException | DiscoveryException ex) { //we do not reconnect in here do to the fact //that we are discarding messages which are //send during a disconnection phase throw new ChannelException("Exception while connecting to RabbitMQ!", ex); } } } Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); return channel; } catch (IOException ex) { //in case we can not create a channel //try to establish a new connection try { //try to close old connection never the less connection.close(); } catch (IOException ex1) { //ignore } connection = null; return this.getChannel(); } }
From source file:com.ericsson.research.IoTFrameworkEndpoint.java
License:Open Source License
public void subscribe(String hostName, String StreamId, final DataPointCallback dataPointCallback) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); // listening on port 5672 Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); final String EXCHANGE_NAME = "streams." + StreamId; channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_NAME, ""); dataPointCallback.setConnection(connection); boolean autoAck = true; channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) { @Override// w ww . j av a 2s . com public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { DataPointNotification notification = gson.fromJson(new String(body), DataPointNotification.class); dataPointCallback.handleNotification(notification); } }); }
From source file:com.es.dashboard.ConnectionBroker.java
@PostConstruct public void init() { bigBaite = new LinkedList<>(); readings = new ArrayList<Reading>(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = null; try {// www. j a va 2 s.c om connection = factory.newConnection(); } catch (IOException ex) { logger.error(ex); } catch (TimeoutException ex) { logger.error(ex); } Channel channel = null; try { channel = connection.createChannel(); } catch (IOException ex) { logger.error(ex); } try { channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange } catch (IOException ex) { logger.error(ex); } AMQP.Queue.DeclareOk result = null; try { result = channel.queueDeclare("", false, true, false, null); } catch (IOException ex) { logger.error(ex); } String queuename = result.getQueue(); try { channel.queueBind(queuename, "sensors", "realtime.sensordata"); // Binding key is #, this will consume all messages channel.queueBind(queuename, "sensors", "realtime.alarms"); // Binding key is #, this will consume all messages } catch (IOException ex) { logger.error(ex); } logger.info(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); EventBus eventBus = EventBusFactory.getDefault().eventBus(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> myMap = gson.fromJson(message, type); if (envelope.getRoutingKey().equals("realtime.alarms")) { eventBus.publish("/channel", message); return; } logger.info(envelope.getRoutingKey()); readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("data"), myMap.get("name"), myMap.get("room"))); eventBus.publish("/channel", message); } }; try { //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}" // + "var timeoutdummy = window.setInterval(rpt,2000);"); channel.basicConsume(queuename, true, consumer); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex); } }
From source file:com.es.dashboard.ConnectionBrokerJPA.java
@PostConstruct public void init() { bigBaite = new LinkedList<>(); readings = new ArrayList<Reading>(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = null; try {/*from w ww . j av a2 s . co m*/ connection = factory.newConnection(); } catch (IOException ex) { logger.error(ex); } catch (TimeoutException ex) { logger.error(ex); } Channel channel = null; try { channel = connection.createChannel(); } catch (IOException ex) { logger.error(ex); } try { channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange } catch (IOException ex) { logger.error(ex); } AMQP.Queue.DeclareOk result = null; try { result = channel.queueDeclare("", false, true, false, null); } catch (IOException ex) { logger.error(ex); } String queuename = result.getQueue(); try { channel.queueBind(queuename, "sensors", "dashboard.response"); // Binding key is #, this will consume all messages } catch (IOException ex) { logger.error(ex); } logger.info(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); EventBus eventBus = EventBusFactory.getDefault().eventBus(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> myMap = gson.fromJson(message, type); if (envelope.getRoutingKey().equals("realtime.alarms")) { eventBus.publish("/jpa", message); return; } System.out.println(envelope.getRoutingKey()); logger.info(envelope.getRoutingKey()); //readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("value"), myMap.get("name"), myMap.get("room"))); //System.out.println("publishing " + msg_to_publish); eventBus.publish("/jpa", message); //System.out.println("published"); } }; try { //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}" // + "var timeoutdummy = window.setInterval(rpt,2000);"); channel.basicConsume(queuename, true, consumer); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex); } }
From source file:com.es.dashboard.ConnectionBrokerJPA.java
public void requestData() throws IOException, TimeoutException, InterruptedException { System.out.println("ran"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("sensors", "topic"); JSONObject json = new JSONObject(); json.put("name", "Temperatura dos Narcisos"); json.put("room", "masterbath"); json.put("start", System.currentTimeMillis() - 3600000); json.put("end", System.currentTimeMillis()); channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes()); json = new JSONObject(); json.put("name", "Humidade da Cave"); json.put("room", "masterbath"); json.put("start", System.currentTimeMillis() - 3600000); json.put("end", System.currentTimeMillis()); channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes()); json = new JSONObject(); json.put("name", "Luminosidade da Estufa"); json.put("room", "masterbath"); json.put("start", System.currentTimeMillis() - 3600000); json.put("end", System.currentTimeMillis()); channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes()); json = new JSONObject(); json.put("name", "Sensor de Fumo"); json.put("room", "masterbath"); json.put("start", System.currentTimeMillis() - 3600000); json.put("end", System.currentTimeMillis()); channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes()); //System.err.println("booting"); }
From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java
public static void main(String[] args) { //activate logging level if it is DEBUG, default is INFO so no need for any //action if it is otherwise Injector propInjector = Guice.createInjector(new GeminiPropertiesModule()); GeminiProperties properties = propInjector.getInstance(GeminiProperties.class); if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) { Configurator.defaultConfig().level(Level.DEBUG).activate(); }/*from w w w . j av a 2 s . co m*/ //inject the mapper as it will be used in all the threads Injector mapperInjector = Guice.createInjector(new GeminiMapperModule()); mapper = mapperInjector.getInstance(GeminiMapper.class); //the app.yml to deployment.yml converter Thread yamlConverterThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("YAML_MAPPER_TOPIC")); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex); continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE Integer status = 0; if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) { status = mapApptoDeployment(jsonBody); } else { continue; } if (status == 0) { try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } else { //failed so requeue the message try { channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); } catch (IOException ex) { Logger.error("Could not nack message. Exception: {}", ex); } } } }); yamlConverterThread.start(); //the networking message recevier Thread networkingThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("NETWORK_TOPIC")); // channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT"))); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Could not get message from queue. Exception: {}", ex); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) { createNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) { updateNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) { deleteNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) { createSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) { updateSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) { deleteSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) { createRouter(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) { updateRouter(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) { deleteRouter(jsonBody); } try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } }); networkingThread.start(); //the load balancer Thread lbThread = new Thread(() -> { }); lbThread.start(); //the security thread Thread securityThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("SECURITY_TOPIC")); // channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT"))); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Could not get message from queue. Exception: {}", ex); continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) { createSecurityGroup(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) { updateSecurityGroup(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) { deleteSecurityGroup(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) { createSecurityGroupRule(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) { updateSecurityGroupRule(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) { deleteSecurityGroupRule(jsonBody); } try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } }); securityThread.start(); }
From source file:com.github.dann.wspusher.pubsub.publisher.impl.RabbitMQPublisherImpl.java
License:Apache License
public void publish(String exchange, String message) { Connection connection = null; Channel channel = null; try {/*from w w w. j ava2s . c om*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(WsConfig.getMQServerHost()); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(exchange, EXCHANGE_TYPE); channel.basicPublish(exchange, "", null, message.getBytes(WsConstants.ENCODING_UTF8)); } catch (Exception e) { logger.error("Publishing message faile", e); throw new WsRuntimeException("Publishig message failed", e); } finally { RabbitMQResourceUtils.closeQuietly(channel); RabbitMQResourceUtils.closeQuietly(connection); } }
From source file:com.github.dann.wspusher.pubsub.subscriber.impl.RabbitMQSubscriberImpl.java
License:Apache License
@Override public void subscribe(String exchange, DataPusherWebSocket webSocket) { Connection connection = null; Channel channel = null; try {/* w w w. jav a 2 s . c o m*/ // FIXME Cache connection! ConnectionFactory factory = new ConnectionFactory(); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(exchange, DEFAULT_EXCHANGE_TYPE); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchange, ""); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); doWork(consumer, webSocket); } catch (Exception e) { logger.error("Error occured", e); throw new WsRuntimeException(e); } finally { RabbitMQResourceUtils.closeQuietly(channel); RabbitMQResourceUtils.closeQuietly(connection); } }
From source file:com.groupx.recipientlist.test.RecipientList.java
public static void main(String[] argv) throws java.io.IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String message = getMessage(argv); channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close();//w ww . j a v a 2 s .com connection.close(); }
From source file:com.groupx.recipientlist.test.TranslatorMock.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_NAME, ""); System.out.println(" [*] Waiting for messages. To exit press X+ENTER"); Consumer consumer = new DefaultConsumer(channel) { @Override/*from w ww. j a v a 2 s . com*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(queueName, true, consumer); try { Scanner in = new Scanner(System.in); String input = in.next(); if ("x".equals(input)) { System.exit(0); } } catch (Exception e) { } }