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.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//w w w. java 2 s.c o 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 + "'"); //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//from www .j a v a2 s . c om 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.nesscomputing.amqp.ExchangePublisher.java
License:Apache License
@Override protected void publish(final PublisherData publisherData) throws IOException { final Channel channel = channelConnect(); // An exchange has its own name and the default routing key... channel.basicPublish(getName(), routingKey, publisherData.getProperties(), publisherData.getData()); }
From source file:com.nesscomputing.amqp.QueuePublisher.java
License:Apache License
@Override protected void publish(final PublisherData publisherData) throws IOException { final Channel channel = channelConnect(); // A queue is a routing key on the default exchange... channel.basicPublish("", getName(), publisherData.getProperties(), publisherData.getData()); }
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 w w . j a v a2 s.com 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();/* www. ja v a2 s . c o m*/ 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.smsreceiverserver.PublishSms.java
@GET public Response processSmsRequest(@DefaultValue(DEFAULT_MSIDIN) @QueryParam("mobile_number") String msisdn, @DefaultValue(DEFAULT_MSG_TYPE) @QueryParam("message_type") String msgType, @DefaultValue(DEFAULT_MESSAGE) @QueryParam("message") String message, @DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gateway_id") String gatewayId, @DefaultValue(DEFAULT_SENDER_ID) @QueryParam("sender_id") String senderId, @DefaultValue(DEFAULT_PRIORITY) @QueryParam("priority") String priority, @Context HttpServletRequest requestContext) throws TimeoutException, IOException { Logger logger = LoggerFactory.getLogger(PublishSms.class); Long REF_ID = null;/* w w w . j av a 2 s . c o m*/ try { REF_ID = AppConstants.refIdCounter().getAndIncrement(); //adding gateway stats per hour wise AppConstants.getHazelcastClient().getAtomicLong( "PUBSMS_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())) .incrementAndGet(); //logger.info("TOTAL_HITS:"+AppConstants.getHazelcastClient().getAtomicLong("PUBSMS_GATEWAY_"+gatewayId+"_"+new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date())).get()); } catch (Exception e) { logger.error("REF_ID:" + REF_ID + "|HAZELCAST_ERROR:" + e.getMessage()); logger.error( "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")); logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:" + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001")); return Response.status(400).entity( "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001") + "</desc></error></response></HTTP>") .build(); } logger.info("REF_ID:" + REF_ID + "|QUERY_STRING:" + requestContext.getQueryString()); logger.info("REF_ID:" + REF_ID + "|IP:" + requestContext.getRemoteAddr()); //logger.info("REF_ID:" + REF_ID + "|GAT:" + AppConstants.getGatewayCode(gatewayId)); if ((msisdn == null ? (DEFAULT_MSIDIN != null) : !msisdn.equals(DEFAULT_MSIDIN) && !msisdn.isEmpty()) && (msgType == null ? (DEFAULT_MSG_TYPE != null) : !msgType.equals(DEFAULT_MSG_TYPE) && !msgType.isEmpty()) && (message == null ? (DEFAULT_MESSAGE != null) : !message.equals(DEFAULT_MESSAGE) && !message.isEmpty()) && (gatewayId == null ? (DEFAULT_GATEWAY_ID != null) : !gatewayId.equals(DEFAULT_GATEWAY_ID) && !gatewayId.isEmpty()) && (senderId == null ? (DEFAULT_SENDER_ID != null) : !senderId.equals(DEFAULT_SENDER_ID) && !senderId.isEmpty()) && (priority == null ? (DEFAULT_PRIORITY != null) : !priority.equals(DEFAULT_PRIORITY) && !priority.isEmpty())) { Boolean isValidGateway = Utilities.isValidGateway(gatewayId); if (isValidGateway) { try { final String payload = "ref_id" + AppConstants.getPayloadKVSeparator() + REF_ID + AppConstants.getPayloadGroupSeparator() + "gateway_id" + AppConstants.getPayloadKVSeparator() + gatewayId + AppConstants.getPayloadGroupSeparator() + "message" + AppConstants.getPayloadKVSeparator() + URLEncoder.encode(message, "UTF-8") + AppConstants.getPayloadGroupSeparator() + "msisdn" + AppConstants.getPayloadKVSeparator() + msisdn + AppConstants.getPayloadGroupSeparator() + "sender_id" + AppConstants.getPayloadKVSeparator() + senderId + AppConstants.getPayloadGroupSeparator() + "message_type" + AppConstants.getPayloadKVSeparator() + msgType; logger.info("REF_ID:" + REF_ID + "|PAYLOAD_FOR_MQ:" + payload); Channel channel = AppConstants.getRabbitMqConnection().createChannel(); channel.exchangeDeclare(AppConstants.getSmsReceiverExchangeName(), "direct"); channel.queueDeclare(AppConstants.getSmsReceiverQueuePrefix() + gatewayId, true, false, false, null); channel.queueBind(AppConstants.getSmsReceiverQueuePrefix() + gatewayId, AppConstants.getSmsReceiverExchangeName(), gatewayId); channel.basicPublish(AppConstants.getSmsReceiverExchangeName(), gatewayId, null, payload.getBytes()); channel.close(); //AppConstants.getRabbitMqConnection().close(); logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:" + AppConstants.getApplicationCodeMessage("HSMART_GEN_1000")); return Response.status(200).entity("<?xml version='1.0'?><HTTP><response><requestid>" + REF_ID + "</requestid></response></HTTP>").build(); } catch (NumberFormatException | IOException | TimeoutException e) { logger.error("REF_ID:" + REF_ID + "|EXCEPTION:" + e.getMessage()); logger.error("REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001")); logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:" + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001")); return Response.status(400).entity( "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1001</code><desc>" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1001") + "</desc></error></response></HTTP>") .build(); } } else { logger.error("REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002")); logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:" + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001")); return Response.status(400).entity( "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1002</code><desc>" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1002") + "</desc></error></response></HTTP>") .build(); } } else { logger.error( "REF_ID:" + REF_ID + "|ERROR:" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003")); logger.info("REF_ID:" + REF_ID + "|PUBLISH_STATUS:" + AppConstants.getApplicationCodeMessage("HSMART_GEN_1001")); return Response.status(400).entity( "<?xml version='1.0'?><HTTP><response><status>fail</status><error><code>HSMART_PUBSMS_1003</code><desc>" + AppConstants.getApplicationCodeMessage("HSMART_PUBSMS_1003") + "</desc></error></response></HTTP>") .build(); } }
From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQProducer.java
License:Apache License
/** * Send a message borrowing a channel from the pool. * * @param exchange Target exchange/*from w ww. ja va 2s . c o m*/ * @param routingKey Routing key * @param properties Header properties * @param body Body content */ private void basicPublish(final String exchange, final String routingKey, final AMQP.BasicProperties properties, final byte[] body) throws Exception { if (channelPool == null) { // Open connection and channel lazily openConnectionAndChannelPool(); } execute(new ChannelCallback<Void>() { @Override public Void doWithChannel(Channel channel) throws Exception { channel.basicPublish(exchange, routingKey, properties, body); return null; } }); }
From source file:com.pcs.test.amqp.Publisher.java
License:Open Source License
public static void main(String[] args) throws IOException, TimeoutException { System.out.println("starting"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("pcss-hdop04"); factory.setAutomaticRecoveryEnabled(true); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "first message , hello world"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("message sent"); channel.close();//from w w w. j a v a2 s .c o m connection.close(); }
From source file:com.project.finalproject.Send.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.queueDeclare(QUEUE_NAME, false, false, false, null); try {/*from w ww .j a v a 2 s . co m*/ InputStream is = new FileInputStream("hr.json"); String jsontxt = IOUtils.toString(is); JSONObject jsonObject = new JSONObject(jsontxt); JSONArray stream = jsonObject.getJSONArray("stream"); for (int i = 0; i < stream.length(); i++) { String message = stream.getJSONObject(i).getString("value"); channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); TimeUnit.SECONDS.sleep(1); } } catch (FileNotFoundException fe) { fe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } channel.close(); connection.close(); }