Java tutorial
/* * 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_DLR_CONSUMERS_1000 -Dhsmart-config-path=/home/vibhor/installs/HSMART2/config */ package com.netcore.hsmart.dlrconsumers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hazelcast.core.IMap; 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.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 org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider; import javax.ws.rs.ProcessingException; import java.util.logging.Level; import com.netcore.hsmart.hibernate.HibernateUtil; import com.netcore.hsmart.hibernate.entities.DlrStatusMap; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.logging.log4j.ThreadContext; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.json.JSONObject; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * @author root */ public class DlrConsumer559 { 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 DlrConsumer559Runnable(Integer.toString(i)); executor.execute(worker); } } /** * *******worker class******** */ public static class DlrConsumer559Runnable implements Runnable { private final String threadId; private ClientConfig CLIENT_CONFIG = new ClientConfig().connectorProvider(new GrizzlyConnectorProvider()); private Client CLIENT = null; private final static String GATEWAY_ID = "559"; private final static String VENDOR_DLR_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; private final static String VENDOR_TIME_ZONE = "Asia/Jakarta"; private final static String INDIAN_TIME_ZONE = "Asia/Kolkata"; private final static String EXPECTED_DLR_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private final static String DEFAULT_STATUS_FIELD_NAME = "status"; private final static String VENDOR_STATUS_FIELD_NAME = "delivery_status"; private final static String VENDOR_DLR_TIME_FIELD_NAME = "delivery_date"; private final static String DEFAULT_DLR_TIME_FIELD_NAME = "delivery_time"; private final static String DEFAULT_DLR_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private final static String CLIENT_MSG_ID_NAME = "MessageId"; private static IMap<String, String> refIdMap; /** * @param args * the command line arguments * @throws java.lang.Exception */ public DlrConsumer559Runnable(String str) { CLIENT_CONFIG.property(ClientProperties.CONNECT_TIMEOUT, 10000); CLIENT_CONFIG.property(ClientProperties.READ_TIMEOUT, 10000); CLIENT = ClientBuilder.newClient(CLIENT_CONFIG); threadId = str; } @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); } Logger logger = LoggerFactory.getLogger(this.getClass()); refIdMap = AppConstants.getHazelcastClient().getMap(GATEWAY_ID + "_REF_ID_MAP"); // refIdMap.put("0D0000006DFC571B", "1514121900101"); // logger.info("HSMART_REF_ID:"+refIdMap.get(CLIENT_MSG_ID_NAME)); try { 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"); } } }); 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.basicQos(1000); 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 = Utilities.decrypt(new String(body, "UTF-8")); JSONObject dataToPost = new JSONObject(payload); // Map<String, String> dataToPost = new HashMap<>(); logger.info("START+++++++++++++++"); logger.info("PAYLOAD:" + payload); // at time on DLR only if ("DLR".equals(dataToPost.getString("dlr_type"))) { // IMP logger.info("Fetching HSMART refId from Hazelcast"); dataToPost.put("ref_id", refIdMap.get(dataToPost.get(CLIENT_MSG_ID_NAME))); } long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { channel.basicAck(deliveryTag, false); if ("DLR".equals(dataToPost.getString("dlr_type"))) { // IMP refIdMap.delete(dataToPost.get(CLIENT_MSG_ID_NAME)); } } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); dataToPost = null; } }; String cTag = channel.basicConsume(AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID, false, consumer); logger.info("CONSUMER TAG : " + cTag); } catch (IOException e) { logger.error("RMQ_ERROR:" + e.getMessage()); } } private Map<String, String> getDmStatusDetails(String vendorStatus, String statusType) { ThreadContext.put("gatewayId", GATEWAY_ID); Logger logger = LoggerFactory.getLogger(this.getClass()); SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; List statusResult = null; Map<String, String> data = new HashMap<>(); try { String hql = "FROM DlrStatusMap WHERE status = :status AND gateway_id = :gateway_id AND type = :statusType"; tx = session.beginTransaction(); Query query = session.createQuery(hql); query.setParameter("status", vendorStatus); query.setParameter("gateway_id", GATEWAY_ID); query.setParameter("statusType", statusType); statusResult = query.list(); // if (statusResult.isEmpty()) { // // statusResult = null; // // String hql2 = "FROM DlrStatusMap WHERE status = :status AND // gateway_id = :gateway_id"; // Query query2 = session.createQuery(hql2); // query2.setParameter("status", DEFAULT_VENDOR_STATUS); // query2.setParameter("gateway_id", GATEWAY_ID); // // statusResult = query2.list(); // } for (Iterator iterator = statusResult.iterator(); iterator.hasNext();) { DlrStatusMap map = (DlrStatusMap) iterator.next(); data.put("id", map.getId().toString()); data.put("dm_status", map.getDmStatusMapped()); } tx.commit(); return data; } catch (HibernateException e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return null; } private Map<String, String> getISTDlrTime(String vendorDlrTime, String statusType) { ThreadContext.put("gatewayId", GATEWAY_ID); Logger logger = LoggerFactory.getLogger(this.getClass()); Map<String, String> data = new HashMap<>(); LocalDateTime ldt = null; if ("DLR".equals(statusType)) { logger.info("TIMEZONE_CONVERSION_SCHEME:" + VENDOR_TIME_ZONE + " TO " + INDIAN_TIME_ZONE); ldt = LocalDateTime.parse(vendorDlrTime, DateTimeFormatter.ofPattern(VENDOR_DLR_TIME_FORMAT)); ZoneId vendorZoneId = ZoneId.of(VENDOR_TIME_ZONE); ZonedDateTime vendorZonedDateTime = ldt.atZone(vendorZoneId); ZoneId kolkataZoneId = ZoneId.of(INDIAN_TIME_ZONE); ZonedDateTime kolkataDateTime = vendorZonedDateTime.withZoneSameInstant(kolkataZoneId); DateTimeFormatter format = DateTimeFormatter.ofPattern(EXPECTED_DLR_TIME_FORMAT); data.put("istZoneTime", format.format(kolkataDateTime)); data.put("vendorZoneTime", format.format(vendorZonedDateTime)); return data; } else { logger.info("TIMEZONE_CONVERSION_SCHEME:" + INDIAN_TIME_ZONE + " TO " + VENDOR_TIME_ZONE); ldt = LocalDateTime.parse(vendorDlrTime, DateTimeFormatter.ofPattern(DEFAULT_DLR_TIME_FORMAT)); ZoneId kolkataZoneId = ZoneId.of(INDIAN_TIME_ZONE); ZonedDateTime kolkataZonedDateTime = ldt.atZone(kolkataZoneId); ZoneId vendorZoneId = ZoneId.of(VENDOR_TIME_ZONE); ZonedDateTime vendorDateTime = kolkataZonedDateTime.withZoneSameInstant(vendorZoneId); DateTimeFormatter format = DateTimeFormatter.ofPattern(EXPECTED_DLR_TIME_FORMAT); data.put("istZoneTime", format.format(kolkataZonedDateTime)); data.put("vendorZoneTime", format.format(vendorDateTime)); return data; } } private boolean invokeApiCall(JSONObject dataToPost) { ThreadContext.put("gatewayId", GATEWAY_ID); Logger logger = LoggerFactory.getLogger(this.getClass()); try { // get type of status to fetch String statusType = dataToPost.getString("dlr_type"); Map<String, String> dlrTimeIST = null; // convert dlr time to IST time zone // get dm status Map<String, String> dmData = null; logger.info("REF_ID:" + dataToPost.get("ref_id") + "|GETTING_TIME_AND_STATUS_FOR_" + statusType); if ("DLR".equals(statusType)) { if (dataToPost.has(VENDOR_DLR_TIME_FIELD_NAME)) { dlrTimeIST = getISTDlrTime(dataToPost.getString(VENDOR_DLR_TIME_FIELD_NAME), statusType); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|NO_DLR_TIME_FOUND:assigning default)"); dlrTimeIST = getISTDlrTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), statusType); } if (dataToPost.has(VENDOR_STATUS_FIELD_NAME)) { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|STATUS_VAL_RECD:" + dataToPost.get(VENDOR_STATUS_FIELD_NAME)); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|FETCHING_DM_MAP_DATA"); dmData = getDmStatusDetails(dataToPost.get(VENDOR_STATUS_FIELD_NAME).toString(), statusType); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_STATUS,SETTING TO DEFAULT"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|FETCHING_DM_MAP_DATA_FOR_DEFAULT"); dmData = getDmStatusDetails(dataToPost.getString(DEFAULT_STATUS_FIELD_NAME), statusType); } } else { dlrTimeIST = getISTDlrTime(dataToPost.getString(DEFAULT_DLR_TIME_FIELD_NAME), statusType); dmData = getDmStatusDetails(dataToPost.getString(DEFAULT_STATUS_FIELD_NAME), statusType); } logger.info( "REF_ID:" + dataToPost.get("ref_id") + "|IST_DLR_TIME:" + dlrTimeIST.get("istZoneTime")); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|VENDOR_DLR_TIME:" + dlrTimeIST.get("vendorZoneTime")); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PK_ID_MAPPED:" + dmData.get("id")); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DM_STATUS:" + dmData.get("dm_status")); WebTarget webTarget = CLIENT.target(AppConstants.getDmDlrReturnApi()); WebTarget dlrTimeParam = webTarget.queryParam("delivery_time", dlrTimeIST.get("istZoneTime")); WebTarget statusParam = dlrTimeParam.queryParam("status", dmData.get("dm_status")); WebTarget gatewayIdParam = statusParam.queryParam("gateway_id", dataToPost.get("gateway_id")); WebTarget txnIdParam = gatewayIdParam.queryParam("transaction_id", dataToPost.get("ref_id")); WebTarget errorParam = txnIdParam.queryParam("error_code", dmData.get("dm_status")); URI u = errorParam.getUri(); Invocation.Builder invocationBuilder = errorParam.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); Integer responseStatus = response.getStatus(); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|HTTP_STATUS:" + responseStatus); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|RESPONSE_TEXT:" + responseText); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|URI:" + u.toString() + "|LENGTH:" + u.getQuery().length()); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|LATENCY:" + elapsedTime + "ms"); try { String g = Utilities.encrypt("ref_id" + AppConstants.getPayloadKVSeparator() + dataToPost.get("ref_id") + AppConstants.getPayloadGroupSeparator() + "expected_dlr_time_format" + AppConstants.getPayloadKVSeparator() + EXPECTED_DLR_TIME_FORMAT + AppConstants.getPayloadGroupSeparator() + "dlr_timestamp" + AppConstants.getPayloadKVSeparator() + dlrTimeIST.get("istZoneTime") + AppConstants.getPayloadGroupSeparator() + "dm_map_id" + AppConstants.getPayloadKVSeparator() + dmData.get("id") + AppConstants.getPayloadGroupSeparator() + "response_text" + AppConstants.getPayloadKVSeparator() + dataToPost.toString() + AppConstants.getPayloadGroupSeparator() + "vendor_dlr_time" + AppConstants.getPayloadKVSeparator() + dlrTimeIST.get("vendorZoneTime")); // Connection connection = // AppConstants.getRabbitMqObject().newConnection(); Channel channel = AppConstants.getRabbitMqConnection().createChannel(); channel.exchangeDeclare(AppConstants.getDlrDataExchangeName(), "direct"); channel.queueDeclare(AppConstants.getDlrDataQueuePrefix() + GATEWAY_ID, true, false, false, null); channel.queueBind(AppConstants.getDlrDataQueuePrefix() + GATEWAY_ID, AppConstants.getDlrDataExchangeName(), GATEWAY_ID); channel.basicPublish(AppConstants.getDlrDataExchangeName(), GATEWAY_ID, null, g.getBytes()); channel.close(); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_DATA:" + g); g = null; dataToPost = null; return true; } catch (Exception ex) { logger.error("ERROR:" + ex.getMessage() + Arrays.toString(ex.getStackTrace())); return false; } } catch (ProcessingException e) { logger.error("ERROR:" + e.getMessage() + Arrays.toString(e.getStackTrace())); return false; } catch (Exception ex) { logger.error("ERROR:" + ex.getMessage() + Arrays.toString(ex.getStackTrace())); return false; } } } }