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.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.DlrResponseData; import com.netcore.hsmart.hibernate.entities.DlrStatusMap; import java.text.DateFormat; 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.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * * @author root */ public class DlrConsumer1000 { private final static String GATEWAY_ID = "557"; private static final String VENDOR_DLR_TIME_FORMAT = "yyMMddHHmm"; private static final String VENDOR_TIME_ZONE = "Asia/Singapore"; private static final String EXPECTED_DLR_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * set this in case status value is empty or null */ private static final String DEFAULT_VENDOR_STATUS = "unknown"; /** * @param args the command line arguments * @throws java.lang.Exception */ public static void main(String[] args) throws Exception { /** * Set properties at runtime */ System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log"); AppConstants.loadAppConfig(); final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getDlrReceiverExchangeName(); final String routingKey = GATEWAY_ID; Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); try { Connection connection = AppConstants.getRabbitMqObject().newConnection(); connection.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 = 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 { 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 static Map<String, String> getDmStatusDetails(String vendorStatus) { Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Transaction tx = null; Map<String, String> data = new HashMap<String, String>(); try { String hql = "FROM DlrStatusMap WHERE status = :status AND gateway_id = :gateway_id"; tx = session.beginTransaction(); Query query = session.createQuery(hql); query.setParameter("status", vendorStatus); query.setParameter("gateway_id", GATEWAY_ID); List statusResult = query.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 static String getISTDlrTime(String vendorDlrTime) { if (vendorDlrTime != null) { LocalDateTime ldt = LocalDateTime.parse(vendorDlrTime, DateTimeFormatter.ofPattern(VENDOR_DLR_TIME_FORMAT)); ZoneId singaporeZoneId = ZoneId.of(VENDOR_TIME_ZONE); ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId); ZoneId kolkataZoneId = ZoneId.of("Asia/Kolkata"); ZonedDateTime kolkataDateTime = asiaZonedDateTime.withZoneSameInstant(kolkataZoneId); DateTimeFormatter format = DateTimeFormatter.ofPattern(EXPECTED_DLR_TIME_FORMAT); return format.format(kolkataDateTime); } else { Date now = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(EXPECTED_DLR_TIME_FORMAT); return formatter.format(now); } } private static boolean invokeApiCall(Map<String, String> dataToPost) { Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class); try { //convert dlr time to IST time zone String dlrTimeIST = getISTDlrTime(dataToPost.get("scts")); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|IST_DLR_TIME:" + dlrTimeIST); //get dm status Map<String, String> dmData = null; if (dataToPost.get("status") == null) { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_STATUS,SETTING TO DEFAULT"); dmData = getDmStatusDetails(DEFAULT_VENDOR_STATUS); } else { dmData = getDmStatusDetails(dataToPost.get("status")); } 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")); ClientConfig clientConfig = new ClientConfig(); clientConfig.connectorProvider(new GrizzlyConnectorProvider()); Client client = ClientBuilder.newClient(clientConfig); WebTarget webTarget = client.target(AppConstants.getDmDlrReturnApi()); WebTarget dlrTimeParam = webTarget.queryParam("delivery_time", dlrTimeIST); 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); response.close(); client.close(); 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"); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB operation started"); 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(EXPECTED_DLR_TIME_FORMAT); Date inputDate = dateFormat.parse(dlrTimeIST); res.setDlrTime(inputDate); res.setStatusMapId(dmData.get("id")); Date now = new Date(); res.setCreatedTime(now); session.save(res); session.getTransaction().commit(); logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DATA_SAVED"); return true; } catch (Exception e) { logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_ERROR:" + e.getMessage()); return false; } } catch (ProcessingException e) { logger.error("ERROR:" + e.getMessage() + Arrays.toString(e.getStackTrace())); return false; } catch (Exception ex) { java.util.logging.Logger.getLogger(DlrConsumer1000.class.getName()).log(Level.SEVERE, null, ex); return false; } } }