com.netcore.hsmart.dlrreceiverserver.PublishDlr.java Source code

Java tutorial

Introduction

Here is the source code for com.netcore.hsmart.dlrreceiverserver.PublishDlr.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.
 */
/**
 * @TODO
 * ref_id parameter is MUST- it is a hash of ref_id + gateway_id
 * vendors can append their parameters in this webhook
 *
 * extract ref_id and decrypt - done
 * extract gateway id n check if valid - done
 * push to rabbitmq - done
 * correct json string - done
 * data to be put in status_map -
 *
 */

/**
 * TODO: 
 * Jetty based 
 * remove ref_id 
 * remove decryption
 * publish based on gid
 * 
 */
package com.netcore.hsmart.dlrreceiverserver;

import com.netcore.hsmart.AppConstants;
import com.netcore.hsmart.Utilities;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.rabbitmq.client.Channel;
import org.json.JSONObject;
import javax.ws.rs.core.MultivaluedMap;

/**
 *
 * @author root
 */
// @Path("publishDlr")
@Path("DlrPingback")
@Produces(MediaType.APPLICATION_JSON)
public class PublishDlr {

    private final static String DEFAULT_GATEWAY_ID = "NAN";

    // private Map<String, String> PAYLOAD = new HashMap<>();
    JSONObject PAYLOAD = new JSONObject();

    @POST
    @Path("post")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response processDlrRequestPOST(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
            @Context HttpServletRequest requestContext, MultivaluedMap<String, String> queryParams)
            throws TimeoutException, IOException {

        Logger logger = LoggerFactory.getLogger(PublishDlr.class);

        logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
                + "|GATEWAY_ID:" + AppConstants.getGatewayIdByCode(tempGatewayId) + "|QUERY_STRING:"
                + queryParams.toString());

        if (tempGatewayId == null || DEFAULT_GATEWAY_ID.equals(tempGatewayId) || "".equals(tempGatewayId)) { // gateway param in GET is not present

            if (queryParams.containsKey("gid")) {
                tempGatewayId = queryParams.get("gid").get(0);
                logger.info("gid param in POST");
                queryParams.add("gid", tempGatewayId);
            } else {
                queryParams.add("gid", null);
                logger.info("gid paramter missing");
            }
        } else {
            logger.info("gid param in GET");
            queryParams.add("gid", tempGatewayId);
        }

        logger.info("GID: " + tempGatewayId);

        if (queryParams.get("gid") != null
                && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

            String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

            // adding gateway stats per hour wise
            AppConstants.getHazelcastClient().getAtomicLong(
                    "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                    .incrementAndGet();

            try {

                // adding DLR type too

                PAYLOAD.put("gateway_id", gatewayId);
                PAYLOAD.put("dlr_type", "DLR");

                queryParams.forEach((k, v) -> buildPayload(k, v.get(0)));

                logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();

                channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                        null);
                channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                        AppConstants.getDlrReceiverExchangeName(), gatewayId);
                channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                        Utilities.encrypt(PAYLOAD.toString()).getBytes());

                channel.close();

                logger.info("PUBLISH_STATUS:SUCCESS");

