List of usage examples for com.rabbitmq.client Channel exchangeDeclare
Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable) throws IOException;
From source file:com.sitewhere.protobuf.test.ActiveMQTests.java
License:Open Source License
@Test public void doRabbitMQTest() throws Exception { String exchangeName = "sitewhere"; String queueName = "SITEWHERE.IN"; String routingKey = "sitewhere"; ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://localhost:5672/SITEWHERE.IN"); 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); byte[] messageBodyBytes = generateEncodedMeasurementsMessage(); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); channel.close();/*from w ww . ja v a2 s.c o m*/ connection.close(); }
From source file:com.sitewhere.sources.ActiveMQTests.java
License:Open Source License
@Test public void doRabbitMQTest() throws Exception { String exchangeName = "sitewhere"; String queueName = "sitewhere.input"; String routingKey = "sitewhere"; ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://localhost:5672"); 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); byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); channel.close();//from w w w. j a v a 2 s . c o m connection.close(); }
From source file:com.siva.rabbitmq.AmqpMsgPublisher.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("admin"); factory.setPassword("welcome01"); factory.setPort(5672);//from w w w . ja va 2 s . co m factory.setVirtualHost("/admin_vhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); String routingKey = "mqtt_topic.iot.admin_vhost"; String message = "Test Message from IoT"; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); connection.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 w w .j a v a 2 s . 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.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./* ww w. ja v a2 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: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 w w . j a va 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:deck36.storm.plan9.RabbitMQDeclarator.java
License:Open Source License
@Override public void execute(Channel channel) { try {/* www .ja v a 2 s . com*/ channel.exchangeDeclare(exchange, // name "topic", // type true // durable? ); channel.queueDeclare(queue, // name true, // durable? false, // exclusive? false, // autoDelete null // Map(<String, Object> arguments ); channel.queueBind(queue, exchange, routingKey); } catch (IOException e) { throw new RuntimeException("Error executing rabbitmq declarations.", e); } }
From source file:edu.jhu.pha.vospace.jobs.JobsProcessorQueuedImpl.java
License:Apache License
@Override public void run() { final JobsProcessor parentProc = this; QueueConnector.goAMQP("submitJob", new QueueConnector.AMQPWorker<Boolean>() { @Override/*from w w w. ja v a 2 s. co m*/ public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel) throws IOException { channel.exchangeDeclare(conf.getString("transfers.exchange.submited"), "topic", true); channel.queueDeclare(conf.getString("transfers.queue.submited.server_initialised"), true, false, false, null); channel.queueBind(conf.getString("transfers.queue.submited.server_initialised"), conf.getString("transfers.exchange.submited"), "direction." + JobDescription.DIRECTION.PUSHFROMVOSPACE); channel.queueBind(conf.getString("transfers.queue.submited.server_initialised"), conf.getString("transfers.exchange.submited"), "direction." + JobDescription.DIRECTION.PULLTOVOSPACE); channel.queueBind(conf.getString("transfers.queue.submited.server_initialised"), conf.getString("transfers.exchange.submited"), "direction." + JobDescription.DIRECTION.LOCAL); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(conf.getString("transfers.queue.submited.server_initialised"), false, consumer); try { // The main cycle to process the jobs while (!jobsThread.isInterrupted()) { for (Iterator<Future<STATE>> it = workers.iterator(); it.hasNext();) { Future<STATE> next = it.next(); if (next.isDone()) { it.remove(); logger.debug("Job " + next + " is removed from the workers."); } } if (workers.size() >= jobsPoolSize) { logger.debug("Waiting for a jobs pool, size: " + workers.size()); synchronized (JobsProcessor.class) { JobsProcessor.class.wait(); } logger.debug("End waiting for a jobs pool, size: " + workers.size()); } else { logger.debug("Waiting for a job"); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); // Job JSON notation JobDescription job = (new ObjectMapper()).readValue(delivery.getBody(), 0, delivery.getBody().length, JobDescription.class); logger.debug("There's a submited job! " + job.getId()); TransferThread thread = new TransferThread(job, parentProc); Future<STATE> future = service.submit(thread); workers.add(future); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (InterruptedException ex) { // server restarted } return true; } }); }
From source file:edu.jhu.pha.vospace.jobs.JobsProcessorQueuedImpl.java
License:Apache License
public void submitJob(final String login, final JobDescription job) { super.submitJob(login, job); if (job.getDirection() == DIRECTION.PUSHFROMVOSPACE || job.getDirection() == DIRECTION.PULLTOVOSPACE || job.getDirection() == DIRECTION.LOCAL) { QueueConnector.goAMQP("submitJob", new QueueConnector.AMQPWorker<Boolean>() { @Override/* w w w . j a va2 s.c om*/ public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel) throws IOException { channel.exchangeDeclare(conf.getString("transfers.exchange.submited"), "topic", true); byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(job); channel.basicPublish(conf.getString("transfers.exchange.submited"), "direction." + job.getDirection(), null, jobSer); return true; } }); } }
From source file:edu.jhu.pha.vospace.node.ContainerNode.java
License:Apache License
@Override public void copy(VospaceId newLocationId, boolean keepBytes) { if (!isStoredMetadata()) throw new NotFoundException("NodeNotFound"); if (getMetastore().isStored(newLocationId)) { throw new ForbiddenException("DestinationNodeExists"); }/*from w w w . ja va2s .c o m*/ if (newLocationId.getNodePath().isParent(this.getUri().getNodePath())) { throw new ForbiddenException("Forbidden to copy into itself"); } Node newDataNode = NodeFactory.createNode(newLocationId, owner, this.getType()); newDataNode.setNode(null); newDataNode.getStorage().updateNodeInfo(newLocationId.getNodePath(), newDataNode.getNodeInfo()); newDataNode.getMetastore().storeInfo(newLocationId, newDataNode.getNodeInfo()); newDataNode.getMetastore().updateUserProperties(newLocationId, getNodeMeta(PropertyType.property)); NodesList childrenList = getDirectChildren(false, 0, -1); List<Node> children = childrenList.getNodesList(); for (Node child : children) { Node childNode = NodeFactory.getNode(child.getUri(), owner); String relativePath = childNode.getUri().getNodePath() .getParentRelativePath(this.getUri().getNodePath()); try { VospaceId newChildId = newLocationId.appendPath(new NodePath(relativePath)); logger.debug("Copying child " + childNode.getUri() + " with relpath " + relativePath + " to " + newChildId.toString()); childNode.copy(newChildId, keepBytes); } catch (URISyntaxException e) { logger.error("Error copying child " + childNode.getUri().toString() + ": " + e.getMessage()); } } if (!keepBytes) { getMetastore().remove(this.getUri()); if (this.getUri().getNodePath().getNodeStoragePathArray().length == 1) { // moving first-level container to another one getStorage().remove(this.getUri().getNodePath(), false); } } QueueConnector.goAMQP("movedNode", new QueueConnector.AMQPWorker<Boolean>() { @Override public Boolean go(com.rabbitmq.client.Connection conn, com.rabbitmq.client.Channel channel) throws IOException { channel.exchangeDeclare(conf.getString("vospace.exchange.nodechanged"), "fanout", false); Map<String, Object> nodeData = new HashMap<String, Object>(); nodeData.put("uri", getUri().toString()); nodeData.put("owner", getOwner()); nodeData.put("container", getUri().getNodePath().getParentPath().getNodeStoragePath()); byte[] jobSer = (new ObjectMapper()).writeValueAsBytes(nodeData); channel.basicPublish(conf.getString("vospace.exchange.nodechanged"), "", null, jobSer); return true; } }); }