List of usage examples for com.rabbitmq.client Delivery getProperties
public AMQP.BasicProperties getProperties()
From source file:bankreplyaggrigator.Aggregator.java
private static void handleMessage() throws IOException, InterruptedException { while (true) { Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); String correlationID = delivery.getProperties().getCorrelationId(); System.out.println("Message recived: " + message); Aggregate aggregate = (Aggregate) activeAggregates.get(correlationID); if (aggregate == null) { aggregate = new LoanAggregate(new BankLoan()); aggregate.addMessage(message); activeAggregates.put(correlationID, aggregate); } else {/*from w w w .ja v a 2s. com*/ aggregate.addMessage(message); } publishResult(aggregate, correlationID); } }
From source file:com.hopped.running.rabbitmq.rpc.ARPCServer.java
License:Open Source License
/** * /*from w ww.ja v a2 s .c o m*/ */ public void consume() { checkConsumer(); while (true) { try { Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); byte[] payload = processRequest(delivery); channel.basicPublish("", props.getReplyTo(), replyProps, payload); } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException | IOException e) { logger.error(e.getMessage()); closeConnection(); } } }
From source file:com.surgeplay.visage.master.VisageMaster.java
License:Open Source License
@Override public void run() { try {/*from ww w. ja va 2s. c o m*/ Log.setLog(new LogShim(Visage.log)); long total = Runtime.getRuntime().totalMemory(); long max = Runtime.getRuntime().maxMemory(); if (Visage.debug) Visage.log.finer("Current heap size: " + humanReadableByteCount(total, false)); if (Visage.debug) Visage.log.finer("Max heap size: " + humanReadableByteCount(max, false)); if (total < max) { Visage.log.warning( "You have set your minimum heap size (Xms) lower than the maximum heap size (Xmx) - this can cause GC thrashing. It is strongly recommended to set them both to the same value."); } if (max < (1000 * 1000 * 1000)) { Visage.log.warning( "The heap size (Xmx) is less than one gigabyte; it is recommended to run Visage with a gigabyte or more. Use -Xms1G and -Xmx1G to do this."); } Visage.log.info("Setting up Jetty"); Server server = new Server( new InetSocketAddress(config.getString("http.bind"), config.getInt("http.port"))); List<String> expose = config.getStringList("expose"); String poweredBy; if (expose.contains("server")) { if (expose.contains("version")) { poweredBy = "Visage v" + Visage.VERSION; } else { poweredBy = "Visage"; } } else { poweredBy = null; } ResourceHandler resource = new ResourceHandler(); resource.setResourceBase(config.getString("http.static")); resource.setDirectoriesListed(false); resource.setWelcomeFiles(new String[] { "index.html" }); resource.setHandler(new VisageHandler(this)); if (!"/dev/null".equals(config.getString("log"))) { new File(config.getString("log")).getParentFile().mkdirs(); server.setRequestLog(new AsyncNCSARequestLog(config.getString("log"))); } GzipHandler gzip = new GzipHandler(); gzip.setHandler(new HeaderHandler("X-Powered-By", poweredBy, resource)); server.setHandler(gzip); String redisHost = config.getString("redis.host"); int redisPort = config.getInt("redis.port"); Visage.log.info("Connecting to Redis at " + redisHost + ":" + redisPort); resolverNum = config.getInt("redis.resolver-db"); skinNum = config.getInt("redis.skin-db"); JedisPoolConfig jpc = new JedisPoolConfig(); jpc.setMaxIdle(config.getInt("redis.max-idle-connections")); jpc.setMaxTotal(config.getInt("redis.max-total-connections")); jpc.setMinIdle(config.getInt("redis.min-idle-connections")); if (config.hasPath("redis.password")) { password = config.getString("redis.password"); } pool = new JedisPool(jpc, redisHost, redisPort); Visage.log.info("Connecting to RabbitMQ at " + config.getString("rabbitmq.host") + ":" + config.getInt("rabbitmq.port")); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(config.getString("rabbitmq.host")); factory.setPort(config.getInt("rabbitmq.port")); factory.setRequestedHeartbeat(10); if (config.hasPath("rabbitmq.user")) { factory.setUsername(config.getString("rabbitmq.user")); factory.setPassword(config.getString("rabbitmq.password")); } String queue = config.getString("rabbitmq.queue"); Closer closer = Closer.create(); steve = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("steve.png"))); alex = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("alex.png"))); closer.close(); conn = factory.newConnection(); channel = conn.createChannel(); if (Visage.debug) Visage.log.finer("Setting up queue '" + queue + "'"); channel.queueDeclare(queue, false, false, true, null); channel.basicQos(1); if (Visage.debug) Visage.log.finer("Setting up reply queue"); replyQueue = channel.queueDeclare().getQueue(); consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueue, consumer); if (config.getBoolean("slave.enable")) { Visage.log.info("Starting fallback slave"); fallback = new VisageSlave( config.getConfig("slave").withValue("rabbitmq", config.getValue("rabbitmq"))); fallback.start(); } Visage.log.info("Starting Jetty"); server.start(); Visage.log.info("Listening for finished jobs"); try { while (run) { Delivery delivery = consumer.nextDelivery(); if (Visage.trace) Visage.log.finest("Got delivery"); try { String corrId = delivery.getProperties().getCorrelationId(); if (queuedJobs.containsKey(corrId)) { if (Visage.trace) Visage.log.finest("Valid"); responses.put(corrId, delivery.getBody()); Runnable run = queuedJobs.get(corrId); queuedJobs.remove(corrId); if (Visage.trace) Visage.log.finest("Removed from queue"); run.run(); if (Visage.trace) Visage.log.finest("Ran runnable"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); if (Visage.trace) Visage.log.finest("Ack'd"); } else { Visage.log.warning("Unknown correlation ID?"); channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); } } catch (Exception e) { Visage.log.log(Level.WARNING, "An unexpected error occured while attempting to process a response.", e); } } } catch (InterruptedException e) { } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occured in the master run loop.", e); System.exit(2); } try { Visage.log.info("Shutting down master"); server.stop(); pool.destroy(); conn.close(5000); } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred while shutting down the master.", e); } } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occured while initializing the master.", e); System.exit(1); } }
From source file:com.surgeplay.visage.slave.RenderThread.java
License:Open Source License
@Override public void run() { try {/*ww w.j av a 2 s . c om*/ Visage.log.info("Waiting for jobs"); try { while (run) { if (!toProcess.isEmpty()) { Delivery delivery = toProcess.pop(); try { processDelivery(delivery); } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occurred while rendering", e); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); ByteArrayOutputStream ex = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ex); oos.writeObject(e); oos.flush(); parent.channel.basicPublish("", props.getReplyTo(), replyProps, buildResponse(1, ex.toByteArray())); parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } else { synchronized (toProcess) { toProcess.wait(); } } } for (Renderer r : renderers) { if (r != null) { r.destroy(); } } } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred in the render thread run loop.", e); } } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred while setting up a render thread.", e); } }
From source file:com.surgeplay.visage.slave.RenderThread.java
License:Open Source License
private void processDelivery(Delivery delivery) throws Exception { BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build(); DataInputStream data = new DataInputStream( new InflaterInputStream(new ByteArrayInputStream(delivery.getBody()))); RenderMode mode = RenderMode.values()[data.readUnsignedByte()]; int width = data.readUnsignedShort(); int height = data.readUnsignedShort(); int supersampling = data.readUnsignedByte(); GameProfile profile = Profiles.readGameProfile(data); Map<String, String[]> params = Maps.newHashMap(); int len = data.readUnsignedShort(); for (int i = 0; i < len; i++) { String key = data.readUTF(); String[] val = new String[data.readUnsignedByte()]; for (int v = 0; v < val.length; v++) { val[v] = data.readUTF(); }// w ww. jav a2s. c o m params.put(key, val); } byte[] skinData = new byte[data.readInt()]; data.readFully(skinData); BufferedImage skinRaw = new PngImage().read(new ByteArrayInputStream(skinData), false); BufferedImage skin = Images.toARGB(skinRaw); Visage.log.info("Received a job to render a " + width + "x" + height + " " + mode.name().toLowerCase() + " (" + supersampling + "x supersampling) for " + (profile == null ? "null" : profile.getName())); byte[] pngBys = draw(mode, width, height, supersampling, profile, skin, params); if (Visage.trace) Visage.log.finest("Got png bytes"); parent.channel.basicPublish("", props.getReplyTo(), replyProps, buildResponse(0, pngBys)); if (Visage.trace) Visage.log.finest("Published response"); parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); if (Visage.trace) Visage.log.finest("Ack'd message"); }
From source file:normalizerbankfour.NormalizerBankFour.java
/** * @param args the command line arguments *//* w ww.j a v a 2 s . co m*/ public static void main(String[] args) { ConnectionCreator creator = ConnectionCreator.getInstance(); try { channelIn = creator.createChannel(); channelIn.queueDeclare(IN_QUEUE, false, false, false, null); channelOut = creator.createChannel(); channelOut.queueDeclare(OUT_QUEUE, false, false, false, null); consumer = new QueueingConsumer(channelIn); channelIn.basicConsume(IN_QUEUE, consumer); } catch (IOException ex) { Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex); } while (true) { try { System.out.println("Normalizer for BankFour is running"); Delivery delivery = consumer.nextDelivery(); channelIn.basicAck(delivery.getEnvelope().getDeliveryTag(), false); System.out.println("Got message: " + new String(delivery.getBody())); String message = normalizeMessage(new String(delivery.getBody())); BasicProperties probs = new BasicProperties().builder() .correlationId(delivery.getProperties().getCorrelationId()).build(); channelOut.basicPublish("", OUT_QUEUE, probs, message.getBytes()); } catch (InterruptedException ex) { Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex); } catch (ShutdownSignalException ex) { Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex); } catch (ConsumerCancelledException ex) { Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:normalizerbankthree.NormalizerBankThree.java
/** * @param args the command line arguments *///from w w w. j a v a 2 s. co m public static void main(String[] args) { ConnectionCreator creator = ConnectionCreator.getInstance(); try { channelIn = creator.createChannel(); channelIn.queueDeclare(IN_QUEUE, false, false, false, null); channelOut = creator.createChannel(); channelOut.queueDeclare(OUT_QUEUE, false, false, false, null); consumer = new QueueingConsumer(channelIn); channelIn.basicConsume(IN_QUEUE, true, consumer); } catch (IOException ex) { Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Normalizer for Bankthree is running"); while (true) { try { Delivery delivery = consumer.nextDelivery(); System.out.println("Got message: " + new String(delivery.getBody())); String message = normalizeMessage(new String(delivery.getBody())); BasicProperties probs = new BasicProperties().builder() .correlationId(delivery.getProperties().getCorrelationId()).build(); channelOut.basicPublish("", OUT_QUEUE, probs, message.getBytes()); System.out.println("reply: " + message); } catch (InterruptedException ex) { Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex); } catch (ShutdownSignalException ex) { Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex); } catch (ConsumerCancelledException ex) { Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java
License:Open Source License
private void handleDelivery(final Delivery delivery) { final BasicProperties properties = delivery.getProperties(); final Envelope envelope = delivery.getEnvelope(); final byte[] body = delivery.getBody(); final String hashKey = envelope.getExchange() + ":" + envelope.getRoutingKey(); Map<String, String> headers = null; try {//from ww w . j a v a2 s . c o m final String correlationId = properties.getCorrelationId(); LogUtil.enhanceLogWithCorrelationId(log, correlationId); if (log.isDebugEnabled()) { log.debug("Received message from RabbitMQ ({}//{}): {}", envelope, properties, new String(body, StandardCharsets.UTF_8)); } headers = extractHeadersFromMessage(properties, envelope); final ExternalMessageBuilder externalMessageBuilder = ExternalMessageFactory .newExternalMessageBuilder(headers); final String contentType = properties.getContentType(); final String text = new String(body, CharsetDeterminer.getInstance().apply(contentType)); if (shouldBeInterpretedAsBytes(contentType)) { externalMessageBuilder.withBytes(body); } else { externalMessageBuilder.withTextAndBytes(text, body); } externalMessageBuilder.withAuthorizationContext(authorizationContext); externalMessageBuilder.withEnforcement(headerEnforcementFilterFactory.getFilter(headers)); externalMessageBuilder.withHeaderMapping(headerMapping); externalMessageBuilder.withSourceAddress(sourceAddress); final ExternalMessage externalMessage = externalMessageBuilder.build(); inboundMonitor.success(externalMessage); forwardToMappingActor(externalMessage, hashKey); } catch (final DittoRuntimeException e) { log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage()); if (headers != null) { // send response if headers were extracted successfully forwardToMappingActor(e.setDittoHeaders(DittoHeaders.of(headers)), hashKey); inboundMonitor.failure(headers, e); } else { inboundMonitor.failure(e); } } catch (final Exception e) { log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage()); if (headers != null) { inboundMonitor.exception(headers, e); } else { inboundMonitor.exception(e); } } }
From source file:org.mule.transport.amqp.AbstractAmqpOutboundITCase.java
License:Open Source License
protected void dispatchTestMessageAndAssertValidReceivedMessage(final String flowName) throws Exception { final String customHeaderValue = UUID.getUUID(); final String payload = RandomStringUtils.randomAlphanumeric(20); new MuleClient(muleContext).dispatch("vm://" + flowName + ".in", payload, Collections.singletonMap("customHeader", customHeaderValue)); final Delivery dispatchedMessage = consumeMessageWithAmqp(getQueueName(flowName), getTestTimeoutSecs() * 1000L); assertNotNull(dispatchedMessage);/*from ww w .ja v a2 s .co m*/ assertEquals(payload, new String(dispatchedMessage.getBody())); assertEquals(customHeaderValue, dispatchedMessage.getProperties().getHeaders().get("customHeader").toString()); }
From source file:org.mule.transport.amqp.AmqpBridgeITCase.java
License:Open Source License
private void dispatchTestMessageAndAssertValidReceivedMessage(final String flowName, final String targetQueueName) throws Exception { final String payload = RandomStringUtils.randomAlphanumeric(20); final String correlationId = publishMessageWithAmqp(payload.getBytes(), flowName); final Delivery dispatchedMessage = consumeMessageWithAmqp(targetQueueName, DEFAULT_MULE_TEST_TIMEOUT_SECS * 1000L); assertNotNull(dispatchedMessage);/* w ww . j a va2s. c om*/ assertEquals(payload, new String(dispatchedMessage.getBody())); assertEquals(correlationId, dispatchedMessage.getProperties().getCorrelationId()); }