List of usage examples for com.rabbitmq.client Channel exchangeDeclare
Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type) throws IOException;
From source file:com.mycompany.javateste.queues.topic.EmitLogTopic.java
public static void main(String[] argv) { Connection connection = null; Channel channel = null; try {//from w w w. j a va2 s . c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String routingKey = getRouting(argv); String message = getMessage(argv); channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:com.mycompany.javateste.queues.topic.ReceiveLogsTopic.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); if (argv.length < 1) { System.err.println("Usage: ReceiveLogsTopic [binding_key]..."); System.exit(1);// w w w . j av a 2 s .com } for (String bindingKey : argv) { channel.queueBind(queueName, EXCHANGE_NAME, bindingKey); } System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 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 '" + envelope.getRoutingKey() + "':'" + message + "'"); } }; channel.basicConsume(queueName, true, consumer); }
From source file:com.mycompany.loanbroker.requestLoan.java
/** * Web service operation/*w w w . j av a 2s . c om*/ */ @WebMethod(operationName = "request") public String request(@WebParam(name = "ssn") String ssn, @WebParam(name = "loanAmount") double loanAmount, @WebParam(name = "loanDuration") int loanDuration) throws IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel sendingchannel = connection.createChannel(); Channel listeningChannel = connection.createChannel(); listeningChannel.exchangeDeclare(EXCHANGE, "direct"); listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null); listeningChannel.queueBind(LISTENING_QUEUE_NAME, EXCHANGE, ssn.replace("-", "")); sendingchannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null); message = ssn + "," + loanAmount + "," + loanDuration; sendingchannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes()); sendingchannel.close(); Consumer consumer = new DefaultConsumer(listeningChannel) { @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] The LoanBroker Has Received '" + message + "'"); result = message; } }; listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer); //connection.close(); return result; }
From source file:com.mycompany.net.Run.java
/** * @param args the command line arguments * @throws java.io.IOException/*from www . j a va 2s.com*/ * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { // TODO code application logic here JPA jpa = new JPA(); jpa.initDB(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange AMQP.Queue.DeclareOk result = channel.queueDeclare("", false, true, false, null); String queuename = result.getQueue(); //bind to sensor info channel.queueBind(queuename, "sensors", "gateway.data"); // Binding key is #, this will consume all messages //bind to the dashboard channel.queueBind(queuename, "sensors", "dashboard.request"); //bind to Processing units output channel.queueBind(queuename, "sensors", "database.put"); logger.info(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String message = new String(body, "UTF-8"); Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> myMap = gson.fromJson(message, type); logger.info(" [x] " + envelope.getRoutingKey() + " - Received '" + message + "'"); String routing_key = envelope.getRoutingKey(); if ("gateway.data".equals(routing_key)) { jpa.saveRawToDB(myMap); } else if ("database.put".equals(routing_key)) { jpa.saveAlertToDB(myMap); } else if ("dashboard.request".equals(routing_key)) { Thread.sleep(1000); jpa.processRequest(myMap, channel); } else logger.error("NOT A VALID MESSAGE!"); } catch (Exception e) { logger.error(e.toString()); } } }; channel.basicConsume(queuename, true, consumer); //channel.close(); //connection.close(); //entityManager.close(); //entityManagerFactory.close(); }
From source file:com.mycompany.normalizer.Normalizer.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); final Channel sendingChannel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); sendingChannel.exchangeDeclare(SENDING_QUEUE_NAME, "fanout"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override/*from w w w . ja v a 2 s . com*/ 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 + "'"); //HANDLE HERE if (message.startsWith("{")) { // Transform with GSON schoolBank = message.contains("-"); if (!schoolBank) { message = message.replace("-", ""); JResponse jresponse = gson.fromJson(message, JResponse.class); jresponse.setBank("cphbusiness.bankJSON"); message = gson.toJson(jresponse); } else { message = message.replace("-", ""); JResponse jresponse = gson.fromJson(message, JResponse.class); jresponse.setBank("DreamTeamBankJSON"); message = gson.toJson(jresponse); } sendingChannel.basicPublish(SENDING_QUEUE_NAME, "", null, message.getBytes()); } else { schoolBank = message.contains("-"); String result = ""; if (!schoolBank) { message = message.replace("-", ""); JSONObject soapDatainJsonObject = XML.toJSONObject(message); result = gson.toJson(soapDatainJsonObject); result = result.replace("{\"map\":{\"LoanResponse\":{\"map\":", ""); result = result.replace("}}}", ""); JResponse jresponse = gson.fromJson(result, JResponse.class); jresponse.setBank("cphbusiness.bankXML"); result = gson.toJson(jresponse); } else { message = message.replace("-", ""); JSONObject soapDatainJsonObject = XML.toJSONObject(message); result = gson.toJson(soapDatainJsonObject); result = result.replace("{\"map\":{\"LoanResponse\":{\"map\":", ""); result = result.replace("}}}", ""); JResponse jresponse = gson.fromJson(result, JResponse.class); jresponse.setBank("DreamTeamBankXML"); result = gson.toJson(jresponse); } // XResponse response = gson.fromJson(soapDatainJsonObject, XResponse.class); sendingChannel.basicPublish(SENDING_QUEUE_NAME, "", null, result.getBytes()); } } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
From source file:com.mycompany.receiptlist.ReceiptList.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); factory.setUsername("Dreamteam"); factory.setPassword("bastian"); Connection connection = factory.newConnection(); Channel listeningChannel = connection.createChannel(); final Channel sendingChannel = connection.createChannel(); listeningChannel.queueDeclare(QUEUE_NAME, false, false, false, null); sendingChannel.exchangeDeclare(EXCHANGE_NAME, "direct"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(listeningChannel) { @Override//ww w . j a v a 2 s. co m 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 + "'"); String[] arr = message.split(","); for (int i = 0; i < arr.length; i++) { switch (arr[i]) { case "DreamTeamXMLQueue": sendingChannel.basicPublish(EXCHANGE_NAME, "DreamTeamBankXML", null, message.getBytes()); break; case "DreamTeamJSONQueue": sendingChannel.basicPublish(EXCHANGE_NAME, "DreamTeamBankJSON", null, message.getBytes()); break; case "cphbusiness.bankXML": sendingChannel.basicPublish(EXCHANGE_NAME, "CphBusinessXML", null, message.getBytes()); break; case "cphbusiness.bankJSON": sendingChannel.basicPublish(EXCHANGE_NAME, "CphBusinessJSON", null, message.getBytes()); break; } } } }; listeningChannel.basicConsume(QUEUE_NAME, true, consumer); }
From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception// w ww. j a v a 2 s. co m */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); //check if any parameter is empty if (s.length == 2) { dataToPost.put(s[0], s[1]); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]); dataToPost.put(s[0], null); } } long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }
From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java
@POST @Path("post") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response processDlrRequestPOST(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId, @Context HttpServletRequest requestContext, MultivaluedMap<String, String> queryParams) throws TimeoutException, IOException { Logger logger = LoggerFactory.getLogger(PublishDlr.class); logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod() + "|GATEWAY_ID:" + AppConstants.getGatewayIdByCode(tempGatewayId) + "|QUERY_STRING:" + queryParams.toString());/* w ww . ja v a 2 s . c o m*/ if (tempGatewayId == null || DEFAULT_GATEWAY_ID.equals(tempGatewayId) || "".equals(tempGatewayId)) { // gateway param in GET is not present if (queryParams.containsKey("gid")) { tempGatewayId = queryParams.get("gid").get(0); logger.info("gid param in POST"); queryParams.add("gid", tempGatewayId); } else { queryParams.add("gid", null); logger.info("gid paramter missing"); } } else { logger.info("gid param in GET"); queryParams.add("gid", tempGatewayId); } logger.info("GID: " + tempGatewayId); if (queryParams.get("gid") != null && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) { String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId); // adding gateway stats per hour wise AppConstants.getHazelcastClient().getAtomicLong( "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())) .incrementAndGet(); try { // adding DLR type too PAYLOAD.put("gateway_id", gatewayId); PAYLOAD.put("dlr_type", "DLR"); queryParams.forEach((k, v) -> buildPayload(k, v.get(0))); logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD); Channel channel = AppConstants.getRabbitMqConnection().createChannel(); channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct"); channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false, null); channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, AppConstants.getDlrReceiverExchangeName(), gatewayId); channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null, Utilities.encrypt(PAYLOAD.toString()).getBytes()); channel.close(); logger.info("PUBLISH_STATUS:SUCCESS"); return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build(); } catch (Exception e) { logger.error("ERROR:HSMART_PUBDLR_1600"); logger.error("EXCEPTION:" + e.getMessage()); logger.info("PUBLISH_STATUS:FAIL"); return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600")) .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600", AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString()) .build(); } } else { logger.error("ERROR:HSMART_PUBDLR_1001"); logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")); logger.info("PUBLISH_STATUS:FAIL"); return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001")) .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001", AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString()) .build(); } }
From source file:com.netcore.hsmart.dlrreceiverserver.PublishDlr.java
@GET @Path("get") public Response processDlrRequestGET(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId, @Context HttpServletRequest requestContext) throws TimeoutException, IOException { Logger logger = LoggerFactory.getLogger(PublishDlr.class); Map<String, String[]> queryParams = requestContext.getParameterMap(); logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod() + "|QUERY_STRING:" + requestContext.getQueryString()); logger.info(AppConstants.getGatewayIdByCode(tempGatewayId)); if (queryParams.get("gid") != null && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) { String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId); // adding gateway stats per hour wise AppConstants.getHazelcastClient().getAtomicLong( "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())) .incrementAndGet();/* w ww. j av a 2 s . com*/ try { // adding DLR type too // PAYLOAD = AppConstants.getPayloadGroupSeparator() + // "gateway_id" + AppConstants.getPayloadKVSeparator() // + gatewayId+AppConstants.getPayloadGroupSeparator() + // "dlr_type" + AppConstants.getPayloadKVSeparator() // + "DLR"; PAYLOAD.put("gateway_id", gatewayId); PAYLOAD.put("dlr_type", "DLR"); // queryParams.forEach((k, v) -> buildPayload(k, v)); Iterator i = queryParams.keySet().iterator(); while (i.hasNext()) { String key = (String) i.next(); String value = ((String[]) queryParams.get(key))[0]; buildPayload(key, value); } logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD); Channel channel = AppConstants.getRabbitMqConnection().createChannel(); channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct"); channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false, null); channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, AppConstants.getDlrReceiverExchangeName(), gatewayId); channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null, Utilities.encrypt(PAYLOAD.toString()).getBytes()); channel.close(); logger.info("PUBLISH_STATUS:SUCCESS"); return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build(); } catch (Exception e) { logger.error("ERROR:HSMART_PUBDLR_1600"); logger.error("EXCEPTION:" + e.getMessage()); logger.info("PUBLISH_STATUS:FAIL"); return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600")) .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600", AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString()) .build(); } } else { logger.error("ERROR:HSMART_PUBDLR_1001"); logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")); logger.info("PUBLISH_STATUS:FAIL"); return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001")) .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001", AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString()) .build(); } }
From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception/*from ww w .j ava2 s . c o m*/ */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getSmsReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { //throw new UnsupportedOperationException("Not supported yet."); if (cause.isHardError()) { Connection conn; conn = (Connection) cause.getReference(); if (!cause.isInitiatedByApplication()) { Method reason = cause.getReason(); logger.info("REASON:" + reason.toString()); } } else { Channel ch = (Channel) cause.getReference(); logger.info("NO HARDSHUTDOWN"); } } }); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); channel.basicQos(1000); //channel.addShutdownListener(listener); logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C"); Consumer consumer; consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); dataToPost.put(s[0], s[1]); } logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { if (saveRequestData()) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); API_CALL_STATS.clear(); dataToPost.clear(); payloadParts = null; } }; String cTag = channel.basicConsume(queueName, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException | TimeoutException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } }