From 258b1633d5ef29559a558c88b565876d07ce0a17 Mon Sep 17 00:00:00 2001 From: Lincpay Tech Date: Tue, 11 Nov 2025 01:00:04 +0530 Subject: [PATCH 1/2] added a testing class for billers --- .../bbps/dto/CustomerParamDAO.java | 8 +- ...se.java => FetchBillValidateResponse.java} | 9 +- .../bbps/entites/BillValidation.java | 61 ++++++ .../entites/CustomerParamBillValidation.java | 33 +++ .../repository/BillValidationRepository.java | 11 + .../bbps/repository/BillerDataRepository.java | 1 - .../bbps/serviceImpl/AgentServiceImpl.java | 166 ++++++++++++++- .../bbps/serviceImpl/HttpService.java | 2 +- .../serviceImpl/MasterDataServiceImpl.java | 2 +- .../bbps/util/BBPSConstant.java | 2 +- .../billpaymentservice/bbps/util/Helper.java | 42 +++- .../bbps/BBPSAutomationTest.java | 189 ++++++++++++++++++ 12 files changed, 505 insertions(+), 21 deletions(-) rename src/main/java/com/billpaymentservice/bbps/dto/response/{FetchBillValidatestResponse.java => FetchBillValidateResponse.java} (79%) create mode 100644 src/main/java/com/billpaymentservice/bbps/entites/BillValidation.java create mode 100644 src/main/java/com/billpaymentservice/bbps/entites/CustomerParamBillValidation.java create mode 100644 src/main/java/com/billpaymentservice/bbps/repository/BillValidationRepository.java create mode 100644 src/test/java/com/billpaymentservice/bbps/BBPSAutomationTest.java diff --git a/src/main/java/com/billpaymentservice/bbps/dto/CustomerParamDAO.java b/src/main/java/com/billpaymentservice/bbps/dto/CustomerParamDAO.java index 838b960..4d96f6b 100644 --- a/src/main/java/com/billpaymentservice/bbps/dto/CustomerParamDAO.java +++ b/src/main/java/com/billpaymentservice/bbps/dto/CustomerParamDAO.java @@ -7,8 +7,8 @@ import lombok.Setter; @Getter @Setter public class CustomerParamDAO { - @NotBlank private String paramsId; - @NotBlank private String name; - @NotBlank private String value; - private String type; + private String paramsId; + private String name; + private String value; + private String type; } diff --git a/src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidatestResponse.java b/src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidateResponse.java similarity index 79% rename from src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidatestResponse.java rename to src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidateResponse.java index 0d95ce2..2d2047f 100644 --- a/src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidatestResponse.java +++ b/src/main/java/com/billpaymentservice/bbps/dto/response/FetchBillValidateResponse.java @@ -1,5 +1,8 @@ package com.billpaymentservice.bbps.dto.response; +import java.util.List; + +import com.billpaymentservice.bbps.dto.CustomerParamDAO; import com.billpaymentservice.bbps.dto.GeneralResp; import com.fasterxml.jackson.annotation.JsonProperty; @@ -7,12 +10,14 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.ToString; @Getter @Setter @AllArgsConstructor @NoArgsConstructor -public class FetchBillValidatestResponse { +@ToString +public class FetchBillValidateResponse { @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private GeneralResp genericResponse; @@ -24,7 +29,7 @@ public class FetchBillValidatestResponse { private String userId; private String billerResponse; private String additionalInfo; - private String customerParams; + private List customerParams; private String planInfoDaos; private String creationDate; private String modifiedDate; diff --git a/src/main/java/com/billpaymentservice/bbps/entites/BillValidation.java b/src/main/java/com/billpaymentservice/bbps/entites/BillValidation.java new file mode 100644 index 0000000..97677ef --- /dev/null +++ b/src/main/java/com/billpaymentservice/bbps/entites/BillValidation.java @@ -0,0 +1,61 @@ +package com.billpaymentservice.bbps.entites; + + +import java.util.List; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "bill_validation") +@Data +@AllArgsConstructor +@NoArgsConstructor +public class BillValidation { + + @Id + @Column(name = "bill_id", nullable = false, length = 100) + private String billId; + + @Column(name = "ref_id", length = 100) + private String refId; + + @Column(name = "biller_id", length = 100) + private String billerId; + + @Column(name = "status", length = 100) + private String status; + + @Column(name = "action_type", length = 100) + private String actionType; + + @Column(name = "user_id", length = 100) + private String userId; + + @Column(name = "biller_response", columnDefinition = "TEXT") + private String billerResponse; + + @Column(name = "additional_info", columnDefinition = "TEXT") + private String additionalInfo; + + // šŸ‘‡ Proper nested customer params (OneToMany) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "bill") + private List customerParams; + + @Column(name = "plan_info_daos", columnDefinition = "TEXT") + private String planInfoDaos; + + @Column(name = "creation_date", length = 50) + private String creationDate; + + @Column(name = "modified_date", length = 50) + private String modifiedDate; + + @Column(name = "created_epoch_date", length = 50) + private String createdEpochDate; + + @Column(name = "modified_epoch_date", length = 50) + private String modifiedEpochDate; +} diff --git a/src/main/java/com/billpaymentservice/bbps/entites/CustomerParamBillValidation.java b/src/main/java/com/billpaymentservice/bbps/entites/CustomerParamBillValidation.java new file mode 100644 index 0000000..cf3571e --- /dev/null +++ b/src/main/java/com/billpaymentservice/bbps/entites/CustomerParamBillValidation.java @@ -0,0 +1,33 @@ +package com.billpaymentservice.bbps.entites; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "customer_params_bill_validate") +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CustomerParamBillValidation { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "value") + private String value; + + @Column(name = "type") + private String type; + + // āœ… Many Params → One Bill + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "bill_id_fk") + private BillValidation bill; +} diff --git a/src/main/java/com/billpaymentservice/bbps/repository/BillValidationRepository.java b/src/main/java/com/billpaymentservice/bbps/repository/BillValidationRepository.java new file mode 100644 index 0000000..6926652 --- /dev/null +++ b/src/main/java/com/billpaymentservice/bbps/repository/BillValidationRepository.java @@ -0,0 +1,11 @@ +package com.billpaymentservice.bbps.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.billpaymentservice.bbps.entites.BillValidation; + +@Repository +public interface BillValidationRepository extends JpaRepository { + +} diff --git a/src/main/java/com/billpaymentservice/bbps/repository/BillerDataRepository.java b/src/main/java/com/billpaymentservice/bbps/repository/BillerDataRepository.java index f4f7b2f..ed6cca6 100644 --- a/src/main/java/com/billpaymentservice/bbps/repository/BillerDataRepository.java +++ b/src/main/java/com/billpaymentservice/bbps/repository/BillerDataRepository.java @@ -12,5 +12,4 @@ import com.billpaymentservice.bbps.entites.BillerDetails; public interface BillerDataRepository extends JpaRepository { Optional findByBillerId(String billerId); - } diff --git a/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java b/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java index 89c630e..98d5c5a 100644 --- a/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java +++ b/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java @@ -17,7 +17,7 @@ import com.billpaymentservice.bbps.dto.request.FetchBillRequest; import com.billpaymentservice.bbps.dto.request.FetchBillValidatestRequest; import com.billpaymentservice.bbps.dto.response.BillDataResponse; import com.billpaymentservice.bbps.dto.response.FetchBillResponse; -import com.billpaymentservice.bbps.dto.response.FetchBillValidatestResponse; +import com.billpaymentservice.bbps.dto.response.FetchBillValidateResponse; import com.billpaymentservice.bbps.entites.BharatConnectMaster; import com.billpaymentservice.bbps.entites.BillInitiate; import com.billpaymentservice.bbps.entites.BillMaster; @@ -277,20 +277,159 @@ public class AgentServiceImpl implements AgentService { @Override public ResponseModel initiateBillValidate(FetchBillValidatestRequest fetchBillValidateRequest) { - // TODO Auto-generated method stub - return null; - } + + LOGGER.info("Initiating bill Validate for request ID: {} and MID", fetchBillValidateRequest.getReqId(), + fetchBillValidateRequest.getMid()); + String apiName = "InitiateBillValidate"; + String txnId = helper.generateTxnId(15); + String reqId = fetchBillValidateRequest.getReqId(); + String fullUrl = agentDtaUrl + BBPSConstant.BILLER_VALIDATE_URL; + helper.validateMerchant(fetchBillValidateRequest.getMid()); + + 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(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + String requestJson = helper.convertObjectToJson(fetchBillValidateRequest); + + // āœ… Create inbound & outbound logs + InboundTraceLog inboundLog = helper.createInboundLog(reqId, txnId, apiName, fetchBillValidateRequest.getMid(), + "POST", requestJson); + OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, reqId, apiName, fullUrl, "POST", + requestJson); + LOGGER.debug("Outbound log created successfully for txnId: {} and reqId: {}", txnId, reqId); + + try { + LOGGER.info("Calling external API: {}", fullUrl); + Map responseMap = httpService.postRequest(fullUrl, requestJson, headers); + String responseData = responseMap.get("data"); + + helper.updateOutboundLogResponse(outboundLog, responseData); + LOGGER.debug("Response received from BBPS: {}", responseData); + + Map dataMap = objectMapper.readValue(responseData, + new TypeReference>() { + }); + if (!dataMap.containsKey("genericResponse")) { + helper.updateInboundLogFailure(inboundLog, responseData, "INVALID_RESPONSE"); + LOGGER.warn("Invalid response received for txnId: {}", txnId); + 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"))); + } + + BillMaster billMaster = new BillMaster(); + billMaster.setBillId((String) dataMap.get("billId")); + billMaster.setReqId(fetchBillValidateRequest.getReqId()); + billMaster.setTxnId(txnId); + billMasterRepository.save(billMaster); + LOGGER.info("BillMaster saved for billId: {}", billMaster.getBillId()); + + FetchBillResponse fetchBillResponse = objectMapper.convertValue(dataMap, FetchBillResponse.class); + GeneralResp generalResponse = fetchBillResponse.getGenericResponse(); + helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus()); + + BillInitiate billInitiate = new BillInitiate(); + billInitiate.setBillId((String) dataMap.get("billId")); + billInitiate.setReqId(fetchBillValidateRequest.getReqId()); + billInitiate.setTxnId(txnId); + billIntiateRepository.save(billInitiate); + LOGGER.info("BillInitiate entry saved for billId: {}", billInitiate.getBillId()); + + BillFetchByBillIdRequest billFetchByBillIdRequest = new BillFetchByBillIdRequest(); + billFetchByBillIdRequest.setBillId(fetchBillResponse.getBillId()); + billFetchByBillIdRequest.setMid(fetchBillValidateRequest.getMid()); + billFetchByBillIdRequest.setReqId(reqId); + LOGGER.info("Waiting for 2 seconds before fetching bill by ID..."); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.warn("Thread interrupted during delay: {}", e.getMessage()); + } + LOGGER.info("Calling internal method Fetching bill by ID: {}", billFetchByBillIdRequest.getBillId()); + return BillvaidateByBillId(billFetchByBillIdRequest, inboundLog); + } catch (JsonProcessingException e) { + LOGGER.error("JSON Parsing Error: {}", e.getMessage(), e); + helper.updateInboundLogFailure(inboundLog, e.getMessage(), "JSON_ERROR"); + throw new CustomException("Invalid JSON received from API"); + } + + } - @Override - public ResponseModel initiateBillValidateByBillId(BillFetchByBillIdRequest billRequest) { - // TODO Auto-generated method stub - return null; - } - + public ResponseModel BillvaidateByBillId( BillFetchByBillIdRequest billRequest,InboundTraceLog inboundLog) { { + LOGGER.info("Validating bill by BILLID for request ID={} and MID={}", billRequest.getReqId(), billRequest.getMid()); + String apiName = "FetchBillById"; + String txnId = helper.generateTxnId(15); + String reqId = billRequest.getReqId(); + String billId = billRequest.getBillId(); + String fullUrl = agentDtaUrl + BBPSConstant.BILL_VALIDATE_ID_URL+ "c9670952-ebd7-487a-b6ea-49f2b4d4a718"; + helper.validateMerchant(billRequest.getMid()); + + 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, reqId, apiName, fullUrl, "GET", null); + LOGGER.debug("Outbound log created successfully for FetchBillById: {}", fullUrl); + + try { + LOGGER.info("Calling external API: {}", fullUrl); + Map responseMap = httpService.getRequest(fullUrl, headers); + String responseData = responseMap.get("data"); + LOGGER.info("Bill FetchById Response: {}", responseData); + + helper.updateOutboundLogResponse(outboundLog, responseData); + + Map dataMap = objectMapper.readValue(responseData, new TypeReference>() {}); + + if (!dataMap.containsKey("genericResponse")) { + helper.updateInboundLogFailure(inboundLog, responseData, "INVALID_RESPONSE"); + LOGGER.warn("Invalid response structure for txnId: {}", txnId); + 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")) + ); + } + + FetchBillValidateResponse responseWrapper = objectMapper.convertValue(dataMap, FetchBillValidateResponse.class); + GeneralResp generalResp = responseWrapper.getGenericResponse(); + + String status = generalResp.getStatus(); + LOGGER.info("Current Bill Status: {}", status); + + helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus()); + System.out.println("responseWrapper:"+responseWrapper); + helper.saveBillValidation(responseWrapper,billRequest); + LOGGER.info("Bill data saved successfully for billId: {}", billId); + + return new ResponseModel( + generalResp.getMessage(), + generalResp.getStatus(), + Integer.parseInt(generalResp.getStatusCode()), + responseWrapper + ); + } catch (JsonProcessingException e) { + LOGGER.error("Error parsing BillById JSON: {}", e.getMessage(), e); + helper.updateInboundLogFailure(inboundLog, e.getMessage(), "JSON_ERROR"); + throw new CustomException("Invalid JSON received from API"); + } + } /* * @Override public ResponseModel @@ -481,3 +620,10 @@ public class AgentServiceImpl implements AgentService { */ } + + + @Override + public ResponseModel initiateBillValidateByBillId(BillFetchByBillIdRequest billRequest) { + // TODO Auto-generated method stub + return null; + }} diff --git a/src/main/java/com/billpaymentservice/bbps/serviceImpl/HttpService.java b/src/main/java/com/billpaymentservice/bbps/serviceImpl/HttpService.java index 0874403..8193af8 100644 --- a/src/main/java/com/billpaymentservice/bbps/serviceImpl/HttpService.java +++ b/src/main/java/com/billpaymentservice/bbps/serviceImpl/HttpService.java @@ -141,7 +141,7 @@ public class HttpService { return response; } - + } \ No newline at end of file diff --git a/src/main/java/com/billpaymentservice/bbps/serviceImpl/MasterDataServiceImpl.java b/src/main/java/com/billpaymentservice/bbps/serviceImpl/MasterDataServiceImpl.java index 97ac26d..e1a6c6f 100644 --- a/src/main/java/com/billpaymentservice/bbps/serviceImpl/MasterDataServiceImpl.java +++ b/src/main/java/com/billpaymentservice/bbps/serviceImpl/MasterDataServiceImpl.java @@ -117,7 +117,7 @@ public class MasterDataServiceImpl implements MasterDataService { OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, fullUrl, "GET", null); Map responseMap = httpService.getRequest(fullUrl); String responseData = responseMap.get("data"); - LOGGER.info("Response Data: {}", responseData); + //LOGGER.info("Response Data: {}", responseData); helper.updateOutboundLogResponse(outboundLog, responseData); Map dataMap = objectMapper.readValue(responseData, new TypeReference>() { diff --git a/src/main/java/com/billpaymentservice/bbps/util/BBPSConstant.java b/src/main/java/com/billpaymentservice/bbps/util/BBPSConstant.java index 11eb29f..5e7945f 100644 --- a/src/main/java/com/billpaymentservice/bbps/util/BBPSConstant.java +++ b/src/main/java/com/billpaymentservice/bbps/util/BBPSConstant.java @@ -33,7 +33,7 @@ public class BBPSConstant { public static final String INITIATING_CHANNEL = "/initiatingChannel"; public static final String BILLER_VALIDATE_URL = "/couapp/bills/validate"; - public static final String BILL_ID_URL = "/couapp/bills/validate/byId?billId="; + public static final String BILL_VALIDATE_ID_URL = "/couapp/bills/validate/byId?billId="; public static final String BILLER_DATA_FETCH_URL = "/billersById?billerId="; public static final String CUSTOMPARAM_URL = "/customerParam?billerId="; diff --git a/src/main/java/com/billpaymentservice/bbps/util/Helper.java b/src/main/java/com/billpaymentservice/bbps/util/Helper.java index 71219cd..dc5815b 100644 --- a/src/main/java/com/billpaymentservice/bbps/util/Helper.java +++ b/src/main/java/com/billpaymentservice/bbps/util/Helper.java @@ -6,7 +6,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; +import java.util.stream.Collectors; +import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -16,12 +18,15 @@ import com.billpaymentservice.bbps.dto.CustomerParamDAO; import com.billpaymentservice.bbps.dto.ResponseModel; import com.billpaymentservice.bbps.dto.request.BillFetchByBillIdRequest; import com.billpaymentservice.bbps.dto.response.BillDataResponse; +import com.billpaymentservice.bbps.dto.response.FetchBillValidateResponse; import com.billpaymentservice.bbps.entites.AdditionalInfoBill; import com.billpaymentservice.bbps.entites.BBPSMastersData; import com.billpaymentservice.bbps.entites.BillMaster; +import com.billpaymentservice.bbps.entites.BillValidation; import com.billpaymentservice.bbps.entites.BillerDetails; import com.billpaymentservice.bbps.entites.BillerResponse; import com.billpaymentservice.bbps.entites.CustomerParamBill; +import com.billpaymentservice.bbps.entites.CustomerParamBillValidation; import com.billpaymentservice.bbps.entites.InboundTraceLog; import com.billpaymentservice.bbps.entites.OutboundTraceLog; import com.billpaymentservice.bbps.entites.PaymentChannel; @@ -29,6 +34,7 @@ import com.billpaymentservice.bbps.entites.PaymentMode; import com.billpaymentservice.bbps.exception.CustomException; import com.billpaymentservice.bbps.repository.BBPSMasterDataRepo; import com.billpaymentservice.bbps.repository.BillMasterRepository; +import com.billpaymentservice.bbps.repository.BillValidationRepository; import com.billpaymentservice.bbps.repository.BillerDataRepository; import com.billpaymentservice.bbps.repository.InboundTraceLogRepository; import com.billpaymentservice.bbps.repository.OutboundTraceLogRepository; @@ -48,16 +54,18 @@ public class Helper { private final BBPSMasterDataRepo bbpsMasterDataRepo; private final BillerDataRepository billerDataRespository; private final BillMasterRepository billMasterRepository; + private final BillValidationRepository billValidationRepository; // Constructor Injection public Helper(BBPSMasterDataRepo bbpsMasterDataRepo, InboundTraceLogRepository inboundTraceLogRepository, OutboundTraceLogRepository outboundTraceLogRepository,BillerDataRepository billerDataRepository, - BillMasterRepository billMasterRepository) { + BillMasterRepository billMasterRepository,BillValidationRepository billValidationRepository) { this.bbpsMasterDataRepo = bbpsMasterDataRepo; this.inboundTraceLogRepository = inboundTraceLogRepository; this.outboundTraceLogRepository = outboundTraceLogRepository; this.billerDataRespository=billerDataRepository; this.billMasterRepository=billMasterRepository; + this.billValidationRepository=billValidationRepository; } /** @@ -301,6 +309,38 @@ public class Helper { billMasterRepository.save(billMaster); } + public void saveBillValidation(FetchBillValidateResponse responseWrapper, BillFetchByBillIdRequest billRequest) { + System.out.println("responseWrapper"); + ModelMapper modelMapper = new ModelMapper(); + + try { + LOGGER.info("Saving bill validation data for billId={}", responseWrapper.getBillId()); + // āœ… Map the main object + BillValidation billEntity = modelMapper.map(responseWrapper, BillValidation.class); + // āœ… Manually handle only the nested relationship part + if (responseWrapper.getCustomerParams() != null) { + List customerParams = responseWrapper.getCustomerParams() + .stream() + .map(param -> { + CustomerParamBillValidation cp = modelMapper.map(param, CustomerParamBillValidation.class); + cp.setBill(billEntity); // maintain relation + return cp; + }) + .collect(Collectors.toList()); + billEntity.setCustomerParams(customerParams); + } + // āœ… Save everything (cascade handles child) + + billValidationRepository.save(billEntity); + + LOGGER.info("Bill validation saved successfully for billId={}", billEntity.getBillId()); + } catch (Exception ex) { + LOGGER.error("Error saving BillValidation data: {}", ex.getMessage(), ex); + throw new RuntimeException("Failed to save bill validation data", ex); + } + + } +} \ No newline at end of file diff --git a/src/test/java/com/billpaymentservice/bbps/BBPSAutomationTest.java b/src/test/java/com/billpaymentservice/bbps/BBPSAutomationTest.java new file mode 100644 index 0000000..2c67322 --- /dev/null +++ b/src/test/java/com/billpaymentservice/bbps/BBPSAutomationTest.java @@ -0,0 +1,189 @@ +package com.billpaymentservice.bbps; + +import java.net.URI; +import java.net.http.*; +import java.util.*; +import java.util.concurrent.*; +import org.json.*; + +public class BBPSAutomationTest { + + private static final String BASE_URL = "http://localhost:9090/masterData"; + private static final String BILLER_API = "https://bbps-staging.digiledge.in/agent/cou-master/masters/billers"; + private static final HttpClient client = HttpClient.newHttpClient(); + + // Run 10 threads in parallel + private static final ExecutorService executor = Executors.newFixedThreadPool(10); + + public static void main(String[] args) { + try { + System.out.println("šŸš€ Starting BBPS Test Flow (Multi-Threaded)...\n"); + + List categories = getAllCategories(); + if (categories.isEmpty()) { + System.out.println("āŒ No categories found. Exiting..."); + return; + } + + System.out.println("\nāœ… Total Categories Found: " + categories.size()); + + int count = 1; + for (String category : categories) { + System.out.println("\nšŸ“‚ [" + count++ + "/" + categories.size() + "] Category: " + category); + + List billerIds = Collections.emptyList(); + try { + billerIds = fetchBillersByCategory(category); + } catch (Exception ex) { + System.err.println("āš ļø Skipping category '" + category + "' due to error: " + ex.getMessage()); + continue; // skip and go to next category + } + + if (billerIds == null || billerIds.isEmpty()) { + System.out.println("āš ļø No billers found for: " + category + " — Skipping..."); + continue; + } + + System.out.println("šŸ”¹ Found " + billerIds.size() + " billers. Fetching details in parallel..."); + + // Run all biller calls in parallel threads + List> futures = new ArrayList<>(); + for (String billerId : billerIds) { + futures.add(executor.submit(() -> { + try { + sendBillerDetails(billerId); + } catch (Exception e) { + System.err.println("āŒ Error with biller " + billerId + ": " + e.getMessage()); + } + })); + } + + // Wait for all billers to finish + for (Future f : futures) { + try { + f.get(); + } catch (Exception e) { + System.err.println("āš ļø Thread interrupted: " + e.getMessage()); + } + } + + System.out.println("āœ… Completed all billers for category: " + category); + } + + executor.shutdown(); + System.out.println("\nšŸŽÆ All categories processed successfully (multi-threaded & safe)!"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Step 1 - Get All Categories + private static List getAllCategories() throws Exception { + String reqId = UUID.randomUUID().toString(); + + JSONObject body = new JSONObject(); + body.put("mid", "ALLCOS00117BHO"); + body.put("reqId", reqId); + body.put("secretKey", "ABCD1234SECRET"); + + JSONObject device = new JSONObject(); + device.put("deviceId", "DEVICE001"); + device.put("deviceName", "Samsung Galaxy S23"); + device.put("os", "Android 14"); + device.put("appVersion", "1.0.5"); + device.put("ipAddress", "192.168.1.101"); + body.put("deviceDetial", device); + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(BASE_URL + "/getAllMastersData")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body.toString())) + .build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + System.out.println("āŒ getAllMastersData failed | HTTP " + response.statusCode()); + return Collections.emptyList(); + } + + JSONObject json = new JSONObject(response.body()); + JSONArray catArray = json.optJSONObject("data") != null + ? json.getJSONObject("data").optJSONArray("categoryRespList") + : null; + + List categories = new ArrayList<>(); + if (catArray != null && catArray.length() > 0) { + for (int i = 0; i < catArray.length(); i++) { + categories.add(catArray.getJSONObject(i).getString("categoryName")); + } + } + + System.out.println("āœ… Categories found: " + categories.size()); + return categories; + } + + // Step 2 - Fetch Billers by Category + private static List fetchBillersByCategory(String category) throws Exception { + // Encode category to handle spaces & special characters safely + String encodedCategory = java.net.URLEncoder.encode(category, java.nio.charset.StandardCharsets.UTF_8); + String url = BILLER_API + "?category=" + encodedCategory + "&page=0&pagesize=50"; + + HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + if (response.statusCode() != 200) { + System.out.println("āŒ Failed to fetch billers for " + category + " | HTTP " + response.statusCode()); + return Collections.emptyList(); + } + + JSONObject json = new JSONObject(response.body()); + JSONArray billersArray = json.optJSONArray("billerResp"); + + if (billersArray == null || billersArray.length() == 0) { + System.out.println("āš ļø billerResp empty or null for category: " + category); + return Collections.emptyList(); + } + + List billerIds = new ArrayList<>(); + for (int i = 0; i < billersArray.length(); i++) { + billerIds.add(billersArray.getJSONObject(i).getString("billerId")); + } + + return billerIds; + } + + // Step 3 - Get Biller Details + private static void sendBillerDetails(String billerId) throws Exception { + String reqId = UUID.randomUUID().toString(); + + JSONObject body = new JSONObject(); + body.put("mid", "ALLCOS00117BHO"); + body.put("reqId", reqId); + body.put("billerId", billerId); + body.put("secretKey", "ABCD1234SECRET"); + + JSONObject device = new JSONObject(); + device.put("deviceId", "DEVICE001"); + device.put("deviceName", "Samsung Galaxy S23"); + device.put("os", "Android 14"); + device.put("appVersion", "1.0.5"); + device.put("ipAddress", "192.168.1.101"); + body.put("deviceDetial", device); + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(BASE_URL + "/getBillerDetails")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body.toString())) + .build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + synchronized (System.out) { // thread-safe log printing + if (response.statusCode() == 200) { + System.out.println("āœ… Success: " + billerId); + } else { + System.out.println("āŒ Failed: " + billerId + " | HTTP " + response.statusCode()); + } + } + } +} From 579220f6c631ac494135be80384bcdbf36a92541 Mon Sep 17 00:00:00 2001 From: Lincpay Tech Date: Tue, 11 Nov 2025 11:42:54 +0530 Subject: [PATCH 2/2] added billValidate --- .../billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java b/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java index c8630dd..d001ea3 100644 --- a/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java +++ b/src/main/java/com/billpaymentservice/bbps/serviceImpl/AgentServiceImpl.java @@ -141,7 +141,7 @@ public class AgentServiceImpl implements AgentService { billFetchByBillIdRequest.setReqId(requestId); LOGGER.info("Waiting for 2 seconds before fetching bill by ID..."); try { - Thread.sleep(2000); + Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.warn("Thread interrupted during delay: {}", e.getMessage()); @@ -347,7 +347,7 @@ public class AgentServiceImpl implements AgentService { billFetchByBillIdRequest.setReqId(reqId); LOGGER.info("Waiting for 2 seconds before fetching bill by ID..."); try { - Thread.sleep(2000); + Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.warn("Thread interrupted during delay: {}", e.getMessage());