List of usage examples for com.rabbitmq.client DefaultConsumer DefaultConsumer
public DefaultConsumer(Channel channel)
From source file:Release1.Controllers.AlarmController.java
/** * * mtodo para recibir mensajes de los sensores de alarmas de movimiento * dependiendo del mensaje recibido se envia la respuesta a los sensores * @throws IOException//from ww w . j a va2s.com * @throws TimeoutException */ private void receiveMoveMessage() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ID_CHANNEL_AMOVE_SENSOR, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ID_CHANNEL_AMOVE_SENSOR, ""); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public synchronized void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { setMessage(new String(body, "UTF-8")); logger.info("Class ALARM MOVE Controller --- RECEIVED from Sensor --- Value: " + new String(body, "UTF-8")); if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) { try { sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_ON);//envio de mensajes para encender la alarma de movimiento logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW"); } catch (TimeoutException ex) { logger.error(ex); } } else { try { sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_OFF);//envio de mensajes para apagar la alarma de movimientos } catch (TimeoutException ex) { logger.error(ex); } } } }; channel.basicConsume(queueName, true, consumer); }
From source file:Release2.Controllers.AlarmFireController.java
private synchronized void receivedAlarmFireSensorMessage() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST);//from ww w .j av a2 s . c o m Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ID_CHANNEL_AFIRE_SENSOR, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ID_CHANNEL_AFIRE_SENSOR, ""); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public synchronized void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { setMessage(new String(body, "UTF-8")); logger.info("Class ALARM FIRE Controller --- RECEIVED from Sensor --- Value: " + new String(body, "UTF-8")); if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {//si el valor obtenido es mayor al permitido para simular las alarmas se activa la alarma try { sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_ON);//envio de mensaje para encender alarma la alarma de ventnaa logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW"); } catch (TimeoutException ex) { logger.error(ex); } } else { try { sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_OFF);//envio de mensaje apra apagar la alarma de ventana } catch (TimeoutException ex) { logger.error(ex); } } } }; channel.basicConsume(queueName, true, consumer); }
From source file:rmq.sender.impl.MQSender.java
License:Apache License
@Override public String consumer() { final String[] message = new String[1]; try {// w ww. j av a2s . c o m Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { message[0] = new String(body, "UTF-8"); log.info(" [x] Received '" + message[0] + "'"); } }; channel.basicConsume(queueName, true, consumer); } catch (Exception e) { log.error(E_PUBLISH_CHAN, e); } log.info("Again Recieved: " + message[0]); return message[0]; }
From source file:server.MessengerServer.java
MessengerServer() throws IOException, TimeoutException { factory = new ConnectionFactory(); System.out.print("input host : "); String host = sc.nextLine();// w w w. j a v a 2 s. c o m if (!host.equalsIgnoreCase("localhost")) { System.out.print("input port : "); int port = Integer.parseInt(sc.nextLine()); factory.setPort(port); } factory.setHost(host); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(SERVER_QUEUE_NAME, true, false, false, null); //channel.basicQos(1); ArrayList<String> groupNames = getGroups(); for (String name : groupNames) { channel.exchangeDeclare(name, "fanout"); } ArrayList<String> userNames = getUserId(); for (String name : userNames) { channel.queueDeclare(name, true, false, false, null); } //consumer = new QueueingConsumer(channel); //channel.basicConsume(SERVER_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Message message; try { message = Message.toMessage(body); System.out.println(message.getType()); switch (message.getType()) { //PM case 0: { System.out.println("PERSONAL MESSAGE: " + message.getSender()); if (isFriend(message.getSender(), message.getFriendID())) { sendMessage(message.getFriendID(), message.getSender(), message.getContent()); } else { String response = "dia bukan teman anda"; sendMessage(message.getFriendID(), message.getSender(), message.getContent()); } break; } //GROUP case 1: { System.out.println("GROUP MESSAGE: " + message.getSender()); sendGroupMessage(message.getGroupName(), message.getSender(), message.getContent()); break; } //COMMAND case 2: { System.out.println(message.getContent()); String[] contents = message.getContent().split(" "); Message m; if (contents[0].equalsIgnoreCase("register")) { System.out.println("REGISTER: " + message.getSender()); String userId = contents[1]; String password = contents[2]; if (getUserName(userId).equalsIgnoreCase(userId)) { System.out.println("REGISTER: user already exist!"); m = new Message(1, SERVER_QUEUE_NAME, "FAIL"); } else { registerUser(userId, password); System.out.println("REGISTER: success!"); m = new Message(1, SERVER_QUEUE_NAME, "SUCCESS"); } BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, m.toBytes()); } else if (contents[0].equalsIgnoreCase("login")) { System.out.println("LOGIN: " + message.getSender()); System.out.println(loginUser(contents[1], contents[2])); m = new Message(2, SERVER_QUEUE_NAME, loginUser(contents[1], contents[2])); System.out.println("Friends: " + getFriends(message.getSender()).size()); m.setListFriend(getFriends(message.getSender())); System.out.println("Groups: " + getGroups(message.getSender()).size()); m.setListGroup(getGroups(message.getSender())); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, m.toBytes()); } else if (contents[0].equalsIgnoreCase("creategroup")) { System.out.println("CREATE GROUP: " + message.getSender()); String res = createGroup(message.getGroupName(), message.getListUser(), message.getSender()); String[] cek = res.split(" "); if (cek[0].equalsIgnoreCase("success")) { System.out.println("CREATE GROUP: BERHASIL"); //send to member channel.exchangeDeclare(message.getGroupName(), "fanout"); for (String name : getMember(message.getGroupName())) { channel.queueBind(name, message.getGroupName(), ""); } m = new Message(2, SERVER_QUEUE_NAME, "joingroup"); m.setGroupName(message.getGroupName()); channel.basicPublish(message.getGroupName(), "", null, m.toBytes()); } else { System.out.println("CREATE GROUP: GAGAL"); } //send to sender Message mu = new Message(2, SERVER_QUEUE_NAME, res); mu.setListGroup(getGroups(message.getSender())); channel.basicPublish("", message.getSender(), null, mu.toBytes()); } else if (contents[0].equalsIgnoreCase("leavegroup")) { System.out.println("LEAVE GROUP: " + message.getSender()); String res = leaveGroup(message.getGroupName(), message.getSender()); System.out.println("LEAVEGROUP: " + res); sendMessage(message.getSender(), SERVER_QUEUE_NAME, res, 2); } else if (contents[0].equalsIgnoreCase("addusertogroup")) { System.out.println("JOIN GROUP: " + message.getSender()); String res = joinGroup(message.getGroupName(), message.getFriendID(), message.getSender()); System.out.println("JOIN GROUP: " + res); sendMessage(message.getSender(), SERVER_QUEUE_NAME, res, 2); channel.queueBind(message.getFriendID(), message.getGroupName(), ""); sendMessage(message.getFriendID(), SERVER_QUEUE_NAME, "joingroup " + message.getGroupName(), 2); } else if (contents[0].equalsIgnoreCase("addfriend")) { System.out.println("ADD FRIEND: " + message.getSender()); if (!isFriend(message.getSender(), message.getFriendID())) { if (addFriend(message.getSender(), message.getFriendID())) { sendFriendMessage(message.getSender(), message.getFriendID(), message.getContent(), 2); sendFriendMessage(message.getFriendID(), message.getSender(), message.getContent(), 2); } else { System.out.println("ADD FRIEND: GAGAL"); } } else { String res = "sudah berteman"; sendMessage(message.getSender(), SERVER_QUEUE_NAME, res, 2); } } break; } } } catch (ClassNotFoundException ex) { Logger.getLogger(MessengerServer.class.getName()).log(Level.SEVERE, null, ex); } ; } }; boolean autoAck = true; // acknowledgment is covered below channel.basicConsume(SERVER_QUEUE_NAME, autoAck, consumer); }
From source file:server.Server.java
License:Open Source License
/** * @param rootDirectory/*from w w w . j av a 2s. c o m*/ * @param port */ public Server(String rootDirectory, int port, String host, WebServer window) throws Exception { this.rootDirectory = rootDirectory; this.port = port; this.host = host; this.stop = false; this.connections = 0; this.serviceTime = 0; this.window = window; this.counter = 0; // performance improvement - queue this.clientRequests = new HashMap<String, Integer>(); this.bannedClients = new ArrayList<String>(); this.clients = new HashMap<String, ConnectionHandler>(); // initialize responseCodes map this.responseCodes = new HashMap<Integer, String>(); this.responseCodes.put(Protocol.OK_CODE, Protocol.GET); this.responseCodes.put(Protocol.POST_CODE, Protocol.POST); this.responseCodes.put(Protocol.PUT_CODE, Protocol.PUT); this.responseCodes.put(Protocol.DELETE_CODE, Protocol.DELETE); // create Worker Servers WorkerServer wsGet = new WorkerServer(Protocol.GET_QUEUE, this); WorkerServer wsGet2 = new WorkerServer(Protocol.GET_QUEUE, this); WorkerServer wsPut = new WorkerServer(Protocol.PUT_QUEUE, this); WorkerServer wsPost = new WorkerServer(Protocol.POST_QUEUE, this); WorkerServer wsDelete = new WorkerServer(Protocol.DELETE_QUEUE, this); Thread getThread = new Thread(wsGet); Thread get2Thread = new Thread(wsGet2); Thread putThread = new Thread(wsPut); Thread postThread = new Thread(wsPost); Thread deleteThread = new Thread(wsDelete); getThread.start(); get2Thread.start(); putThread.start(); postThread.start(); deleteThread.start(); // retrieve responses from responses queue factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); boolean durable = true; channel.queueDeclare(Protocol.RESPONSE_QUEUE, durable, false, false, null); channel.basicQos(1); 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 { HttpResponse response; String[] requestParts = message.split("\\" + Protocol.DELIMITER); String status = requestParts[0]; String key = requestParts[requestParts.length - 1]; String requestType = responseCodes.get(Integer.parseInt(status)); if (requestType != null) { String file = requestParts[1]; File f = new File(file); response = HttpResponseFactory.createRequestWithFile(f, Protocol.CLOSE, requestType); } else { response = HttpResponseFactory.createRequest(status, Protocol.CLOSE); } ConnectionHandler ch = clients.get(key); ch.setResponse(response); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println(" [x] Done"); channel.basicAck(envelope.getDeliveryTag(), false); // send a proper acknowledgment from the worker, once we're done with a task } } }; channel.basicConsume(Protocol.RESPONSE_QUEUE, false, consumer); }
From source file:server.Worker.java
License:Open Source License
/** * @param args// www.j a v a 2 s .co m * @throws IOException * @throws TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection requestConnection = factory.newConnection(); Channel requestChannel = requestConnection.createChannel(); requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Connection responseConnection = factory.newConnection(); final Channel responseChannel = responseConnection.createChannel(); responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null); Consumer consumer = new DefaultConsumer(requestChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { PriorityRequest request = (PriorityRequest) SerializationUtils.deserialize(body); System.out.println(" [x] Received"); System.out.println(request.request.toString()); System.out.println("*************************************"); System.out.println(request.request.getMethod()); HttpResponse response = PluginManager.getInstance().process(request.request, request.rootDir); if (response == null) { response = HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } try { System.out.println(request.id); } catch (Exception e) { e.printStackTrace(); } response.id = request.id; byte[] data = SerializationUtils.serialize(response); responseChannel.basicPublish("", RESPONSE_QUEUE_NAME, null, data); } }; requestChannel.basicConsume(REQUEST_QUEUE_NAME, true, consumer); }
From source file:server.WorkerServer.java
License:Open Source License
@Override public void run() { //System.out.println("Running worker queue for: " + QUEUE_NAME); try {// w w w .j a va 2s.c o m factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); boolean durable = true; channel.queueDeclare(QUEUE_NAME, durable, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(10); 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"); HttpRequest request = createRequest(message); System.out.println(" [x] Received '" + message + "'"); try { doWork(request); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println(" [x] Done"); // send a proper acknowledgment from the worker, once we're done with a task channel.basicAck(envelope.getDeliveryTag(), false); } } private HttpRequest createRequest(String message) { String[] requestParts = message.split("\\" + Protocol.DELIMITER); String method = requestParts[0]; String uri = requestParts[1]; String version = requestParts[2]; HashMap<String, String> header = new HashMap<String, String>(); for (int i = 3; i < requestParts.length - 2; i += 2) { header.put(requestParts[i], requestParts[i + 1]); } String body = requestParts[requestParts.length - 2]; String key = requestParts[requestParts.length - 1]; return new HttpRequest(method, uri, version, header, body, key); } }; channel.basicConsume(QUEUE_NAME, false, consumer); } catch (Exception 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 www. jav a 2 s .co m 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:stock84885customer.CustomerController.java
private void initResultChannel() throws IOException, TimeoutException { resultChannel = connection.createChannel(); resultChannel.exchangeDeclare(resultsExchangeName, "direct"); resultQueueName = resultChannel.queueDeclare().getQueue(); resultChannel.queueBind(resultQueueName, resultsExchangeName, name); resultConsumer = new DefaultConsumer(resultChannel) { @Override/*ww w.j av a 2 s . c om*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { handleOrderResult(new String(body, "UTF-8")); } catch (Exception ex) { logger.error(ex.toString()); } } }; }
From source file:stock84885customer.CustomerController.java
private void initDeliveryChannel() throws IOException, TimeoutException { deliveryChannel = connection.createChannel(); deliveryChannel.exchangeDeclare(deliveryExchangeName, "direct"); deliveryQueueName = deliveryChannel.queueDeclare().getQueue(); deliveryChannel.queueBind(deliveryQueueName, deliveryExchangeName, name); deliveryConsumer = new DefaultConsumer(deliveryChannel) { @Override/* w w w. ja v a 2 s . c o m*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String orderID = new String(body, "UTF-8"); logger.trace(name + " received order " + orderID + "!"); try { releaseNetworkResources(); } catch (TimeoutException ex) { logger.error(ex.toString()); } } }; }