com.netcore.hsmart.smsconsumers.SmsConsumer555.java Source code

Java tutorial

Introduction

Here is the source code for com.netcore.hsmart.smsconsumers.SmsConsumer555.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
    
mvn exec:java@HSMART_SMS_CONSUMERS_1000 -Dhsmart-config-path=/home/vibhor/installs/HSMART2/config
 */
package com.netcore.hsmart.smsconsumers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netcore.hsmart.AppConstants;
import com.netcore.hsmart.Utilities;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.Method;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import javax.ws.rs.ProcessingException;
import java.util.logging.Level;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.logging.log4j.ThreadContext;
import org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider;

import org.json.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author root
 */
public class SmsConsumer555 {

    private static final int COUNTERS = 10;

    public static void main(String args[]) throws Exception {

        ExecutorService executor = Executors.newCachedThreadPool();

        for (int i = 1; i <= COUNTERS; i++) {
            Runnable worker = new SmsConsumer555Runnable(Integer.toString(i));
            executor.execute(worker);
        }
    }

    /**
     * *******worker class********
     */
    public static class SmsConsumer555Runnable implements Runnable {

        private final static String GATEWAY_ID = "555";

        private final static String GATEWAY_URL = "http://smsgw.sprintasia.net:8085/OTPmobile/msg_netcore.php";
        //private final String GATEWAY_URL = "http://192.168.104.89:5000/testgateway";
        private final static String API_SUCCESS_CALL_STATUS_VAL = "0";

        private final Map<String, String> API_CALL_STATS = new HashMap<>();
        private final Map<String, String> DATA_POSTED = new HashMap<>();
        private String encRefId = null;
        private final ClientConfig CLIENT_CONFIG = new ClientConfig()
                .connectorProvider(new GrizzlyConnectorProvider());
        private final Client CLIENT = ClientBuilder.newClient(CLIENT_CONFIG);
        private final String threadId;

        public SmsConsumer555Runnable(String str) {
            threadId = str;

        }

        /**
         * @param args the command line arguments
         * @throws java.lang.Exception
         */
        //public static void main(String[] args) throws Exception {
        @Override
        public void run() {
            /**
             * Set properties at runtime
             */

            System.setProperty("smsconsumer_logfile_" + GATEWAY_ID, GATEWAY_ID + "_sms_consumer");
            ThreadContext.put("threadId", threadId);

            try {
                AppConstants.loadAppConfig();
            } catch (ConfigurationException ex) {
                java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            }

            final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
            final String exchangeName = AppConstants.getSmsReceiverExchangeName();
            final String routingKey = GATEWAY_ID;

            Logger logger = LoggerFactory.getLogger(this.getClass());

            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 {
                        ThreadContext.put("threadId", threadId);

                        String payload = new String(body, "UTF-8");

                        String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                        for (String payloadPart : payloadParts) {
                            String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                            DATA_POSTED.put(s[0], s[1]);
                        }
                        logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|START+++++++++++++++");
                        logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|PAYLOAD:" + payload);

                        long deliveryTag = envelope.getDeliveryTag();

                        if (invokeApiCall()) {
                            if (saveRequestData()) {

                                channel.basicAck(deliveryTag, false);
                            } else {
                                channel.basicNack(deliveryTag, false, true);
                            }

                        } else {
                            channel.basicNack(deliveryTag, false, true);
                        }

                        /**
                         * release memory
                         */
                        logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|END-----------------");
                        API_CALL_STATS.clear();
                        DATA_POSTED.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());
            }
        }