                return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

            } catch (Exception e) {
                logger.error("ERROR:HSMART_PUBDLR_1600");
                logger.error("EXCEPTION:" + e.getMessage());
                logger.info("PUBLISH_STATUS:FAIL");
                return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                        .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                                AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                        .build();

            }

        } else {
            logger.error("ERROR:HSMART_PUBDLR_1001");
            logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                    .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                    .build();

        }

    }

    @GET
    @Path("get")
    public Response processDlrRequestGET(@DefaultValue(DEFAULT_GATEWAY_ID) @QueryParam("gid") String tempGatewayId,
            @Context HttpServletRequest requestContext) throws TimeoutException, IOException {

        Logger logger = LoggerFactory.getLogger(PublishDlr.class);

        Map<String, String[]> queryParams = requestContext.getParameterMap();

        logger.info("IP:" + requestContext.getRemoteAddr() + "|METHOD:" + requestContext.getMethod()
                + "|QUERY_STRING:" + requestContext.getQueryString());

        logger.info(AppConstants.getGatewayIdByCode(tempGatewayId));

        if (queryParams.get("gid") != null
                && Utilities.isValidGateway(AppConstants.getGatewayIdByCode(tempGatewayId))) {

            String gatewayId = AppConstants.getGatewayIdByCode(tempGatewayId);

            // adding gateway stats per hour wise
            AppConstants.getHazelcastClient().getAtomicLong(
                    "PUBDLR_GATEWAY_" + gatewayId + "_" + new SimpleDateFormat("yyyy-MM-dd-HH").format(new Date()))
                    .incrementAndGet();

            try {

                // adding DLR type too
                // PAYLOAD = AppConstants.getPayloadGroupSeparator() +
                // "gateway_id" + AppConstants.getPayloadKVSeparator()
                // + gatewayId+AppConstants.getPayloadGroupSeparator() +
                // "dlr_type" + AppConstants.getPayloadKVSeparator()
                // + "DLR";
                PAYLOAD.put("gateway_id", gatewayId);
                PAYLOAD.put("dlr_type", "DLR");

                // queryParams.forEach((k, v) -> buildPayload(k, v));

                Iterator i = queryParams.keySet().iterator();

                while (i.hasNext()) {

                    String key = (String) i.next();
                    String value = ((String[]) queryParams.get(key))[0];
                    buildPayload(key, value);

                }

                logger.info("PAYLOAD_FOR_MQ:" + PAYLOAD);

                Channel channel = AppConstants.getRabbitMqConnection().createChannel();

                channel.exchangeDeclare(AppConstants.getDlrReceiverExchangeName(), "direct");
                channel.queueDeclare(AppConstants.getDlrReceiverQueuePrefix() + gatewayId, true, false, false,
                        null);
                channel.queueBind(AppConstants.getDlrReceiverQueuePrefix() + gatewayId,
                        AppConstants.getDlrReceiverExchangeName(), gatewayId);
                channel.basicPublish(AppConstants.getDlrReceiverExchangeName(), gatewayId, null,
                        Utilities.encrypt(PAYLOAD.toString()).getBytes());

                channel.close();

                logger.info("PUBLISH_STATUS:SUCCESS");

                return Response.status(200).entity(buildJsonResponse("SUCCESS", "NULL", "NULL").toString()).build();

            } catch (Exception e) {
                logger.error("ERROR:HSMART_PUBDLR_1600");
                logger.error("EXCEPTION:" + e.getMessage());
                logger.info("PUBLISH_STATUS:FAIL");
                return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1600"))
                        .entity(buildJsonResponse("FAIL", "HSMART_PUBDLR_1600",
                                AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1600")).toString())
                        .build();

            }

        } else {
            logger.error("ERROR:HSMART_PUBDLR_1001");
            logger.error("ERROR_MSG:" + AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001"));
            logger.info("PUBLISH_STATUS:FAIL");
            return Response.status(AppConstants.getApplicationCodeHttpStatus("HSMART_PUBDLR_1001"))
                    .entity(buildJsonResponse("fail", "HSMART_PUBDLR_1001",
                            AppConstants.getApplicationCodeMessage("HSMART_PUBDLR_1001")).toString())
                    .build();

        }

    }

    private void buildPayload(String key, String value) {

        PAYLOAD.put(key, value);
    }

    private JSONObject buildJsonResponse(String status, String errorCode, String errorDesc) {

        JSONObject jsonResponseBody = new JSONObject();

        JSONObject statusElement = new JSONObject();
        statusElement.accumulate("status", status);

        JSONObject errorElement = new JSONObject();
        errorElement.accumulate("code", errorCode);
        errorElement.accumulate("desc", errorDesc);

        jsonResponseBody.accumulate("response", statusElement);
        jsonResponseBody.accumulate("response", errorElement);

        // System.out.println(jsonResponseBody.toString());
        return jsonResponseBody;

    }
}