com.netcore.hsmart.dataconsumers.SmsDataConsumer.java Source code

Java tutorial

Introduction

Here is the source code for com.netcore.hsmart.dataconsumers.SmsDataConsumer.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.
 */
package com.netcore.hsmart.dataconsumers;

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.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

import java.util.logging.Level;

import com.netcore.hsmart.hibernate.HibernateUtil;
import com.netcore.hsmart.hibernate.entities.SmsRequestData;

import java.util.Date;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.logging.log4j.ThreadContext;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONObject;

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

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

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

        ExecutorService executor = Executors.newCachedThreadPool();

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

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

        private final String threadId;
        private final String GATEWAY_ID;

        public SmsDataConsumerRunnable(String str, String gatewayId) {

            threadId = str;
            GATEWAY_ID = gatewayId;
        }

        @Override
        public void run() {

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

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

            try {

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

                AppConstants.getRabbitMqConnection().addShutdownListener(new ShutdownListener() {
                    @Override
                    public void shutdownCompleted(ShutdownSignalException cause) {
                        // throw new UnsupportedOperationException("Not
                        // supported yet.");
                        ThreadContext.put("gatewayId", GATEWAY_ID);
                        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 = 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.basicQos(1000);
                // channel.addShutdownListener(listener);
                logger.info(" [*] Waiting for messages  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);
                        // Map<String, String> dataToPost = new HashMap<>();
                        String payload = Utilities.decrypt(new String(body, "UTF-8"));
                        long deliveryTag = envelope.getDeliveryTag();
                        // logger.info(payload);
                        JSONObject dataToPost = new JSONObject(payload);
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_OPERATION_START");
                        SessionFactory factory = HibernateUtil.getSessionFactory();
                        try (Session session = factory.getCurrentSession()) {
                            session.getTransaction().begin();
                            SmsRequestData req = new SmsRequestData();
                            req.setRefId(dataToPost.get("ref_id").toString());
                            req.setGatewayId(dataToPost.get("gateway_id").toString());
                            // req.setEncText(dataToPost.get("enc_text").toString());
                            req.setUri(dataToPost.get("uri").toString());
                            req.setHttpStatus(dataToPost.get("http_status").toString());
                            req.setResponseText(dataToPost.get("response_text").toString());
                            req.setLatency(dataToPost.get("latency").toString());
                            req.setApiCallStatus(dataToPost.get("api_call_status").toString());
                            req.setMsgCount(dataToPost.get("msg_count").toString());
                            req.setMsgId(dataToPost.get("msg_id").toString());
                            req.setPrice(dataToPost.get("price").toString());
                            req.setBalance(dataToPost.get("balance").toString());
                            req.setApiCallErrorText(dataToPost.get("api_call_error_text").toString());

                            Date now = new Date();
                            req.setCreatedTime(now);
                            session.save(req);
                            session.getTransaction().commit();

                            channel.basicAck(deliveryTag, false);

                            logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DATA_SAVED");

                        } catch (Exception e) {
                            channel.basicNack(deliveryTag, false, true);
                            logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_ERROR:" + e.getMessage());

                        }
                    }
                };

                String cTag = channel.basicConsume(AppConstants.getSmsDataQueuePrefix() + GATEWAY_ID, false,
                        consumer);
                logger.info("CONSUMER TAG : " + cTag);

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

    }
}