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

Java tutorial

Introduction

Here is the source code for com.netcore.hsmart.smsconsumers.SmsConsumer561Multipart.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.hazelcast.core.IMap;
import com.netcore.hsmart.AppConstants;
import com.netcore.hsmart.InsecureHostnameVerifier;
import com.netcore.hsmart.InsecureTrustManager;
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.math.BigInteger;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
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 org.glassfish.jersey.client.ClientProperties;

import javax.ws.rs.ProcessingException;
import java.util.logging.Level;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.logging.log4j.ThreadContext;

import org.json.JSONObject;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider;

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

    private static final int COUNTERS = ((System.getProperty("thread-count") != null)
            ? Integer.parseInt(System.getProperty("thread-count"))
            : 1);

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

        ExecutorService executor = Executors.newCachedThreadPool();

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

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

        private final static String GATEWAY_ID = "561";

        private final String GATEWAY_URL = "https://s-esms.maxis.net.my:8443/servlet/smsdirect.jsp";
        //private final String GATEWAY_URL = "http://192.168.104.89:4000/api/dlr";
        private final String API_SUCCESS_CALL_STATUS_VAL = "01010";

        private Map<String, String> API_CALL_STATS = new HashMap<>();
        private Map<String, String> DATA_POSTED = new HashMap<>();

        private final String threadId;
        private final static String NULLSTR = "null";
        private ClientConfig CLIENT_CONFIG = new ClientConfig().connectorProvider(new GrizzlyConnectorProvider());
        private Client CLIENT = null;
        private static IMap<String, String> refIdMap = null;

        public SmsConsumer561MultipartRunnable(String str) {

            CLIENT_CONFIG.property(ClientProperties.CONNECT_TIMEOUT, 10000);
            CLIENT_CONFIG.property(ClientProperties.READ_TIMEOUT, 10000);
            CLIENT = ClientBuilder.newClient(CLIENT_CONFIG);

            SSLContext sc;
            try {
                sc = SSLContext.getInstance("TLSv1");
                TrustManager[] trustAllCerts = { new InsecureTrustManager() };
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                System.setProperty("https.protocols", "TLSv1");// Java 8
                HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
                CLIENT = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            threadId = str;
        }

        /**
         * @param args
         *            the command line arguments
         * @throws java.lang.Exception
         */
        @Override
        public void run() {

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

            // log file is same as 561 sms consumer
            Logger logger = LoggerFactory.getLogger(this.getClass());
            refIdMap = AppConstants.getHazelcastClient().getMap(GATEWAY_ID + "_REF_ID_MAP");

            try {

                // Connection connection =
                // AppConstants.getRabbitMqObject().newConnection();

                AppConstants.getRabbitMqConnection().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");
                        }
                    }
                });

                // note change in exchange and queue name
                Channel channel = AppConstants.getRabbitMqConnection().createChannel();
                channel.exchangeDeclare(AppConstants.getSmsReceiverExchangeName() + "_after_multipart_check",
                        "direct");
                channel.queueDeclare(
                        AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID + "_after_multipart_check", true,
                        false, false, null);
                channel.queueBind(AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID + "_after_multipart_check",
                        AppConstants.getSmsReceiverExchangeName() + "_after_multipart_check", GATEWAY_ID);
                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("gatewayId", GATEWAY_ID);

                        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(
                        AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID + "_after_multipart_check", false,
                        consumer);
                logger.info("CONSUMER TAG : " + cTag);

            } catch (IOException e) {
                logger.error("RMQ_ERROR:" + e.getMessage());
            }
        }

        private boolean invokeApiCall() {
            ThreadContext.put("gatewayId", GATEWAY_ID);

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

            try {

                String msg = null;
                switch (DATA_POSTED.get("message_type")) {
                case "1":
                    msg = DATA_POSTED.get("message");
                    break;
                case "2":

                    byte[] msgBytes = URLDecoder.decode(DATA_POSTED.get("message"), "UTF-8").getBytes("UTF-16BE");
                    BigInteger bigInt = new BigInteger(msgBytes);
                    String hexString = bigInt.toString(16); // 16 is the radix
                    StringBuilder buffer = new StringBuilder();

                    while ((buffer.length() + hexString.length()) < (2 * msgBytes.length)) {
                        buffer.append("0");
                    }
                    buffer.append(hexString);
                    msg = buffer.toString();

                    break;

                }

                WebTarget webTarget = CLIENT.target(GATEWAY_URL + "?Message=" + msg);

                WebTarget apiKeyParam = webTarget.queryParam("ID", "netcored11");
                WebTarget apiSecretParam = apiKeyParam.queryParam("Password", "Ne$c0re157");
                WebTarget toParam = apiSecretParam.queryParam("Mobile", DATA_POSTED.get("msisdn"));
                WebTarget dlrFlag = toParam.queryParam("DR", "true");
                WebTarget textType = dlrFlag.queryParam("Type",
                        ("1".equals(DATA_POSTED.get("message_type")) ? "A" : "U"));

                // IMP for multipart SMS

                URI u = null;
                Invocation.Builder invocationBuilder = null;

                if (DATA_POSTED.containsKey("is_multipart_msg")) {
                    WebTarget userHeader = textType.queryParam("UserHeader", DATA_POSTED.get("part_identifier"));
                    u = userHeader.getUri();
                    invocationBuilder = userHeader.request().header("Content-Length", u.getQuery().length());
                } else {

                    u = textType.getUri();
                    invocationBuilder = textType.request().header("Content-Length", u.getQuery().length());
                }

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

                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("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);

                //retry if get other than 200
                if (responseStatus != 200) {
                    logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|REQUEING_FOR_RETRY");
                    return false;
                }

                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_FUNC_ERROR: " + ex.getMessage()
                        + Arrays.toString(ex.getStackTrace()));
                java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
                return false;
            }

        }

        /**
         * TODO: handle HTTP status other than 200
         *
         * @param responseStatus
         * @param responseText
         * @return
         */
        private boolean parseVendorApiResponse(Integer responseStatus, String responseText) {
            ThreadContext.put("gatewayId", GATEWAY_ID);

            Logger logger = LoggerFactory.getLogger(this.getClass());
            // 01010,GW16_15101402402486155
            String s[] = responseText.split(",");

            logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_STATUS:" + s[0]);
            API_CALL_STATS.put("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") + "|MSG_ID:" + NULLSTR);
                API_CALL_STATS.put("msg_id", NULLSTR);

                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");

                refIdMap.put(DATA_POSTED.get("ref_id"), DATA_POSTED.get("ref_id"));

                callDlrApi();

            } else {

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

                API_CALL_STATS.put("msg_id", s[1]);

                API_CALL_STATS.put("api_call_error_text", NULLSTR);

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

                refIdMap.put(s[1], DATA_POSTED.get("ref_id"));
            }

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

            API_CALL_STATS.put("msg_count", NULLSTR);
            API_CALL_STATS.put("price", NULLSTR);
            API_CALL_STATS.put("balance", NULLSTR);

            return true;

        }

        private void callDlrApi() {
            ThreadContext.put("gatewayId", GATEWAY_ID);
            Logger logger = LoggerFactory.getLogger(this.getClass());

            Map<String, String> INSTANT_DLR_STATS = new HashMap<>();
            logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|SENDING_INSTANT_DLR");

            INSTANT_DLR_STATS.put("status", API_CALL_STATS.get("api_call_status"));
            INSTANT_DLR_STATS.put("gateway_id", GATEWAY_ID);
            INSTANT_DLR_STATS.put("ref_id", API_CALL_STATS.get("ref_id"));
            INSTANT_DLR_STATS.put("error_code", API_CALL_STATS.get("api_call_status"));
            INSTANT_DLR_STATS.put("dlr_type", "API");
            INSTANT_DLR_STATS.put("delivery_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            try {
                JSONObject jobj = new JSONObject(INSTANT_DLR_STATS);
                String g = Utilities.encrypt(jobj.toString());

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();

                channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID, true, false, false,
                        null);
                channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID,
                        AppConstants.getDlrReceiverExchangeName(), GATEWAY_ID);
                channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), GATEWAY_ID, null, g.getBytes());
                channel.close();
                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|INSTANT_DLR_DATA:" + g);
                g = null;
            } catch (Exception ex) {
                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|ERROR_PUBLISHING_INSTANT_DLR_DATA:"
                        + ex.getMessage());
            }

        }

        private boolean saveRequestData() {
            ThreadContext.put("gatewayId", GATEWAY_ID);
            Logger logger = LoggerFactory.getLogger(this.getClass());

            try {
                JSONObject jobj = new JSONObject(API_CALL_STATS);
                String g = Utilities.encrypt(jobj.toString());

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();

                channel.exchangeDeclare(AppConstants.getSmsDataExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getSmsDataQueuePrefix() + GATEWAY_ID, true, false, false, null);
                channel.queueBind(AppConstants.getSmsDataQueuePrefix() + GATEWAY_ID,
                        AppConstants.getSmsDataExchangeName(), GATEWAY_ID);
                channel.basicPublish(AppConstants.getSmsDataExchangeName(), GATEWAY_ID, null, g.getBytes());
                channel.close();
                logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|DB_DATA:" + g);
                g = null;
            } catch (Exception ex) {
                logger.info(
                        "REF_ID:" + API_CALL_STATS.get("ref_id") + "|ERROR_PUBLISHING_SMS_DATA:" + ex.getMessage());
            }

            return true;

        }
    }
}