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

Java tutorial

Introduction

Here is the source code for com.netcore.hsmart.dataconsumers.DlrDataConsumer.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.DlrResponseData;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;

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

    private static final int COUNTERS = Integer.parseInt(System.getProperty("thread-count"));
    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 DlrDataConsumerRunnable(Integer.toString(i), Integer.toString(GID));
            executor.execute(worker);
        }
    }

    /**
     * *******worker class********
     */
    public static class DlrDataConsumerRunnable implements Runnable {
        private final String threadId;
        private final String GATEWAY_ID;

        public DlrDataConsumerRunnable(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 {
                final String queueName = AppConstants.getDlrDataQueuePrefix() + GATEWAY_ID;
                final String exchangeName = AppConstants.getDlrDataExchangeName();
                final String routingKey = GATEWAY_ID;

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

                connection.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 = 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  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"));
                        String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());
                        for (String payloadPart : payloadParts) {
                            String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                            dataToPost.put(s[0], s[1]);
                        }

                        long deliveryTag = envelope.getDeliveryTag();

                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_OPERATION_START");
                        SessionFactory factory = HibernateUtil.getSessionFactory();
                        try (Session session = factory.getCurrentSession()) {
                            session.getTransaction().begin();
                            DlrResponseData res = new DlrResponseData();

                            res.setRefId(dataToPost.get("ref_id"));

                            DateFormat dateFormat = new SimpleDateFormat(
                                    dataToPost.get("expected_dlr_time_format"));
                            Date inputDate = dateFormat.parse(dataToPost.get("dlr_timestamp"));
                            Date vendorDate = dateFormat.parse(dataToPost.get("vendor_dlr_time"));
                            res.setDlrTime(inputDate);
                            res.setVendorDlrTime(vendorDate);
                            res.setResponseText(dataToPost.get("response_text"));
                            res.setStatusMapId(dataToPost.get("dm_map_id"));

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

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

                            channel.basicAck(deliveryTag, false);

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

                        }
                        dataToPost = null;
                        payload = null;
                        payloadParts = null;

                    }
                };

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

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

    }
}