List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java
License:Apache License
@Override public void run() { Connection connection = null; Channel channel = null;// w w w . j a v a 2 s .c o m try { ConnectionFactory factory = new ConnectionFactory(); logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname); factory.setHost(hostname); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(rpcQueueName, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(rpcQueueName, false, consumer); while (true) { String response = null; // Block and fetch next msg from queue QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); try { String message = new String(delivery.getBody(), "UTF-8"); logger.trace("Received msg: " + message); // Convert the message to a JSON request object JSONObject request = (JSONObject) JSONValue.parse(message); // Delegate to the server request handler for handling the // request and computing an answer JSONObject reply = serverRequestHandler.handleRequest(request); // Convert the answer back into a string for replying to // client response = reply.toJSONString(); } catch (Exception e) { logger.error(" Exception in MQDAemon run()/while true] " + e.toString()); response = "wrong"; } finally { logger.trace("Returning answer: " + response); channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); logger.trace("Answer acknowledged."); } } } catch (Exception e) { logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage()); e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:de.dhbw.mannheim.assemblylinesim.AssemblyLineSim.java
License:Open Source License
/** * * @param hostname of the rabbitMq/* w w w .j a v a 2s.com*/ * @param speedUpFactor speed up factor to speed up simulation, e.g. 10 --> 10 times faster * @throws IOException is thrown if the connection to rabbitmq fails */ private AssemblyLineSim(String hostname, double speedUpFactor) throws IOException { (new RabbitListener(hostname)).start(); this.speedUpFactor = speedUpFactor; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostname); Connection connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(REPORT_EXCHANGE_NAME, "fanout"); }
From source file:de.dhbw.mannheim.erpsim.ErpSimulator.java
License:Open Source License
/** * * * @param args command line parameter//from ww w .java2s . c o m * args[0] number of customer orders that should be created * args[1] hostname of rabbitMQ * @throws IOException */ public static void main(String[] args) throws IOException { int numOfCustomerOrder = 10; String rabbitMqHostName = "localhost"; String rabbitMqUserName = null; String rabbitMqPassword = null; if (args.length >= 1) { try { numOfCustomerOrder = Integer.parseInt(args[0]); System.out.println("Number of customer orders: " + numOfCustomerOrder); } catch (Exception e) { System.err.println("Could not parse number of customer orders " + args[0]); } } if (args.length >= 2 && args[1] != null) { rabbitMqHostName = args[1]; System.out.println("Host of rabbitMq: " + rabbitMqHostName); } if (args.length >= 4 && args[2] != null && args[3] != null) { rabbitMqUserName = args[2]; rabbitMqPassword = args[3]; System.out.println("Username of rabbitMq: " + rabbitMqUserName); } CustomerOrder[] customerOrders = new CustomerOrder[numOfCustomerOrder]; for (int i = 0; i < customerOrders.length; i++) { customerOrders[i] = CustomerOrderGenerator.getCustomOrder(); } XStream xstream = new XStream(); xstream.registerConverter(new Converter() { @Override public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) { MachineOrder mo = (MachineOrder) o; writer.startNode("id"); writer.setValue(mo.getId()); writer.endNode(); } @Override public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) { return null; } @Override public boolean canConvert(Class aClass) { return aClass == MachineOrder.class; } }); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMqHostName); if (rabbitMqPassword != null && rabbitMqUserName != null) { factory.setUsername(rabbitMqUserName); factory.setPassword(rabbitMqPassword); } Connection connection = factory.newConnection(); Channel channelCO = connection.createChannel(); channelCO.exchangeDeclare(CUSTOMER_ORDER_EXCHANGE_NAME, "fanout"); for (CustomerOrder co : customerOrders) { String message = xstream.toXML(co); channelCO.basicPublish(CUSTOMER_ORDER_EXCHANGE_NAME, "", null, message.getBytes()); System.out.println("Send customer order"); } channelCO.close(); Channel channelMO = connection.createChannel(); channelMO.exchangeDeclare(MACHINE_ORDER_EXCHANGE_NAME, "fanout"); MachineOrder mo = MachineOrderGenerator.getRandomMachineOrder(); xstream = new XStream(); // reconstruct XStream to parse the full machine order, not just only the id while (mo != null) { int i = System.in.read(); String message = xstream.toXML(mo); channelMO.basicPublish(MACHINE_ORDER_EXCHANGE_NAME, "", null, message.getBytes()); System.out.println("Send Machine order"); mo = MachineOrderGenerator.getRandomMachineOrder(); } channelMO.close(); connection.close(); }
From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java
License:Apache License
/** * Creates an instance of {@link AMQPEndpoint} whilst * mocking all RabbitMQ-Classes / ifaces involved. * /*ww w . j av a2 s .co m*/ * @throws IOException */ @Test public void testAMQPLifecycle() throws IOException { // prepare mocks ConnectionFactory fac = mock(ConnectionFactory.class); Connection con = mock(Connection.class); Channel chan = mock(Channel.class); Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class); // ConnectionFactory when(fac.newConnection()).thenReturn(con); // Connection when(con.createChannel()).thenReturn(chan); // Channel when(chan.queueDeclare()).thenReturn(declareOK); // DeclareOK result object String queueName = "testQueue"; when(declareOK.getQueue()).thenReturn(queueName); AMQPEndpoint ep = new AMQPEndpoint(); Whitebox.setInternalState(ep, "connectionFactory", fac); ep.configure(this.exampleConf); ep.start(); // verify "important" connect methods were called verify(fac).newConnection(); verify(con).createChannel(); verify(chan).queueDeclare(); verify(declareOK).getQueue(); // in the example conf we're bindingn to 3 queues, let's check that String exchange = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_EXCHANGE_NAME); String routingKey = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_ROUTING_KEY); // listens for broadcasts verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast")); // listens for tasks verify(chan, times(1)).queueBind(eq("cit_stream_tasks_queue_" + routingKey), eq(exchange), eq("task." + routingKey)); // listens for broadcasts to broadcast.test verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast." + routingKey)); String exclusiveQueueName = Whitebox.getInternalState(ep, "exclusiveQueueName"); assertEquals(queueName, exclusiveQueueName); }
From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java
License:Apache License
/** * Tests sending a "normal" non-{@link de.tuberlin.cit.livescale.messaging.RequestMessage} * //from www.java 2 s . c o m * @throws IOException * @throws URISyntaxException */ @Test public void testAMQPSendNoResponse() throws IOException, URISyntaxException { ConnectionFactory fac = mock(ConnectionFactory.class); Connection con = mock(Connection.class); Channel chan = mock(Channel.class); Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class); // ConnectionFactory when(fac.newConnection()).thenReturn(con); // Connection when(con.createChannel()).thenReturn(chan); // Channel when(chan.queueDeclare()).thenReturn(declareOK); // DeclareOK result object String queueName = "testQueue"; when(declareOK.getQueue()).thenReturn(queueName); AMQPEndpoint ep = new AMQPEndpoint(); ep.setName("amqpTest"); Whitebox.setInternalState(ep, "connectionFactory", fac); ep.configure(this.exampleConf); // configuredRoutingKey String routingKey = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_ROUTING_KEY); URI targetURI = new URI("amqp:///test"); MessageCenter mc = new MessageCenter(false, this.emptyConf); mc.addEndpoint(ep); mc.startAllEndpoints(); assertTrue(mc.hasEndpointToURI(targetURI)); // kickin the jams mc.send(new TestMessage(), targetURI); // verify(chan, times(1)).basicPublish(eq(""), eq(routingKey), (BasicProperties) isNull(), (byte[]) any()); }
From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java
License:Apache License
/** * Tests message arrival on a {@link AMQPEndpoint} and * correctness of the generated responseURI in the * {@link MessageManifest} /*from w w w .j ava 2 s . c o m*/ * * @throws IOException * @throws URISyntaxException */ @Test public void testArrival() throws IOException, URISyntaxException { ConnectionFactory fac = mock(ConnectionFactory.class); Connection con = mock(Connection.class); Channel chan = mock(Channel.class); Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class); // ConnectionFactory when(fac.newConnection()).thenReturn(con); // Connection when(con.createChannel()).thenReturn(chan); // Channel when(chan.queueDeclare()).thenReturn(declareOK); // DeclareOK result object String queueName = "testQueue"; when(declareOK.getQueue()).thenReturn(queueName); AMQPEndpoint ep = new AMQPEndpoint(); String endpointName = "amqpTest"; ep.setName(endpointName); Whitebox.setInternalState(ep, "connectionFactory", fac); ep.configure(this.exampleConf); // hookup a listener MessageEndpointListener listener = mock(MessageEndpointListener.class); ep.addMessageEndpointListener(listener); // kickin the jams ep.start(); // hook up the consumer / manually call the callback ArgumentCaptor<DefaultConsumer> consumer = ArgumentCaptor.forClass(DefaultConsumer.class); // should in total consume the own queue and the tasks queue // depends on config settings verify(chan, times(2)).basicConsume(anyString(), anyBoolean(), (Consumer) anyObject()); verify(chan).basicConsume(eq(queueName), anyBoolean(), consumer.capture()); String replyQueueName = "replyQueue"; // faux envelope Envelope envelope = new Envelope(-1l, false, "daExchange", "daRoutingKey"); // faux properties BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName) .appId(UUID.randomUUID().toString()).build(); // faux message TestRequestMessage message = new TestRequestMessage(); // faux manifest MessageManifest mmIn = new MessageManifest(message, new URI("amqp:///targetQueue")); // call the callback function consumer.getValue().handleDelivery("leTag", envelope, props, MessageFactory.encode(mmIn)); ArgumentCaptor<MessageManifest> mm = ArgumentCaptor.forClass(MessageManifest.class); verify(listener).handleMessageReceived(mm.capture()); assertEquals("amqp", mm.getValue().getResponseURI().getScheme()); assertEquals(endpointName, mm.getValue().getResponseURI().getAuthority()); assertEquals("/" + replyQueueName, mm.getValue().getResponseURI().getPath()); }
From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java
License:Open Source License
public static void main(String[] argv) { Connection connection = null; Channel channel = null;/* w w w . ja v a 2 s . c o m*/ try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println("Starting server waiting for client requests:"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); DataInputStream dis = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(delivery.getBody()))); try { int type = dis.readInt(); byte[] response; if (type == 2) { response = handleMarketRequest(dis); } else { response = handleQuoteRequest(dis); } channel.basicPublish("", props.getReplyTo(), replyProps, response); dis.close(); } catch (IOException | ClassNotFoundException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException ignore) { } } } }
From source file:dk.bankjsonrabbit.messaging.Send.java
public static void sendMessage(String message, BasicProperties props) throws IOException, TimeoutException { String taskQueueName = props.getReplyTo(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(taskQueueName, true, false, false, null); channel.basicPublish("", taskQueueName, props, message.getBytes()); channel.close();//from w w w. ja v a 2 s. c o m connection.close(); }
From source file:dk.cphbusiness.group11.Translators.PoorBankWS.TranslatorPoorBankWS.java
private void parseAndProcessXmlMessage(String xmlMessage) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document loanRequestXml = builder.parse(new ByteArrayInputStream(xmlMessage.getBytes())); XPath xPath = XPathFactory.newInstance().newXPath(); Element loanDetailsElement = (Element) xPath.compile("/LoanDetails").evaluate(loanRequestXml, XPathConstants.NODE); String ssn = loanDetailsElement.getElementsByTagName("ssn").item(0).getTextContent(); int creditScore = Integer .parseInt(loanDetailsElement.getElementsByTagName("creditScore").item(0).getTextContent()); double loanAmount = Double .parseDouble(loanDetailsElement.getElementsByTagName("loanAmount").item(0).getTextContent()); String temp = loanDetailsElement.getElementsByTagName("loanDurationInMonths").item(0).getTextContent(); int loanDurationInMonths = Integer.parseInt(temp); PoorBankService_Service service = new PoorBankService_Service(); PoorBankService port = service.getPoorBankServiceImplPort(); PoorLoanResponsee result = port.poorLoan(ssn, creditScore, loanAmount, loanDurationInMonths); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(SENDING_QUEUE, "fanout"); String xmlReturnMessage = "<LoanResponse>" + "<interestRate>" + result.getInterestRate() + "</interestRate> \n" + " <ssn>" + result.getSsn() + "</ssn> \n" + "</LoanResponse>"; channel.basicPublish(SENDING_QUEUE, "", null, xmlReturnMessage.getBytes()); }
From source file:dk.cphbusiness.group11.Translators.PoorBankWS.TranslatorPoorBankWS.java
public void run() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(RECEIVING_QUEUE, "fanout"); String queueName = channel.queueDeclare(RECEIVING_QUEUE, false, false, false, null).getQueue(); channel.queueBind(queueName, RECEIVING_QUEUE, ""); System.out.println("Waiting for messages on queue: " + RECEIVING_QUEUE); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (this.isRunning) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("Received '" + message + "'"); this.parseAndProcessXmlMessage(message); }/*from w w w . ja va 2 s . c o m*/ }