List of usage examples for com.rabbitmq.client Channel queueDeclare
Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) throws IOException;
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());//www. j a va 2s. 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 a v a 2 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.smsconsumers.SmsConsumer1000.java
/** * @param args the command line arguments * @throws java.lang.Exception//w w w . ja v a 2 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()); } }
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 a v 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.RabbitMQEndpoint.java
License:Apache License
/** * If needed, declare Exchange, declare Queue and bind them with Routing Key *//* w w w . j ava2s . c o m*/ public void declareExchangeAndQueue(Channel channel) throws IOException { HashMap<String, Object> queueArgs = null; if (deadLetterExchange != null) { queueArgs = new HashMap<String, Object>(); queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_EXCHANGE, getDeadLetterExchange()); queueArgs.put(RabbitMQConstants.RABBITMQ_DEAD_LETTER_ROUTING_KEY, getDeadLetterRoutingKey()); channel.exchangeDeclare(getDeadLetterExchange(), getDeadLetterExchangeType(), isDurable(), isAutoDelete(), new HashMap<String, Object>()); channel.queueDeclare(getDeadLetterQueue(), isDurable(), false, isAutoDelete(), null); channel.queueBind(getDeadLetterQueue(), getDeadLetterExchange(), getDeadLetterRoutingKey() == null ? "" : getDeadLetterRoutingKey()); } channel.exchangeDeclare(getExchangeName(), getExchangeType(), isDurable(), isAutoDelete(), new HashMap<String, Object>()); if (getQueue() != null) { // need to make sure the queueDeclare is same with the exchange declare channel.queueDeclare(getQueue(), isDurable(), false, isAutoDelete(), queueArgs); channel.queueBind(getQueue(), getExchangeName(), getRoutingKey() == null ? "" : getRoutingKey()); } }
From source file:com.pcs.test.amqp.Consumer.java
License:Open Source License
public static void main(String[] args) throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("pcss-hdop04"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println("listen for messages"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String msg = new String(delivery.getBody(), "UTF-8"); System.out.println("Msg received " + msg); }//from w w w . jav a2 s .c om }
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();/* w w w .jav a2 s . c o m*/ connection.close(); }
From source file:com.project.finalproject.Recv.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); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override//w ww . j a va2 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 + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
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 va2 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(); }
From source file:com.qt.core.util.MqConnectionUtil.java
License:Open Source License
public Channel getChannel(String key, String queueName, boolean durable) throws IOException { Connection connection = connectionMap.get(key); Channel channel = channelMap.get(key + queueName); if (channel == null || !channel.isOpen()) { channel = connection.createChannel(); channel.queueDeclare(queueName, durable, false, false, null); // ??? channelMap.put(key + queueName, channel); }//www . j a v a 2 s . c om return channel; }