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_SMS_CONSUMERS_1000 -Dhsmart-config-path=/home/vibhor/installs/HSMART2/config */ package com.netcore.hsmart.smsconsumers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netcore.hsmart.AppConstants; import com.netcore.hsmart.InsecureHostnameVerifier; import com.netcore.hsmart.InsecureTrustManager; 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.net.URLEncoder; 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 javax.ws.rs.ProcessingException; import java.util.logging.Level; import java.text.SimpleDateFormat; import java.util.Date; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.logging.log4j.ThreadContext; import org.json.JSONObject; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider; /** * * @author root */ public class SmsConsumer558 { private static final int COUNTERS = 10; public static void main(String args[]) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); for (int i = 1; i <= COUNTERS; i++) { Runnable worker = new SmsConsumer558Runnable(Integer.toString(i)); executor.execute(worker); } } /** * *******worker class******** */ public static class SmsConsumer558Runnable implements Runnable { private final String GATEWAY_ID = "558"; private final String GATEWAY_URL = "https://kudisms.net/netcore"; //private final String GATEWAY_URL = "http://192.168.104.89:5558/testgateway"; private final String API_SUCCESS_CALL_STATUS_VAL = "OK"; private Map<String, String> API_CALL_STATS = new HashMap<>(); private Map<String, String> DATA_POSTED = new HashMap<>(); private String encRefId = null; private final String threadId; private final static String NULLSTR = "null"; private final ClientConfig CLIENT_CONFIG = new ClientConfig() .connectorProvider(new GrizzlyConnectorProvider()); private final Client CLIENT = ClientBuilder.newClient(CLIENT_CONFIG); public SmsConsumer558Runnable(String str) { threadId = str; } /** * @param args the command line arguments * @throws java.lang.Exception */ @Override public void run() { /** * Set properties at runtime */ System.setProperty("smsconsumer_logfile_" + GATEWAY_ID, GATEWAY_ID + "_sms_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.getSmsReceiverQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getSmsReceiverExchangeName(); 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."); 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); String payload = new String(body, "UTF-8"); String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator()); for (String payloadPart : payloadParts) { String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator()); DATA_POSTED.put(s[0], s[1]); } logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|START+++++++++++++++"); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|PAYLOAD:" + payload); long deliveryTag = envelope.getDeliveryTag(); if (invokeApiCall()) { if (saveRequestData()) { channel.basicAck(deliveryTag, false); } else { channel.basicNack(deliveryTag, false, true); } } else { channel.basicNack(deliveryTag, false, true); } /** * release memory */ logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|END-----------------"); API_CALL_STATS.clear(); DATA_POSTED.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 boolean invokeApiCall() { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); try { encRefId = Utilities.encrypt(DATA_POSTED.get("ref_id") + "_" + DATA_POSTED.get("gateway_id")); SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8 System.setProperty("https.protocols", "TLSv1");//Java 8 TrustManager[] trustAllCerts = { new InsecureTrustManager() }; sc.init(null, trustAllCerts, new java.security.SecureRandom()); HostnameVerifier allHostsValid = new InsecureHostnameVerifier(); Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build(); WebTarget webTarget = client.target(GATEWAY_URL + "?message=" + DATA_POSTED.get("message")); //WebTarget webTarget = CLIENT.target(GATEWAY_URL); WebTarget apiKeyParam = webTarget.queryParam("username", "ncv@netcore.co.in"); WebTarget apiSecretParam = apiKeyParam.queryParam("password", "testcore**"); WebTarget refIdParam = apiSecretParam.queryParam("ref_id", encRefId); WebTarget fromParam = refIdParam.queryParam("sender", DATA_POSTED.get("sender_id")); WebTarget toParam = fromParam.queryParam("mobiles", DATA_POSTED.get("msisdn")); //WebTarget msgParam = toParam.queryParam("message", URLEncoder.encode(DATA_POSTED.get("message"),"UTF-8")); URI u = toParam.getUri(); Invocation.Builder invocationBuilder = toParam.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(); // response.close(); // client.close(); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|ENC_TEXT:" + encRefId); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|URI:" + u.toString() + "|LENGTH:" + u.getQuery().length()); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|LATENCY:" + elapsedTime + "ms"); API_CALL_STATS.put("ref_id", DATA_POSTED.get("ref_id")); API_CALL_STATS.put("gateway_id", DATA_POSTED.get("gateway_id")); API_CALL_STATS.put("enc_text", encRefId); API_CALL_STATS.put("uri", u.toString()); API_CALL_STATS.put("latency", String.valueOf(elapsedTime)); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|HTTP_STATUS:" + responseStatus); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|RESPONSE_TEXT:" + responseText); API_CALL_STATS.put("http_status", responseStatus.toString()); API_CALL_STATS.put("response_text", responseText); return parseVendorApiResponse(responseStatus, responseText); } catch (ProcessingException e) { logger.error("REF_ID: " + DATA_POSTED.get("ref_id") + "|VENDOR_API_CALL_ERROR:" + e.getMessage() + Arrays.toString(e.getStackTrace())); return false; } catch (Exception ex) { logger.error("REF_ID: " + DATA_POSTED.get("ref_id") + "|INVOKE_FUN_ERROR: " + ex.getMessage() + Arrays.toString(ex.getStackTrace())); java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex); return false; } } private boolean parseVendorApiResponse(Integer responseStatus, String responseText) { Logger logger = LoggerFactory.getLogger(this.getClass()); JSONObject jsonObj = new JSONObject(responseText); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|BALANCE:" + NULLSTR); API_CALL_STATS.put("balance", NULLSTR); /** * If http status other than 200 - fail if response status string * not equal to success status - fail Action: build DLR API url with * instant_dlr=true param and post to DLR receiver server */ if (!jsonObj.has("status") || !"200".equals(responseStatus.toString())) { logger.info( "REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_STATUS:" + jsonObj.getString("errno")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_COUNT:" + NULLSTR); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|PRICE:" + NULLSTR); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_ERROR_TEXT:" + jsonObj.getString("error")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_ID:" + NULLSTR); API_CALL_STATS.put("api_call_status", jsonObj.getString("errno")); API_CALL_STATS.put("msg_count", NULLSTR); API_CALL_STATS.put("price", NULLSTR); API_CALL_STATS.put("api_call_error_text", jsonObj.getString("error")); API_CALL_STATS.put("msg_id", NULLSTR); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_FAIL"); callDlrApi(); } else { logger.info( "REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_STATUS:" + jsonObj.getString("status")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_COUNT:" + jsonObj.get("count")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|PRICE:" + jsonObj.get("price")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_ERROR_TEXT:" + NULLSTR); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|MSG_ID:" + jsonObj.getString("kudi_id")); API_CALL_STATS.put("api_call_status", jsonObj.getString("status")); API_CALL_STATS.put("msg_count", Integer.toString(jsonObj.getInt("count"))); API_CALL_STATS.put("price", Integer.toString(jsonObj.getInt("price"))); API_CALL_STATS.put("api_call_error_text", NULLSTR); API_CALL_STATS.put("msg_id", jsonObj.getString("kudi_id")); logger.info("REF_ID:" + DATA_POSTED.get("ref_id") + "|API_CALL_SUCCESS"); } return true; } /** * Call and capture response */ private void callDlrApi() { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|SENDING_INSTANT_DLR"); try { WebTarget webTarget = CLIENT .target(AppConstants.getHttpProtocol() + "://" + AppConstants.getDlrrecvServerHost() + ":" + AppConstants.getDlrrecvServerPort() + "/publishDlr"); WebTarget refParam = webTarget.queryParam("ref_id", API_CALL_STATS.get("enc_text")); WebTarget statusParam = refParam.queryParam("status", API_CALL_STATS.get("api_call_status")); WebTarget gatewayIdParam = statusParam.queryParam("gateway_id", GATEWAY_ID); WebTarget txnIdParam = gatewayIdParam.queryParam("transaction_id", API_CALL_STATS.get("ref_id")); WebTarget errorParam = txnIdParam.queryParam("error_code", API_CALL_STATS.get("api_call_status")); WebTarget dlrTypeParam = errorParam.queryParam("dlr_type", "instant-API"); String dlrTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); WebTarget dlrTimeParam = dlrTypeParam.queryParam("delivery_time", dlrTime); URI u = dlrTimeParam.getUri(); logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|INSTANT_DLR_URL:" + u.toString()); Invocation.Builder invocationBuilder = dlrTimeParam.request(); 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:" + API_CALL_STATS.get("ref_id") + "|INSTANT_DLR_CALL_STATUS:" + responseText + "|HTTP_STATUS:" + responseStatus + "|DELAY:" + elapsedTime + "ms"); } catch (Exception ex) { logger.error("REF_ID:" + API_CALL_STATS.get("ref_id") + "|ERROR_CALLING_DLR_API:" + ex); } //response.close(); //CLIENT.close(); } private boolean saveRequestData() { Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadContext.put("threadId", threadId); try { JSONObject jobj = new JSONObject(API_CALL_STATS); String g = Utilities.encrypt(jobj.toString()); final String queueName = AppConstants.getSmsDataQueuePrefix() + GATEWAY_ID; final String exchangeName = AppConstants.getSmsDataExchangeName(); 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:" + API_CALL_STATS.get("ref_id") + "|DB_DATA:" + g); g = null; } catch (Exception ex) { java.util.logging.Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex); } return true; } } }