List of usage examples for com.rabbitmq.client Channel close
@Override void close() throws IOException, TimeoutException;
From source file:com.trivago.mail.pigeon.daemon.Daemon.java
License:Apache License
/** * Main Daemon method containing the event loop. * * @param args command line args//from w w w. ja va 2 s. c om * @throws java.io.IOException */ public static void main(String[] args) throws IOException { Connection conn = null; Channel channel = null; try { conn = ConnectionPool.getConnection(); channel = conn.createChannel(); boolean autoAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(channelName, autoAck, consumer); MailFacade mailFacade = new MailFacade(); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(); } catch (InterruptedException ie) { continue; } String jsonContent = new String(delivery.getBody()); MailTransport mailTransport = JSONParser.defaultJSONParser().parse(MailTransport.class, jsonContent); mailFacade.sendMail(mailTransport); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } finally { if (channel != null) { channel.close(); } if (conn != null) { conn.close(); } } }
From source file:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java
License:Apache License
private void queueNewsletter(Mail mail, Sender sender, Recipient recipient, Campaign campaign) { Connection conn = ConnectionPool.getConnection(); Channel channel = null; MailTransport transport = templateProcessor.processMail(mail, recipient, sender, campaign); if (transport == null) { log.warn(/* w ww . j a v a 2s. c om*/ "Template processor returned null instead of a mail transport object. This is probably a bug!"); return; } if (transport.shouldAbortSending() && !transport.shouldEnforceSending()) { log.info("Skipped mail to " + transport.getTo() + " because transport aborted sending."); return; } String json = JSON.defaultJSON().forValue(transport); try { channel = conn.createChannel(); channel.exchangeDeclare("mailpidgeon", "direct", true); channel.queueDeclare(channelName, true, false, false, null); channel.queueBind(channelName, "mailpidgeon", "mailpidgeon"); byte[] messageBodyBytes = json.getBytes(); channel.basicPublish("mailpidgeon", "mailpidgeon", null, messageBodyBytes); } catch (IOException e) { log.error(e); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { log.error("Could not close channel", e); } } } }
From source file:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java
License:Apache License
public int getProgress(long newsletterId) { Connection conn = ConnectionPool.getConnection(); Channel channel = null; try {/*from w ww .ja va2s . c o m*/ channel = conn.createChannel(); AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(channelName); return declareOk.getMessageCount(); } catch (Exception e) { log.error("Error while fetching progress", e); } finally { assert channel != null; try { channel.close(); } catch (IOException e) { log.error("Could not close channel", e); } } return 0; }
From source file:com.UseCaseSimpleConsumer.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try {/* w w w . j a va 2 s . com*/ channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); } try { channel.queueDeclarePassive(ROUTE_KEY); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.queueDeclare(ROUTE_KEY, false, false, false, null); } channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY); String param = "IBM"; String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + " <m:order>\n" + " <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + " <m:quantity>" + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + " <m:symbol>" + param + "</m:symbol>\n" + " </m:order>\n" + "</m:placeOrder>"; channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY, new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes()); System.out.println(" [x] Sent '" + msg + "'"); channel.close(); connection.close(); }
From source file:com.vmware.bdd.utils.RabbitMQConsumer.java
License:Open Source License
/** * Receive and process each message until the listener indicating. A new * queue will be created when start and will be deleted when stopping * receiving message.//from w w w.j a v a 2 s . co m * * FIXME Is it a best practice to create one queue for one task? Or we should * create one thread to handle all messages? * * @param listener * message processor callback * @throws IOException */ public void processMessage(MessageListener listener) throws IOException { ConnectionFactory factory = new ConnectionFactory(); if (username != null && !username.equals("")) { factory.setUsername(username); factory.setPassword(password); } factory.setVirtualHost("/"); factory.setHost(host); factory.setPort(port); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); /** * make exchange and queue non-durable */ channel.exchangeDeclare(exchangeName, "direct", true); if (!getQueue) { channel.queueDeclare(queueName, false, true, true, null); } else { queueName = channel.queueDeclare().getQueue(); } channel.queueBind(queueName, exchangeName, routingKey); boolean noAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, noAck, consumer); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(mqRecvTimeoutMs); } catch (InterruptedException e) { logger.warn("message consumer interrupted", e); continue; } if (delivery == null) { logger.debug("timeout, no message received"); if (stopping && new Date().after(mqExpireTime)) { logger.error("stop receiving messages without normal termination"); break; } continue; } String message = new String(delivery.getBody()); if (graceStopping) { extendExpirationTime(); } logger.info("message received: " + message); try { if (!listener.onMessage(message)) { logger.info("stop receiving messages normally"); break; } } catch (Throwable t) { logger.error("calling message listener failed", t); // discard and continue in non-debug mode AuAssert.unreachable(); } channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } try { channel.queueDelete(queueName); } catch (AlreadyClosedException e) { logger.error("failed to delete queue: " + queueName, e); } try { channel.close(); } catch (AlreadyClosedException e) { logger.error("failed to close channel, queue: " + queueName, e); } try { conn.close(); } catch (AlreadyClosedException e) { logger.error("failed to close connection, queue: " + queueName, e); } }
From source file:com.wakkir.rabbitmq.basic.Sender.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.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close();//from w ww.ja va 2s.co m }
From source file:com.zuehlke.carrera.javapilot.show.ConfirmDontLoseMessages.java
License:Mozilla Public License
public static void main1(String[] args) throws IOException, InterruptedException, TimeoutException { connectionFactory = new ConnectionFactory(); String POWER_QUEUE = "/app/pilots/power"; String json = new JacksonSerializer().serialize(new PowerControl(200, "team", "access", 0L)); Connection conn = connectionFactory.newConnection(); Channel ch = conn.createChannel(); //ch.queueDeclare(POWER_QUEUE, true, false, false, null); AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().expiration("0").build(); ch.basicPublish("", POWER_QUEUE, props, json.getBytes()); String SENSOR_QUEUE = "/topic/pilots/starterkit/sensor"; SensorEvent sensorEvent = SensorEvent.createEmptyCarSensor().withRaceTrackId("simulator"); json = new JacksonSerializer().serialize(sensorEvent); //ch.queueDeclare(SENSOR_QUEUE, true, false, false, null); ch.basicPublish("", SENSOR_QUEUE, props, json.getBytes()); ch.close(); conn.close();//w w w .ja va2 s. c om }
From source file:controllers.TargetController.java
License:Open Source License
/** * This method pushes a message onto a RabbitMQ queue for given target * using global settings from project configuration file. * * @param target The field URL of the target * @return// w ww. j av a 2 s . c o m */ public static Result archive(Long id) { Target target = Target.findById(id); Logger.debug("archiveTarget() " + target); if (target != null) { if (!target.isInScopeAllOrInheritedWithoutLicense()) { return ok(infomessage.render("On-demand archiving is only supported for NPLD targets.")); } // Send the message: try { String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST); String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT); String queueName = Play.application().configuration().getString(Const.QUEUE_NAME); String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY); String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME); Logger.debug("archiveTarget() queue host: " + queueHost); Logger.debug("archiveTarget() queue port: " + queuePort); Logger.debug("archiveTarget() queue name: " + queueName); Logger.debug("archiveTarget() routing key: " + routingKey); Logger.debug("archiveTarget() exchange name: " + exchangeName); JsonNode jsonData = Json.toJson(target); String message = jsonData.toString(); Logger.debug("Crawl Now message: " + message); ConnectionFactory factory = new ConnectionFactory(); if (queueHost != null) { factory.setHost(queueHost); } if (queuePort != null) { factory.setPort(Integer.parseInt(queuePort)); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); BasicProperties.Builder propsBuilder = new BasicProperties.Builder(); propsBuilder.deliveryMode(2); channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes()); channel.close(); connection.close(); } catch (IOException e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } catch (Exception e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } } else { Logger.debug("There was a problem sending the message. Target field for archiving is empty"); return ok(infomessage .render("There was a problem sending the message. Target field for archiving is empty")); } return ok(ukwalicenceresult.render()); }
From source file:de.dhbw.mannheim.erpsim.ErpSimulator.java
License:Open Source License
/** * * * @param args command line parameter/*from w w w .j a v a2s . c o m*/ * args[0] number of customer orders that should be created * args[1] hostname of rabbitMQ * @throws IOException */ public static void main(String[] args) throws IOException { int numOfCustomerOrder = 10; String rabbitMqHostName = "localhost"; String rabbitMqUserName = null; String rabbitMqPassword = null; if (args.length >= 1) { try { numOfCustomerOrder = Integer.parseInt(args[0]); System.out.println("Number of customer orders: " + numOfCustomerOrder); } catch (Exception e) { System.err.println("Could not parse number of customer orders " + args[0]); } } if (args.length >= 2 && args[1] != null) { rabbitMqHostName = args[1]; System.out.println("Host of rabbitMq: " + rabbitMqHostName); } if (args.length >= 4 && args[2] != null && args[3] != null) { rabbitMqUserName = args[2]; rabbitMqPassword = args[3]; System.out.println("Username of rabbitMq: " + rabbitMqUserName); } CustomerOrder[] customerOrders = new CustomerOrder[numOfCustomerOrder]; for (int i = 0; i < customerOrders.length; i++) { customerOrders[i] = CustomerOrderGenerator.getCustomOrder(); } XStream xstream = new XStream(); xstream.registerConverter(new Converter() { @Override public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) { MachineOrder mo = (MachineOrder) o; writer.startNode("id"); writer.setValue(mo.getId()); writer.endNode(); } @Override public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) { return null; } @Override public boolean canConvert(Class aClass) { return aClass == MachineOrder.class; } }); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMqHostName); if (rabbitMqPassword != null && rabbitMqUserName != null) { factory.setUsername(rabbitMqUserName); factory.setPassword(rabbitMqPassword); } Connection connection = factory.newConnection(); Channel channelCO = connection.createChannel(); channelCO.exchangeDeclare(CUSTOMER_ORDER_EXCHANGE_NAME, "fanout"); for (CustomerOrder co : customerOrders) { String message = xstream.toXML(co); channelCO.basicPublish(CUSTOMER_ORDER_EXCHANGE_NAME, "", null, message.getBytes()); System.out.println("Send customer order"); } channelCO.close(); Channel channelMO = connection.createChannel(); channelMO.exchangeDeclare(MACHINE_ORDER_EXCHANGE_NAME, "fanout"); MachineOrder mo = MachineOrderGenerator.getRandomMachineOrder(); xstream = new XStream(); // reconstruct XStream to parse the full machine order, not just only the id while (mo != null) { int i = System.in.read(); String message = xstream.toXML(mo); channelMO.basicPublish(MACHINE_ORDER_EXCHANGE_NAME, "", null, message.getBytes()); System.out.println("Send Machine order"); mo = MachineOrderGenerator.getRandomMachineOrder(); } channelMO.close(); connection.close(); }
From source file:dk.bankjsonrabbit.messaging.Send.java
public static void sendMessage(String message, BasicProperties props) throws IOException, TimeoutException { String taskQueueName = props.getReplyTo(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(taskQueueName, true, false, false, null); channel.basicPublish("", taskQueueName, props, message.getBytes()); channel.close(); connection.close();/* w ww . j av a2 s .c om*/ }