List of usage examples for com.rabbitmq.client Channel queueDeclare
Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) throws IOException;
From source file:server.WorkerServer.java
License:Open Source License
private void doWork(HttpRequest request) throws Exception { // Parse the request try {/*from www . j a v a2 s . c o m*/ String[] uri = request.getUri().split("/"); String requestTypeString = request.getMethod(); String pluginString = uri[1]; String servletString = uri[2]; HashMap<String, IPlugin> plugins = server.getPlugins(); IPlugin currPlugin = plugins.get(pluginString); if (currPlugin == null) { throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This plugin doesn't exist"); } IServlet servlet = currPlugin.getServlet(requestTypeString + ":/" + servletString); if (servlet == null) { System.out.println("servlet is null"); throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This servlet doesn't exist"); } System.out.println("requestTypeString: " + requestTypeString); HttpResponse response = servlet.processRequest(request, null); // publish response to response queue Connection connection2 = factory.newConnection(); Channel channel2 = connection2.createChannel(); boolean durable = true; //System.out.println("response: " + response.getBytes(request.getKey())); channel2.queueDeclare(Protocol.RESPONSE_QUEUE, durable, false, false, null); channel2.basicPublish("", Protocol.RESPONSE_QUEUE, MessageProperties.PERSISTENT_TEXT_PLAIN, response.getBytes(request.getKey())); } catch (ProtocolException e) { e.printStackTrace(); } }
From source file:src.main.java.server.MsgReceiveServer.java
public MsgReceiveServer(int SERVER_PORT, String logDirname, String zipDirname, String dbUser, String dbPwd, boolean withLog) throws IOException, TimeoutException, JSONException { super(SERVER_PORT); this.withLog = withLog; this.logDir = logDirname; this.zipDir = zipDirname; dataSource = new DataSource(dbUser, dbPwd); HashMap<String, Message> user2msg; allMsg = new HashMap<String, HashMap<String, Message>>(); ArrayList<Pair<String, String>> res = dataSource.getGroupUser(); for (Pair<String, String> p : res) { msg = new Message("{}", p.getR()); msg.init(p.getR(), "localhost"); msg.bindTo(p.getL(), p.getR());/*from w w w . j a v a 2 s.c om*/ if (allMsg.containsKey(p.getL())) { allMsg.get(p.getL()).put(p.getR(), msg); } else { user2msg = new HashMap<String, Message>(); user2msg.put(p.getR(), msg); allMsg.put(p.getL(), user2msg); } } loginMsg = new Message("{}", ""); loginMsg.init("login_request", "localhost"); loginMsg.bindTo("login_auth", "login_request"); normalMsg = new Message("{}", ""); normalMsg.init("normal_msg", "localhost"); normalMsg.bindTo("msg_send", "normal_msg"); logoutMsg = new Message("{}", ""); logoutMsg.init("logout_msg", "localhost"); logoutMsg.bindTo("msg_send", "logout_msg"); reloginMsg = new Message("{}", ""); reloginMsg.init("relogin_msg", "localhost"); reloginMsg.bindTo("msg_send", "relogin_msg"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel loginSuccessChannel = connection.createChannel(); loginSuccessChannel.queueDeclare("login_success", true, false, false, null); loginSuccessConsumer = new DefaultConsumer(loginSuccessChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String sLoginSuccessMsg = new String(body, "UTF-8"); try { Message loginSuccessMsg = new Message("{}", ""); loginSuccessMsg.reset(sLoginSuccessMsg); String loginSuccessUsername = loginSuccessMsg.getValue("username"); if (user_list.contains(loginSuccessUsername) == false) { user_list.add(loginSuccessUsername); } System.out.println(user_list.size()); } catch (JSONException e) { e.printStackTrace(); } } }; loginSuccessChannel.basicConsume("login_success", true, loginSuccessConsumer); }
From source file:taucalcmanager.TaucalcManager.java
/** * @param args the command line arguments * @throws java.io.IOException//from ww w. j a va 2 s. co m * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); int calcs = Integer.parseInt(args[0]); int triesPerCalc = Integer.parseInt(args[1]); int[] results = new int[calcs]; byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8), (byte) (triesPerCalc) }; System.out.println("Start Publishing"); for (int i = 0; i < calcs; i++) { channel.basicPublish("", WORKQUEUENAME, null, task); } System.out.println("Done Publishing"); GetResponse response; System.out.println("Start Gathering results"); for (int i = 0; i < calcs; i++) { System.out.println("Waiting for next result: ( " + i + " )"); do { response = channel.basicGet(RESULTQUEUENAME, true); } while (response == null); results[i] = ByteBuffer.wrap(response.getBody()).getInt(); System.out.println("Received result: " + results[i]); } System.out.println("Done gathering results"); System.out.println("Calculating tau"); BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc); System.out.println("Tau = " + result); BigDecimal two = new BigDecimal(2); System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP)); channel.close(); connection.close(); }
From source file:taucalcworker.TaucalcWorker.java
/** * @param args the command line arguments * @throws java.io.IOException/*from w w w .j av a2 s .c o m*/ * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); byte[] inputbyte = { 0, 0, 0, 0 }; String input = ""; do { if (System.in.available() > 0) { System.in.read(inputbyte); input = new String(inputbyte); } GetResponse response = channel.basicGet(WORKQUEUENAME, false); if (response != null) { long deliverytag = response.getEnvelope().getDeliveryTag(); byte[] body = response.getBody(); int tries = ByteBuffer.wrap(body).getInt(); System.out.println("Task received: " + tries); int success = 0; for (int i = 0; i < tries; i++) { double x = Math.random(); double y = Math.random(); if (x * x + y * y <= 1) { success++; } } System.out.println("success: " + success + " out of " + tries); double tau = ((double) success / tries) * 8; System.out.println("Tau = " + tau); byte[] resultbytes = new byte[8]; ByteBuffer.wrap(resultbytes).putDouble(tau); channel.basicPublish("", RESULTQUEUENAME, null, resultbytes); channel.basicAck(deliverytag, false); } } while (!input.equals("stop")); channel.close(); connection.close(); System.out.println("You stopped the program."); }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
/** * Sends a message to the specified queue * @param queue//from ww w . ja v a2 s . c om * @param in * @param host * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public void sendMessage(String queue, Object in, String host) throws IOException, InterruptedException, TimeoutException { String message; Builder propBuilder = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder(); if (in.getClass().equals(String.class)) { message = (String) in; } else { message = Utils.objectToJson(in); if (in.getClass().equals(WorkerState.class)) { host = ((WorkerState) in).getResource().getHostName(); } } if (host != null) { Map<String, Object> headers = new HashMap(); headers.put("host", host); propBuilder.headers(headers); } BasicProperties mProp = propBuilder.build(); Connection connectionSend = getRmqConn(); Channel channel = connectionSend.createChannel(); channel.confirmSelect(); channel.queueDeclare(queue, true, false, false, null); channel.basicPublish("", queue, mProp, message.getBytes()); channel.waitForConfirmsOrDie(5000); logger.info(queue + " sent: " + message); channel.close(); closeRmqConn(connectionSend); }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
public void sendFile(String queue, String host, File f) throws IOException, InterruptedException, TimeoutException { Map<String, Object> headers = new HashMap(); headers.put("host", host); BasicProperties mProp = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build(); Connection connectionSend = getRmqConn(); Channel channel = connectionSend.createChannel(); channel.confirmSelect();/*w w w . j av a 2 s.c o m*/ channel.queueDeclare(queue, true, false, false, null); channel.basicPublish("", queue, mProp, Files.readAllBytes(f.toPath())); channel.waitForConfirmsOrDie(5000); logger.info(queue + " file: " + f.getAbsolutePath()); channel.close(); closeRmqConn(connectionSend); }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
public void cleanQueue(String queue, String match) throws IOException, InterruptedException { logger.trace(queue.concat(": ").concat(match)); Connection connectionRcv = getRmqConn(); Channel channel = connectionRcv.createChannel(); channel.queueDeclare(queue, true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000); Set seen = new HashSet(); while (delivery != null) { String body = new String(delivery.getBody()); if (seen.contains(body)) { break; }//from ww w.j av a 2s . c o m if (body.contains(match)) { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } else { channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); seen.add(body); } delivery = consumer.nextDelivery(1000); } channel.close(); closeRmqConn(connectionRcv); }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
public List<File> getFiles(String queue, Path outFolder, boolean ack) throws IOException, InterruptedException { List files = new ArrayList(); Connection connectionRcv = getRmqConn(); Channel channel = connectionRcv.createChannel(); channel.queueDeclare(queue, true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000); Set seen = new HashSet(); while (delivery != null) { String host = delivery.getProperties().getHeaders().get("host").toString(); File outTo = Paths.get(outFolder.toString(), host + ".tar.gz").toFile(); FileUtils.writeByteArrayToFile(outTo, delivery.getBody()); if (ack) { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } else {/*from ww w . j a v a 2s . co m*/ channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); } if (seen.contains(delivery.getProperties().getHeaders().get("host"))) { break; } seen.add(delivery.getProperties().getHeaders().get("host")); files.add(outTo); logger.info(queue + " retrieved: " + outTo.getAbsolutePath()); delivery = consumer.nextDelivery(1000); } logger.warn("getFiles done"); channel.close(); closeRmqConn(connectionRcv); return files; }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
public WorkerState getWorkerState(String queue, long wait) throws IOException, InterruptedException { WorkerState ws = null;// ww w . jav a2s. c o m Connection connectionRcv = getRmqConn(); Channel channel = connectionRcv.createChannel(); channel.queueDeclare(queue, true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); QueueingConsumer.Delivery delivery; if (wait == -1) { delivery = consumer.nextDelivery(); // will block until response } else { delivery = consumer.nextDelivery(wait); } if (delivery != null) { String message = new String(delivery.getBody()); ws = (WorkerState) Utils.jsonToObject(message, WorkerState.class); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } channel.close(); closeRmqConn(connectionRcv); return ws; }
From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java
License:Open Source License
/** * Gets a single message from a queue, ideal for getting an item of work. * @param queue/*from w w w . jav a 2s . c o m*/ * @param wait * @return A JSON string representing an object, you need to know what type of object the queue will return and handle this outside of here * @throws IOException * @throws InterruptedException */ public String getMessageString(String queue, long wait) throws IOException, InterruptedException { String message = null; Connection connectionRcv = getRmqConn(); Channel channel = connectionRcv.createChannel(); channel.queueDeclare(queue, true, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); QueueingConsumer.Delivery delivery; if (wait == -1) { delivery = consumer.nextDelivery(); // will block until response } else { delivery = consumer.nextDelivery(wait); } if (delivery != null) { message = new String(delivery.getBody()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); logger.info(queue + " recieved: " + message); } channel.close(); closeRmqConn(connectionRcv); return message; }