List of usage examples for com.rabbitmq.client Envelope getDeliveryTag
public long getDeliveryTag()
From source file:it.polimi.tower4clouds.observers.hdb.manager.Queue.java
License:Apache License
private void internalAddSubscription(MessageParser pars) throws IOException { boolean autoAck = false; if (this.parser != null) { internalRemoveSubscription();// ww w .jav a2s . co m } this.parser = pars; channel.basicConsume(queueName, autoAck, queueName + "@" + queueHost, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); String message = new String(body); logger.debug("Message received:\n{}", message); parser.parseMessage(message); channel.basicAck(deliveryTag, false); } }); }
From source file:mapas.Mapas.java
public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPassword("test"); factory.setUsername("test"); final Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1);/*from w w w . ja v a2s . c o m*/ final 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"); System.out.println(" [x] Received '" + message + "'"); try { doWork(message); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(" [x] Done"); channel.basicAck(envelope.getDeliveryTag(), false); } }; channel.basicConsume(TASK_QUEUE_NAME, false, consumer); }
From source file:mobisocial.musubi.service.AMQPService.java
License:Apache License
void attachToQueues() throws IOException { Log.i(TAG, "Setting up identity exchange and device queue"); DefaultConsumer consumer = new DefaultConsumer(mIncomingChannel) { @Override/*from w w w . j a va2 s.c o m*/ public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException { if (DBG) Log.i(TAG, "recevied message: " + envelope.getExchange()); assert (body != null); //TODO: throttle if we have too many incoming? //TODO: check blacklist up front? //TODO: check hash up front? MEncodedMessage encoded = new MEncodedMessage(); encoded.encoded_ = body; mEncodedMessageManager.insertEncoded(encoded); getContentResolver().notifyChange(MusubiService.ENCODED_RECEIVED, null); //we have to do this in our AMQP thread, or add synchronization logic //for all of the AMQP related fields. mAMQPHandler.post(new Runnable() { public void run() { if (mIncomingChannel == null) { //it can close in this time window return; } try { mIncomingChannel.basicAck(envelope.getDeliveryTag(), false); if (mFailedOperation == FailedOperationType.FailedReceive) { mFailureDelay = MIN_DELAY; mFailedOperation = FailedOperationType.FailedNone; } } catch (Throwable e) { Log.e(TAG, "failed to ack message on AMQP", e); //next connection that receives a packet wins closeConnection(FailedOperationType.FailedReceive); } } }); } }; byte[] device_name = new byte[8]; ByteBuffer.wrap(device_name).putLong(mDeviceManager.getLocalDeviceName()); String device_queue_name = encodeAMQPname("ibedevice-", device_name); //leaving these since they mark the beginning of the connection and shouldn't be too frequent (once per drop) Log.v(TAG, "queueDeclare " + device_queue_name); mIncomingChannel.queueDeclare(device_queue_name, true, false, false, null); //TODO: device_queue_name needs to involve the identities some how? or be a larger byte array List<MIdentity> mine = mIdentitiesManager.getOwnedIdentities(); for (MIdentity me : mine) { IBHashedIdentity id = IdentitiesManager.toIBHashedIdentity(me, 0); String identity_exchange_name = encodeAMQPname("ibeidentity-", id.identity_); Log.v(TAG, "exchangeDeclare " + identity_exchange_name); mIncomingChannel.exchangeDeclare(identity_exchange_name, "fanout", true); Log.v(TAG, "queueBind " + device_queue_name + " " + identity_exchange_name); mIncomingChannel.queueBind(device_queue_name, identity_exchange_name, ""); try { Log.v(TAG, "queueDeclarePassive " + "initial-" + identity_exchange_name); Channel incoming_initial = mConnection.createChannel(); incoming_initial.queueDeclarePassive("initial-" + identity_exchange_name); try { Log.v(TAG, "queueUnbind " + "initial-" + identity_exchange_name + " " + identity_exchange_name); // we now have claimed our identity, unbind this queue incoming_initial.queueUnbind("initial-" + identity_exchange_name, identity_exchange_name, ""); //but also drain it } catch (IOException e) { } Log.v(TAG, "basicConsume " + "initial-" + identity_exchange_name); mIncomingChannel.basicConsume("initial-" + identity_exchange_name, consumer); } catch (IOException e) { //no one sent up messages before we joined //IF we deleted it: we already claimed our identity, so we ate this queue up } } Log.v(TAG, "basicConsume " + device_queue_name); mIncomingChannel.basicConsume(device_queue_name, false, "", true, true, null, consumer); }
From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java
License:Apache License
private DefaultConsumer getDefaultConsumer(Channel channel, String flag, String exchange, String routingKey, String queueName, Consumer<String> consumer) { return new DefaultConsumer(channel) { @Override//from ww w.j a v a 2 s. c om public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { setMQHeader(flag, properties.getHeaders()); String message = new String(body, StandardCharsets.UTF_8); Object funResult = receiveBeforeFun.invoke(exchange, routingKey, queueName, properties); try { consumer.accept(message); } catch (RuntimeException e) { receiveErrorFun.invoke(e, funResult); throw e; } finally { channel.basicAck(envelope.getDeliveryTag(), false); receiveFinishFun.invoke(funResult); } } }; }
From source file:net.echinopsii.ariane.community.messaging.rabbitmq.MsgTranslator.java
License:Open Source License
/** * Decode given Message into Map message * @param message a RabbitMQ friendly message * @return Map message/*from ww w . j av a 2 s .c om*/ */ @Override public Map<String, Object> decode(Message message) { Envelope envelope = message.getEnvelope(); BasicProperties properties = (BasicProperties) message.getProperties(); byte[] body = message.getBody(); LinkedHashMap<String, Object> decodedMessage = new LinkedHashMap<String, Object>(); if (envelope != null) { decodedMessage.put(MSG_RBQ_DELIVERY_TAG, envelope.getDeliveryTag()); decodedMessage.put(MSG_RBQ_EXCHANGE, envelope.getExchange()); decodedMessage.put(MSG_RBQ_ROUTINGKEY, envelope.getRoutingKey()); } if (properties != null) { decodedMessage.put(MSG_APPLICATION_ID, properties.getAppId()); decodedMessage.put(MSG_RBQ_CONTENT_ENCODING, properties.getContentEncoding()); decodedMessage.put(MSG_RBQ_CONTENT_TYPE, properties.getContentType()); decodedMessage.put(MSG_CORRELATION_ID, properties.getCorrelationId()); decodedMessage.put(MSG_DELIVERY_MODE, properties.getDeliveryMode()); decodedMessage.put(MSG_EXPIRATION, properties.getExpiration()); decodedMessage.put(MSG_MESSAGE_ID, properties.getMessageId()); decodedMessage.put(MSG_PRIORITY, properties.getPriority()); decodedMessage.put(MSG_REPLY_TO, properties.getReplyTo()); decodedMessage.put(MSG_TIMESTAMP, properties.getTimestamp()); decodedMessage.put(MSG_TYPE, properties.getType()); decodedMessage.put(MSG_RBQ_USER_ID, properties.getUserId()); Map<String, Object> headerFields = properties.getHeaders(); if (headerFields != null) { for (String key : headerFields.keySet()) if (headerFields.get(key) != null) { if (headerFields.get(key) instanceof LongString) decodedMessage.put(key, headerFields.get(key).toString()); else decodedMessage.put(key, headerFields.get(key)); } else decodedMessage.put(key, headerFields.get(key)); } } if (body.length == 0) decodedMessage.put(MSG_BODY, null); else decodedMessage.put(MSG_BODY, body); return decodedMessage; }
From source file:net.orzo.queue.TaskConsumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try {//from www . j ava 2 s. c o m String rawMessage = new String(body, "utf-8"); CeleryMessage msg = new Gson().fromJson((rawMessage), CeleryMessage.class); Observer obs = (Observable o, Object arg) -> { String result; try { getChannel().basicAck(envelope.getDeliveryTag(), false); if (o instanceof Task) { result = new Gson().toJson(((Task) o).getResult()); this.responseClient.response(result); if (this.resultStorage.isActive()) { this.resultStorage.set(msg.id, result); } } } catch (IOException e) { LoggerFactory.getLogger(TaskConsumer.class) .error(String.format("Failed to acknowledge sender: %s", e.getMessage())); } catch (ResourceNotAvailable e) { LoggerFactory.getLogger(TaskConsumer.class) .error(String.format("Failed to send response message: %s", e.getMessage())); } }; if (msg.task != null) { String taskId = this.taskManager.registerTask(msg.task, msg.args.toArray(new String[msg.args.size()]), obs); this.taskManager.startTask(taskId); } else { throw new IllegalArgumentException(String.format("Invalid message: %s", rawMessage)); } } catch (Exception e) { LoggerFactory.getLogger(TaskConsumer.class).error(e.getMessage()); getChannel().basicAck(envelope.getDeliveryTag(), false); // to get rid of invalid message } }
From source file:nl.uva.sne.drip.drip.component_example.Consumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //Create the reply properties which tells us where to reply, and which id to use. //No need to change anything here AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); String response = ""; try {//from w ww . j a v a 2 s . c om //The queue only moves bytes so we need to convert them to stting String message = new String(body, "UTF-8"); response = invokeComponent(message); } catch (JSONException | IOException ex) { response = ex.getMessage(); Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } finally { //We send the response back. No need to change anything here channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(envelope.getDeliveryTag(), false); } }
From source file:nl.uva.sne.drip.drip.planner.Consumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //Create the reply properties which tells us where to reply, and which id to use. //No need to change anything here AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); String response = ""; try {/*from ww w .ja v a 2s .c o m*/ //The queue only moves bytes so we need to convert them to stting String message = new String(body, "UTF-8"); //Create a tmp folder to save the output. File[] inputFiles; File tempDir = new File(System.getProperty("java.io.tmpdir") + File.separator + this.getClass().getSimpleName() + "-" + Long.toString(System.nanoTime())); if (!(tempDir.mkdirs())) { throw new FileNotFoundException("Could not create output directory: " + tempDir.getAbsolutePath()); } //We need to extact the call parameters form the json message. // inputFiles = jacksonUnmarshalExample(message); //Call the method with the extracted parameters // List<File> files = panner.plan(inputFiles[0].getAbsolutePath(), inputFiles[1].getAbsolutePath(), tempDir.getAbsolutePath()); //Here we do the same as above with a different API // inputFiles = simpleJsonUnmarshalExample(message); //Call the method with the extracted parameters // files = panner.plan(inputFiles[0].getAbsolutePath(), inputFiles[1].getAbsolutePath(), tempDir.getAbsolutePath()); //Now we need to put the result of the call to a message and respond //Example 1 // response = jacksonMarshalExample(files); //Example 2 // response = simpleJsonMarshalExample(files); } catch (Exception ex) { response = ex.getMessage(); Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } finally { //We send the response back. No need to change anything here channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(envelope.getDeliveryTag(), false); } }
From source file:nl.uva.sne.drip.drip.provisioner.v0.Consumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //Create the reply properties which tells us where to reply, and which id to use. //No need to change anything here AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); String response = ""; try {/*from www . j a v a2s. c o m*/ //The queue only moves bytes so we need to convert them to stting String message = new String(body, "UTF-8"); String tempInputDirPath = System.getProperty("java.io.tmpdir") + File.separator + "Input-" + Long.toString(System.nanoTime()) + File.separator; File tempInputDir = new File(tempInputDirPath); if (!(tempInputDir.mkdirs())) { throw new FileNotFoundException( "Could not create input directory: " + tempInputDir.getAbsolutePath()); } ArrayList topologyInfoArray; topologyInfoArray = invokeProvisioner(message, tempInputDirPath); response = generateResponse(topologyInfoArray); } catch (Throwable ex) { try { response = generateExeptionResponse(ex); Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex1) { response = "{\"creationDate\": " + System.currentTimeMillis() + ",\"parameters\": [{\"url\": null,\"encoding\": UTF-8," + "\"value\": \"" + ex.getMessage() + "\",\"name\": \"" + ex.getClass().getName() + "\",\"attributes\": null}]}"; } } finally { Logger.getLogger(Consumer.class.getName()).log(Level.INFO, "Sending Response: {0}", response); //We send the response back. No need to change anything here channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(envelope.getDeliveryTag(), false); } }
From source file:nl.uva.sne.drip.drip.provisioner.v1.Consumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //Create the reply properties which tells us where to reply, and which id to use. //No need to change anything here AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); String response = ""; try {/*from w w w .j a v a 2s . c om*/ //The queue only moves bytes so we need to convert them to string String message = new String(body, "UTF-8"); String tempInputDirPath = System.getProperty("java.io.tmpdir") + File.separator + "Input-" + Long.toString(System.nanoTime()) + File.separator; File tempInputDir = new File(tempInputDirPath); if (!(tempInputDir.mkdirs())) { throw new FileNotFoundException( "Could not create input directory: " + tempInputDir.getAbsolutePath()); } ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); String owner = mapper.readValue(message, Message.class).getOwner(); DRIPLogHandler handler = new DRIPLogHandler(messageBrokerHost); handler.setOwner(owner); logger.addHandler(handler); response = mapper.writeValueAsString(invokeProvisioner(message, tempInputDirPath)); } catch (Throwable ex) { try { response = generateExeptionResponse(ex); // Logger.getLogger(Consumer.class.getName()) logger.log(Level.SEVERE, null, ex); } catch (JSONException ex1) { response = "{\"creationDate\": " + System.currentTimeMillis() + ",\"parameters\": [{\"url\": null,\"encoding\": UTF-8," + "\"value\": \"" + ex.getMessage() + "\",\"name\": \"" + ex.getClass().getName() + "\",\"attributes\": null}]}"; } } finally { logger.fine("Sending Response: {0}" + response); // Logger.getLogger(Consumer.class.getName()).log(Level.INFO, "Sending Response: {0}", response); //We send the response back. No need to change anything here channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(envelope.getDeliveryTag(), false); } }