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.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.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.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; 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 DlrConsumer558 { private static final int COUNTERS = 5; public static void main(String args[]) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); for (int i = 1; i <= COUNTERS; i++) { Runnable worker = new DlrConsumer558Runnable(Integer.toString(i)); executor.execute(worker); } } /** * *******worker class******** */ public static class DlrConsumer558Runnable implements Runnable { private final String threadId; private final ClientConfig CLIENT_CONFIG = new ClientConfig() .connectorProvider(new GrizzlyConnectorProvider()); private final Client CLIENT = ClientBuilder.newClient(CLIENT_CONFIG); private final static String GATEWAY_ID = "558"; private final static String VENDOR_DLR_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private final static String VENDOR_TIME_ZONE = "Africa/Lagos"; 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_VENDOR_STATUS = "unknown"; private final static String STATUS_FIELD_NAME = "status"; private final static String DLR_TIME_FIELD_NAME = "time"; 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"; /** * @param args the command line arguments * @throws java.lang.Exception */ public DlrConsumer558Runnable(String str) { threadId = str; } @Override public void run() { /** * Set properties at runtime */ System.setProperty("dlrconsumer_logfile_" + GATEWAY_ID, GATEWAY_ID + "_dlr_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.getDlrReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrReceiverExchangeName(); 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."); ThreadContext.put("threadId", threadId); 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); Map<String, String> dataToPost = new HashMap<>(); String payload = new String(body, "UTF-8"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); //check if any parameter is empty if (s.length == 2) { dataToPost.put(s[0], s[1]); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]); dataToPost.put(s[0], null); } } long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall(dataToPost)) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------"); dataToPost.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 Map<String, String> getDmStatusDetails(String vendorStatus, String statusType) { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); 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) { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); 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(Map<String, String> dataToPost) { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); try { //get type of status to fetch String statusType = "DLR"; if (dataToPost.get("dlr_type") != null) { String d[] = dataToPost.get("dlr_type").split("-"); statusType = d[1]; } Map<String, String> dlrTimeIST = null; //convert dlr time to IST time zone if (null != dataToPost.get(DLR_TIME_FIELD_NAME)) { //getting dlr from vendors dlrTimeIST = getISTDlrTime(dataToPost.get(DLR_TIME_FIELD_NAME), statusType); } else { //instant DLR dlrTimeIST = getISTDlrTime(dataToPost.get(DEFAULT_DLR_TIME_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")); //get dm status Map<String, String> dmData = null; if (dataToPost.get(STATUS_FIELD_NAME) == null) { 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(DEFAULT_VENDOR_STATUS, statusType); } else { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|STATUS_VAL_RECD:" + dataToPost.get(STATUS_FIELD_NAME)); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|FETCHING_DM_MAP_DATA"); dmData = getDmStatusDetails(dataToPost.get(STATUS_FIELD_NAME), statusType); } 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 { JSONObject json = new JSONObject(dataToPost); 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() + json.toString(2) + AppConstants.getPayloadGroupSeparator() + "vendor_dlr_time" + AppConstants.getPayloadKVSeparator() + dlrTimeIST.get("vendorZoneTime")); final String queueName = AppConstants.getDlrDataQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrDataExchangeName(); 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:" + dataToPost.get("ref_id") + "|DB_DATA:" + g); g = null; json = null; return true; } catch (Exception ex) { java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex); return false; } } catch (ProcessingException e) { logger.error("ERROR:" + e.getMessage() + Arrays.toString(e.getStackTrace())); return false; } catch (Exception ex) { java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex); return false; } } } }