        private boolean invokeApiCall() {
            Logger logger = LoggerFactory.getLogger(this.getClass());
            ThreadContext.put("threadId", threadId);
            try {

                encRefId = Utilities.encrypt(DATA_POSTED.get("ref_id") + "_" + DATA_POSTED.get("gateway_id"));

                WebTarget webTarget = CLIENT.target(GATEWAY_URL + "?m=" + DATA_POSTED.get("message"));
                WebTarget userParam = webTarget.queryParam("u", "netc0r3");
                WebTarget passParam = userParam.queryParam("p", "Ne7c053");

                //            WebTarget userParam = webTarget.queryParam("u", "NetcoteT3s");
                //            WebTarget passParam = userParam.queryParam("p", "JerBdwIcHer");
                WebTarget refIdParam = passParam.queryParam("r", encRefId);
                WebTarget gatewayIdParam = refIdParam.queryParam("g", GATEWAY_ID);
                WebTarget msisdnParam = gatewayIdParam.queryParam("d", DATA_POSTED.get("msisdn"));
                //WebTarget msgParam = msisdnParam.queryParam("m", URLEncoder.encode(DATA_POSTED.get("message"),"UTF-8"));
                WebTarget senderParam = msisdnParam.queryParam("s", DATA_POSTED.get("sender_id"));

                URI u = senderParam.getUri();

                Invocation.Builder invocationBuilder = senderParam.request();
                long startTime = System.currentTimeMillis();
                Response response = invocationBuilder.get();
                long elapsedTime = System.currentTimeMillis() - startTime;
                String responseText = response.readEntity(String.class);
                Integer responseStatus = response.getStatus();

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|ENC_TEXT:" + encRefId);
                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|URI:" + u.toString() + "|LENGTH:"
                        + u.getQuery().length());
                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|LATENCY:" + elapsedTime + "ms");

                API_CALL_STATS.put("ref_id", DATA_POSTED.get("ref_id"));
                API_CALL_STATS.put("gateway_id", DATA_POSTED.get("gateway_id"));
                API_CALL_STATS.put("enc_text", encRefId);
                API_CALL_STATS.put("uri", u.toString());
                API_CALL_STATS.put("latency", String.valueOf(elapsedTime));

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|HTTP_STATUS:" + responseStatus);
                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|RESPONSE_TEXT:" + responseText);

                API_CALL_STATS.put("http_status", responseStatus.toString());
                API_CALL_STATS.put("response_text", responseText);

                return parseVendorApiResponse(responseStatus, responseText);

            } catch (ProcessingException e) {
                logger.error("REF_ID: " + DATA_POSTED.get("ref_id") + "|VENDOR_API_CALL_ERROR:" + e.getMessage()
                        + Arrays.toString(e.getStackTrace()));
                return false;

            } catch (Exception ex) {
                logger.error("REF_ID: " + DATA_POSTED.get("ref_id") + "|INVOKE_FUN_ERROR: " + ex.getMessage()
                        + Arrays.toString(ex.getStackTrace()));
                java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
                return false;
            }

        }

        private boolean parseVendorApiResponse(Integer responseStatus, String responseText) {

            Logger logger = LoggerFactory.getLogger(this.getClass());
            ThreadContext.put("threadId", threadId);
            String nullStr = "NULL";

            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_COUNT:" + nullStr);

            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_ID:" + nullStr);
            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|PRICE:" + nullStr);
            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|BALANCE:" + nullStr);

            String s[] = responseText.split("-");

            API_CALL_STATS.put("api_call_status", s[0]);
            API_CALL_STATS.put("msg_id", s[1]);
            API_CALL_STATS.put("msg_count", nullStr);
            API_CALL_STATS.put("price", nullStr);
            API_CALL_STATS.put("balance", nullStr);

            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_STATUS:" + s[0]);

            /**
             * If http status other than 200 - fail if response status string
             * not equal to success status - fail Action: build DLR API url with
             * instant_dlr=true param and post to DLR receiver server
             */
            if ((s[0] == null ? API_SUCCESS_CALL_STATUS_VAL != null : !s[0].equals(API_SUCCESS_CALL_STATUS_VAL))
                    || !"200".equals(responseStatus.toString())) {

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_ERROR_TEXT:" + s[0]);

                API_CALL_STATS.put("api_call_error_text", s[0]);

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_FAIL");

                callDlrApi();

            } else {

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_ERROR_TEXT:" + nullStr);

                API_CALL_STATS.put("api_call_error_text", nullStr);

                logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_SUCCESS");
            }

            return true;

        }

        /**
         * Call and capture response
         */
        private void callDlrApi() {
            Logger logger = LoggerFactory.getLogger(this.getClass());
            ThreadContext.put("threadId", threadId);
            logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|SENDING_INSTANT_DLR");
            try {
                WebTarget webTarget = CLIENT
                        .target(AppConstants.getHttpProtocol() + "://" + AppConstants.getDlrrecvServerHost() + ":"
                                + AppConstants.getDlrrecvServerPort() + "/publishDlr");

                WebTarget refParam = webTarget.queryParam("ref_id", API_CALL_STATS.get("enc_text"));
                WebTarget statusParam = refParam.queryParam("status", API_CALL_STATS.get("api_call_status"));
                WebTarget gatewayIdParam = statusParam.queryParam("gateway_id", GATEWAY_ID);
                WebTarget txnIdParam = gatewayIdParam.queryParam("transaction_id", API_CALL_STATS.get("ref_id"));
                WebTarget errorParam = txnIdParam.queryParam("error_code", API_CALL_STATS.get("api_call_status"));
                WebTarget dlrTypeParam = errorParam.queryParam("dlr_type", "instant-API");

                String dlrTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                WebTarget dlrTimeParam = dlrTypeParam.queryParam("delivery_time", dlrTime);

                URI u = dlrTimeParam.getUri();

                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|INSTANT_DLR_URL:" + u.toString());

                Invocation.Builder invocationBuilder = dlrTimeParam.request();
                long startTime = System.currentTimeMillis();
                Response response = invocationBuilder.get();
                long elapsedTime = System.currentTimeMillis() - startTime;
                String responseText = response.readEntity(String.class);
                Integer responseStatus = response.getStatus();

                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|INSTANT_DLR_CALL_STATUS:" + responseText
                        + "|HTTP_STATUS:" + responseStatus + "|DELAY:" + elapsedTime + "ms");
            } catch (Exception ex) {
                logger.error("REF_ID:" + API_CALL_STATS.get("ref_id") + "|ERROR_CALLING_DLR_API:" + ex);
            } //response.close();
            //CLIENT.close();
        }

        private boolean saveRequestData() {
            Logger logger = LoggerFactory.getLogger(this.getClass());
            ThreadContext.put("threadId", threadId);
            try {
                JSONObject jobj = new JSONObject(API_CALL_STATS);
                String g = Utilities.encrypt(jobj.toString());

                final String queueName = AppConstants.getSmsDataQueuePrefix() + GATEWAY_ID;
                final String exchangeName = AppConstants.getSmsDataExchangeName();
                final String routingKey = GATEWAY_ID;
                Connection connection = AppConstants.getRabbitMqObject().newConnection();
                Channel channel = connection.createChannel();

                channel.exchangeDeclare(exchangeName, "direct");
                channel.queueDeclare(queueName, true, false, false, null);
                channel.queueBind(queueName, exchangeName, routingKey);
                channel.basicPublish(exchangeName, routingKey, null, g.getBytes());

                channel.close();
                connection.close();

                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|DB_DATA:" + g);
                g = null;
            } catch (Exception ex) {
                java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            }

            return true;

        }

    }
}