added a testing class for billers
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
+7
-2
@@ -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<CustomerParamDAO> customerParams;
|
||||
private String planInfoDaos;
|
||||
private String creationDate;
|
||||
private String modifiedDate;
|
||||
@@ -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<CustomerParamBillValidation> 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<BillValidation, String> {
|
||||
|
||||
}
|
||||
@@ -12,5 +12,4 @@ import com.billpaymentservice.bbps.entites.BillerDetails;
|
||||
public interface BillerDataRepository extends JpaRepository<BillerDetails, String> {
|
||||
|
||||
Optional<BillerDetails> findByBillerId(String billerId);
|
||||
|
||||
}
|
||||
|
||||
@@ -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<String, String> responseMap = httpService.postRequest(fullUrl, requestJson, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
LOGGER.debug("Response received from BBPS: {}", responseData);
|
||||
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData,
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
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<String, String> responseMap = httpService.getRequest(fullUrl, headers);
|
||||
String responseData = responseMap.get("data");
|
||||
LOGGER.info("Bill FetchById Response: {}", responseData);
|
||||
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
|
||||
|
||||
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;
|
||||
}}
|
||||
|
||||
@@ -141,7 +141,7 @@ public class HttpService {
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public class MasterDataServiceImpl implements MasterDataService {
|
||||
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, fullUrl, "GET", null);
|
||||
Map<String, String> responseMap = httpService.getRequest(fullUrl);
|
||||
String responseData = responseMap.get("data");
|
||||
LOGGER.info("Response Data: {}", responseData);
|
||||
//LOGGER.info("Response Data: {}", responseData);
|
||||
helper.updateOutboundLogResponse(outboundLog, responseData);
|
||||
Map<String, Object> dataMap = objectMapper.readValue(responseData,
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
|
||||
@@ -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=";
|
||||
|
||||
@@ -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<CustomerParamBillValidation> 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<Future<?>> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user