ConnectionFactory connFactory = new ConnectionFactory();
connFactory.setUri(uri);
Connection conn = connFactory.newConnection();
final Channel ch = conn.createChannel();
String queueName =
(requestedQueueName.equals("")
? ch.queueDeclare()
: ch.queueDeclare(requestedQueueName,
false, false, false, null)).getQueue();
if (exchange != null || routingKey != null) {
if (exchange == null) {
System.err.println("Please supply exchange name to bind to (-e)");
System.exit(2);
}
if (routingKey == null) {
System.err.println("Please supply routing key pattern to bind to (-k)");
System.exit(2);
}
ch.exchangeDeclare(exchange, exchangeType);
ch.queueBind(queueName, exchange, routingKey);
}
QueueingConsumer consumer = new QueueingConsumer(ch);
ch.basicConsume(queueName, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
Map<String, Object> headers = delivery.getProperties().getHeaders();
byte[] body = delivery.getBody();
Object headerFilenameO = headers.get("filename");
String headerFilename =
(headerFilenameO == null)
? UUID.randomUUID().toString()
: headerFilenameO.toString();
File givenName = new File(headerFilename);
if (givenName.getName().equals("")) {
System.out.println("Skipping file with empty name: " + givenName);
} else {
File f = new File(outputDir, givenName.getName());
System.out.print("Writing " + f + " ...");
FileOutputStream o = new FileOutputStream(f);
o.write(body);
o.close();
System.out.println(" done.");
}
ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch (Exception ex) {
System.err.println("Main thread caught exception: " + ex);
ex.printStackTrace();
System.exit(1);