List of usage examples for com.rabbitmq.client Channel basicPublish
void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;
From source file:com.zuehlke.carrera.javapilot.show.ConfirmDontLoseMessages.java
License:Mozilla Public License
public static void main1(String[] args) throws IOException, InterruptedException, TimeoutException { connectionFactory = new ConnectionFactory(); String POWER_QUEUE = "/app/pilots/power"; String json = new JacksonSerializer().serialize(new PowerControl(200, "team", "access", 0L)); Connection conn = connectionFactory.newConnection(); Channel ch = conn.createChannel(); //ch.queueDeclare(POWER_QUEUE, true, false, false, null); AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().expiration("0").build(); ch.basicPublish("", POWER_QUEUE, props, json.getBytes()); String SENSOR_QUEUE = "/topic/pilots/starterkit/sensor"; SensorEvent sensorEvent = SensorEvent.createEmptyCarSensor().withRaceTrackId("simulator"); json = new JacksonSerializer().serialize(sensorEvent); //ch.queueDeclare(SENSOR_QUEUE, true, false, false, null); ch.basicPublish("", SENSOR_QUEUE, props, json.getBytes()); ch.close();//from ww w. j av a 2 s. co m conn.close(); }
From source file:controllers.TargetController.java
License:Open Source License
/** * This method pushes a message onto a RabbitMQ queue for given target * using global settings from project configuration file. * * @param target The field URL of the target * @return/* www. jav a 2 s .c o m*/ */ public static Result archive(Long id) { Target target = Target.findById(id); Logger.debug("archiveTarget() " + target); if (target != null) { if (!target.isInScopeAllOrInheritedWithoutLicense()) { return ok(infomessage.render("On-demand archiving is only supported for NPLD targets.")); } // Send the message: try { String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST); String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT); String queueName = Play.application().configuration().getString(Const.QUEUE_NAME); String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY); String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME); Logger.debug("archiveTarget() queue host: " + queueHost); Logger.debug("archiveTarget() queue port: " + queuePort); Logger.debug("archiveTarget() queue name: " + queueName); Logger.debug("archiveTarget() routing key: " + routingKey); Logger.debug("archiveTarget() exchange name: " + exchangeName); JsonNode jsonData = Json.toJson(target); String message = jsonData.toString(); Logger.debug("Crawl Now message: " + message); ConnectionFactory factory = new ConnectionFactory(); if (queueHost != null) { factory.setHost(queueHost); } if (queuePort != null) { factory.setPort(Integer.parseInt(queuePort)); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); BasicProperties.Builder propsBuilder = new BasicProperties.Builder(); propsBuilder.deliveryMode(2); channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes()); channel.close(); connection.close(); } catch (IOException e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } catch (Exception e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } } else { Logger.debug("There was a problem sending the message. Target field for archiving is empty"); return ok(infomessage .render("There was a problem sending the message. Target field for archiving is empty")); } return ok(ukwalicenceresult.render()); }
From source file:coyote.mq.AbstractMessagingTest.java
License:Open Source License
public void sendMessage(String queueName, DataFrame message) { if (StringUtil.isNotBlank(queueName) && message != null) { byte[] data = message.getBytes(); try {//ww w .jav a 2 s .c om ConnectionFactory factory = new ConnectionFactory(); factory.setUri(broker.getBrokerUri()); factory.useSslProtocol(); // username:password should be in the URI for our tests try (Connection connection = factory.newConnection()) { Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); channel.basicPublish("", queueName, null, data); Log.debug("Sent " + data.length + " bytes to '" + queueName + "'"); } } catch (Exception e) { Log.error("Could not send message: " + e.getClass().getSimpleName() + "-" + e.getMessage()); } } }
From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java
License:Apache License
@Override public void run() { Connection connection = null; Channel channel = null; try {/*from ww w. j a va 2 s . co m*/ 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.erpsim.ErpSimulator.java
License:Open Source License
/** * * * @param args command line parameter/* w w w. j a va 2s. c om*/ * 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:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java
License:Open Source License
private static void processSendAndRecivePackets(QueueingConsumer consumer, Channel channel) throws InterruptedException, IOException { while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build();/* w w w. ja v a2s .com*/ try { byte[] body = delivery.getBody(); if (body.length == 0) { break; } else { Object obj = SerializationUtils.deserialize(body); if (obj instanceof MarketData) { MarketData response = sendMarketData((MarketData) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } else { QuoteRequest response = sendQuoteRequest((QuoteRequest) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } } } catch (IOException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } }
From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java
License:Open Source License
public static void main(String[] argv) { Connection connection = null; Channel channel = null; try {/* ww w. ja v a 2 s . c om*/ 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 . java 2s. 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.getcreditscore.messaging.Send.java
public static void sendMessage(String message) throws IOException { 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(TASK_QUEUE_NAME, true, false, false, null); channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); channel.close();//from ww w .java 2 s .c o m connection.close(); }