Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllerStuff; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import java.io.IOException; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author thor */ public class ControllerPublisher { public static final String EXCHANGE_CONTOLLER_CMD = "controllerCommandExchange"; public static final String EXCHANGE_CONTROLLER_REGETRY = "controllerExchange"; public static final String BIND_KEY_BASE = "controller."; private final Connection connection; private final String nodeID; private Channel controllerChannel = null; /** * * @param connection * @param controllerObject */ public ControllerPublisher(Connection connection, String nodeID) { this.connection = connection; this.nodeID = nodeID; try { controllerChannel = connection.createChannel(); controllerChannel.exchangeDeclare(EXCHANGE_CONTROLLER_REGETRY, "topic"); } catch (IOException ex) { Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex); } } private void registerController(Controller controllerObject) { byte[] obj = controllerObject.toJsonString(); // String name = controllerObject.getName(); // System.out.println(" obj: "+ obj+" name " + name); try { controllerChannel.basicPublish(EXCHANGE_CONTROLLER_REGETRY, BIND_KEY_BASE + '.' + nodeID + '.' + controllerObject.getName(), null, obj); } catch (IOException ex) { Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex); } } private void attachControllerCallback(Controller controllerObject) { try { Channel controllerCallbackChannel = connection.createChannel(); controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic"); String sensChName = controllerCallbackChannel.queueDeclare().getQueue(); controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD, BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug controllerCallbackChannel.basicConsume(sensChName, true, new DefaultConsumer(controllerCallbackChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { controllerObject.call(new String(body, "UTF-8")); } }); } catch (IOException ex) { Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex); } } public void publishController(Controller controllerObject) { registerController(controllerObject); attachControllerCallback(controllerObject); } }