added logging methods in helper
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.billpaymentservice.bbps.serviceImpl;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
@@ -23,8 +24,12 @@ import com.billpaymentservice.bbps.dto.response.FetchBillResponse;
|
||||
import com.billpaymentservice.bbps.dto.response.TransactionStatusResponse;
|
||||
import com.billpaymentservice.bbps.entites.BharatConnectMaster;
|
||||
import com.billpaymentservice.bbps.entites.BillPayment;
|
||||
import com.billpaymentservice.bbps.entites.InboundTraceLog;
|
||||
import com.billpaymentservice.bbps.entites.OutboundTraceLog;
|
||||
import com.billpaymentservice.bbps.exception.CustomException;
|
||||
import com.billpaymentservice.bbps.repository.BharatConnectMasterRepository;
|
||||
import com.billpaymentservice.bbps.repository.InboundTraceLogRepository;
|
||||
import com.billpaymentservice.bbps.repository.OutboundTraceLogRepository;
|
||||
import com.billpaymentservice.bbps.repository.PaymentRepository;
|
||||
import com.billpaymentservice.bbps.service.PaymentService;
|
||||
import com.billpaymentservice.bbps.util.BBPSConstant;
|
||||
@@ -43,99 +48,30 @@ public class PaymentServiceImpl implements PaymentService {
|
||||
private final HttpService httpService;
|
||||
private final Helper helper;
|
||||
private final PaymentRepository paymentRepository;
|
||||
private final InboundTraceLogRepository inboundTraceLogRepository;
|
||||
private final OutboundTraceLogRepository outboundTraceLogRepository;
|
||||
|
||||
public PaymentServiceImpl(BharatConnectMasterRepository beneficiaryDetailsRepository, HttpService httpService,
|
||||
Helper helper, PaymentRepository paymentRepository) {
|
||||
Helper helper, PaymentRepository paymentRepository, InboundTraceLogRepository inboundTraceLogRepository,
|
||||
OutboundTraceLogRepository outboundTraceLogRepository) {
|
||||
this.beneficiaryDetailsRepository = beneficiaryDetailsRepository;
|
||||
this.httpService = httpService;
|
||||
this.helper = helper;
|
||||
this.paymentRepository = paymentRepository;
|
||||
this.inboundTraceLogRepository = inboundTraceLogRepository;
|
||||
this.outboundTraceLogRepository = outboundTraceLogRepository;
|
||||
}
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MasterDataServiceImpl.class);
|
||||
|
||||
@Override
|
||||
public ResponseModel initiatePayment(BillPaymentRequest billPaymentRequest) {
|
||||
String apiName = "InitiatePayment";
|
||||
String txnId = helper.generateTxnId(15);
|
||||
String requestId = billPaymentRequest.getReqId();
|
||||
String url = paymentUrl + BBPSConstant.PAYMENT_URL;
|
||||
|
||||
String url = paymentUrl + BBPSConstant.PAYMENT_URL;
|
||||
System.out.println(url);
|
||||
|
||||
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId("ORG001");
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("x-digiledge-key", headersData.getXDigiledgeKey());
|
||||
headers.set("agentId", headersData.getAgentId());
|
||||
headers.set("tenantId", headersData.getTenantId());
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
ResponseModel responseModel = new ResponseModel();
|
||||
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
|
||||
// ✅ Convert request to JSON
|
||||
String json = objectMapper.writeValueAsString(billPaymentRequest);
|
||||
|
||||
// ✅ Call the API using httpService
|
||||
Map<String, String> responseMap = httpService.postRequest(url, json, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
|
||||
LOGGER.info("📦 Bill Fetch API Response: {}", responseData);
|
||||
|
||||
if (responseData == null || responseData.isEmpty()) {
|
||||
throw new CustomException("Empty response from BBPS server");
|
||||
}
|
||||
|
||||
// ✅ Convert JSON string → Map
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData,
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
|
||||
// ✅ Validate generalResp
|
||||
if (!dataMap.containsKey("genericResponse")) {
|
||||
throw new CustomException("Invalid response structure from BBPS");
|
||||
}
|
||||
|
||||
// ✅ Convert to your custom DTO
|
||||
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
|
||||
System.out.print(billPaymentResponse);
|
||||
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
|
||||
|
||||
//
|
||||
// start a new thread here
|
||||
/*
|
||||
* helper.startPolling(fetchBillResponse, res -> { BillFetchByBillIdRequest
|
||||
* pollReq = new BillFetchByBillIdRequest(); pollReq.setBillId(res.getBillId());
|
||||
* return fetchBillById(pollReq); }, 3, // interval in seconds 15 // total time
|
||||
* in seconds );
|
||||
*/
|
||||
|
||||
ModelMapper mapper = new ModelMapper();
|
||||
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
|
||||
BillPayment entity = mapper.map(billPaymentResponse, BillPayment.class);
|
||||
paymentRepository.save(entity);
|
||||
TransactionStatusRequest transactionStatusRequest=new TransactionStatusRequest();
|
||||
//call the checkTransactionStatus
|
||||
transactionStatusRequest.setTxnId(helper.generateTxnId(15));
|
||||
System.out.println(transactionStatusRequest);
|
||||
responseModel= checkTrasactionStatus(transactionStatusRequest);
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("❌ Exception in initiateBillFetch(): {}", e.getMessage(), e);
|
||||
responseModel.setStatus("500");
|
||||
responseModel.setMessage("Exception occurred");
|
||||
responseModel.setData(e.getMessage());
|
||||
}
|
||||
|
||||
return responseModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest) {
|
||||
|
||||
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
|
||||
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId("ORG001");
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("x-digiledge-key", headersData.getXDigiledgeKey());
|
||||
headers.set("agentId", headersData.getAgentId());
|
||||
@@ -143,22 +79,171 @@ public class PaymentServiceImpl implements PaymentService {
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
|
||||
String requestJson = helper.convertObjectToJson(billPaymentRequest);
|
||||
|
||||
// ✅ Create inbound & outbound logs
|
||||
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnId, apiName, billPaymentRequest.getMid(), "POST", requestJson);
|
||||
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, "POST", requestJson);
|
||||
|
||||
try {
|
||||
Map<String, String> responseMap = httpService.postRequest(url, requestJson, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
|
||||
LOGGER.info("📦 Payment API Response: {}", responseData);
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
|
||||
if (responseData == null || responseData.isEmpty()) {
|
||||
helper.updateInboundLogFailure(inboundLog, "Empty response from BBPS", "FAILED");
|
||||
throw new CustomException("Empty response from BBPS server");
|
||||
}
|
||||
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
|
||||
if (!dataMap.containsKey("genericResponse")) {
|
||||
helper.updateInboundLogFailure(inboundLog, responseData, "INVALID_STRUCTURE");
|
||||
throw new CustomException("Invalid response structure from BBPS");
|
||||
}
|
||||
|
||||
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
|
||||
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
|
||||
|
||||
ModelMapper mapper = new ModelMapper();
|
||||
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
|
||||
BillPayment entity = mapper.map(billPaymentResponse, BillPayment.class);
|
||||
paymentRepository.save(entity);
|
||||
|
||||
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
|
||||
|
||||
// ✅ Trigger transaction status check
|
||||
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
|
||||
transactionStatusRequest.setTxnId(entity.getTxnId());
|
||||
transactionStatusRequest.setReqId(requestId);
|
||||
|
||||
return checkTrasactionStatus(transactionStatusRequest, inboundLog);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
LOGGER.error("❌ JSON Parsing Error: {}", e.getMessage());
|
||||
helper.updateInboundLogFailure(inboundLog, e.getMessage(), "JSON_ERROR");
|
||||
throw new CustomException("Invalid JSON received from API");
|
||||
} catch (CustomException ce) {
|
||||
throw ce; // will be handled by global exception handler
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("❌ Exception in initiatePayment(): {}", e.getMessage(), e);
|
||||
helper.updateInboundLogFailure(inboundLog, e.getMessage(), "EXCEPTION");
|
||||
throw new CustomException("Payment initiation failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest,InboundTraceLog inboundLog) {
|
||||
String apiName = "CheckTransactionStatus";
|
||||
String txnId = helper.generateTxnId(15); //our genrated txnId
|
||||
String requestId = transactionStatusRequest.getReqId();
|
||||
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId(); ;
|
||||
|
||||
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId("ORG001");
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("x-digiledge-key", headersData.getXDigiledgeKey());
|
||||
headers.set("agentId", headersData.getAgentId());
|
||||
headers.set("tenantId", headersData.getTenantId());
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, "GET", null);
|
||||
|
||||
// ✅ Polling configuration
|
||||
long startTime = System.currentTimeMillis();
|
||||
long maxWaitTimeMs = 40000; // 40 seconds timeout
|
||||
long intervalMs = 5000; // retry every 5 seconds
|
||||
long maxWaitTimeMs = 40000;
|
||||
long intervalMs = 5000;
|
||||
|
||||
while (true) {
|
||||
Map<String, String> responseMap = httpService.getRequest(url, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
LOGGER.info("Transaction status response: {}", responseData);
|
||||
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
|
||||
try {
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
|
||||
|
||||
if (!dataMap.containsKey("generalResp")) {
|
||||
helper.updateInboundLogFailure(inboundLog, responseData, "INVALID_RESPONSE");
|
||||
throw new CustomException(
|
||||
String.valueOf(dataMap.get("message")),
|
||||
String.valueOf(dataMap.get("status")),
|
||||
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
|
||||
String.valueOf(dataMap.get("remarks"))
|
||||
);
|
||||
}
|
||||
|
||||
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap, TransactionStatusResponse.class);
|
||||
GeneralResp generalResp = responseWrapper.getGeneralResp();
|
||||
|
||||
String status = generalResp.getStatus();
|
||||
LOGGER.info("Current transaction status: {}", status);
|
||||
|
||||
if ("INPROGRESS".equalsIgnoreCase(status)) {
|
||||
if (System.currentTimeMillis() - startTime > maxWaitTimeMs) {
|
||||
helper.updateInboundLogFailure(inboundLog, "Timeout after 40 seconds", "FAILED");
|
||||
throw new CustomException("Timeout waiting for transaction completion", "FAILED", 408, "Transaction still in progress");
|
||||
}
|
||||
|
||||
Thread.sleep(intervalMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
ResponseModel responseModel = new ResponseModel(
|
||||
generalResp.getMessage(),
|
||||
generalResp.getStatus(),
|
||||
Integer.parseInt(generalResp.getStatusCode()),
|
||||
responseWrapper
|
||||
);
|
||||
|
||||
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
|
||||
return responseModel;
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
LOGGER.error("Error parsing transaction status JSON: {}", e.getMessage());
|
||||
helper.updateInboundLogFailure(inboundLog, e.getMessage(), "JSON_ERROR");
|
||||
throw new CustomException("Invalid JSON received from API");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
helper.updateInboundLogFailure(inboundLog, e.getMessage(), "INTERRUPTED");
|
||||
throw new CustomException("Thread interrupted during transaction check");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest) {
|
||||
helper.validateMerchant(transactionStatusRequest.getMid());
|
||||
String txnID = helper.generateTxnId(15);
|
||||
String apiName = "checkTrasactionStatus";
|
||||
String requestId = transactionStatusRequest.getReqId();
|
||||
String requestJson = helper.convertObjectToJson(transactionStatusRequest);
|
||||
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
|
||||
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId("ORG001");
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("x-digiledge-key", headersData.getXDigiledgeKey());
|
||||
headers.set("agentId", headersData.getAgentId());
|
||||
headers.set("tenantId", headersData.getTenantId());
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName, transactionStatusRequest.getMid(), "POST",
|
||||
requestJson);
|
||||
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, url, "GET", null);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
Map<String, String> responseMap = httpService.getRequest(url, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
LOGGER.info("Transaction status response data: {}", responseData);
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
|
||||
try {
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
|
||||
|
||||
// If genericResponse key missing, throw exception
|
||||
if (!dataMap.containsKey("generalResp")) {
|
||||
helper.updateInboundLogFailure(inboundLog, responseData, String.valueOf(dataMap.get("status")));
|
||||
throw new CustomException(
|
||||
String.valueOf(dataMap.get("message")),
|
||||
String.valueOf(dataMap.get("status")),
|
||||
@@ -175,43 +260,18 @@ public class PaymentServiceImpl implements PaymentService {
|
||||
|
||||
String status = generalResp.getStatus();
|
||||
LOGGER.info("Current transaction status: {}", status);
|
||||
|
||||
// ✅ If IN_PROGRESS → wait & retry
|
||||
if ("INPROGRESS".equalsIgnoreCase(status)) {
|
||||
|
||||
if (System.currentTimeMillis() - startTime > maxWaitTimeMs) {
|
||||
// Timeout after 40 sec
|
||||
throw new CustomException(
|
||||
"Timeout waiting for transaction completion",
|
||||
"FAILED",
|
||||
408,
|
||||
"Transaction still in progress after 40 seconds"
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(intervalMs);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new CustomException("Thread interrupted during retry");
|
||||
}
|
||||
|
||||
LOGGER.info("Transaction still IN_PROGRESS... retrying after {} seconds", (intervalMs / 1000));
|
||||
continue; // retry
|
||||
}
|
||||
|
||||
// ✅ If status is SUCCESS / FAILED / etc. → return response
|
||||
ResponseModel responseModel = new ResponseModel(
|
||||
generalResp.getMessage(),
|
||||
generalResp.getStatus(),
|
||||
Integer.parseInt(generalResp.getStatusCode()),
|
||||
responseWrapper
|
||||
);
|
||||
|
||||
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
|
||||
return responseModel;
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
LOGGER.error("Error parsing responseData JSON: {}", e.getMessage());
|
||||
helper.updateInboundLogFailure(inboundLog, e.getMessage(), "JSON_ERROR");
|
||||
throw new CustomException("Invalid JSON received from API");
|
||||
}
|
||||
}
|
||||
@@ -267,4 +327,4 @@ public class PaymentServiceImpl implements PaymentService {
|
||||
* }
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user