This commit is contained in:
Gaurav Kumar
2025-03-19 11:22:01 +05:30
parent 8998b79b30
commit 5af89fc550
1141 changed files with 36854 additions and 472482 deletions

View File

@@ -0,0 +1,304 @@
//package com.realnet.Billing.Api.Controllers;
//
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map.Entry;
//import java.util.Optional;
//import java.util.Set;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.google.gson.JsonArray;
//import com.google.gson.JsonElement;
//import com.google.gson.JsonObject;
//import com.google.gson.JsonParser;
//import com.realnet.Billing.Entitys.ServiceOrder_t;
//import com.realnet.Billing.Repositorys.ServiceOrder_Repository;
//import com.realnet.Billing.Services.ServiceOrder_Service;
//import com.realnet.Communication.Models.Com_jobTable;
//import com.realnet.Communication.Repos.JobTablerepo;
//import com.realnet.Customer_master.Entity.Customer_master_t;
//import com.realnet.Customer_master.Repository.Customer_master_Repository;
//import com.realnet.DocumentBuilder.Entity.DocumentBuilder_t;
//import com.realnet.DocumentBuilder.Entity.Document_builder_lines;
//import com.realnet.DocumentBuilder.Services.DocumentBuilder_Service;
//import com.realnet.DocumentBuilder.Services.StringReplacementService;
//
//@RestController
//
//public class BillingSequentialApi {
//
// @Autowired
// private ServiceOrder_Repository serviceOrder_Repository;
//
// @Autowired
// private DocumentBuilder_Service Service;
//
//// @Autowired
//// private Fileupload_helper fileuploadhelper;
//
// @Autowired
// private StringReplacementService replacementService;
//
// @Autowired
// private Customer_master_Repository customer_master_Repository;
//
// @Autowired
// private JobTablerepo Com_jobTablerepo;
//
// @Value("${projectPath}")
// private String projectPath;
//
// public final String UPLOAD_DIREC = "/Files";
//
// @Autowired
// private ServiceOrder_Service serviceOrder_Service;
//
// @GetMapping("/process-all-customers")
// public ResponseEntity<String> processAllCustomers() {
// try {
// // Step 1: Create Service Orders for all customers
// List<Customer_master_t> customers = customer_master_Repository.findAll();
// for (Customer_master_t customer : customers) {
// serviceOrder_Service.createServiceOrderFromCustomer(customer);
//
// }
//
// // Step 2: Approve all pending service orders
// int updatedCount = serviceOrder_Service.approvePendingOrders();
//
// // step 3:
//
// List<Long> autoApprovedServiceOrderIds = serviceOrder_Repository.findIdsByStatusOrderByAsc("AutoApproved");
//
// // Process the service orders
// for (Long serviceOrderId : autoApprovedServiceOrderIds) {
// Optional<ServiceOrder_t> serviceOrderOptional = serviceOrder_Repository.findById(serviceOrderId);
//
// if (serviceOrderOptional.isPresent()) {
// ServiceOrder_t serviceOrder = serviceOrderOptional.get();
// String entityName = serviceOrder.getEntity();
//
// // Fetch the corresponding customer(s) by entity name
// List<Customer_master_t> customers1 = customer_master_Repository.findByEntityName(entityName);
//
// if (!customers1.isEmpty()) {
// // Assuming you want to process each customer found
// for (Customer_master_t customer : customers1) {
// // Now you have the serviceOrderId, entityName, and customer for processing
// String proformaInvoiceFileName = generateProformaInvoice(serviceOrderId);
//
// // step 4
// sendEmailWithProformaInvoice(customer, proformaInvoiceFileName);
// }
// } else {
// // Handle the case where no customer was found for the given entity name
// }
// } else {
// // Handle the case where no service order was found for the given ID
// }
// }
//
// return ResponseEntity.ok("Processed all customers and generated invoices. " + updatedCount
// + " service orders were approved.");
// } catch (Exception e) {
// // Handle exceptions appropriately
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
// .body("Error processing customers: " + e.getMessage());
// }
// }
//
// private String generateProformaInvoice(Long serviceOrderId) throws Exception {
//
// long documentId = 98;
// HashMap<String, String> map = new HashMap<>();
// JsonParser parser = new JsonParser();
// DocumentBuilder_t doc = Service.getdetailsbyId(documentId);
// String file_name = doc.getFile_name();
// String file_path = doc.getFile_path();
//
// String replacerule = "";
// String operation = null;
// String replaceWith = null;
// String startstring = null;
// String endstring = null;
// String keyword = null;
// String linestring = null;
// String cellAddress = null;
// JsonObject getbodyobject = null;
// String ModifyfileName = null;
//
// // .....................//
//
// List<Document_builder_lines> docline = doc.getDocument_builder_lines();
//
// for (Document_builder_lines line : docline) {
// String model = line.getModel();
// JsonParser parser1 = new JsonParser();
// JsonArray jsonArray = parser1.parse(model).getAsJsonArray();
//
// for (JsonElement element : jsonArray) {
// JsonObject jsonObject = element.getAsJsonObject();
// if (jsonObject.has("name")) {
// ModifyfileName = jsonObject.get("name").getAsString();
// break; // Break the loop once you find the first object with a "name" field
// }
// }
//
// if (ModifyfileName != null) {
// // Now 'nameValue' contains the value of the "name" field
// System.out.println("nameValue: " + ModifyfileName);
// break; // Break the outer loop as well, if needed
// }
// }
//
// if (ModifyfileName == null) {
// // Handle the case where no object with a "name" field was found
// System.out.println("No object with a 'name' field found.");
// }
//
// // long serviceOrderId = serviceOrderId2.getId();
// ModifyfileName = ModifyfileName.replace("?", String.valueOf(serviceOrderId));
// ModifyfileName = ModifyfileName + ".docx";
// String newFilepath = replacementService.copyWordFile(file_path, file_name, file_path, ModifyfileName);
//
// // ..........................//
//
// List<Document_builder_lines> lines = doc.getDocument_builder_lines();
//
// for (Document_builder_lines line : lines) {
// String model = line.getModel();
// JsonElement element = parser.parse(model);
// JsonArray models = element.getAsJsonArray();
//
// for (JsonElement mod : models) {
// JsonObject object = mod.getAsJsonObject();
//
// String type = object.get("type").getAsString();
// if (type.equalsIgnoreCase("Initialize")) {
// String a_uri = object.get("a_uri").toString().replaceAll("\"", "");
// a_uri = a_uri.replace("?", String.valueOf(serviceOrderId));
// System.out.println(a_uri);
//
// Object body = GET(a_uri).getBody();
// ObjectMapper objectMapper = new ObjectMapper();
// String json = objectMapper.writeValueAsString(body);
// JsonElement getbody = parser.parse(json);
// getbodyobject = getbody.getAsJsonObject();
//
// }
// }
//
// for (JsonElement mod : models) {
// JsonObject object = mod.getAsJsonObject();
//
// String type = object.get("type").getAsString();
// if (type.equalsIgnoreCase("Mapper")) {
// String mapper = object.get("mappers").getAsString();
//
// JsonElement parse = parser.parse(mapper);
// JsonArray mapArray = parse.getAsJsonArray();
// for (JsonElement maps : mapArray) {
// JsonObject jsonObject = maps.getAsJsonObject();
// startstring = jsonObject.get("start_string").toString().replaceAll("\"", "");
// endstring = jsonObject.get("end_string").toString().replaceAll("\"", "");
// replaceWith = jsonObject.get("replace_with").toString().replaceAll("\"", "");
// keyword = jsonObject.get("Keyword").toString().replaceAll("\"", "");
// linestring = jsonObject.get("line_string").toString().replaceAll("\"", "");
// operation = jsonObject.get("operation").toString().replaceAll("\"", "");
// cellAddress = jsonObject.get("cellAddress").toString().replaceAll("\"", "");
// Set<Entry<String, JsonElement>> entrySet = getbodyobject.entrySet();
// for (Entry<String, JsonElement> entry : entrySet) {
//
// String key = entry.getKey().toString().replaceAll("\"", "");
// String value = entry.getValue().toString().replaceAll("\"", "");
//
// if (replaceWith.equalsIgnoreCase(key)) {
// replaceWith = value;
// break;
// }
//
// }
//
// if (operation.contains("replacebyfirstandlast")) {
//
// replacerule = replacementService.replacewithstartandend(file_path, file_name, startstring,
// endstring, replaceWith);
//
// }
//
// if (operation.contains("appending")) {
// replacerule = replacementService.appendToSlide(linestring, replaceWith, file_path,
// file_name);
// }
//
// if (operation.contains("linereplacement")) {
// replacerule = replacementService.linereplacementForPPT(file_path, file_name, keyword,
// replaceWith);
// }
// if (operation.contains("replacement")) {
// replacerule = replacementService.replacesting(newFilepath, file_name, keyword, replaceWith,
// ModifyfileName);
//
// }
//
// if (operation.contains("excelcellReplace")) {
// replacerule = replacementService.excelcellReplace(file_path, file_name, cellAddress,
// replaceWith);
//
// }
//
// }
// }
//
// }
// }
//
// return replacerule;
//
// }
//
// private void sendEmailWithProformaInvoice(Customer_master_t customer, String fileName) {
//
// Long id = customer.getId();
// String email = customer.getEmail();
//
// String gateway = "EMAIL";
// String sendTo = email;
// String replacementString = "no";
// String cc = email;
// String template = "PerfomaInvoice";
//
// // Create a new Com_jobTable instance and set its values
// Com_jobTable comJobTable = new Com_jobTable();
// comJobTable.setJob_type("EMAIL"); // Set the job type to "EMAIL"
// comJobTable.setSend_to(sendTo);
// comJobTable.setGatewayName(gateway);
// comJobTable.setAttachment(fileName);
// comJobTable.setGatewaydone("N");
// comJobTable.setReplacement_string(replacementString);
// comJobTable.setCc(cc);
// comJobTable.setReplacement_string(replacementString);
// comJobTable.setTemplate_name(template);
// // Save the Com_jobTable entity using your repository or service
// Com_jobTablerepo.save(comJobTable);
//
// }
//
// public ResponseEntity<Object> GET(String get) {
// RestTemplate restTemplate = new RestTemplate();
//
// ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
//
// return u;
//
// }
//
//}

View File

@@ -0,0 +1,403 @@
//package com.realnet.Billing.Api.Controllers;
//
//import java.io.ByteArrayOutputStream;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map.Entry;
//import java.util.Optional;
//import java.util.Set;
//
//import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.ss.usermodel.Sheet;
//import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.PutMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.google.gson.JsonArray;
//import com.google.gson.JsonElement;
//import com.google.gson.JsonObject;
//import com.google.gson.JsonParser;
//import com.realnet.Billing.Entitys.Invoice_t;
//import com.realnet.Billing.Entitys.ServiceOrder_t;
//import com.realnet.Billing.Repositorys.ServiceOrder_Repository;
//import com.realnet.Billing.Services.ServiceOrder_Service;
//import com.realnet.Communication.Models.Com_jobTable;
//import com.realnet.Communication.Repos.JobTablerepo;
//import com.realnet.Customer_master.Entity.Customer_master_t;
//import com.realnet.Customer_master.Repository.Customer_master_Repository;
//import com.realnet.DocumentBuilder.Entity.DocumentBuilder_t;
//import com.realnet.DocumentBuilder.Entity.Document_builder_lines;
//import com.realnet.DocumentBuilder.Services.DocumentBuilder_Service;
//import com.realnet.DocumentBuilder.Services.StringReplacementService;
//import com.realnet.fileupload.helper.Fileupload_helper;
//
//@RestController
//@RequestMapping("/api/serviceorders")
//public class ServiceOrderApiController {
//
// @Autowired
// private ServiceOrder_Service serviceOrder_Service;
//
// @Autowired
// private ServiceOrder_Repository serviceOrder_Repository;
//
// @Autowired
// private DocumentBuilder_Service Service;
//
// @Autowired
// private Fileupload_helper fileuploadhelper;
//
// @Autowired
// private StringReplacementService replacementService;
//
// @Autowired
// private Customer_master_Repository customer_master_Repository;
//
// @Autowired
// private JobTablerepo Com_jobTablerepo;
//
// @Value("${projectPath}")
// private String projectPath;
//
// public final String UPLOAD_DIREC = "/Files";
//
// // based on the period autocomplete all pending status
// @GetMapping("/update-status")
// public ResponseEntity<String> updateStatusForExpiredOrders() {
// int updatedCount = serviceOrder_Service.updateStatusForExpiredOrders();
// return ResponseEntity.ok("Updated " + updatedCount + " orders");
// }
//
// // download profoma invoice
// @GetMapping("/generate-excel/{id}")
// public ResponseEntity<byte[]> generateExcel(@PathVariable Long id) {
// ServiceOrder_t serviceOrder = serviceOrder_Service.findById(id);
//
// if (serviceOrder != null) {
// Workbook workbook = generateExcelForServiceOrder(serviceOrder);
//
// try {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// workbook.write(outputStream);
// byte[] excelBytes = outputStream.toByteArray();
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// headers.setContentDispositionFormData("attachment", "service_order.xlsx");
// return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
// } catch (Exception e) {
// // Handle exceptions
// }
// }
//
// return ResponseEntity.notFound().build();
// }
//
// public Workbook generateExcelForServiceOrder(ServiceOrder_t serviceOrder) {
// Workbook workbook = new XSSFWorkbook();
// Sheet sheet = workbook.createSheet("Service Order");
//
// // Create header row
// Row headerRow = sheet.createRow(0);
// headerRow.createCell(0).setCellValue("Service Order ID");
// headerRow.createCell(1).setCellValue("Service Order Seq");
//
// // Add more header cells for other fields as needed...
//
// // Create data row
// Row dataRow = sheet.createRow(1);
// dataRow.createCell(0).setCellValue(serviceOrder.getId());
// dataRow.createCell(1).setCellValue(serviceOrder.getServiceOrderSeq());
// // Add more data cells for other fields as needed...
//
// return workbook;
// }
//
// // to HOLD status
//// @PutMapping("/change-service-order-status/{profomaInvoiceId}")
//// public ResponseEntity<String> changeServiceOrderStatus(@PathVariable Long profomaInvoiceId) {
//// // Fetch the ProfomaInvoice by ID
//// ProfomaInvoice profomaInvoice = profomaInvoice_Service.findById(profomaInvoiceId);
////
//// if (profomaInvoice != null) {
//// // Get the associated ServiceOrderId from ProfomaInvoice
//// Long serviceOrderId = profomaInvoice.getServiceOrderId();
////
//// // Fetch the associated ServiceOrder_t entity
//// ServiceOrder_t serviceOrder = serviceOrder_Service.findById(serviceOrderId);
////
//// if (serviceOrder != null) {
//// // Update the status to "HOLD"
//// serviceOrder.setStatus("HOLD");
//// serviceOrder_Service.saveData(serviceOrder);
////
//// return ResponseEntity.ok("ServiceOrder status updated to HOLD");
//// }
//// }
////
//// return ResponseEntity.notFound().build();
//// }
//
// // Auto Creation Service order to invoicecopyServiceOrderToInvoice api
// @GetMapping("/copyServiceOrderToInvoice")
// public List<Invoice_t> copyServiceOrderToInvoice() {
// List<Invoice_t> createdInvoice = serviceOrder_Service.createInvoicesForAutoApprovedServiceOrders();
// return createdInvoice;
// }
//
////document status HOLD api (custmer hold) (old history table crude insert record),,service order release then it release hold
// @PutMapping("/updateHoldstatus/{id}")
// public ResponseEntity<String> updateStatusById(@PathVariable Long id) {
// try {
// // Hardcode the new status value to "HOLD"
// serviceOrder_Service.updateStatusById(id, "HOLD");
// return ResponseEntity.ok("Status updated to HOLD successfully");
// } catch (Exception e) {
// // Handle exceptions, e.g., if the entity with the given ID is not found
// return ResponseEntity.badRequest().body("Failed to update status: " + e.getMessage());
// }
// }
//
////so release hold
// @PutMapping("/updateResolvestatus/{id}")
// public ResponseEntity<String> updateStatusResolvedById(@PathVariable Long id) {
// try {
//
// serviceOrder_Service.updateStatusById(id, "RESOLVED");
// return ResponseEntity.ok("Status updated to HOLD successfully");
// } catch (Exception e) {
// // Handle exceptions, e.g., if the entity with the given ID is not found
// return ResponseEntity.badRequest().body("Failed to update status: " + e.getMessage());
// }
// }
//
// @PutMapping("/updateCustomerApprovedestatus/{id}")
// public ResponseEntity<String> updateStatusCustomerApprovedById(@PathVariable Long id) {
// try {
//
// serviceOrder_Service.updateStatusById(id, "CustomerApproved");
// return ResponseEntity.ok("Status updated to Approvec successfully");
// } catch (Exception e) {
// // Handle exceptions, e.g., if the entity with the given ID is not found
// return ResponseEntity.badRequest().body("Failed to update status: " + e.getMessage());
// }
// }
//
// @GetMapping("/customerGenerate")
// public void generateServiceOrder() {
// serviceOrder_Service.generateServiceOrders();
// }
//
// @GetMapping("/approvePending")
// public ResponseEntity<String> approvePendingOrders() {
// int updatedCount = serviceOrder_Service.approvePendingOrders();
// return ResponseEntity.ok("Approved " + updatedCount + " pending orders");
// }
//
// @GetMapping("/perfomaInvoiceCreation/{serviceOrderId}")
// public ResponseEntity<?> perfomaInvoiceCreation(@PathVariable long serviceOrderId) throws Exception {
//
// long documentId = 98;
// HashMap<String, String> map = new HashMap<>();
// JsonParser parser = new JsonParser();
// DocumentBuilder_t doc = Service.getdetailsbyId(documentId);
// String file_name = doc.getFile_name();
// String file_path = doc.getFile_path();
//
// String replacerule = "";
// String operation = null;
// String replaceWith = null;
// String startstring = null;
// String endstring = null;
// String keyword = null;
// String linestring = null;
// String cellAddress = null;
// JsonObject getbodyobject = null;
// String ModifyfileName = null;
//
// // .....................//
//
// List<Document_builder_lines> docline = doc.getDocument_builder_lines();
//
// for (Document_builder_lines line : docline) {
// String model = line.getModel();
// JsonParser parser1 = new JsonParser();
// JsonArray jsonArray = parser1.parse(model).getAsJsonArray();
//
// for (JsonElement element : jsonArray) {
// JsonObject jsonObject = element.getAsJsonObject();
// if (jsonObject.has("name")) {
// ModifyfileName = jsonObject.get("name").getAsString();
// break; // Break the loop once you find the first object with a "name" field
// }
// }
//
// if (ModifyfileName != null) {
// // Now 'nameValue' contains the value of the "name" field
// System.out.println("nameValue: " + ModifyfileName);
// break; // Break the outer loop as well, if needed
// }
// }
//
// if (ModifyfileName == null) {
// // Handle the case where no object with a "name" field was found
// System.out.println("No object with a 'name' field found.");
// }
//
// ModifyfileName = ModifyfileName.replace("?", String.valueOf(serviceOrderId));
// ModifyfileName = ModifyfileName + ".docx";
// String newFilepath = replacementService.copyWordFile(file_path, file_name, file_path, ModifyfileName);
//
// // ..........................//
//
// List<Document_builder_lines> lines = doc.getDocument_builder_lines();
//
// for (Document_builder_lines line : lines) {
// String model = line.getModel();
// JsonElement element = parser.parse(model);
// JsonArray models = element.getAsJsonArray();
//
// for (JsonElement mod : models) {
// JsonObject object = mod.getAsJsonObject();
//
// String type = object.get("type").getAsString();
// if (type.equalsIgnoreCase("Initialize")) {
// String a_uri = object.get("a_uri").toString().replaceAll("\"", "");
// a_uri = a_uri.replace("?", String.valueOf(serviceOrderId));
// System.out.println(a_uri);
//// Object body = GET(a_uri).getBody();
//// JsonElement getbody = parser.parse(body.toString());
//// getbodyobject = getbody.getAsJsonObject();
// Object body = GET(a_uri).getBody();
// ObjectMapper objectMapper = new ObjectMapper();
// String json = objectMapper.writeValueAsString(body);
// JsonElement getbody = parser.parse(json);
// getbodyobject = getbody.getAsJsonObject();
//
// }
// }
//
// for (JsonElement mod : models) {
// JsonObject object = mod.getAsJsonObject();
//
// String type = object.get("type").getAsString();
// if (type.equalsIgnoreCase("Mapper")) {
// String mapper = object.get("mappers").getAsString();
//
// JsonElement parse = parser.parse(mapper);
// JsonArray mapArray = parse.getAsJsonArray();
// for (JsonElement maps : mapArray) {
// JsonObject jsonObject = maps.getAsJsonObject();
// startstring = jsonObject.get("start_string").toString().replaceAll("\"", "");
// endstring = jsonObject.get("end_string").toString().replaceAll("\"", "");
// replaceWith = jsonObject.get("replace_with").toString().replaceAll("\"", "");
// keyword = jsonObject.get("Keyword").toString().replaceAll("\"", "");
// linestring = jsonObject.get("line_string").toString().replaceAll("\"", "");
// operation = jsonObject.get("operation").toString().replaceAll("\"", "");
// cellAddress = jsonObject.get("cellAddress").toString().replaceAll("\"", "");
// Set<Entry<String, JsonElement>> entrySet = getbodyobject.entrySet();
// for (Entry<String, JsonElement> entry : entrySet) {
//
// String key = entry.getKey().toString().replaceAll("\"", "");
// String value = entry.getValue().toString().replaceAll("\"", "");
//
// if (replaceWith.equalsIgnoreCase(key)) {
// replaceWith = value;
// break;
// }
//
// }
//
// if (operation.contains("replacebyfirstandlast")) {
//
// replacerule = replacementService.replacewithstartandend(file_path, file_name, startstring,
// endstring, replaceWith);
//
// }
//
// if (operation.contains("appending")) {
// replacerule = replacementService.appendToSlide(linestring, replaceWith, file_path,
// file_name);
// }
//
// if (operation.contains("linereplacement")) {
// replacerule = replacementService.linereplacementForPPT(file_path, file_name, keyword,
// replaceWith);
// }
// if (operation.contains("replacement")) {
// replacerule = replacementService.replacesting(newFilepath, file_name, keyword, replaceWith,
// ModifyfileName);
//
// }
//
// if (operation.contains("excelcellReplace")) {
// replacerule = replacementService.excelcellReplace(file_path, file_name, cellAddress,
// replaceWith);
//
// }
//
// }
// }
//
// }
// }
//
// return new ResponseEntity<>(replacerule, HttpStatus.CREATED);
// }
//
// @GetMapping("/sendEmail/{id}/{fileName}")
// public ResponseEntity<String> sendEmail(@PathVariable Long id, @PathVariable String fileName) {
//
// Optional<Customer_master_t> customer_master_t = customer_master_Repository.findById(id);
//
// String email = null;
// if (customer_master_t.isPresent()) {
// Customer_master_t customer = customer_master_t.get();
// email = customer.getEmail();
//
// }
//
// String gateway = "EMAIL";
// String sendTo = email;
// String replacementString = "no";
// String cc = email;
// String template = "PerfomaInvoice";
//
// // Create a new Com_jobTable instance and set its values
// Com_jobTable comJobTable = new Com_jobTable();
// comJobTable.setJob_type("EMAIL"); // Set the job type to "EMAIL"
// comJobTable.setSend_to(sendTo);
// comJobTable.setGatewayName(gateway);
// comJobTable.setAttachment(fileName);
// comJobTable.setGatewaydone("N");
// comJobTable.setReplacement_string(replacementString);
// comJobTable.setCc(cc);
// comJobTable.setReplacement_string(replacementString);
// comJobTable.setTemplate_name(template);
// // Save the Com_jobTable entity using your repository or service
// Com_jobTablerepo.save(comJobTable);
//
// return new ResponseEntity<>("Email sent successfully and job data saved!", HttpStatus.OK);
// }
//
// public ResponseEntity<Object> GET(String get) {
// RestTemplate restTemplate = new RestTemplate();
//
// ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
//
// return u;
//
// }
//
//}

View File

@@ -0,0 +1,67 @@
package com.realnet.Billing.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.Billing.Entitys.ApprovalHistory_t;
import com.realnet.Billing.Services.ApprovalHistory_Service;
@RequestMapping(value = "/ApprovalHistory")
@RestController
public class ApprovalHistory_Controller {
@Autowired
private ApprovalHistory_Service Service;
@PostMapping("/ApprovalHistory")
public ApprovalHistory_t Savedata(@RequestBody ApprovalHistory_t data) {
ApprovalHistory_t save = Service.Savedata(data);
return save;
}
@GetMapping("/ApprovalHistory")
public List<ApprovalHistory_t> getdetails() {
List<ApprovalHistory_t> get = Service.getdetails();
return get;
}
@GetMapping("/ApprovalHistory/{id}")
public ApprovalHistory_t getdetailsbyId(@PathVariable Long id) {
ApprovalHistory_t get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/ApprovalHistory/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/ApprovalHistory/{id}")
public ApprovalHistory_t update(@RequestBody ApprovalHistory_t data, @PathVariable Long id) {
ApprovalHistory_t update = Service.update(data, id);
return update;
}
// @PutMapping("/updateServiceOrderStatus")
// public ResponseEntity<ServiceOrderDto> updateServiceOrderStatus(
// @RequestParam Long serviceOrderId,
// @RequestParam String newStatus,
// @RequestParam String actionedBy,
// @RequestParam String comments
// ) {
// ServiceOrderDto updatedServiceOrder = Service.updateServiceOrderStatus(serviceOrderId, newStatus, actionedBy, comments);
// return new ResponseEntity<>(updatedServiceOrder, HttpStatus.OK);
// }
//
}

View File

@@ -0,0 +1,89 @@
package com.realnet.Billing.Controllers;
import com.realnet.Billing.Dto.ApprovalNote_SO;
import com.realnet.Billing.Dto.ApprovalQueue_SO;
import com.realnet.Billing.Repositorys.ApprovalReturnHistory_Repo;
import com.realnet.Billing.Services.ApprovalQueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/billing/approval")
public class ApprovalQueue_Controller {
@Autowired
private ApprovalQueueService approvalQueueService;
@PostMapping("/add")
public ResponseEntity<?> addApprovalQueue(
@RequestBody ApprovalQueue_SO approvalQueueSOSO
) {
return ResponseEntity.ok(approvalQueueService.saveApprovalQueue(approvalQueueSOSO));
}
@GetMapping("/getAll")
public List<ApprovalQueue_SO> getAllApprovalQueue() {
return approvalQueueService.getAllApprovalQueue();
}
@GetMapping("/get/{id}")
public ResponseEntity<ApprovalQueue_SO> getApprovalQueueById(
@PathVariable Long id) {
ApprovalQueue_SO approvalQueueSOSO = approvalQueueService.getApprovalQueueById(id);
if (approvalQueueSOSO != null) {
return ResponseEntity.ok(approvalQueueSOSO);
} else {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/getall/{docSeq}")
public ResponseEntity<List<ApprovalQueue_SO>> getAllQueueForDoc(@PathVariable Long docSeq) {
List<ApprovalQueue_SO> approvalQueueSOSOList = approvalQueueService.getAllQueueForDocument(docSeq);
if (approvalQueueSOSOList.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(approvalQueueSOSOList);
}
@PutMapping("/update/{id}")
public ResponseEntity<ApprovalQueue_SO> updateApprovalQueue(
@PathVariable Long id, @RequestBody ApprovalQueue_SO updatedApprovalQueueSOSO) {
ApprovalQueue_SO existingApprovalQueueSOSO = approvalQueueService.getApprovalQueueById(id);
if (existingApprovalQueueSOSO != null) {
existingApprovalQueueSOSO.setApprover(updatedApprovalQueueSOSO.getApprover());
existingApprovalQueueSOSO.setActionType(updatedApprovalQueueSOSO.getActionType());
existingApprovalQueueSOSO.setActionTaken(updatedApprovalQueueSOSO.getActionTaken());
existingApprovalQueueSOSO.setComments(updatedApprovalQueueSOSO.getComments());
existingApprovalQueueSOSO.setActionedAt(updatedApprovalQueueSOSO.getActionedAt());
ApprovalQueue_SO updatedQueue = approvalQueueService.saveApprovalQueue(existingApprovalQueueSOSO);
return ResponseEntity.ok(updatedQueue);
} else {
return ResponseEntity.notFound().build();
}
}
// ******************************************************************************* \\
// History-Controller \\
@Autowired
private ApprovalReturnHistory_Repo returnHistoryRepo;
@PostMapping("/return")
public ResponseEntity<?> saveReturnResponse(
@RequestBody ApprovalNote_SO history
){
history.setActionDate(new Date());
System.out.println(history);
return ResponseEntity.ok(returnHistoryRepo.save(history));
}
}

View File

@@ -0,0 +1,27 @@
package com.realnet.Billing.Dto;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
public class ApprovalNote_SO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String documentSeq;
private String actionTaken;
private String actionNote;
private Date actionDate;
@ManyToOne
@JoinColumn(name = "approval_queue_id")
@JsonBackReference
private ApprovalQueue_SO approvalQueueSO;
}

View File

@@ -0,0 +1,44 @@
package com.realnet.Billing.Dto;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
@Entity
@Data
public class ApprovalQueue_SO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String formCode;
private String documentSeq;
private String approver;
private String actionType;
private String actionTaken;
private String comments;
private Date actionedAt;
private String tablename;
@OneToMany(mappedBy = "approvalQueueSO", cascade = CascadeType.ALL)
@JsonManagedReference
private List<ApprovalNote_SO> history;
// @ManyToOne(fetch = FetchType.LAZY)
// @JoinColumn(name = "service_order_id")
// @JsonBackReference
private Long service_order_id;
}

View File

@@ -0,0 +1,32 @@
package com.realnet.Billing.Dto;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class BillingPeriodsResponse {
@JsonFormat(pattern = "yyyy-MM-dd")
private Date periodStart;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date periodEnd;
// Constructors, getters, setters
public BillingPeriodsResponse(Date periodStart, Date periodEnd) {
this.periodStart = periodStart;
this.periodEnd = periodEnd;
}
}

View File

@@ -0,0 +1,22 @@
package com.realnet.Billing.Dto;
import lombok.Data;
@Data
public class ServiceOrderDto {
private Long id;
private String orderType;
private String orderNo;
private String orderGenerationDate;
private String serviceRequestBy;
private String serviceRenderedFrom;
private String serviceRenderedTo;
private String contactNumber;
private String poNumber;
private String status;
private String remarks;
private String deliveryTerms;
// Other attributes as needed
// Getters and setters
}

View File

@@ -0,0 +1,48 @@
package com.realnet.Billing.Dto;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import lombok.Data;
@Data
public class ServiceWithDiscount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String memo;
private boolean active;
private String type;
private String period;
private String sellPrice;
private String selfCost;
private String serviceCode;
private String hsnCodes;
private boolean exempt;
private boolean nonGst;
private String taxRateType;
private String tarrifCode;
private String hsn_sacNumber;
private String natureOfTrans;
private String productType;
@Lob
private String inputJson;
private String disc;
private String gst ;
}

View File

@@ -0,0 +1,26 @@
package com.realnet.Billing.Entitys;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class ApprovalHistory_t {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String document_type;
private Long document_id;
private String actioned_by;
private String action;
private String comments;
private String approvalStatus;
}

View File

@@ -0,0 +1,26 @@
package com.realnet.Billing.Entitys;
import lombok.*;
import java.util.Date;
import javax.persistence.*;
@Entity
@Data
public class BillingPeriods_t {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date periodStart;
private Date periodEnd;
private Date dueDate;
private String status;
}

View File

@@ -0,0 +1,32 @@
package com.realnet.Billing.Entitys;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.realnet.WhoColumn.Entity.Who_column;
import lombok.Data;
@Entity
@Data
public class CustomerRates_t extends Who_column {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String rateCard;
private String destination;
private String numericPrefix;
private String sellRate;
private String blockMinDuration;
private String initBlockRate;
private String dateStart;
private String dateEnd;
private String enabled;
private String dateAdded;
private String dateModified;
}

View File

@@ -0,0 +1,325 @@
//package com.realnet.Billing.Job.Controller;
//
//import java.sql.SQLException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpEntity;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import com.google.gson.JsonArray;
//import com.google.gson.JsonElement;
//import com.google.gson.JsonObject;
//import com.google.gson.JsonParser;
//import com.realnet.Billing.Job.Entity.BillingJobEntity;
//import com.realnet.Billing.Job.Repository.BillingJobRepository;
//
//import com.realnet.utils.Port_Constant;
//
//@RestController
//@RequestMapping("/token/BillingWorkflow/surejob")
//public class BillingJobServiceController {
// Logger log = LoggerFactory.getLogger(BillingJobServiceController.class);
//
// @Autowired
// private BillingJobRepository jobrepo;
//
// @Autowired
// private BillingPerfomaWorkFlowLineRepository flowrepo;
//
// @Autowired
// private BillingPerfomaWorkFlowLineRepository line_repo;
//
// @Autowired
// private BillingTaxInvoiceWorkFlowLineRepository billingTaxInvoiceWorkFlowLineRepository;
//
// @Autowired
// BillingJobService service;
//
// @PostMapping("/assignJob")
// public ResponseEntity<?> jobAssign() {
// BillingJobEntity obj = new BillingJobEntity();
// BillingJobEntity obj2 = new BillingJobEntity();
// // DataflowJobConsolidationEntity obj3 = new DataflowJobConsolidationEntity();
//
// obj.setConnection_name(null);
// obj.setJob_type("PerfomaInvoice");
// obj.setMethod("GET");
// obj.setParameters(null);
// obj.setUrl("/token/PerfomaSequentialApi/executeWorkflow");
// obj.setRef(null);
// jobrepo.save(obj);
//
// obj2.setConnection_name(null);
// obj2.setJob_type("TaxInvoice");
// obj2.setMethod("GET");
// obj2.setParameters(null);
// obj2.setRef(null);
// obj2.setUrl("/token/consolidation/MergeData");
// jobrepo.save(obj2);
//
// return new ResponseEntity<>(obj2, HttpStatus.ACCEPTED);
// }
//
// @GetMapping("/getjob/{job_type}")
// public ResponseEntity<?> getByJob(@PathVariable String job_type) {
//
// BillingJobEntity jobtype = jobrepo.getByJobType(job_type);
// return new ResponseEntity<>(jobtype, HttpStatus.ACCEPTED);
// }
//
// @GetMapping("/create_job/{id}")
// public ResponseEntity<?> createjob(@PathVariable Long id) throws SQLException {
//
// String job_url = "";
// String CRON_exp = "";
// String job_type = "";
// String title = "";
// String node = "";
// ArrayList<Object> list = new ArrayList<>();
// BillingPerfomaWorkFlowLine lines = flowrepo.getSetuWorkflowlines(id);
// String str = lines.getModel();
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(str);
// JsonArray array = element.getAsJsonArray();
//// Iterator iterator = array.iterator();
//
// List<String> jobNamesList = new ArrayList<>();
//
// for (JsonElement jsonElement : array) {
//
// JsonObject jsonObject = jsonElement.getAsJsonObject();
//
// title = jsonObject.get("title").getAsString();
//
// StringBuilder builder = new StringBuilder();
//
// builder.append("no data");
// System.out.println(builder.toString());
//
// Map<String, String> jobprodata = new HashMap<String, String>();
// jobprodata.put("jobName", title + "_" + System.currentTimeMillis());
// jobprodata.put("jobGroup", "PerfomaInvoice");
//
// jobprodata.put("startTime", "2022-12-26T13:02");
// jobprodata.put("counter", "5");
// jobprodata.put("repeatTime", "5");
// jobprodata.put("cronExpression", "0/10 * * * * ?");
// jobprodata.put("line_id", id.toString());
// jobprodata.put("node_id", "null");
//
// System.out.println(jobprodata);
//
// System.out.println(jobprodata);
//
// RestTemplate restTemplate = new RestTemplate();
// String jobprourl2 = "http://" + Port_Constant.LOCAL_HOST + ":" + Port_Constant.SURE_JOB_8089
// + "/surejob/schedule";
// HttpHeaders headers2 = getHeaders();
// HttpEntity<Object> request2 = new HttpEntity<Object>(jobprodata, headers2);
//
// ResponseEntity<Object> res2 = restTemplate.postForEntity(jobprourl2, request2, Object.class);
// System.out.println(res2.getStatusCodeValue());
//
// if (res2.getStatusCodeValue() == 200) {
// log.info("Gitea data inserted in sure job");
// System.out.println(res2.getBody());
// jobNamesList.add(jobprodata.get("jobName"));
// // jobNamesList.add(jobprodata.get("jobGroup"));
//
// }
// }
//
// return new ResponseEntity<>(jobNamesList, HttpStatus.ACCEPTED);
// }
//
// @GetMapping("/surejob/{id}")
// public ResponseEntity<?> forjobscheduler(@PathVariable Long id) throws SQLException {
//
// ArrayList<Object> list = new ArrayList<>();
// BillingPerfomaWorkFlowLine lines = flowrepo.getSetuWorkflowlines(id);
// String str = lines.getModel();
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(str);
// JsonArray array = element.getAsJsonArray();
// Iterator iterator = array.iterator();
//
// String job_url = "";
// String CRON_exp = "";
// String job_type = "";
// BillingJobEntity job = null;
//
// Boolean auto_mapping = true;
// while (iterator.hasNext()) {
//
// Object next = iterator.next();
// JsonElement parse = parser.parse(next.toString());
// JsonObject jsonObject = parse.getAsJsonObject();
// // int i = jsonObject.get("id").getAsInt();
//
//
// job_type = "PerfomaInvoice";
//
//// if (job_type.isEmpty() || job_type.contains("null") || job_type == null) {
//// job_type = jsonObject.get("type").toString().replaceAll("\"", "");
//// }
//
// job = jobrepo.getByJobType(job_type);
//
// break;
//// }
//
// }
// return new ResponseEntity<>(job, HttpStatus.ACCEPTED);
// }
//// GET DATA FLOW LINE
//
// @GetMapping("/getline/{id}")
// public ResponseEntity<?> getline(@PathVariable Long id) {
//
// return new ResponseEntity<>(line_repo.getSetuWorkflowlines(id), HttpStatus.ACCEPTED);
//
// }
//
// private HttpHeaders getHeaders() {
// HttpHeaders headers = new HttpHeaders();
// headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
// headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
// return headers;
// }
//
// // Tax Invoice Job Start
//
// @GetMapping("/create_job/{id}")
// public ResponseEntity<?> createjobforTaxInvoice(@PathVariable Long id) throws SQLException {
//
// String job_url = "";
// String CRON_exp = "";
// String job_type = "";
// String title = "";
// String node = "";
// ArrayList<Object> list = new ArrayList<>();
// BillingTaxInvoiceWorkFlowLine lines = billingTaxInvoiceWorkFlowLineRepository.getSetuWorkflowlines(id);
// String str = lines.getModel();
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(str);
// JsonArray array = element.getAsJsonArray();
//// Iterator iterator = array.iterator();
//
// List<String> jobNamesList = new ArrayList<>();
//
// for (JsonElement jsonElement : array) {
//
// JsonObject jsonObject = jsonElement.getAsJsonObject();
//
// title = jsonObject.get("title").getAsString();
//
// StringBuilder builder = new StringBuilder();
//
// builder.append("no data");
// System.out.println(builder.toString());
//
// Map<String, String> jobprodata = new HashMap<String, String>();
// jobprodata.put("jobName", title + "_" + System.currentTimeMillis());
// jobprodata.put("jobGroup", "TaxInvoice");
//
// jobprodata.put("startTime", "2022-12-26T13:02");
// jobprodata.put("counter", "5");
// jobprodata.put("repeatTime", "5");
// jobprodata.put("cronExpression", "0/10 * * * * ?");
// jobprodata.put("line_id", id.toString());
// jobprodata.put("node_id", "null");
//
// System.out.println(jobprodata);
//
// System.out.println(jobprodata);
//
// RestTemplate restTemplate = new RestTemplate();
// String jobprourl2 = "http://" + Port_Constant.LOCAL_HOST + ":" + Port_Constant.SURE_JOB_8089
// + "/surejob/schedule";
// HttpHeaders headers2 = getHeaders();
// HttpEntity<Object> request2 = new HttpEntity<Object>(jobprodata, headers2);
//
// ResponseEntity<Object> res2 = restTemplate.postForEntity(jobprourl2, request2, Object.class);
// System.out.println(res2.getStatusCodeValue());
//
// if (res2.getStatusCodeValue() == 200) {
// log.info("Gitea data inserted in sure job");
// System.out.println(res2.getBody());
// jobNamesList.add(jobprodata.get("jobName"));
// // jobNamesList.add(jobprodata.get("jobGroup"));
//
// }
// }
//
// return new ResponseEntity<>(jobNamesList, HttpStatus.ACCEPTED);
// }
//
//
//
//
//
//
//
//
//
// @GetMapping("/surejob/taxInvoice/{id}")
// public ResponseEntity<?> forjobschedulerInvoicetax(@PathVariable Long id) throws SQLException {
//
// ArrayList<Object> list = new ArrayList<>();
// BillingTaxInvoiceWorkFlowLine lines = billingTaxInvoiceWorkFlowLineRepository.getSetuWorkflowlines(id);
// String str = lines.getModel();
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(str);
// JsonArray array = element.getAsJsonArray();
// Iterator iterator = array.iterator();
//
// String job_url = "";
// String CRON_exp = "";
// String job_type = "";
// BillingJobEntity job = null;
//
// Boolean auto_mapping = true;
// while (iterator.hasNext()) {
//
// Object next = iterator.next();
// JsonElement parse = parser.parse(next.toString());
// JsonObject jsonObject = parse.getAsJsonObject();
// // int i = jsonObject.get("id").getAsInt();
//
//
// job_type = "TaxInvoice";
//
//// if (job_type.isEmpty() || job_type.contains("null") || job_type == null) {
//// job_type = jsonObject.get("type").toString().replaceAll("\"", "");
//// }
//
// job = jobrepo.getByJobType(job_type);
//
// break;
//// }
//
// }
// return new ResponseEntity<>(job, HttpStatus.ACCEPTED);
// }
//
//}

View File

@@ -0,0 +1,25 @@
package com.realnet.Billing.Job.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class BillingJobEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String parameters;
private String url;
private String method;
private String connection_name;
private String job_type;
private String ref;
}

View File

@@ -0,0 +1,16 @@
package com.realnet.Billing.Job.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.Billing.Job.Entity.BillingJobEntity;
@Repository
public interface BillingJobRepository extends JpaRepository<BillingJobEntity, Long> {
@Query(value = "SELECT * FROM billing_job_entity where job_type=?1", nativeQuery = true)
BillingJobEntity getByJobType(String jobtype);
}

View File

@@ -0,0 +1,23 @@
//package com.realnet.Billing.Job.Service;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import com.realnet.DataConsolidation.Entity.DataflowJobConsolidationEntity;
//import com.realnet.DataConsolidation.Repository.DataflowJobConsolidationRepository;
//
//
//@Service
//public class BillingJobService {
//
// @Autowired
// private DataflowJobConsolidationRepository jobrepo;
//
// public DataflowJobConsolidationEntity getJobtype(String jobtype) {
// DataflowJobConsolidationEntity byJobType = jobrepo.getByJobType(jobtype);
// return byJobType;
// }
//
//
//
//}

View File

@@ -0,0 +1,11 @@
package com.realnet.Billing.Repositorys;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.Billing.Entitys.ApprovalHistory_t;
@Repository
public interface ApprovalHistory_Repository extends JpaRepository<ApprovalHistory_t, Long> {
}

View File

@@ -0,0 +1,13 @@
package com.realnet.Billing.Repositorys;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.Billing.Dto.ApprovalQueue_SO;
import java.util.List;
@Repository
public interface ApprovalQueue_Repository extends JpaRepository<ApprovalQueue_SO, Long> {
List<ApprovalQueue_SO> findByDocumentSeq(Long docid);
}

View File

@@ -0,0 +1,9 @@
package com.realnet.Billing.Repositorys;
import com.realnet.Billing.Dto.ApprovalNote_SO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ApprovalReturnHistory_Repo extends JpaRepository<ApprovalNote_SO,Long> {
}

View File

@@ -0,0 +1,135 @@
package com.realnet.Billing.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.Billing.Entitys.ApprovalHistory_t;
import com.realnet.Billing.Repositorys.ApprovalHistory_Repository;
@Service
public class ApprovalHistory_Service {
@Autowired
private ApprovalHistory_Repository Repository;
// @Autowired
// private ServiceOrder_Repository serviceOrder_Repository1;
public ApprovalHistory_t Savedata(ApprovalHistory_t data) {
return Repository.save(data);
}
public List<ApprovalHistory_t> getdetails() {
return (List<ApprovalHistory_t>) Repository.findAll();
}
public ApprovalHistory_t getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public ApprovalHistory_t update(ApprovalHistory_t data, Long id) {
ApprovalHistory_t old = Repository.findById(id).get();
old.setDocument_type(data.getDocument_type());
old.setDocument_id(data.getDocument_id());
old.setActioned_by(data.getActioned_by());
old.setAction(data.getAction());
old.setComments(data.getComments());
final ApprovalHistory_t test = Repository.save(old);
return test;
}
// public ServiceOrder_t updateServiceOrderStatus(Long serviceOrderId, String newStatus, String actionedBy, String comments) {
// try {
// Optional<ServiceOrder_t> optionalServiceOrder = serviceOrder_Repository.findById(serviceOrderId);
// if (optionalServiceOrder.isEmpty()) {
// throw new EntityNotFoundException("Service Order not found with ID: " + serviceOrderId);
// }
//
// ServiceOrder_t serviceOrder = optionalServiceOrder.get();
// serviceOrder.setStatus(newStatus);
// serviceOrder_Repository.save(serviceOrder);
//
// // Insert data into Approval History table
// ApprovalHistory_t approvalHistory = new ApprovalHistory_t();
// approvalHistory.setDocument_type("ServiceOrder");
// approvalHistory.setDocument_id(serviceOrderId);
// approvalHistory.setActioned_by(actionedBy);
// approvalHistory.setAction("Status Updated");
// approvalHistory.setComments(comments);
// // Set other fields in the Approval History table as needed
//
// Repository.save(approvalHistory);
//
// return serviceOrder;
// } catch (EntityNotFoundException ex) {
// // Handle EntityNotFoundException (Service Order not found)
// // You can log the error, return a custom error response, or throw a new exception.
// throw ex;
// } catch (Exception ex) {
// // Handle other exceptions (e.g., database errors, unexpected issues)
// // You can log the error, return a custom error response, or throw a new exception.
// throw new RuntimeException("Error updating Service Order status.", ex);
// }
// }
//
// public ServiceOrderDto updateServiceOrderStatus(Long serviceOrderId, String newStatus, String actionedBy, String comments) {
// // ... existing code to update status ...
//
//
//
// // Convert ServiceOrder_t entity to ServiceOrderDto
// ServiceOrderDto serviceOrderDto = convertToDto(serviceOrder);
//
// return serviceOrderDto;
// }
//
// public ServiceOrderDto updateServiceOrderStatus(Long serviceOrderId, String newStatus, String actionedBy,
// String comments) {
// try {
// Optional<ServiceOrder_t> optionalServiceOrder = serviceOrder_Repository.findById(serviceOrderId);
// if (!optionalServiceOrder.isPresent()) {
// throw new EntityNotFoundException("Service Order not found with ID: " + serviceOrderId);
// }
//
// ServiceOrder_t serviceOrder = optionalServiceOrder.get();
// serviceOrder.setStatus(newStatus);
// serviceOrder_Repository.save(serviceOrder);
//
// // Insert data into Approval History table
// ApprovalHistory_t approvalHistory = new ApprovalHistory_t();
// approvalHistory.setDocument_type("ServiceOrder");
// approvalHistory.setDocument_id(serviceOrderId);
// approvalHistory.setActioned_by(actionedBy);
// approvalHistory.setAction("Status Updated");
// approvalHistory.setComments(comments);
// // Set other fields in the Approval History table as needed
//
// Repository.save(approvalHistory);
//
// // Convert ServiceOrder_t entity to DTO and return
// return convertToDto(serviceOrder);
// } catch (EntityNotFoundException ex) {
// // Handle EntityNotFoundException (Service Order not found)
// // You can log the error, return a custom error response, or throw a new
// // exception.
// throw ex;
// } catch (Exception ex) {
// // Handle other exceptions (e.g., database errors, unexpected issues)
// // You can log the error, return a custom error response, or throw a new
// // exception.
// throw new RuntimeException("Error updating Service Order status.", ex);
// }
// }
// private ServiceOrderDto convertToDto(ServiceOrder_t serviceOrder) {
// // Perform mapping from ServiceOrder_t entity to ServiceOrderDto
// ModelMapper modelMapper = new ModelMapper();
// return modelMapper.map(serviceOrder, ServiceOrderDto.class);
// }
}

View File

@@ -0,0 +1,31 @@
package com.realnet.Billing.Services;
import com.realnet.Billing.Dto.ApprovalQueue_SO;
import com.realnet.Billing.Repositorys.ApprovalQueue_Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ApprovalQueueService {
@Autowired
private ApprovalQueue_Repository approvalQueueRepository;
public ApprovalQueue_SO saveApprovalQueue(ApprovalQueue_SO approvalQueueSOSO) {
return approvalQueueRepository.save(approvalQueueSOSO);
}
public List<ApprovalQueue_SO> getAllApprovalQueue() {
return approvalQueueRepository.findAll();
}
public ApprovalQueue_SO getApprovalQueueById(Long id) {
return approvalQueueRepository.findById(id).orElse(null);
}
public List<ApprovalQueue_SO> getAllQueueForDocument(Long docid) {
return approvalQueueRepository.findByDocumentSeq(docid);
}
}

View File

@@ -0,0 +1,21 @@
package com.realnet.Builders.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Builder_entity_t {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String job_type;
private String job_name;
}

View File

@@ -0,0 +1,15 @@
package com.realnet.Builders.Repos;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.Builders.Entity.Builder_entity_t;
@Repository
public interface BuilderRepository extends JpaRepository<Builder_entity_t, Long> {
@Query(value = "select * from builder_entity_t where job_name= ?1 && job_type=?2", nativeQuery = true)
Builder_entity_t findByjobTypeAndName(String job_name, String job_type);
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
package com.realnet.BulkUpload.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.BulkUpload.Entity.BulkUpload_t;
import com.realnet.BulkUpload.Services.BulkUpload_Service;
@RequestMapping(value = "/BulkUpload")
@RestController
public class BulkUpload_Controller {
@Autowired
private BulkUpload_Service Service;
@PostMapping("/BulkUpload")
public BulkUpload_t Savedata(@RequestBody BulkUpload_t data) {
BulkUpload_t save = Service.Savedata(data) ;
return save;
}
@GetMapping("/BulkUpload")
public List<BulkUpload_t> getdetails() {
List<BulkUpload_t> get = Service.getdetails();
return get;
}
@GetMapping("/BulkUpload/{id}")
public BulkUpload_t getdetailsbyId(@PathVariable Long id ) {
BulkUpload_t get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/BulkUpload/{id}")
public void delete_by_id(@PathVariable Long id ) {
Service.delete_by_id(id);
}
@PutMapping("/BulkUpload/{id}")
public BulkUpload_t update(@RequestBody BulkUpload_t data,@PathVariable Long id ) {
BulkUpload_t update = Service.update(data,id);
return update;
}

View File

@@ -0,0 +1,124 @@
package com.realnet.BulkUpload.Controllers;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
//import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.realnet.BulkUpload.Entity.MappingRule;
import com.realnet.BulkUpload.Services.MappingRuleService;
@RestController
@RequestMapping("/MappingRule")
public class MappingRuleController {
@Autowired
private MappingRuleService Service;
@PostMapping("/MappingRule")
public MappingRule Savedata(@RequestBody MappingRule data) {
MappingRule save = Service.Savedata(data);
return save;
}
@GetMapping("/MappingRule")
public List<MappingRule> getdetails() {
List<MappingRule> get = Service.getdetails();
return get;
}
@GetMapping("/MappingRule/{id}")
public MappingRule getdetailsbyId(@PathVariable Long id) {
MappingRule get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/MappingRule/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/MappingRule/{id}")
public MappingRule update(@RequestBody MappingRule data, @PathVariable Long id) {
MappingRule update = Service.update(data, id);
return update;
}
@GetMapping("/getHeaders")
public ResponseEntity<?> getFileHeadersForSheet(
@RequestParam("file") MultipartFile excelFile,
@RequestParam("sheetName") String sheetName) {
try (Workbook workbook = WorkbookFactory.create(excelFile.getInputStream())) {
List<String> sheetHeaders = new ArrayList<>();
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
return ResponseEntity.notFound().build(); // Sheet not found
}
Row headerRow = sheet.getRow(0);
if (headerRow != null) {
for (Cell cell : headerRow) {
String header = cell.getStringCellValue();
sheetHeaders.add(header);
}
}
return ResponseEntity.ok(sheetHeaders);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing Excel file.");
}
}
// @GetMapping("/getHeadersMapping")
// public ResponseEntity<?> getAllSheetHeadersForMapping(@RequestParam("file") MultipartFile excelFile,@RequestParam("sheetName") String sheetName) {
// try (Workbook workbook = WorkbookFactory.create(excelFile.getInputStream())) {
// Map<String, List<Map<String, String>>> sheetHeadersMap = new LinkedHashMap<>();
//
// for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
// Sheet sheet = workbook.getSheet(sheetName);
// List<Map<String, String>> sheetHeaders = new ArrayList<>();
//
// Row headerRow = sheet.getRow(0);
//
// if (headerRow != null) {
// for (Cell cell : headerRow) {
// String header = cell.getStringCellValue();
// Map<String, String> headerObject = new LinkedHashMap<>();
// headerObject.put("headerName", header);
// headerObject.put("value", ""); // Empty value
// sheetHeaders.add(headerObject);
// }
// }
//
// sheetHeadersMap.put(sheet.getSheetName(), sheetHeaders);
// }
//
// return ResponseEntity.ok(sheetHeadersMap);
// } catch (Exception e) {
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing Excel file.");
// }
// }
}

View File

@@ -0,0 +1,600 @@
package com.realnet.BulkUpload.Controllers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.realnet.BulkUpload.Entity.BulkUpload_t;
import com.realnet.BulkUpload.Repository.BulkUpload_Repository;
import com.realnet.BulkUpload.Services.BulkUpload_Service;
import com.realnet.template.entity.TemplateFileUpload;
import com.realnet.template.repository.TemplatedataRepo;
import com.realnet.template.service.DynamicTemplateService;
import com.realnet.template.service.FileUploadService;
@RestController
@RequestMapping("/masterimport")
public class MasterImportController {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private TemplatedataRepo temprepo;
@Autowired
private DynamicTemplateService dynamicTemplateService;
@Autowired
private BulkUpload_Service bulkUpload_Service;
@Autowired
private BulkUpload_Repository bulkUpload_Repository;
@Autowired
private FileUploadService fileUploadService;
@Autowired
private ObjectMapper objectMapper;
@Value("${projectPath}")
private String projectPath;
@GetMapping("/demo/download/{file_type}")
public ResponseEntity<?> demoTemplate(@PathVariable String file_type) throws IOException {
Workbook workbook = new XSSFWorkbook();
if (file_type.equalsIgnoreCase("Customer")) {
// Create Customer sheet with headers only
String[] customerHeaders = { "balance", "c_status", "city", "country","currency_code","customer_id",
"date_of_birth", "defaultsite_id", "email", "entity_name","file_name","file_path",
"first_name", "gender", "gst_no", "gst_state","house_no","mobile_no",
"pan_no", "sales_rep", "special_price", "state","street_address","street_address2",
"time_zone", "postal_code", "contact_number"};
createSheetWithHeaders(workbook, "Customer", customerHeaders);
// Create Site sheet with headers only
String[] siteHeaders = { "Site Name", "Site Description", "Active", "Test" };
createSheetWithHeaders(workbook, "Site", siteHeaders);
} else {
return new ResponseEntity<String>("Not found", HttpStatus.BAD_REQUEST);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
workbook.write(out);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file_type + "_template.xlsx")
.contentType(MediaType.parseMediaType("application/vnd.ms-excel")).body(out.toByteArray());
}
private void createSheetWithHeaders(Workbook workbook, String sheetName, String[] headers) {
Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
// Create headers
for (int col = 0; col < headers.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(headers[col]);
}
}
@PostMapping("/DownloadExcelForMaster/{id}")
public ResponseEntity<?> DownloadExcelForMaster(@PathVariable Long id,
@RequestBody Map<String, List<Map<String, Object>>> jsonData) {
try {
List<TemplateFileUpload> templateFileUpload = temprepo.findUnprocessedRecordsOrderedByIdAsc();
if (!templateFileUpload.isEmpty()) {
for (TemplateFileUpload upload : templateFileUpload) {
String entity_name = upload.getEntity_name();
BulkUpload_t bulkUpload_t = bulkUpload_Repository.getentityName(entity_name);
String ruleLine = bulkUpload_t.getRule_line();
// BulkUpload_t bulkUpload_t = bulkUpload_Repository.getentityName(entity_name);
// String ruleLine = bulkUpload_t.getRule_line();
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(ruleLine);
JsonArray array = element.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
String fromsheet = null;
String fromColumn = null;
String validationTable = null;
String checkColumn = null;
String useColumn = null;
String replacementtable = null;
String replacementcolumn = null;
while (iterator.hasNext()) {
JsonElement next = iterator.next();
JsonObject jsonObject = next.getAsJsonObject();
fromsheet = jsonObject.get("fromsheet").getAsString();
fromColumn = jsonObject.get("fromColumn").getAsString();
validationTable = jsonObject.get("validationTable").getAsString();
checkColumn = jsonObject.get("checkColumn").getAsString();
useColumn = jsonObject.get("useColumn").getAsString();
replacementtable = jsonObject.get("useTable").getAsString();
replacementcolumn = jsonObject.get("replacementcolumn").getAsString();
break;
}
String customerTableName = validationTable;
String siteTableName = replacementtable;
Set<String> tableNames = jsonData.keySet(); // Get all unique table names
String siteEntityName = null;
for (String tableName : tableNames) {
List<Map<String, Object>> tableData = jsonData.get(tableName);
// Process tableData based on the tableName (e.g., "Site" or "Customer")
System.out.println("Table Name: " + tableName);
for (Map<String, Object> row : tableData) {
// Process individual rows within the table data
System.out.println("Row Data: " + row);
}
}
List<Map<String, Object>> processedDataList = new ArrayList<>(); // List to hold processed data rows
// Iterate through each customer data entry
List<Map<String, Object>> customerData = jsonData.get("Customer");
for (Map<String, Object> insertCustomerData : customerData) {
String customerName = (String) insertCustomerData.get(checkColumn);
// Check if the customerName is not null and iterate through "Site" data
List<Map<String, Object>> siteData = jsonData.get(fromsheet);
List<Map<String, Object>> matchedSiteData = new ArrayList<>();
if (customerName != null) {
// Iterate through "Site" data and check for a matching "entity_name"
for (Map<String, Object> siteRow : siteData) {
// Specify the index as "AM" (39th column)
// String columnIndex = "AM";
String columnIndex = fromColumn;
// Retrieve the value at the specified index
for (Map.Entry<String, Object> entry : siteRow.entrySet()) {
if (entry.getKey().equals(columnIndex)) {
siteEntityName = (String) entry.getValue();
break; // Exit the loop once the value is found
}
}
if (customerName.equals(siteEntityName)) {
// Add the matching "Site" data to the list
matchedSiteData.add(siteRow);
}
}
}
ObjectMapper objectMapper = new ObjectMapper();
String insertCustomerDataJson = objectMapper.writeValueAsString(insertCustomerData);
String matchedSiteDataJson = objectMapper.writeValueAsString(matchedSiteData);
String customerSql = getInsertQuery(customerTableName, insertCustomerData);
// Insert data into the customer table
Object[] customerValues = new Object[insertCustomerData.size() + 5];
int index = 0;
for (Object value : insertCustomerData.values()) {
customerValues[index++] = value;
}
customerValues[index++] = new Timestamp(System.currentTimeMillis()); // created_at
customerValues[index++] = null; // created_by
customerValues[index++] = null; // updated_by
customerValues[index++] = new Timestamp(System.currentTimeMillis()); // updated_at
customerValues[index] = null; // account_id
jdbcTemplate.update(customerSql, customerValues);
// we can use useColumn here
Long generatedId = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
List<Map<String, Object>> insertMatchedSiteData = new ArrayList<>(); // List to hold processed
// data rows
for (Map<String, Object> siteRow : matchedSiteData) {
// Replace "Customer Name" with "customer_master_id" if it exists
if (siteRow.containsKey(siteEntityName)) {
siteRow.put(replacementcolumn, generatedId);
siteRow.remove(siteEntityName);
}
insertMatchedSiteData.add(siteRow);
}
for (Map<String, Object> siteRow : insertMatchedSiteData) {
Object[] siteValues = new Object[siteRow.size() + 5]; // Create a new array for each row
int siteIndex = 0;
for (Object value : siteRow.values()) {
siteValues[siteIndex++] = value;
}
siteValues[siteIndex++] = new Timestamp(System.currentTimeMillis()); // created_at
siteValues[siteIndex++] = null; // created_by
siteValues[siteIndex++] = null; // updated_by
siteValues[siteIndex++] = new Timestamp(System.currentTimeMillis()); // updated_at
siteValues[siteIndex] = null; // account_id
String siteSql = getInsertQuery(siteTableName, siteRow);
jdbcTemplate.update(siteSql, siteValues);
}
// Add the processed customer data to the list
processedDataList.add(insertCustomerData);
}
// Use a LinkedHashMap to preserve insertion order in the response
Map<String, List<Map<String, Object>>> response = new LinkedHashMap<>();
response.put("result", processedDataList);
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
return new ResponseEntity<>("No data to process", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
// Handle exceptions and return an appropriate response
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private List<String> getColumnNames(Map<String, Object> dataRow) {
return new ArrayList<>(dataRow.keySet());
}
// Method to write data to a sheet
private void writeDataToSheet(List<Map<String, Object>> dataList, XSSFSheet sheet, List<String> columnNames) {
int rowIndex = 0;
// Create the header row
XSSFRow headerRow = sheet.createRow(rowIndex++);
for (int i = 0; i < columnNames.size(); i++) {
XSSFCell cell = headerRow.createCell(i);
cell.setCellValue(columnNames.get(i));
}
// Add "Status" and "Exception" columns to the sheet
headerRow.createCell(columnNames.size()).setCellValue("Status");
headerRow.createCell(columnNames.size() + 1).setCellValue("Exception");
// Write the data rows
for (Map<String, Object> row : dataList) {
XSSFRow dataRow = sheet.createRow(rowIndex++);
int columnIndex = 0;
for (String columnName : columnNames) {
Object value = row.get(columnName);
XSSFCell cell = dataRow.createCell(columnIndex++);
cell.setCellValue(value != null ? value.toString() : "");
}
// Add "Status" and "Exception" values to the data row
dataRow.createCell(columnIndex++).setCellValue(row.get("Status").toString());
dataRow.createCell(columnIndex).setCellValue(row.get("Exception").toString());
}
}
private String extractExceptionMessage(DataIntegrityViolationException e) {
String errorMessage = e.getMessage();
int startIndex = errorMessage.indexOf("Incorrect ");
int endIndex = errorMessage.indexOf("at row");
if (startIndex != -1 && endIndex != -1) {
return errorMessage.substring(startIndex, endIndex).trim();
}
return errorMessage;
}
private String getInsertQuery(String tableName, Map<String, Object> data) {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("INSERT INTO ");
sqlBuilder.append(tableName);
sqlBuilder.append(" (");
sqlBuilder.append(String.join(", ", data.keySet()));
sqlBuilder.append(", created_at, created_by, updated_by, updated_at, account_id) VALUES (");
sqlBuilder.append(String.join(", ", Collections.nCopies(data.size(), "?")));
sqlBuilder.append(", ?, ?, ?, ?, ?)");
return sqlBuilder.toString();
}
@GetMapping("/sheet/{id}")
public ResponseEntity<?> getSheet(@PathVariable Long id) throws IOException {
ResponseEntity<?> jsonData = convertFileToJsonforsheet(id);
return ResponseEntity.ok(jsonData.getBody());
}
public ResponseEntity<?> convertFileToJsonforsheet(Long id) throws IOException {
// Retrieve the TemplateFileUpload entity based on the provided ID
Optional<TemplateFileUpload> fileUploadOptional = temprepo.findById(id);
if (!fileUploadOptional.isPresent()) {
// Handle the case where the file is not found in the specified location
return ResponseEntity.notFound().build();
}
TemplateFileUpload fileUpload = fileUploadOptional.get();
String location = fileUpload.getFile_location();
String fileName = fileUpload.getFile_changed_name() + ".xlsx";
String filePath = location + File.separator + "processingfile" + File.separator + fileName;
File file = new File(filePath);
if (!file.exists()) {
// Handle the case where the file is not found in the specified location
return ResponseEntity.notFound().build();
}
try (FileInputStream fis = new FileInputStream(file)) {
XSSFWorkbook workbook = new XSSFWorkbook(fis);
List<String> sheetNames = new ArrayList<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
XSSFSheet sheet = workbook.getSheetAt(i);
String sheetName = sheet.getSheetName();
sheetNames.add(sheetName);
}
return ResponseEntity.ok(sheetNames);
} catch (Exception e) {
// Handle any exceptions that may occur during processing
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing Excel file.");
}
}
@GetMapping("/downloadImportStatement/{id}")
public ResponseEntity<?> downloadImportStatement(@PathVariable Long id) {
// Retrieve the file data from the database based on the ID
TemplateFileUpload fileUpload = fileUploadService.getFileById(id);
// Get the file location from the entity
String fileLocation = fileUpload.getDownloadfileLocation();
// String filename = fileUpload.getDownloadfileName();
//
// String filepath = fileLocation + File.separator + filename;
try {
// Read the file content from the specified location
byte[] fileContent = Files.readAllBytes(Paths.get(fileLocation));
// Create a ByteArrayResource from the file content
ByteArrayResource resource = new ByteArrayResource(fileContent);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + fileUpload.getFile_name() + "\"")
.body(resource);
} catch (IOException e) {
// Handle any potential exceptions (e.g., file not found)
e.printStackTrace();
return ResponseEntity.status(500).body("Error occurred while reading the file.");
}
}
@GetMapping("/columns/{tableName}")
public List<String> getColumnNames(@PathVariable String tableName) {
Set<String> columnNamesSet = new HashSet<>();
String convertedTableName = tableName;
List<String> columnNames = jdbcTemplate.queryForList(
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?",
new Object[] { convertedTableName }, String.class);
// Exclude specific column names
List<String> excludedColumns = Arrays.asList("id", "account_id", "updated_at", "created_at", "created_by",
"updated_by");
for (String columnName : columnNames) {
if (!excludedColumns.contains(columnName)) {
columnNamesSet.add(columnName);
}
}
return new ArrayList<>(columnNamesSet);
}
private String getCellValue(Map<String, List<Map<String, Object>>> jsonData, String sheetName, String cellAddress)
throws IOException {
if (jsonData.containsKey(sheetName)) {
List<Map<String, Object>> sheetData = jsonData.get(sheetName);
int size = sheetData.size();
System.out.println(size);
Map<String, Object> firstRowData = sheetData.get(0);
// Separate the numeric part (row part) and non-numeric part (column part)
String rowPart = "";
String columnPart = "";
for (char c : cellAddress.toCharArray()) {
if (Character.isDigit(c)) {
rowPart += c;
} else {
columnPart += c;
}
}
System.out.println("Column Part: " + columnPart);
System.out.println("Row Part: " + rowPart);
int columnIndex = getColumnIndex(columnPart); // Get the column index based on the columnPart
// int rowIndex = Integer.parseInt(rowPart) - 1; // Excel-style 1-based index
System.out.println("Column Index: " + columnIndex);
if (columnIndex >= 0) {
// Get the list of keys from the firstRowData map
List<String> keys = new ArrayList<>(firstRowData.keySet());
// Check if the columnIndex is within the range of keys
if (columnIndex < keys.size()) {
String columnName = keys.get(columnIndex);
return columnName;
}
}
}
return null;
}
private int getColumnIndex(String columnPart) {
int index = 0;
int multiplier = 1;
// Iterate through the columnPart in reverse order (right to left)
for (int i = columnPart.length() - 1; i >= 0; i--) {
char c = columnPart.charAt(i);
index += (c - 'A' + 1) * multiplier;
multiplier *= 26; // Multiply by 26 for each position to calculate the index
}
return index - 1; // Subtract 1 to get a 0-based index
}
@PostMapping("/DownloadExcel/{entityName}")
public ResponseEntity<Resource> importdatadownloadexcel(@PathVariable String entityName,
@RequestBody List<Map<String, Object>> data) throws IOException {
List<Map<String, Object>> processedData = processData(entityName, data);
if (!processedData.isEmpty()) {
Workbook workbook = createWorkbook(processedData);
Resource resource = createExcelResource(workbook);
return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=failed_records.xlsx").body(resource);
}
return ResponseEntity.ok().body(null);
}
private List<Map<String, Object>> processData(String entityName, List<Map<String, Object>> data) {
List<Map<String, Object>> processedData = new ArrayList<>();
try {
String convertedTableName = entityName;
String sql = getInsertQuery(convertedTableName, data.get(0));
for (int i = 0; i < data.size(); i++) {
Map<String, Object> row = data.get(i);
Map<String, Object> processedRow = new HashMap<>();
try {
Object[] values = new Object[row.size() + 5]; // +5 for the additional columns
int index = 0;
for (Object value : row.values()) {
values[index++] = value;
}
values[index++] = new Timestamp(System.currentTimeMillis()); // created_at
values[index++] = null; // created_by
values[index++] = null; // updated_by
values[index++] = new Timestamp(System.currentTimeMillis()); // updated_at
values[index] = null; // account_id
jdbcTemplate.update(sql, values);
processedRow.putAll(row);
processedRow.put("Status", "Success");
processedRow.put("Exception", "NA");
} catch (DataIntegrityViolationException e) {
processedRow.putAll(row);
processedRow.put("Status", "Error");
String exceptionMessage = extractExceptionMessage(e);
processedRow.put("Exception", exceptionMessage);
}
processedData.add(processedRow);
}
} catch (Exception e) {
// Handle any exceptions here if needed
}
return processedData;
}
private Workbook createWorkbook(List<Map<String, Object>> processedData) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Failed Records");
// Add column headers to the worksheet
Row headerRow = sheet.createRow(0);
int columnIndex = 0;
for (String key : processedData.get(0).keySet()) {
Cell cell = headerRow.createCell(columnIndex++);
cell.setCellValue(key);
}
// Add data rows to the worksheet
int rowIndex = 1;
for (Map<String, Object> row : processedData) {
Row dataRow = sheet.createRow(rowIndex++);
columnIndex = 0;
for (Object value : row.values()) {
Cell cell = dataRow.createCell(columnIndex++);
cell.setCellValue(value.toString());
}
}
return workbook;
}
private Resource createExcelResource(Workbook workbook) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return new InputStreamResource(inputStream);
}
// private ResponseEntity<?> getData(@PathVariable String type ){
// if(type.equalsIgnoreCase("Customer")) {
//
//
// String[] customerHeaders = { "balance", "c_status", "city", "country","currency_code","customer_id",
// "date_of_birth", "defaultsite_id", "email", "entity_name","file_name","file_path",
// "first_name", "gender", "gst_no", "gst_state","house_no","mobile_no",
// "pan_no", "sales_rep", "special_price", "state","street_address","street_address2",
// "time_zone", "postal_code", "contact_number"};
//
//
// }
//
// }
}

View File

@@ -0,0 +1,21 @@
package com.realnet.BulkUpload.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class BulkUpload_t{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String entity_name;
private String description;
private String rule_line;
private boolean active;
private String fileType;
}

View File

@@ -0,0 +1,24 @@
package com.realnet.BulkUpload.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class MappingRule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String entity_name;
private String description;
private String mapping_rule;
private boolean active;
private String fileType;
}

View File

@@ -0,0 +1,21 @@
package com.realnet.BulkUpload.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.BulkUpload.Entity.BulkUpload_t;
@Repository
public interface BulkUpload_Repository extends JpaRepository<BulkUpload_t, Long> {
@Query(value = "SELECT * FROM bulk_upload_t where entity_name =?1", nativeQuery = true)
BulkUpload_t getentityName(String name);
// @Query(value = "SELECT * FROM bulk_upload_t where entity_name =?1", nativeQuery = true)
// BulkUpload_t getByName(String name);
}

View File

@@ -0,0 +1,11 @@
package com.realnet.BulkUpload.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.BulkUpload.Entity.MappingRule;
@Repository
public interface MappingRuleRepository extends JpaRepository<MappingRule, Long>{
}

View File

@@ -0,0 +1,40 @@
package com.realnet.BulkUpload.Services;
import com.realnet.BulkUpload.Repository.BulkUpload_Repository;
import com.realnet.BulkUpload.Entity.BulkUpload_t;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BulkUpload_Service {
@Autowired
private BulkUpload_Repository Repository;
public BulkUpload_t Savedata(BulkUpload_t data) {
return Repository.save(data);
}
public List<BulkUpload_t> getdetails() {
return (List<BulkUpload_t>) Repository.findAll();
}
public BulkUpload_t getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public BulkUpload_t update(BulkUpload_t data, Long id) {
BulkUpload_t old = Repository.findById(id).get();
old.setEntity_name(data.getEntity_name());
old.setDescription(data.getDescription());
old.setRule_line(data.getRule_line());
old.setActive(data.isActive());
final BulkUpload_t test = Repository.save(old);
return test;
}
}

View File

@@ -0,0 +1,43 @@
package com.realnet.BulkUpload.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.BulkUpload.Entity.BulkUpload_t;
import com.realnet.BulkUpload.Entity.MappingRule;
import com.realnet.BulkUpload.Repository.MappingRuleRepository;
@Service
public class MappingRuleService {
@Autowired
private MappingRuleRepository Repository;
public MappingRule Savedata(MappingRule data) {
return Repository.save(data);
}
public List<MappingRule> getdetails() {
return (List<MappingRule>) Repository.findAll();
}
public MappingRule getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public MappingRule update(MappingRule data, Long id) {
MappingRule old = Repository.findById(id).get();
old.setEntity_name(data.getEntity_name());
old.setDescription(data.getDescription());
old.setMapping_rule(data.getMapping_rule());
old.setActive(data.isActive());
final MappingRule test = Repository.save(old);
return test;
}
}

View File

@@ -0,0 +1,40 @@
//package com.realnet.CredentialDatabase.Config;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.jdbc.datasource.DriverManagerDataSource;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.JsonMappingException;
//import com.realnet.CredentialDatabase.Service.SurevaultService;
//
//import java.util.Properties;
//
//import javax.sql.DataSource;
//
//@Configuration
//public class Databaseconfig {
//
// @Autowired
// private SurevaultService surevaultService;
//
// @Bean
// public DataSource dataSource() throws JsonMappingException {
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
//
// try {
// dataSource.setUrl(surevaultService.getSurevaultCredentials("databaseUrl"));
// dataSource.setUsername(surevaultService.getSurevaultCredentials("databaseuserName"));
// dataSource.setPassword(surevaultService.getSurevaultCredentials("databasePassword"));
//
// } catch (JsonProcessingException e) {
// // Handle exceptions or log errors
// e.printStackTrace();
// }
//
// // Other DataSource configurations
//
// return dataSource;
// }
//}

View File

@@ -0,0 +1,115 @@
package com.realnet.CredentialDatabase.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.realnet.utils.Port_Constant;
@Service
public class SurevaultService {
@Value("${spring.datasource.url}")
public String url;
@Value("${spring.datasource.username}")
public String username;
@Value("${spring.datasource.password}")
public String password;
public String getSurevaultCredentials(String key) throws JsonProcessingException {
// String SurevaultDeploymentType = Port_Constant.SUREVAULT_DEPLOYMENT_TYPE;
// System.out.println(SurevaultDeploymentType);
// // Obtain the token
// String token = callconnector("surevault").toString();
//
// String surevaultApiUrl =Port_Constant.SURE_VAULT_DOMAIN + "/getcredentials/" + SurevaultDeploymentType;
//
// ResponseEntity<Object> get = GET(surevaultApiUrl, token);
//
// Object responseBody = get.getBody();
//
// JsonNode jsonNode = new ObjectMapper().convertValue(responseBody, JsonNode.class);
// String value = jsonNode.get(key).asText();
String value = "";
switch (key) {
case "databaseUrl":
value = url;
break;
case "databaseuserName":
value = username;
break;
case "databasePassword":
value = password;
break;
default:
break;
}
return value;
}
public String callconnector(String name) throws JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
String url = Port_Constant.SURE_VAULT_DOMAIN + "/token/Sure_Connectbyname/" + name;
System.out.println(Port_Constant.SURE_VAULT_DOMAIN);
ResponseEntity<Object> u = restTemplate.getForEntity(url, Object.class);
Object object = u.getBody();
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(object);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(str);
JsonObject obj = element.getAsJsonObject();
JsonElement token = obj.get("access_token");
System.out.println("token is == " + token);
return token.getAsString();
}
public ResponseEntity<Object> GET(String get, String token) {
RestTemplate restTemplate = new RestTemplate();
String resourceUrl = get;
String token1 = "Bearer " + token;
HttpHeaders headers = getHeaders();
headers.set("Authorization", token1);
HttpEntity<Object> request = new HttpEntity<Object>(headers);
ResponseEntity<Object> u = restTemplate.exchange(resourceUrl, HttpMethod.GET, request, Object.class);
int statusCodeValue = u.getStatusCodeValue();
System.out.println(statusCodeValue);
return u;
}
private HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return headers;
}
}

View File

@@ -0,0 +1,30 @@
//package com.realnet.Dashboard1.Controller;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import com.realnet.Dashboard1.Entity.Dashbord_Header;
//import com.realnet.Dashboard1.Repository.HeaderRepository;
//import com.realnet.Dashboard1.Service.HeaderService;
//
//@RestController
//@RequestMapping("/token/dashboard2")
//public class Dashboard2 {
//
// @Autowired
// private HeaderService headerService;
//
// @Autowired
// private HeaderRepository headerRepository;
//
// @GetMapping("/getdashboardbyname/{name}")
// public Integer getdetailsbyId(@PathVariable String name) {
// Dashbord_Header dash = headerRepository.findByDashboardName(name);
// Integer id=dash.getId();
// return id;
// }
//
//}

View File

@@ -0,0 +1,110 @@
package com.realnet.Dashboard1.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.Dashboard1.Entity.Dashbord1_Line;
import com.realnet.Dashboard1.Entity.Dashbord_Header;
import com.realnet.Dashboard1.Repository.HeaderRepository;
import com.realnet.Dashboard1.Service.HeaderService;
@RestController
public class Dashbord1Controller {
@Autowired
private HeaderService headerService;
@Autowired
private HeaderRepository headerRepository;
// @PreAuthorize("hasAnyRole('SYSADMIN','ProjectManager','Developer')")
@PostMapping("/Savedata")
public Dashbord_Header Savedata(@RequestBody Dashbord_Header dashbord_Header) {
Dashbord_Header dash = headerService.Savedata(dashbord_Header);
return dash;
}
@GetMapping("/get_Dashboard_header")
public List<Dashbord_Header> getdetails() {
List<Dashbord_Header> dash = headerService.getdetails();
return dash;
}
@GetMapping("/get_all_lines")
public List<Dashbord1_Line> get_all_lines() {
List<Dashbord1_Line> dash = headerService.get_all_lines();
return dash;
}
@GetMapping("/get_module_id")
public List<Dashbord_Header> get_by_module_id(@RequestParam(value = "module_id") int module_id) {
List<Dashbord_Header> module = headerService.get_by_module_id(module_id);
return module;
}
@GetMapping("/get_dashboard_headerbyid/{id}")
public Dashbord_Header getdetailsbyId(@PathVariable int id) {
Dashbord_Header dash = headerService.getdetailsbyId(id);
return dash;
}
// @PreAuthorize("hasAnyRole('SYSADMIN','ProjectManager','Developer')")
@PutMapping("/update_dashboard_header")
public Dashbord_Header update_dashboard_header(@RequestBody Dashbord_Header dashbord_Header) {
Dashbord_Header dash = headerService.update_dashboard_header(dashbord_Header);
return dash;
}
// update dashboard line by id
@PutMapping("/update_Dashbord1_Lineby_id/{id}")
public Dashbord1_Line update_Dashbord1_Lineby_id(@PathVariable int id, @RequestBody Dashbord1_Line dashbord1_Line) {
Dashbord1_Line dash = headerService.update_Dashbord1_Lineby_id(id, dashbord1_Line);
return dash;
}
@PostMapping("/update_Dashbord1_Line")
public Dashbord1_Line update_Dashbord1_Line(@RequestBody Dashbord1_Line dashbord1_Line) {
Dashbord1_Line dash1 = headerService.update_Dashbord1_Line(dashbord1_Line);
return dash1;
}
// @PreAuthorize("hasAnyRole('SYSADMIN','ProjectManager','Developer')")
@DeleteMapping("/delete_by_header_id/{id}")
public void delete_by_id(@PathVariable int id) {
headerService.delete_by_id(id);
}
// COUNT OF LIST BUILDER
@GetMapping("/get_dashboard/{module_id}")
public ResponseEntity<?> getREPORT(@PathVariable Integer module_id) {
String count_wireframe = headerRepository.count_dashboardheader(module_id);
if (count_wireframe.isEmpty()) {
return new ResponseEntity<>(0, HttpStatus.OK);
} else {
return new ResponseEntity<>(count_wireframe, HttpStatus.OK);
}
}
}

View File

@@ -0,0 +1,45 @@
package com.realnet.Dashboard1.Entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import lombok.ToString;
@ToString(exclude = { "Dashbord_Header" })
@Data
@Entity
@Table
public class Dashbord1_Line extends dashbord_Who_collumn {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String header_id;
@Column(length = 5000)
private String Model;
@JsonBackReference
@ManyToOne
private Dashbord_Header dashbord_Header;
}

View File

@@ -0,0 +1,63 @@
package com.realnet.Dashboard1.Entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import lombok.ToString;
@ToString(exclude = { "Dashbord1_Line" })
@Entity
@Data
public class Dashbord_Header extends dashbord_Who_collumn {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Integer id;
// ==============================
@Column(name = "MENU_NAME")
private String menuName;
@Column(name = "IS_UPDATED")
private boolean updated;
private String tech_Stack;
private String object_type;
private String sub_object_type;
@Column(name = "IS_BUILD")
private boolean build;
private boolean testing;
private String dashboard_name;
private int module_id;
private String description;
private String secuirity_profile;
private Boolean add_to_home;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "dashbord_Header")
private List<Dashbord1_Line> dashbord1_Line = new ArrayList<>();
}

View File

@@ -0,0 +1,46 @@
package com.realnet.Dashboard1.Entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.Data;
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class dashbord_Who_collumn implements Serializable{
private static final long serialVersionUID = 1L;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED_AT", nullable = false, updatable = false)
@CreatedDate
private Date createdAt;
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createdAt;
@Column(name = "CREATED_BY", updatable = false)
private Long createdBy;
@Column(name = "UPDATED_BY")
private Long updatedBy;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "UPDATED_AT", nullable = false)
@LastModifiedDate
private Date updatedAt;
@Column(name = "ACCOUNT_ID")
private Long accountId;
}

View File

@@ -0,0 +1,20 @@
package com.realnet.Dashboard1.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.realnet.Dashboard1.Entity.Dashbord1_Line;
@Repository
public interface Dashboard_lineRepository extends CrudRepository<Dashbord1_Line, Integer> {
Dashbord1_Line findById(int id);
@Query(value = "SELECT * FROM realnet_CNSBE.dashbord1_line where dashbord_header_id =:id", nativeQuery = true)
List<Dashbord1_Line> getByheader(@Param("id") int id);
}

View File

@@ -0,0 +1,35 @@
package com.realnet.Dashboard1.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.realnet.Dashboard1.Entity.Dashbord_Header;
@Repository
public interface HeaderRepository extends CrudRepository<Dashbord_Header, Integer> {
Dashbord_Header findById(int id);
// @Query(
// value= " select * from dashboard_header where module_id=?1",nativeQuery=true)
// List<Dashbord_Header> findbydashboardmodule(int moduleId);
// public List<Dashbord_Header> findBymodule_id(String module_id);
@Query(value = " select * from dashbord_header where module_id=?1", nativeQuery = true)
List<Dashbord_Header> findbydashboardmodule(int module_id);
// @Query(
// "select u from Dashbord_Header u WHERE u.module_id =:n")
// List<Dashbord_Header> getBymoduleId(int module_id);
@Query(value = "select count(id) from dashbord_header", nativeQuery = true)
public List<Object> findCount();
@Query(value = "SELECT count(id) FROM realnet_CNSBE.dashbord_header where module_id=?1", nativeQuery = true)
String count_dashboardheader(Integer moduleId);
}

View File

@@ -0,0 +1,99 @@
package com.realnet.Dashboard1.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.Dashboard1.Entity.Dashbord1_Line;
import com.realnet.Dashboard1.Entity.Dashbord_Header;
import com.realnet.Dashboard1.Repository.Dashboard_lineRepository;
import com.realnet.Dashboard1.Repository.HeaderRepository;
@Service
public class HeaderService {
@Autowired
private HeaderRepository headerRepository;
@Autowired
private Dashboard_lineRepository dashboard_lineRepository;
public Dashbord_Header Savedata(Dashbord_Header dashbord_Header) {
return headerRepository.save(dashbord_Header);
}
public List<Dashbord_Header> getdetails() {
// TODO Auto-generated method stub
return (List<Dashbord_Header>) headerRepository.findAll();
}
public Dashbord_Header getdetailsbyId(int id) {
// TODO Auto-generated method stub
return headerRepository.findById(id);
}
public void delete_by_id(int id) {
// TODO Auto-generated method stub
headerRepository.deleteById(id);
}
public Dashbord_Header update_dashboard_header(Dashbord_Header dashbord_Header) {
return headerRepository.save(dashbord_Header);
}
public Dashbord1_Line update_Dashbord1_Line(Dashbord1_Line dashbord1_Line) {
// TODO Auto-generated method stub
return dashboard_lineRepository.save(dashbord1_Line);
}
public List<Dashbord_Header> get_by_module_id(int module_id) {
// TODO Auto-generated method stub
return (List<Dashbord_Header>) headerRepository.findbydashboardmodule(module_id);
}
public List<Dashbord1_Line> get_all_lines() {
// TODO Auto-generated method stub
return (List<Dashbord1_Line>) dashboard_lineRepository.findAll();
}
// public List<Dashbord_Header> get_by_module_id(int module_id) {
// // TODO Auto-generated method stub
// return (List<Dashbord_Header>) headerRepository.findAllById(module_id);
// }
// public List<Dashbord_Header> get_by_module_id(String module_id) {
// // TODO Auto-generated method stub
// return (List<Dashbord_Header>) headerRepository.findBymodule_id(module_id);
// }
public Dashbord1_Line update_Dashbord1_Lineby_id(int id, Dashbord1_Line dashbord1_Line) {
Dashbord1_Line oldline= dashboard_lineRepository.findById(id);
// .orElseThrow(() -> new ResourceNotFoundException(Constant.NOT_FOUND_EXCEPTION + " :" + id));
oldline.setAccountId(dashbord1_Line.getAccountId());
oldline.setHeader_id(dashbord1_Line.getHeader_id());
oldline.setModel(dashbord1_Line.getModel());
final Dashbord1_Line newline= dashboard_lineRepository.save(oldline);
return newline;
}
}

View File

@@ -0,0 +1,689 @@
package com.realnet.Dashboard_builder.Controllers;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.realnet.Payment.Paytm.PaytmPayment;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequestMapping("/chart")
@RestController
public class ChartBuilder {
public List<Map<String, Object>> getAllDataFromTable(String tableName) {
List<Map<String, Object>> tableData = new ArrayList<>();
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Establish a database connection
connection = DriverManager.getConnection(
"jdbc:mysql://realnet.cdtynkxfiu2h.ap-south-1.rds.amazonaws.com:3306/suresetu", "cnsdev",
"cnsdev1234");
// Create a SQL statement
statement = connection.createStatement();
// Execute the query to retrieve all data from the table
String query = "SELECT * FROM " + tableName;
resultSet = statement.executeQuery(query);
// Retrieve the column names from the result set
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
List<String> columnNames = new ArrayList<>();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(metaData.getColumnName(i));
}
// Iterate over the result set and store each row in a map
while (resultSet.next()) {
Map<String, Object> rowData = new HashMap<>();
for (String columnName : columnNames) {
Object value = resultSet.getObject(columnName);
rowData.put(columnName, value);
}
tableData.add(rowData);
}
} catch (SQLException e) {
log.error(e.getLocalizedMessage());
} finally {
// Close the resources
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error(e.getLocalizedMessage());
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
log.error(e.getLocalizedMessage());
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e.getLocalizedMessage());
}
}
}
return tableData;
}
//...........................22.07.2023.............................//
// @GetMapping(value = "/getdashjson/{job_type}")
// public ResponseEntity<?> jsonretun(@RequestParam String tableName, @PathVariable String job_type,
// @RequestParam String xAxis, @RequestParam String yAxis) throws IOException {
//
// List<Map<String, Object>> tableData = getAllDataFromTable(tableName); // Retrieve all data from the table
//
// List<Object> yAxisValues = new ArrayList<>();
// List<String> xAxisValues = new ArrayList<>();
//
// for (Map<String, Object> row : tableData) {
// for (Entry<String, Object> entry : row.entrySet()) {
// String key = entry.getKey();
// Object value = entry.getValue();
//
// if (key.equalsIgnoreCase(xAxis)) {
// xAxisValues.add(value.toString());
// } else if (key.equalsIgnoreCase(yAxis)) {
// yAxisValues.add(value);
// }
// }
// }
//
// StringBuilder jsonmap = new StringBuilder();
//
// if (job_type.equalsIgnoreCase("Bar Chart")) {
// jsonmap.append("[\n");
// } else if (job_type.equalsIgnoreCase("Line Chart")) {
// jsonmap.append(" {\r\n" + " \"chartData\": [\r\n" + " { \"data\": [");
// } else if (job_type.equalsIgnoreCase("Doughnut Chart")) {
// jsonmap.append("{\"chartData\": [[");
// }
//
// for (int i = 0; i < xAxisValues.size(); i++) {
// String xValue = xAxisValues.get(i);
// Object yValue = yAxisValues.get(i);
//
// if (job_type.equalsIgnoreCase("Bar Chart")) {
// jsonmap.append("{\"name\": \"" + xValue + "\", \"progress\":\"" + yValue + "\"},\n");
// } else if (job_type.equalsIgnoreCase("Line Chart")) {
// jsonmap.append(yValue + ",");
// } else if (job_type.equalsIgnoreCase("Doughnut Chart")) {
// jsonmap.append(yValue + ",");
// }
// }
//
// if (!xAxisValues.isEmpty() && !yAxisValues.isEmpty()) {
// jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
// }
//
// if (job_type.equalsIgnoreCase("Bar Chart")) {
// jsonmap.append("]");
// } else if (job_type.equalsIgnoreCase("Line Chart")) {
// jsonmap.append("], \"label\": \"" + yAxis + "\" }\r\n" + " ],\r\n" + " \"chartLabels\": [ ");
// } else if (job_type.equalsIgnoreCase("Doughnut Chart")) {
// jsonmap.append("]],\r\n" + " \"chartLabels\": [");
// }
//
// for (String xValue : xAxisValues) {
// jsonmap.append("\"" + xValue + "\",");
// }
//
// if (!xAxisValues.isEmpty()) {
// jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
// }
//
// if (job_type.equalsIgnoreCase("Line Chart")) {
// jsonmap.append("] \n }\n");
// } else if (job_type.equalsIgnoreCase("Doughnut Chart")) {
// jsonmap.append("]\n" + "}");
// }
//
// return new ResponseEntity<>(jsonmap.toString(), HttpStatus.CREATED);
// }
@GetMapping(value = "/getdashjson/{job_type}")
public ResponseEntity<?> jsonretun2(@RequestParam String tableName, @PathVariable String job_type,
@RequestParam(required = false) String xAxis, @RequestParam(required = false) List<String> yAxes)
throws IOException {
StringBuilder jsonmap = new StringBuilder();
if (job_type.equalsIgnoreCase("Grid View")) {
List<Map<String, Object>> allData = getAllDataFromApi(tableName);
jsonmap.append("[\n");
for (Map<String, Object> row : allData) {
jsonmap.append("{\n");
int colCount = 0;
for (String yAxis : yAxes) {
String key = yAxis;
Object value = row.get(key);
jsonmap.append("\"" + key + "\": \"" + value + "\"");
colCount++;
if (colCount < yAxes.size()) {
jsonmap.append(", ");
}
jsonmap.append("\n");
}
jsonmap.append("}");
if (!row.equals(allData.get(allData.size() - 1))) {
jsonmap.append(", ");
}
}
jsonmap.append("\n]\n");
return new ResponseEntity<>(jsonmap.toString(), HttpStatus.CREATED);
}
if (job_type.equalsIgnoreCase("Todo List") && yAxes != null && !yAxes.isEmpty()) {
List<Map<String, Object>> allData = getAllDataFromApi(tableName);
String listName = yAxes.get(0); // Assuming the first column in yAxes to be the list name
List<Object> listData = new ArrayList<>();
for (Map<String, Object> row : allData) {
Object value = row.get(listName);
if (value != null) {
listData.add(value);
}
}
Map<String, Object> response = new HashMap<>();
response.put("listName", listName);
response.put("List", listData);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
List<Map<String, Object>> tableData = getAllDataFromApi(tableName); // Retrieve all data from the table
List<List<Object>> yAxisValuesList = new ArrayList<>();
List<String> xAxisValues = new ArrayList<>();
// Initialize a list for each y-axis parameter
for (int i = 0; i < yAxes.size(); i++) {
yAxisValuesList.add(new ArrayList<>());
}
for (Map<String, Object> row : tableData) {
for (Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.equalsIgnoreCase(xAxis)) {
xAxisValues.add(value.toString());
} else {
int yIndex = yAxes.indexOf(key);
if (yIndex >= 0) {
yAxisValuesList.get(yIndex).add(value);
}
}
}
}
if (job_type.equalsIgnoreCase("Bar Chart")) {
jsonmap.append("{\n \"barChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"barChartLabels\": [ ");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
}
else if (job_type.equalsIgnoreCase("Line Chart")) {
jsonmap.append("{\n \"chartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"chartLabels\": [ ");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
} else if (job_type.equalsIgnoreCase("Doughnut Chart")) {
jsonmap.append("{\"chartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("[");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("]");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"chartLabels\": [");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("]\n}");
}
else if (job_type.equalsIgnoreCase("Radar Chart")) {
jsonmap.append("{\n \"radarChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"radarChartLabels\": [ ");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
}
else if (job_type.equalsIgnoreCase("PolarArea Chart")) {
jsonmap.append("{\n \"polarAreaChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"polarAreaChartLabels\": [ ");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
}
if (job_type.equalsIgnoreCase("Pie Chart")) {
jsonmap.append("{\n \"pieChartData\": [");
for (int i = 0; i < yAxisValuesList.get(0).size(); i++) { // Assuming "mark" is the first item in yAxes
jsonmap.append(yAxisValuesList.get(0).get(i)); // Use the y-axis values
if (i < yAxisValuesList.get(0).size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"pieChartLabels\": [ ");
for (int i = 0; i < xAxisValues.size(); i++) { // Assuming "name" is the x-axis
jsonmap.append("\"" + xAxisValues.get(i) + "\""); // Use the x-axis values
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("] \n }\n");
}
else if (job_type.equalsIgnoreCase("Bubble Chart")) {
jsonmap.append("{\n \"bubbleChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object xValue = xAxisValues.get(i);
Object yValue = yAxisValuesList.get(j).get(i);
int radius = 5 + (i % 3) * 3; // Adjust the radius as needed
jsonmap.append("{ \"x\": " + xValue + ", \"y\": " + yValue + ", \"r\": " + radius + "}");
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"bubbleChartLabels\": [ ");
for (String label : xAxisValues) {
jsonmap.append("\"" + label + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
} else if (job_type.equalsIgnoreCase("Scatter Chart")) {
jsonmap.append("{\n \"scatterChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object xValue = xAxisValues.get(i);
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append("{ \"x\": " + xValue + ", \"y\": " + yValue + "}");
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"scatterChartLabels\": [ ");
for (String label : xAxisValues) {
jsonmap.append("\"" + label + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
}
else if (job_type.equalsIgnoreCase("Dynamic Chart")) {
jsonmap.append("{\n \"dynamicChartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
for (int i = 0; i < xAxisValues.size(); i++) {
Object yValue = yAxisValuesList.get(j).get(i);
jsonmap.append(yValue);
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
jsonmap.append("],\n \"dynamicChartLabels\": [ ");
for (String xValue : xAxisValues) {
jsonmap.append("\"" + xValue + "\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("] \n }\n");
}
return new ResponseEntity<>(jsonmap.toString(), HttpStatus.CREATED);
}
// @GetMapping("/getKey")
public List<Map<String, Object>> getAllKeyFromApi(String apiUrl) {
List<Map<String, Object>> apiData = new ArrayList<>();
try {
// Make a GET request using the provided URL
ResponseEntity<Object> responseEntity = GET(apiUrl);
// Convert the response to a List<Map<String, Object>>
if (responseEntity.getBody() instanceof List) {
// If the response is a list, assume it's a list of maps
apiData = (List<Map<String, Object>>) responseEntity.getBody();
} else {
// If the response is not a list, assume it's a single map
Map<String, Object> singleMap = new HashMap<>();
singleMap.put("data", responseEntity.getBody());
apiData.add(singleMap);
}
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
return apiData;
}
@GetMapping("/getAllKeys")
public Set<String> getAllKeys(@RequestParam String apiUrl) {
List<Map<String, Object>> apiData = getAllKeyFromApi(apiUrl);
return getAllKeys(apiData);
}
private Set<String> getAllKeys(List<Map<String, Object>> apiData) {
Set<String> allKeys = new HashSet<>();
for (Map<String, Object> data : apiData) {
allKeys.addAll(data.keySet());
}
return allKeys;
}
public List<Map<String, Object>> getAllDataFromApi(String apiUrl) {
List<Map<String, Object>> apiData = new ArrayList<>();
try {
// Make a GET request using the provided URL
ResponseEntity<Object> responseEntity = GET(apiUrl);
// Convert the response to a List<Map<String, Object>>
if (responseEntity.getBody() instanceof List) {
// If the response is a list, assume it's a list of maps
apiData = (List<Map<String, Object>>) responseEntity.getBody();
} else {
// If the response is not a list, assume it's a single map
Map<String, Object> singleMap = new HashMap<>();
singleMap.put("data", responseEntity.getBody());
apiData.add(singleMap);
}
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
return apiData;
}
public ResponseEntity<Object> GET(String get) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
return u;
}
}

View File

@@ -0,0 +1,47 @@
package com.realnet.Dashboard_builder.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.Dashboard_builder.Entity.DashboardSchedule_t;
import com.realnet.Dashboard_builder.Services.DashboardSchedule_Service;
@RequestMapping(value = "/DashboardSchedule")
@RestController
public class DashboardSchedule_Controller {
@Autowired
private DashboardSchedule_Service Service;
@PostMapping("/DashboardSchedule")
public DashboardSchedule_t Savedata(@RequestBody DashboardSchedule_t data) {
DashboardSchedule_t save = Service.Savedata(data);
return save;
}
@GetMapping("/DashboardSchedule")
public List<DashboardSchedule_t> getdetails() {
List<DashboardSchedule_t> get = Service.getdetails();
return get;
}
@GetMapping("/DashboardSchedule/{id}")
public DashboardSchedule_t getdetailsbyId(@PathVariable Long id) {
DashboardSchedule_t get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/DashboardSchedule/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/DashboardSchedule/{id}")
public DashboardSchedule_t update(@RequestBody DashboardSchedule_t data, @PathVariable Long id) {
DashboardSchedule_t update = Service.update(data, id);
return update;
}
}

View File

@@ -0,0 +1,55 @@
package com.realnet.Dashboard_builder.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.Dashboard_builder.Entity.Dashboard_builder_t;
import com.realnet.Dashboard_builder.Repository.Dashboard_builder_Repository;
import com.realnet.Dashboard_builder.Services.Dashboard_builder_Service;
@RequestMapping(value = "/Dashboard_builder")
@RestController
public class Dashboard_builder_Controller {
@Autowired
private Dashboard_builder_Service Service;
@Autowired
private Dashboard_builder_Repository builder_Repository;
@PostMapping("/Dashboard_builder")
public Dashboard_builder_t Savedata(@RequestBody Dashboard_builder_t data) {
Dashboard_builder_t save = Service.Savedata(data);
return save;
}
@GetMapping("/Dashboard_builder")
public List<Dashboard_builder_t> getdetails() {
List<Dashboard_builder_t> get = Service.getdetails();
return get;
}
@GetMapping("/Dashboard_builder/{id}")
public Dashboard_builder_t getdetailsbyId(@PathVariable Long id) {
Dashboard_builder_t get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Dashboard_builder/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/Dashboard_builder/{id}")
public Dashboard_builder_t update(@RequestBody Dashboard_builder_t data, @PathVariable Long id) {
Dashboard_builder_t update = Service.update(data, id);
return update;
}
}

View File

@@ -0,0 +1,385 @@
//package com.realnet.Dashboard_builder.Controllers;
//
//import java.io.File;
//import java.io.IOException;
//import java.nio.file.FileSystems;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.time.Instant;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Optional;
//import java.util.stream.Collectors;
//
//import org.apache.commons.io.FilenameUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestPart;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.multipart.MultipartFile;
//
//import com.realnet.Communication.Models.Com_jobTable;
//import com.realnet.Communication.Models.Com_template;
//import com.realnet.Communication.Models.ProcessedJobTable;
//import com.realnet.Communication.Repos.JobTablerepo;
//import com.realnet.Communication.Repos.ProcessedJobTableRepo;
//import com.realnet.Communication.Repos.TemplateRepo;
//import com.realnet.Communication.Services.EmailCommunicationService;
//import com.realnet.Communication.response.EntityResponse;
//import com.realnet.Dashboard_builder.Entity.DashboardSchedule_t;
//import com.realnet.Dashboard_builder.Repository.DashboardSchedule_Repository;
//import com.realnet.Gateway.Entity.Gateway_t;
//import com.realnet.Gateway.Repository.Gateway_Repository;
//import com.realnet.Gateway.Services.Gateway_Service;
//import com.realnet.Gateway.Services.SmsGatwaySmsServices;
//
//@RestController
//@RequestMapping("/dashboard/schedule")
//public class EmailGenerate {
//
//
//
// @Autowired
// private SmsGatwaySmsServices gatwaySmsServices;
//
//
//
//
//
// @Autowired
// private JobTablerepo Com_jobTablerepo;
//
// @Autowired
// private TemplateRepo templateRepo;
//
// @Autowired
// private ProcessedJobTableRepo jobTableRepo;
//
// @Autowired
// private EmailCommunicationService emailService;
//
// @Autowired
// private Gateway_Repository gateway_Repository;
//
//
//// public final String UPLOAD_DIREC = "/src/main/resources/images";
//
//
// @GetMapping("/sendgatewaydashboard")
// public ResponseEntity<?> sendGateway() {
// List<Com_jobTable> get = Com_jobTablerepo.findTopByOrderByIdAsc();
//
// if (!get.isEmpty()) {
// for (Com_jobTable com_jobTable : get) {
// String jobType = com_jobTable.getJob_type();
// if (jobType.equalsIgnoreCase("EMAIL")) {
// ResponseEntity<?> response = sendMailGateway(com_jobTable);
// if (response.getStatusCode() != HttpStatus.OK) {
// return response;
// }
// }
//// else if (jobType.equalsIgnoreCase("SMS")) {
//// ResponseEntity<?> response = sendSmsGateway(com_jobTable);
//// if (response.getStatusCode() != HttpStatus.OK) {
//// return response;
//// }
//// }
// else {
// return new ResponseEntity<>(new EntityResponse("Incorrect job type"), HttpStatus.BAD_REQUEST);
// }
// }
// return new ResponseEntity<>(get, HttpStatus.OK);
// } else {
// return new ResponseEntity<>(new EntityResponse("All SMS/Emails already sent"), HttpStatus.OK);
// }
// }
//
// private ResponseEntity<?> sendMailGateway(Com_jobTable com_jobTable) {
// String gatewayName = com_jobTable.getGatewayName();
// // Long id = Long.parseLong(gatewayName);
// Gateway_t getData=gateway_Repository.findByGatewayName(gatewayName);
//
// Long id=getData.getId();
//
//
// String tempName = com_jobTable.getTemplate_name();
// // Long tempid = Long.parseLong(tempName);
//
// Com_template template = templateRepo.findBytemplatename(tempName);
//
// if (template == null) {
// return new ResponseEntity<>(new EntityResponse("Template not found"), HttpStatus.NOT_FOUND);
// }
//
// String replacement_string = com_jobTable.getReplacement_string();
// String replace_body = template.getBody().replace("<replacement_string>", replacement_string);
//
//
//
// ProcessedJobTable gatewayJobTable = new ProcessedJobTable();
// gatewayJobTable.setJob_type(com_jobTable.getJob_type());
// gatewayJobTable.setSend_to(com_jobTable.getSend_to());
// gatewayJobTable.setCc(com_jobTable.getCc());
// gatewayJobTable.setAttachment(com_jobTable.getAttachment());
// gatewayJobTable.setGatewaydone(com_jobTable.getGatewaydone());
// gatewayJobTable.setTemplate_name(com_jobTable.getTemplate_name());
// gatewayJobTable.setReplacement_string(com_jobTable.getReplacement_string());
// gatewayJobTable.setGatewayName(com_jobTable.getGatewayName());
//
//
// String filename = com_jobTable.getAttachment();
// if(filename!=null) {
//
// Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
// String filepath = Paths.get(path.toString(), UPLOAD_DIREC, filename).toString();
// File file = new File(filepath);
//
//
// boolean sendMailWithAttachment = emailService.sendEmailGatewayWithAttachment(id, com_jobTable.getSend_to(), template.getSubject(), replace_body, com_jobTable.getCc(), file);
//
// System.out.println("email sent with attachment " + sendMailWithAttachment);
//
// gatewayJobTable.setStatus(HttpStatus.OK.value());
// gatewayJobTable.setResp_body("Email sent with attachment");
//
// }
//
// else {
//
// boolean sendemail = emailService.sendEmailGateway(id, com_jobTable.getSend_to(), template.getSubject(),
// replace_body, com_jobTable.getCc());
// System.out.println("email without attachment sent " + sendemail);
//
// gatewayJobTable.setStatus(HttpStatus.OK.value());
// gatewayJobTable.setResp_body("Email sent without attachment");
//
//
// }
//
//
//
// jobTableRepo.save(gatewayJobTable);
// Com_jobTablerepo.delete(com_jobTable);
// return new ResponseEntity<>(HttpStatus.OK);
// }
//
//
//
//
//
//
//
//
//
//
//// public final String UPLOAD_DIREC = "/src/main/resources/images";
//
// public final String UPLOAD_DIREC = "C:/Users/Gyanadipta Pahi/Desktop/SureSetuLast/suresetu-mohasin205/backend/src/main/resources/images";
//
// @PostMapping("/upload")
// public ResponseEntity<String> uploadFile(@RequestPart("file") MultipartFile file) {
// if (file.isEmpty()) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is required.");
// }
//
// try {
// String fileName = generateFileName(file.getOriginalFilename());
// String filePath = UPLOAD_DIREC + File.separator + fileName;
// File dest = new File(filePath);
// file.transferTo(dest);
//
// return ResponseEntity.ok("File uploaded successfully.");
// } catch (IOException e) {
// e.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file.");
// }
// }
//
// private String generateFileName(String originalFilename) {
// String baseName = "dashboardSchedule" + Instant.now().getEpochSecond();
// String extension = FilenameUtils.getExtension(originalFilename);
// if (!StringUtils.isEmpty(extension)) {
// baseName += "." + extension;
// }
// return baseName;
// }
//
//
//
//
//
//
//
//
//
//
//
//
//// @GetMapping("/files/{partialName}")
//// public ResponseEntity<byte[]> getFileByName(@PathVariable("partialName") String partialName) {
//// List<File> matchingFiles = findMatchingFiles(partialName);
////
//// if (matchingFiles.isEmpty()) {
//// return ResponseEntity.notFound().build();
//// } else if (matchingFiles.size() > 1) {
//// // return ResponseEntity.status(HttpStatus.CONFLICT).body("Multiple files match the provided name.");
//// }
////
//// File file = matchingFiles.get(0);
//// try {
//// byte[] fileBytes = Files.readAllBytes(file.toPath());
////
//// HttpHeaders headers = new HttpHeaders();
//// headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//// headers.setContentDispositionFormData("attachment", file.getName());
//// headers.setContentLength(fileBytes.length);
////
//// return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
//// } catch (Exception e) {
//// e.printStackTrace();
//// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
//// }
//// }
////
//// private List<File> findMatchingFiles(String partialName) {
//// List<File> matchingFiles = new ArrayList<>();
////
//// File directory = new File(UPLOAD_DIREC);
//// File[] files = directory.listFiles();
//// if (files != null) {
//// for (File file : files) {
//// if (file.isFile() && file.getName().startsWith(partialName)) {
//// matchingFiles.add(file);
//// }
//// }
//// }
////
//// return matchingFiles;
//// }
//
//// @Autowired
//// private JobTablerepo comJobTableRepository;
//
// @Autowired
// private DashboardSchedule_Repository dashboardSchedule_Repository;
//
// @GetMapping("/files/{partialName}")
// public ResponseEntity<byte[]> getFileByName(@PathVariable("partialName") String partialName) {
// List<File> matchingFiles = findMatchingFiles(partialName);
//
// if (matchingFiles.isEmpty()) {
// return ResponseEntity.notFound().build();
// } else if (matchingFiles.size() > 1) {
// System.out.println("Multiple files match the provided name");
// // return ResponseEntity.status(HttpStatus.CONFLICT).body("Multiple files match the provided name.");
// }
//
// File file = matchingFiles.get(0);
// try {
// byte[] fileBytes = Files.readAllBytes(file.toPath());
//
// // Save file path as attachment in the entity
//// List<DashboardSchedule_t> get = dashboardSchedule_Repository.findTopByOrderByIdAsc();
//// get.setAttachment(file.getAbsolutePath());
//// dashboardSchedule_Repository.save(comJobTable);
//
// // // Replace with the desired DashboardSchedule_t entity ID
// List<DashboardSchedule_t> dashboardSchedules = dashboardSchedule_Repository.findTopByOrderByIdAsc();
// if (!dashboardSchedules.isEmpty()) {
// DashboardSchedule_t dashboardSchedule = dashboardSchedules.get(0);
// dashboardSchedule.setAttachment(file.getAbsolutePath());
// dashboardSchedule.setGatewaydone("N");
// dashboardSchedule_Repository.save(dashboardSchedule);
// } else {
// System.out.println("No dashboard schedules found.");
// }
//
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// headers.setContentDispositionFormData("attachment", file.getName());
// headers.setContentLength(fileBytes.length);
//
// return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
// }
// }
//
// private List<File> findMatchingFiles(String partialName) {
// List<File> matchingFiles = new ArrayList<>();
//
// File directory = new File(UPLOAD_DIREC);
// File[] files = directory.listFiles();
// if (files != null) {
// for (File file : files) {
// if (file.isFile() && file.getName().startsWith(partialName)) {
// matchingFiles.add(file);
// }
// }
// }
//
// return matchingFiles;
// }
//
//
//
//
//
//
//
//
// @GetMapping("/dashboardscheduleid")
// public List<Com_jobTable> getDashboardScheduleId() {
// List<DashboardSchedule_t> dashboardScheduleOptional = dashboardSchedule_Repository.findTopByOrderByIdAsc();
//
// List<DashboardSchedule_t> filteredList = dashboardScheduleOptional.stream()
// .filter(dashboardSchedule -> dashboardSchedule.getAttachment() != null && !dashboardSchedule.getAttachment().isEmpty())
// .collect(Collectors.toList());
//
// List<Com_jobTable> comJobTables = new ArrayList<>();
// for (DashboardSchedule_t dashboardSchedule : filteredList) {
// Com_jobTable comJobTable = new Com_jobTable();
// comJobTable.setAttachment(dashboardSchedule.getAttachment());
// comJobTable.setGatewaydone(dashboardSchedule.getGatewaydone());
// comJobTable.setSend_to(dashboardSchedule.getSendTo());
// comJobTable.setTemplate_name(dashboardSchedule.getTemplate());
// comJobTable.setGatewayName(dashboardSchedule.getGateway());
// comJobTable.setCc(dashboardSchedule.getCc());
// comJobTable.setReplacement_string(dashboardSchedule.getReplacementString());
// comJobTable.setJob_type(dashboardSchedule.getType());
//
//
// comJobTables.add(comJobTable);
// }
//
// List<Com_jobTable> savedComJobTables = Com_jobTablerepo.saveAll(comJobTables);
//
//
// for (DashboardSchedule_t dashboardSchedule : filteredList) {
// dashboardSchedule.setAttachment(null);
// dashboardSchedule.setGatewaydone("Y");
// }
// dashboardSchedule_Repository.saveAll(filteredList);
//
// return savedComJobTables;
// }
//
//
//
//
//
//
//
//
//
//}

View File

@@ -0,0 +1,31 @@
//package com.realnet.Dashboard_builder.Controllers;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//@RestController
//@RequestMapping("/pdf")
//public class PdfController {
//
// private final PdfService pdfService;
//
// @Autowired
// public PdfController(PdfService pdfService) {
// this.pdfService = pdfService;
// }
//
// @GetMapping("/generate/{dashboardName}")
// public ResponseEntity<String> generatePdf(@PathVariable String dashboardName) {
// try {
// pdfService.generatePdf(dashboardName);
// return new ResponseEntity<>("PDF generated successfully!", HttpStatus.OK);
// } catch (Exception e) {
// return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
// }
// }
//}

View File

@@ -0,0 +1,284 @@
//package com.realnet.Dashboard_builder.Controllers;
//
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.time.Instant;
//
//import org.apache.commons.io.FileUtils;
//import org.apache.pdfbox.pdmodel.PDDocument;
//import org.apache.pdfbox.pdmodel.PDPage;
//import org.apache.pdfbox.pdmodel.PDPageContentStream;
//import org.apache.pdfbox.pdmodel.font.PDType1Font;
//import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
//import org.openqa.selenium.By;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
//import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.chrome.ChromeOptions;
//import org.openqa.selenium.remote.DesiredCapabilities;
//import org.openqa.selenium.remote.RemoteWebDriver;
//import org.openqa.selenium.support.ui.ExpectedConditions;
//import org.openqa.selenium.support.ui.WebDriverWait;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import com.itextpdf.text.Document;
//import com.itextpdf.text.DocumentException;
//import com.itextpdf.text.Image;
//import com.itextpdf.text.Rectangle;
//import com.itextpdf.text.pdf.PdfWriter;
//import com.realnet.Dashboard1.Entity.Dashbord_Header;
//import com.realnet.Dashboard1.Repository.HeaderRepository;
//
//@Service
//public class PdfService {
//
// @Autowired
// private HeaderRepository headerRepository;
//
//// public void generatePdf(String dashboardName) throws DocumentException {
//// String pdfPath = "src/main/resources/" + dashboardName + ".pdf";
////
//// System.setProperty("webdriver.chrome.driver",
//// "C:\\Users\\Gyanadipta Pahi\\Desktop\\SureSetuLast\\suresetu-mohasin205\\backend\\src\\main\\resources\\chromedriver\\chromedriver.exe");
////
//// WebDriver driver = new ChromeDriver();
////
//// // driver.get("http://localhost:19004/token/dashboard2/getdashboardbyname/" +
//// // dashboardName);
//// driver.get("http://localhost:4200/#/cns-portal/dashboardrunner/dashrunner/" + dashboardName);
////
//// try {
////
//// String username="sysadmin";
//// String password="test3";
////
//// // Find the username and password fields and login button
//// WebElement usernameField = driver.findElement(By.id("login_username"));
//// WebElement passwordField = driver.findElement(By.id("login_password"));
//// WebElement loginButton = driver.findElement(By.id("login_Buttom"));
////
//// // Enter the login credentials
//// usernameField.sendKeys(username);
//// passwordField.sendKeys(password);
////
//// // Click the login button
//// loginButton.click();
////
//// Document document = new Document();
//// FileOutputStream outputStream = new FileOutputStream(pdfPath);
//// PdfWriter.getInstance(document, outputStream);
//// document.open();
////
//// // Find the dashboard container element in your Angular app
//// // WebElement dashboardContainer =
//// // driver.findElement(By.id("contentContainer"));
////
//// WebDriverWait wait = new WebDriverWait(driver, 10); // Wait up to 10 seconds
//// WebElement dashboardContainer = wait
//// .until(ExpectedConditions.presenceOfElementLocated(By.id("contentContainer")));
////
//// // Capture the screenshot of the dashboard using Selenium
//// byte[] dashboardImageBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
//// Image dashboardImage = Image.getInstance(dashboardImageBytes);
////
//// // Scale the image to fit the PDF page
//// Rectangle pageSize = document.getPageSize();
//// dashboardImage.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
//// dashboardImage.setAlignment(Image.MIDDLE);
////
//// // Add the dashboard image to the PDF document
//// document.add(dashboardImage);
////
//// document.close();
//// driver.quit();
////
//// } catch (Exception e) {
//// throw new DocumentException("Failed to generate PDF: " + e.getMessage());
//// }
//// }
//
//// public String generatePdf2(String dashboardName) throws IOException {
//// Dashbord_Header dashbord_Header = headerRepository.findByDashboardName(dashboardName);
//// Integer id = dashbord_Header.getId();
////
//// System.out.println("id is .. " + id);
////
//// long unixTimestamp = Instant.now().getEpochSecond();
////
//// String pdfFileName = dashboardName + "_" + unixTimestamp + ".pdf";
//// String pdfPath = "/data/images/" + pdfFileName;
//// String chromiumPath = "/usr/bin/chromium"; // Replace with the actual path to your Chromium executable
////
//// System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); // Replace with the correct path
////
//// ChromeOptions options = new ChromeOptions();
//// options.setBinary(chromiumPath);
//// options.addArguments("--headless");
//// options.addArguments("--disable-gpu");
//// options.addArguments("--no-sandbox");
//// options.addArguments("--remote-debugging-address=0.0.0.0");
//// options.addArguments("--remote-debugging-port=9222");
////
//// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
//// capabilities.setCapability(ChromeOptions.CAPABILITY, options);
////
//// try {
//// WebDriver driver = new RemoteWebDriver(capabilities);
//// // by me
//// // WebDriverWait wait = new WebDriverWait(driver, 10);
//// driver.get("http://43.205.154.152:30182/#/cns-portal/dashboardrunner/dashrunner/" + id);
////
//// // Replace these login steps with your actual login logic
//// String username = "sysadmin";
//// String password = "test3";
//// WebElement usernameField = driver.findElement(By.id("login_username"));
//// WebElement passwordField = driver.findElement(By.id("login_password"));
//// WebElement loginButton = driver.findElement(By.id("login_Buttom"));
////
//// usernameField.sendKeys(username);
//// passwordField.sendKeys(password);
//// loginButton.click();
////
//// Thread.sleep(15000); // Wait for the page to load (you can adjust the wait time as needed)
////
//// // Capture the screenshot of the dashboard
//// File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//// FileUtils.copyFile(screenshotFile, new File(pdfPath + ".png"));
////
//// driver.quit();
////
//// // Convert the screenshot to PDF using Apache PDFBox
//// PDDocument document = new PDDocument();
//// PDPage pdfPage = new PDPage();
//// document.addPage(pdfPage);
//// PDPageContentStream contentStream = new PDPageContentStream(document, pdfPage);
//// PDImageXObject imageXObject = PDImageXObject.createFromFile(pdfPath + ".png", document);
//// contentStream.drawImage(imageXObject, 50, 600);
//// contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
//// contentStream.beginText();
//// contentStream.newLineAtOffset(100, 700);
//// contentStream.showText("Your PDF content here"); // Replace with any additional content you want to add
//// contentStream.endText();
//// contentStream.close();
////
//// document.save(pdfPath);
//// document.close();
////
//// // Clean up the temporary screenshot image
//// new File(pdfPath + ".png").delete();
//// } catch (IOException | InterruptedException e) {
//// throw new IOException("Failed to generate PDF: " + e.getMessage());
//// }
////
//// return pdfFileName;
//// }
//
// public String generatePdf(String dashboardName) throws DocumentException {
//
// Dashbord_Header dashbord_Header = headerRepository.findByDashboardName(dashboardName);
// Integer id = dashbord_Header.getId();
//
// System.out.println("id is .. " + id);
//
// long unixTimestamp = Instant.now().getEpochSecond();
//
// String pdfFileName = dashboardName + "_" + unixTimestamp + ".pdf";
//
//// String pdfPath = "src/main/resources/images/" + pdfFileName;
// String pdfPath = "/data/images/" + pdfFileName;
//
// System.setProperty("webdriver.chrome.driver",
// // "C:\\Users\\Gyanadipta Pahi\\Desktop\\SureSetNew\\suresetu-mohasin205\\backend\\src\\main\\resources\\chromedriver\\chromedriver.exe");
// "/usr/local/bin/chromedriver");
//
// System.out.println("test1 ....");
//// WebDriver driver = new ChromeDriver();
// ChromeOptions options = new ChromeOptions();
// options.addArguments("--headless");
// options.addArguments("--disable-gpu");
// options.addArguments("--no-sandbox");
// options.addArguments("--remote-debugging-address=0.0.0.0");
// options.addArguments("--remote-debugging-port=9222");
// WebDriver driver = new ChromeDriver(options);
//
// driver.get("http://43.205.154.152:30182/#/cns-portal/dashboardrunner/dashrunner/" + id);
//
// try {
// System.out.println("test2 ....");
//
// String username = "sysadmin";
// String password = "test3";
//
// // Find the username and password fields and login button
// WebElement usernameField = driver.findElement(By.id("login_username"));
// WebElement passwordField = driver.findElement(By.id("login_password"));
// WebElement loginButton = driver.findElement(By.id("login_Buttom"));
//
// // Enter the login credentials
// usernameField.sendKeys(username);
// passwordField.sendKeys(password);
//
// // Click the login button
// loginButton.click();
//
// Thread.sleep(10000);
//
// Document document = new Document();
// FileOutputStream outputStream = new FileOutputStream(pdfPath);
// PdfWriter.getInstance(document, outputStream);
// document.open();
//
// System.out.println("test3 ....");
//
//// WebDriverWait wait = new WebDriverWait(driver, 10); // Wait up to 10 seconds
//// WebElement dashboardContainer = wait
//// .until(ExpectedConditions.presenceOfElementLocated(By.id("contentContainer")));
////
//// // Capture the screenshot of the dashboard using Selenium
//// byte[] dashboardImageBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
//// Image dashboardImage = Image.getInstance(dashboardImageBytes);
////
//// // Scale the image to fit the PDF page
//// Rectangle pageSize = document.getPageSize();
//// dashboardImage.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
//// dashboardImage.setAlignment(Image.MIDDLE);
////
//// // Add the dashboard image to the PDF document
//// document.add(dashboardImage);
////
//// document.close();
//// driver.quit();
//
//
//
// WebDriverWait wait = new WebDriverWait(driver, 10);
// WebElement dashboardContainer = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("contentContainer")));
//
// // Capture screenshot of the specific element
// File screenshotFile = dashboardContainer.getScreenshotAs(OutputType.FILE);
//
// // Convert the screenshot file into an image
// Image dashboardImage = Image.getInstance(screenshotFile.getAbsolutePath());
//
// // Scale and align the image as needed
// Rectangle pageSize = document.getPageSize();
// dashboardImage.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
// dashboardImage.setAlignment(Image.MIDDLE);
//
// // Add the dashboard image to the PDF document
// document.add(dashboardImage);
//
// document.close();
// driver.quit();
//
// } catch (Exception e) {
// throw new DocumentException("Failed to generate PDF: " + e.getMessage());
// }
//
// return pdfFileName;
// }
//}

View File

@@ -0,0 +1,28 @@
package com.realnet.Dashboard_builder.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class DashboardSchedule_t{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String cron;
private String every;
private String gateway;
private String template;
private Date startTime;
private Date endTime;
private String attachment;
private String sendTo;
private String gatewaydone;
private String cc;
private String replacementString;
private String type;
}

View File

@@ -0,0 +1,20 @@
package com.realnet.Dashboard_builder.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Dashboard_builder_t {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String dashboardname;
}

View File

@@ -0,0 +1,23 @@
package com.realnet.Dashboard_builder.Repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.Dashboard_builder.Entity.DashboardSchedule_t;
@Repository
public interface DashboardSchedule_Repository extends JpaRepository<DashboardSchedule_t, Long> {
@Query(value = "SELECT * FROM dashboard_schedule_t where gatewaydone ='N' order by id asc", nativeQuery = true)
List<DashboardSchedule_t> findTopByOrderByIdAsc();
}

View File

@@ -0,0 +1,14 @@
package com.realnet.Dashboard_builder.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.Dashboard_builder.Entity.Dashboard_builder_t;
@Repository
public interface Dashboard_builder_Repository extends JpaRepository<Dashboard_builder_t, Long> {
}

View File

@@ -0,0 +1,47 @@
package com.realnet.Dashboard_builder.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.Dashboard_builder.Entity.DashboardSchedule_t;
import com.realnet.Dashboard_builder.Repository.DashboardSchedule_Repository;
@Service
public class DashboardSchedule_Service {
@Autowired
private DashboardSchedule_Repository Repository;
public DashboardSchedule_t Savedata(DashboardSchedule_t data) {
data.setGatewaydone("N");
// DashboardSchedule_t save = Repository.save(job);
return Repository.save(data);
}
public List<DashboardSchedule_t> getdetails() {
return (List<DashboardSchedule_t>) Repository.findAll();
}
public DashboardSchedule_t getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public DashboardSchedule_t update(DashboardSchedule_t data, Long id) {
DashboardSchedule_t old = Repository.findById(id).get();
old.setCron(data.getCron());
old.setEvery(data.getEvery());
old.setGateway(data.getGateway());
old.setTemplate(data.getTemplate());
old.setStartTime(data.getStartTime());
old.setEndTime(data.getEndTime());
old.setAttachment(data.getAttachment());
old.setSendTo(data.getSendTo());
final DashboardSchedule_t test = Repository.save(old);
return test;
}
}

View File

@@ -0,0 +1,37 @@
package com.realnet.Dashboard_builder.Services;
import com.realnet.Dashboard_builder.Repository.Dashboard_builder_Repository;
import com.realnet.Dashboard_builder.Entity.Dashboard_builder_t;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Dashboard_builder_Service {
@Autowired
private Dashboard_builder_Repository Repository;
public Dashboard_builder_t Savedata(Dashboard_builder_t data) {
return Repository.save(data);
}
public List<Dashboard_builder_t> getdetails() {
return (List<Dashboard_builder_t>) Repository.findAll();
}
public Dashboard_builder_t getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public Dashboard_builder_t update(Dashboard_builder_t data, Long id) {
Dashboard_builder_t old = Repository.findById(id).get();
old.setDashboardname(data.getDashboardname());
final Dashboard_builder_t test = Repository.save(old);
return test;
}
}

View File

@@ -0,0 +1,126 @@
//package com.realnet.Dashboard_builder.Services;
//
//import java.io.File;
//import java.util.Properties;
//
//import javax.mail.Authenticator;
//import javax.mail.Message;
//import javax.mail.MessagingException;
//import javax.mail.PasswordAuthentication;
//import javax.mail.Session;
//import javax.mail.Transport;
//import javax.mail.internet.InternetAddress;
//import javax.mail.internet.MimeMessage;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.mail.javamail.JavaMailSender;
//import org.springframework.mail.javamail.MimeMessageHelper;
//
//import com.realnet.Gateway.Entity.Gateway_t;
//import com.realnet.Gateway.Services.Gateway_Service;
//
//public class EmailGenerateService {
//
// @Autowired
// private JavaMailSender mailSender;
//
// @Autowired
// private Gateway_Service gateway_Service;
//
// public boolean sendEmailGateway(Long id, String to, String subject, String htmlContent, String cc) {
// // Email to database code start
// Gateway_t getdetails = gateway_Service.getdetailsbyId(id);
//
// String host = getdetails.getHost();
// String username = getdetails.getUserName();
// String password = getdetails.getPassword();
//
// // SMTP server properties
// Properties props = new Properties();
// props.setProperty("mail.smtp.host", host);
// props.setProperty("mail.smtp.port", "587");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.starttls.enable", "true");
//
// try {
// Session session = Session.getInstance(props, new Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(username, password);
// }
// });
//
// // Create a new message
// MimeMessage message = new MimeMessage(session);
//
// // Set the sender
// message.setFrom(new InternetAddress(username));
//
// // Set the recipient
// message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
//
// // Set the CC recipient if provided
// if (cc != null) {
// message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
// }
//
// // Set the subject
// message.setSubject(subject);
//
// // Set the content
// message.setContent(htmlContent, "text/html");
//
// // Send the message
// Transport.send(message);
//
// return true;
// } catch (MessagingException e) {
// e.printStackTrace();
// return false;
// }
// }
//
//
//
//
// public String sendEmailGatewayWithAttachment(Long id, String to, String subject, String htmlContent, String cc, File file) {
// Gateway_t getdetails = gateway_Service.getdetailsbyId(id);
// if (getdetails != null) {
// String host = getdetails.getHost();
// String username = getdetails.getUserName();
// String password = getdetails.getPassword();
//
// // SMTP server properties
// Properties props = new Properties();
// props.setProperty("mail.smtp.host", host);
// props.setProperty("mail.smtp.port", "587");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.starttls.enable", "true");
//
// try {
// Session session = Session.getInstance(props, new Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(username, password);
// }
// });
//
// MimeMessage mimeMessage = new MimeMessage(session);
// MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
// mimeMessageHelper.setTo(to);
// mimeMessageHelper.setSubject(subject);
// mimeMessageHelper.setText(htmlContent, true);
// mimeMessageHelper.setCc(cc);
// mimeMessageHelper.addAttachment(file.getName(), file);
//
// Transport.send(mimeMessage);
//
// return "Mail sent successfully";
// } catch (MessagingException e) {
// return "Error while sending mail: " + e.getMessage();
// }
// } else {
// return "Error: Gateway not found";
// }
// }
//
//
//}

View File

@@ -0,0 +1,62 @@
package com.realnet.FabricIcard.Controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/token")
public class AngularHtmlCode {
@GetMapping("/convert")
public String convertAngularToHtml(@RequestParam String angularCode) {
// Perform conversion logic here (replace Angular-specific syntax with HTML)
String htmlCode = convertAngularToHtmlCode(angularCode);
return htmlCode;
}
// private String convertAngularToHtmlCode(String angularCode) {
// // Replace ng-container with a div
// String htmlCode = angularCode.replace("<ng-container", "<div");
//
// // Replace ngIf with standard HTML attributes
// htmlCode = htmlCode.replace("*ngIf=", "ng-if=");
//
// // Remove Angular-specific directives (ngFor, ngIf) and Angular-specific syntax ([...], {{...}})
// htmlCode = htmlCode.replaceAll("\\[.*?\\]", ""); // Remove [property]="value"
// htmlCode = htmlCode.replaceAll("\\{\\{.*?\\}\\}", ""); // Remove {{expression}}
//
// // Replace Angular-specific structural directives with standard HTML
// htmlCode = htmlCode.replace("*ngFor", "ng-repeat"); // Replace *ngFor with ng-repeat
//
// // Add more replacements as needed for other Angular-specific syntax
//
// return htmlCode;
// }
private String convertAngularToHtmlCode(String angularCode) {
// Replace ng-container with a div
String htmlCode = angularCode.replace("<ng-container", "<div");
// Replace ng-repeat with ng-for
htmlCode = htmlCode.replace("ng-repeat", "ng-for");
// Replace ngIf with standard HTML attributes
htmlCode = htmlCode.replace("*ngIf=", "ng-if=");
// Remove Angular-specific structural directives (ngFor, ngIf) and Angular-specific syntax ([...], {{...}})
htmlCode = htmlCode.replaceAll("\\[.*?\\]", ""); // Remove [property]="value"
htmlCode = htmlCode.replaceAll("\\{\\{.*?\\}\\}", ""); // Remove {{expression}}
// Remove Angular-specific directives
htmlCode = htmlCode.replaceAll("ng-for", ""); // Remove ng-for
htmlCode = htmlCode.replaceAll("ng-if", ""); // Remove ng-if
// Add more replacements as needed for other Angular-specific syntax
return htmlCode;
}
}

View File

@@ -0,0 +1,47 @@
package com.realnet.FabricIcard.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.FabricIcard.Entity.FabricIcard;
import com.realnet.FabricIcard.Services.FabricIcardService;
@RequestMapping(value = "/FabricIcard")
@RestController
public class FabricIcardController {
@Autowired
private FabricIcardService Service;
@PostMapping("/FabricIcard")
public FabricIcard Savedata(@RequestBody FabricIcard data) {
FabricIcard save = Service.Savedata(data);
return save;
}
@GetMapping("/FabricIcard")
public List<FabricIcard> getdetails() {
List<FabricIcard> get = Service.getdetails();
return get;
}
@GetMapping("/FabricIcard/{id}")
public FabricIcard getdetailsbyId(@PathVariable Long id) {
FabricIcard get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/FabricIcard/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/FabricIcard/{id}")
public FabricIcard update(@RequestBody FabricIcard data, @PathVariable Long id) {
FabricIcard update = Service.update(data, id);
return update;
}
}

View File

@@ -0,0 +1,312 @@
package com.realnet.FabricIcard.Controllers;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@RestController
@RequestMapping("/token")
public class LayoutPdf {
@PostMapping("/generate-pdf")
public ResponseEntity<byte[]> generatePdf(@RequestBody String htmlContent) {
try {
// Use Flying Saucer to convert HTML to PDF
byte[] pdfBytes = generatePdf1(htmlContent);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("inline", "output.pdf");
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public byte[] generatePdf1(String htmlContent) throws Exception {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlContent);
renderer.layout();
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
renderer.createPDF(outputStream);
return outputStream.toByteArray();
}
}
@PostMapping("/generateHtml1/{id}")
public String generateHtml1(@RequestBody List<Map<String, Object>> jsonData, @PathVariable Long id)
throws JsonProcessingException {
return generateHtml2(jsonData, id);
}
public String generateHtml2(List<Map<String, Object>> jsonData, Long id) throws JsonProcessingException {
// LayoutBuilder_t layoutBuilder_t = layoutBuilder_Repository.findById(id).get();
//
// LayoutBuilderLines_t layoutBuilderLines_t = layoutBuilderLines_Repository.findById(id).get();
//
// String url = layoutBuilder_t.getUrl();
// String model = layoutBuilderLines_t.getModel();
//
// String serviceOrderId = "146";
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(model);
// JsonArray models = element.getAsJsonArray();
// JsonObject getbodyobject = null;
// List<Map<String, Object>> replacerule = null;
// String operation = null;
// String replaceWith = null;
// String startstring = null;
// String endstring = null;
// String keyword = null;
// String linestring = null;
// String cellAddress = null;
// String ModifyfileName = null;
// String nodeName = null;
//
// String a_uri = url.replace("?", String.valueOf(serviceOrderId));
// System.out.println(a_uri);
//
// Object body = GET(a_uri).getBody();
// ObjectMapper objectMapper = new ObjectMapper();
// String json = objectMapper.writeValueAsString(body);
// JsonElement getbody = parser.parse(json);
// getbodyobject = getbody.getAsJsonObject();
//
//
//
// for (JsonElement mod : models) {
// JsonObject object = mod.getAsJsonObject();
//
// startstring = object.get("start_string").toString().replaceAll("\"", "");
// endstring = object.get("end_string").toString().replaceAll("\"", "");
// replaceWith = object.get("replace_with").toString().replaceAll("\"", "");
// keyword = object.get("Keyword").toString().replaceAll("\"", "");
// linestring = object.get("line_string").toString().replaceAll("\"", "");
// operation = object.get("operation").toString().replaceAll("\"", "");
// cellAddress = object.get("cellAddress").toString().replaceAll("\"", "");
//
// nodeName = object.get("nodeName").toString().replaceAll("\"", "");
//// // nodeName = "listOfItems"; // Set the desired node name
////
// JsonArray values = searchJsonKey(getbodyobject, replaceWith, nodeName);
//
// for (JsonElement element1 : values) {
// String individualValue = element1.getAsString();
//
// replaceWith = individualValue;
//
// System.out.println("Found value: " + individualValue);
//
// if (operation.contains("replacement")) {
// replacerule = replaceStringInJsonData(jsonData, replaceWith, keyword);
//
// }
// }
//
// }
//
// jsonData = replacerule;
StringBuilder htmlBuilder = new StringBuilder();
// Open the main card div
htmlBuilder.append("<div class=\"card\" style=\"padding: 10px; background-color: white;\">");
htmlBuilder.append(
"<div class=\"card-body\" style=\"display: grid; grid-template-columns: repeat(20, 1fr); grid-template-rows: repeat(29, 1fr); gap: 5px;\">");
for (Map<String, Object> item : jsonData) {
// Check for Table type
if ("Table".equals(item.get("type"))) {
htmlBuilder.append("<div style=\"grid-column: ").append(item.get("x")).append(" / span ")
.append(item.get("cols")).append("; grid-row: ").append(item.get("y")).append(" / span ")
.append(item.get("rows")).append(";\">");
// Open the card-title div for Table
htmlBuilder.append("<div class=\"title-card card-title\" style=\"text-align: ")
.append(item.get("alignment") != null ? item.get("alignment") : "left")
.append("; line-height: 1; font-family: Metropolis; font-size: 100%; font-style: normal; font-weight: ")
.append(item.get("bold") != null && (boolean) item.get("bold") ? "bold" : "normal")
.append("; text-decoration: none; background-color: white; color: black;\">");
// Add Table HTML code
htmlBuilder.append("<div style=\"max-width:100%; overflow: auto;\">");
htmlBuilder.append("<table class=\"table\" style=\"margin-top: 10px;\">");
htmlBuilder.append("<thead>");
htmlBuilder.append("<tr>");
// Add table header based on the JSON structure
List<Map<String, String>> values = (List<Map<String, String>>) item.get("values");
for (Map<String, String> value : values) {
htmlBuilder.append("<th>").append(value.get("label")).append("</th>");
}
htmlBuilder.append("</tr>");
htmlBuilder.append("</thead>");
htmlBuilder.append("<tbody>");
htmlBuilder.append("<tr>");
// Add table body content based on the JSON structure
for (Map<String, String> value : values) {
htmlBuilder.append("<td>").append(value.get("value")).append("</td>");
}
// // Add the additional values twice
// for (Map<String, String> additionalValue : values) {
// htmlBuilder.append("<td>").append(additionalValue.get("value")).append("</td>");
// }
htmlBuilder.append("</tr>");
htmlBuilder.append("</tbody>");
htmlBuilder.append("</table>");
htmlBuilder.append("</div>");
// Close the card-title and individual item div for Table
htmlBuilder.append("</div></div>");
}
// Check for Image type
else if ("Image".equals(item.get("type"))) {
htmlBuilder.append("<div style=\"grid-column: ").append(item.get("x")).append(" / span ")
.append(item.get("cols")).append("; grid-row: ").append(item.get("y")).append(" / span ")
.append(item.get("rows")).append(";\">");
// Open the card-title div for Image
htmlBuilder.append("<div class=\"title-card card-title\" style=\"text-align: ")
.append(item.get("alignment") != null ? item.get("alignment") : "left")
.append("; line-height: 1; font-family: Metropolis; font-size: 100%; font-style: normal; font-weight: ")
.append(item.get("bold") != null && (boolean) item.get("bold") ? "bold" : "normal")
.append("; text-decoration: none; background-color: white; color: black;\">");
// Add Image tag
htmlBuilder.append("<img src=\"").append(item.get("imageURL"))
.append("\" alt=\"Image\" style=\"width: ").append(item.get("imagewidth")).append("px;\">");
// Close the card-title and individual item div for Image
htmlBuilder.append("</div></div>");
} else if ("Line".equals(item.get("type"))) {
// Handle Line type
htmlBuilder.append("<div style=\"grid-column: ").append(item.get("x")).append(" / span ")
.append(item.get("cols")).append("; grid-row: ").append(item.get("y")).append(" / span ")
.append(item.get("rows")).append(";\">");
htmlBuilder.append("<hr></hr>");
htmlBuilder.append("</div>");
} else {
// Handle other types
// Open the individual item div
htmlBuilder.append("<div style=\"grid-column: ").append(item.get("x")).append(" / span ")
.append(item.get("cols")).append("; grid-row: ").append(item.get("y")).append(" / span ")
.append(item.get("rows")).append(";\">");
// Open the card-title div
htmlBuilder.append("<div class=\"title-card card-title\" style=\"text-align: ")
.append(item.get("alignment") != null ? item.get("alignment") : "left")
.append("; line-height: 1; font-family: Metropolis; font-size: 100%; font-style: normal; font-weight: ")
.append(item.get("bold") != null && (boolean) item.get("bold") ? "bold" : "normal")
.append("; text-decoration: none; background-color: white; color: black;\">");
// Append the fieldtext content
htmlBuilder.append(item.get("fieldtext"));
// Close the card-title and individual item div
htmlBuilder.append("</div></div>");
}
}
// Close the main card div
htmlBuilder.append("</div></div>");
return htmlBuilder.toString();
}
public ResponseEntity<Object> GET(String get) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
return u;
}
private static JsonArray searchJsonKey(JsonObject jsonObject, String keyToSearch, String nodeName) {
JsonArray resultArray = new JsonArray();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey().replaceAll("\"", "");
JsonElement value = entry.getValue();
if (value.isJsonObject()) {
// Recursively search for the key in the nested object
JsonArray nestedValues = searchJsonKey(value.getAsJsonObject(), keyToSearch, nodeName);
resultArray.addAll(nestedValues);
} else if (nodeName == null || nodeName.isEmpty() || key.equalsIgnoreCase(nodeName)) {
// If nodeName is null or matches the current key, search for the keyToSearch
if (value.isJsonArray()) {
// Handle arrays by iterating through each element
JsonArray jsonArray = value.getAsJsonArray();
for (JsonElement arrayElement : jsonArray) {
if (arrayElement.isJsonObject()) {
JsonObject itemObject = arrayElement.getAsJsonObject();
if (itemObject.has(keyToSearch)) {
resultArray.add(itemObject.get(keyToSearch));
}
}
}
} else if (value.isJsonPrimitive() && key.equals(keyToSearch)) {
// If nodeName is null and the current key matches keyToSearch, add the value to
// the result
resultArray.add(value);
}
}
}
return resultArray;
}
public static List<Map<String, Object>> replaceStringInJsonData(List<Map<String, Object>> jsonData, String keyword,
String replaceWith) {
for (Map<String, Object> entry : jsonData) {
for (Map.Entry<String, Object> keyValue : entry.entrySet()) {
if (keyValue.getValue() instanceof String) {
String value = (String) keyValue.getValue();
if (value.contains(replaceWith)) {
entry.replace(keyValue.getKey(), value.replace(replaceWith, keyword));
}
}
}
}
return jsonData;
}
}

View File

@@ -0,0 +1,40 @@
//package com.realnet.LayoutBuilder.Controllers;
//
//import org.w3c.dom.Element;
//import org.xhtmlrenderer.extend.ReplacedElement;
//import org.xhtmlrenderer.extend.ReplacedElementFactory;
//import org.xhtmlrenderer.extend.UserAgentCallback;
//import org.xhtmlrenderer.layout.LayoutContext;
//import org.xhtmlrenderer.render.BlockBox;
//import org.xhtmlrenderer.simple.extend.FormSubmissionListener;
//
//public class MyImageReplacedElementFactory implements ReplacedElementFactory{
//
// @Override
// public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth,
// int cssHeight) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public void reset() {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void remove(Element e) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void setFormSubmissionListener(FormSubmissionListener listener) {
// // TODO Auto-generated method stub
//
// }
//
//}

View File

@@ -0,0 +1,28 @@
package com.realnet.FabricIcard.Controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.FabricIcard.Entity.PageSource;
import com.realnet.FabricIcard.Repository.PageSourceRepository;
@RestController
@RequestMapping("/api/pages")
public class PageController {
@Autowired
private PageSourceRepository pageSourceRepository;
@PostMapping("/save")
public String savePageSource(@RequestBody String sourceCode) {
PageSource pageSource = new PageSource();
pageSource.setSourceCode(sourceCode);
// Save to the database
pageSourceRepository.save(pageSource);
return "Page source saved successfully!";
}
}

View File

@@ -0,0 +1,108 @@
//package com.realnet.FabricIcard.Controllers;
//
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//@RestController
//@RequestMapping("/token")
//public class TestCode {
// @GetMapping("/dynamicValues")
// public List<Map<String, String>> getDynamicValues() {
// try {
// // Make HTTP request to the first API
// String apiUrl = "http://3.109.61.114:30161/token/Billing/ServiceOrder/ServiceOrder/146";
// String response = sendHttpRequest(apiUrl);
//
// // Parse the response and extract the listOfItems
// return createValuesFromList(response);
// } catch (Exception e) {
// e.printStackTrace();
// return new ArrayList<>(); // Return an empty list in case of an error
// }
// }
//
// private String sendHttpRequest(String apiUrl) throws Exception {
// URL url = new URL(apiUrl);
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
//
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// StringBuilder response = new StringBuilder();
//
// String line;
// while ((line = reader.readLine()) != null) {
// response.append(line);
// }
//
// reader.close();
// connection.disconnect();
//
// return response.toString();
// }
//
// private List<Map<String, String>> createValuesFromList(String jsonResponse) {
// List<Map<String, String>> values = new ArrayList<>();
//
// try {
// // Parse the JSON response using Jackson ObjectMapper
// ObjectMapper objectMapper = new ObjectMapper();
// JsonNode rootNode = objectMapper.readTree(jsonResponse);
//
// // Extract the listOfItems node
// JsonNode listOfItemsNode = rootNode.path("listOfItems");
//
// // Iterate through each item in the listOfItems
// Iterator<JsonNode> itemsIterator = listOfItemsNode.elements();
// while (itemsIterator.hasNext()) {
// JsonNode itemNode = itemsIterator.next();
//
// // Extract relevant information from the item
// String itemCode = itemNode.path("itemCode").asText();
// String unitPrice = itemNode.path("unitPrice").asText();
// String lineTotal = itemNode.path("lineTotal").asText();
//
// // Create the corresponding values
// Map<String, String> itemValues = Map.of(
// "label", "Item and Description",
// "value", itemCode
// );
// Map<String, String> qtyValues = Map.of(
// "label", "Qty",
// "value", "1"
// );
// Map<String, String> rateValues = Map.of(
// "label", "Rate",
// "value", unitPrice
// );
// Map<String, String> amountValues = Map.of(
// "label", "Amount",
// "value", lineTotal
// );
//
// // Add the values to the list
// values.add(itemValues);
// values.add(qtyValues);
// values.add(rateValues);
// values.add(amountValues);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return values;
// }
//}

View File

@@ -0,0 +1,35 @@
package com.realnet.FabricIcard.Entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.realnet.FabricIcardLines.Entity.FabricIcardLines;
import lombok.Data;
@Entity
@Data
public class FabricIcard {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private boolean active;
private String url;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "layoutBuilder_t")
private List<FabricIcardLines> fabricIcardLines = new ArrayList<>();
}

View File

@@ -0,0 +1,19 @@
package com.realnet.FabricIcard.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class PageSource {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sourceCode;
// getters and setters
}

View File

@@ -0,0 +1,12 @@
package com.realnet.FabricIcard.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.FabricIcard.Entity.FabricIcard;
@Repository
public interface FabricIcardRepository extends JpaRepository<FabricIcard, Long> {
}

View File

@@ -0,0 +1,10 @@
package com.realnet.FabricIcard.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.FabricIcard.Entity.PageSource;
@Repository
public interface PageSourceRepository extends JpaRepository<PageSource, Long> {
}

View File

@@ -0,0 +1,41 @@
package com.realnet.FabricIcard.Services;
import com.realnet.FabricIcard.Entity.FabricIcard;
import com.realnet.FabricIcard.Repository.FabricIcardRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FabricIcardService {
@Autowired
private FabricIcardRepository Repository;
public FabricIcard Savedata(FabricIcard data) {
return Repository.save(data);
}
public List<FabricIcard> getdetails() {
return (List<FabricIcard>) Repository.findAll();
}
public FabricIcard getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public FabricIcard update(FabricIcard data, Long id) {
FabricIcard old = Repository.findById(id).get();
old.setName(data.getName());
old.setDescription(data.getDescription());
old.setActive(data.isActive());
old.setUrl(data.getUrl());
final FabricIcard test = Repository.save(old);
return test;
}
}

View File

@@ -0,0 +1,282 @@
package com.realnet.FabricIcard.Services;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.xhtmlrenderer.pdf.ITextRenderer;
@Service
public class LayoutPdfService {
public String generateForm(@RequestBody Map<String, Object> jsonData) {
// Convert JSON to HTML
String htmlForm = convertJsonToHtml(jsonData);
return htmlForm;
}
// public void convertToPdf(@RequestBody String htmlContent) throws IOException {
// // Render HTML content using Flying Saucer
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// ITextRenderer renderer = new ITextRenderer();
// renderer.setDocumentFromString(htmlContent);
// renderer.layout();
// renderer.createPDF(outputStream);
//
//
// // Specify the directory and file name where you want to save the PDF
// String pdfFilePath = "/data/example.pdf";
//
// String path="/data";
//
// Path directory = Paths.get(path);
// if (!Files.exists(directory)) {
// try {
// Files.createDirectories(directory);
// } catch (IOException e) {
// e.printStackTrace();
// // Handle directory creation failure appropriately
// }
// }
//
//
// // Save the PDF to the specified file
// try (FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath)) {
// outputStream.writeTo(fileOutputStream);
// }
//
//
// // Set the response headers
//// response.setContentType("application/pdf");
//// response.setContentLength(outputStream.size());
//// response.setHeader("Content-Disposition", "inline; filename=example.pdf");
////
//// // Write the PDF to the response output stream
//// response.getOutputStream().write(outputStream.toByteArray());
//// response.getOutputStream().flush();
// } catch (Exception e) {
// e.printStackTrace();
// // Handle exceptions appropriately
// }
// }
public void convertToPdf(@RequestBody String htmlContent) throws IOException {
htmlContent="<!DOCTYPE html>\r\n"
+ "<html lang=\"en\">\r\n"
+ "<head>\r\n"
+ " <meta charset=\"UTF-8\"></meta>\r\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></meta>\r\n"
+ " <title>FormName</title>\r\n"
+ " <style>\r\n"
+ " body {\r\n"
+ " font-family: Arial, sans-serif;\r\n"
+ " margin: 20px;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .dashboard {\r\n"
+ " display: grid;\r\n"
+ " grid-template-columns: repeat(24, 1fr);\r\n"
+ " grid-template-rows: repeat(2, 1fr);\r\n"
+ " gap: 10px;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .dashboard-item {\r\n"
+ " grid-column: span 6;\r\n"
+ " grid-row: span 2;\r\n"
+ " border: 1px solid #ccc;\r\n"
+ " padding: 10px;\r\n"
+ " box-sizing: border-box;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .text-center {\r\n"
+ " text-align: center;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .bold {\r\n"
+ " font-weight: bold;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .italic {\r\n"
+ " font-style: italic;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .underline {\r\n"
+ " text-decoration: underline;\r\n"
+ " }\r\n"
+ " \r\n"
+ " .larger {\r\n"
+ " font-size: larger;\r\n"
+ " }\r\n"
+ " </style>\r\n"
+ "</head>\r\n"
+ "<body>\r\n"
+ "\r\n"
+ "<div class=\"dashboard\">\r\n"
+ " <div class=\"dashboard-item text-center bold italic underline larger\" style=\"grid-column: span 3; grid-row: span 2;\">\r\n"
+ " Title\r\n"
+ " </div>\r\n"
+ " <div class=\"dashboard-item\" style=\"grid-column: span 6; grid-row: span 2;\">\r\n"
+ " <label for=\"first_name\">Gyanadipta</label>\r\n"
+ " <input type=\"text\" id=\"first_name\" name=\"first_name\">\r\n"
+ " </input>\r\n"
+ " </div>\r\n"
+ " <div class=\"dashboard-item\" style=\"grid-column: span 6; grid-row: span 2;\">\r\n"
+ " <label for=\"gender\">Male</label>\r\n"
+ " <input type=\"text\" id=\"gender\" name=\"gender\">\r\n"
+ " </input>\r\n"
+ " </div>\r\n"
+ "</div>\r\n"
+ "\r\n"
+ "</body>\r\n"
+ "</html>\r\n";
// Render HTML content using Flying Saucer
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(outputStream);
// Reset the position of the output stream before writing to the file
// outputStream.reset();
// Specify the directory and file name where you want to save the PDF
String pdfFilePath = "/data/example.pdf";
String path = "/data";
Path directory = Paths.get(path);
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
} catch (IOException e) {
e.printStackTrace();
// Handle directory creation failure appropriately
}
}
// Save the PDF to the specified file
try (FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath)) {
outputStream.writeTo(fileOutputStream);
}
} catch (Exception e) {
e.printStackTrace();
// Handle exceptions appropriately
}
}
private String convertJsonToHtml(Map<String, Object> formData) {
StringBuilder htmlBuilder = new StringBuilder("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n");
htmlBuilder.append(" <meta charset=\"UTF-8\"></meta>\n");
htmlBuilder.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></meta>\n");
htmlBuilder.append(String.format(" <title>%s</title>\n", formData.get("name")));
htmlBuilder.append(" <style>\n");
htmlBuilder.append(" body {\n");
htmlBuilder.append(" font-family: Arial, sans-serif;\n");
htmlBuilder.append(" margin: 20px;\n");
htmlBuilder.append(" }\n");
htmlBuilder.append(" .dashboard {\n");
htmlBuilder.append(" display: grid;\n");
htmlBuilder.append(" grid-template-columns: repeat(24, 1fr);\n");
htmlBuilder.append(" grid-template-rows: repeat(2, 1fr);\n");
htmlBuilder.append(" gap: 10px;\n");
htmlBuilder.append(" }\n");
htmlBuilder.append(" .dashboard-item {\n");
htmlBuilder.append(" border: 1px solid #ccc;\n");
htmlBuilder.append(" padding: 10px;\n");
htmlBuilder.append(" box-sizing: border-box;\n");
htmlBuilder.append(" }\n");
// Add styles for different classes (.text-center, .bold, .italic, .underline,
// .larger) if needed
htmlBuilder.append(" </style>\n</head>\n<body>\n\n<div class=\"dashboard\">\n");
// Iterate through the dashboard array
List<Map<String, Object>> dashboard = (List<Map<String, Object>>) formData.get("dashboard");
for (Map<String, Object> element : dashboard) {
htmlBuilder.append(generateFormField(element));
}
htmlBuilder.append("</div>\n\n</body>\n</html>");
return htmlBuilder.toString();
}
private String generateFormField(Map<String, Object> fieldData) {
StringBuilder fieldHtml = new StringBuilder();
String type = (String) fieldData.get("type");
if (type != null) {
fieldHtml.append(
String.format(" <div class=\"dashboard-item\" style=\"%s\">\n", getGridStyle(fieldData)));
fieldHtml.append(String.format(" <label for=\"%s\">%s</label>\n", fieldData.get("fieldName"),
fieldData.get("fieldtext")));
switch (type) {
case "text":
fieldHtml.append(String.format(" <input type=\"text\" id=\"%s\" name=\"%s\" %s/>\n",
fieldData.get("fieldName"), fieldData.get("fieldName"), getAdditionalAttributes(fieldData)));
break;
case "textarea":
fieldHtml.append(
String.format(" <textarea name=\"%s\"></textarea>\n", fieldData.get("fieldName")));
break;
case "select":
fieldHtml.append(String.format(" <select name=\"%s\">\n", fieldData.get("fieldName")));
fieldHtml.append(String.format(" <option>%s</option>\n", fieldData.get("fieldtext")));
fieldHtml.append(" </select>\n");
break;
// Add more cases for other form field types as needed
default:
// Handle unknown field types or add more specific cases
}
fieldHtml.append(" </div>\n");
}
return fieldHtml.toString();
}
private String getGridStyle(Map<String, Object> fieldData) {
int cols = (int) fieldData.get("cols");
int rows = (int) fieldData.get("rows");
int x = (int) fieldData.get("x");
int y = (int) fieldData.get("y");
return String.format("grid-column: span %d; grid-row: span %d; grid-column-start: %d; grid-row-start: %d;",
cols, rows, x, y);
}
private String getAdditionalAttributes(Map<String, Object> fieldData) {
StringBuilder attributes = new StringBuilder();
for (Map.Entry<String, Object> entry : fieldData.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!Arrays.asList("type", "fieldName", "fieldtext", "cols", "rows", "x", "y").contains(key)
&& value != null) {
attributes.append(String.format(" %s=\"%s\"", key, value));
}
}
return attributes.toString();
}
}

View File

@@ -0,0 +1,78 @@
package com.realnet.FabricIcardLines.Controllers;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.realnet.FabricIcardLines.Entity.Dummyfabric;
import com.realnet.FabricIcardLines.Entity.FabricIcardLines;
import com.realnet.FabricIcardLines.Services.FabricIcardLinesService;
@RequestMapping(value = "/FabricIcardLines")
@RestController
public class FabricIcardLinesController {
@Autowired
private FabricIcardLinesService Service;
@PostMapping("/FabricIcardLines")
public FabricIcardLines Savedata(@RequestBody FabricIcardLines data) {
FabricIcardLines save = Service.Savedata(data);
return save;
}
@GetMapping("/FabricIcardLines")
public List<FabricIcardLines> getdetails() {
List<FabricIcardLines> get = Service.getdetails();
return get;
}
@GetMapping("/FabricIcardLines/{id}")
public FabricIcardLines getdetailsbyId(@PathVariable Long id) {
FabricIcardLines get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/FabricIcardLines/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/FabricIcardLines/{id}")
public FabricIcardLines update(@RequestBody FabricIcardLines data, @PathVariable Long id) {
FabricIcardLines update = Service.update(data, id);
return update;
}
// make xml file
@PutMapping("/FabricIcardLines/xml")
public FabricIcardLines makexmlfile(@RequestParam String id, @RequestBody Dummyfabric dummy) throws IOException {
String xml = dummy.getXml();
String json = dummy.getJson();
FabricIcardLines update = Service.makexmlfile(id, xml, json);
return update;
}
// get by headerid
@GetMapping("/FabricIcardLines/headerId/{id}")
public FabricIcardLines getdetailsbyheaderId(@PathVariable String id) {
FabricIcardLines get = Service.getbyheaderid(id);
return get;
}
// file read
@GetMapping("/FabricIcardLines/json/{id}")
public String readfile(@PathVariable String id) throws IOException {
String get = Service.readjson(id);
return get;
}
}

View File

@@ -0,0 +1,117 @@
package com.realnet.FabricIcardLines.Controllers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.FabricIcardLines.Entity.FabricIcardLines;
import com.realnet.FabricIcardLines.Services.FabricIcardLinesService;
@CrossOrigin("*")
@RequestMapping(value = "/FabricIcardLines")
@RestController
public class JsonKeysController {
@Autowired
private FabricIcardLinesService fabricIcardLinesService;
@PostMapping("/getJsonKeys")
public ResponseEntity<List<String>> getJsonKeys(@RequestBody String json) {
try {
// Parse JSON string into JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
// Get all keys from JsonNode
List<String> keys = getAllKeys(jsonNode);
return ResponseEntity.ok(keys);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
private List<String> getAllKeys(JsonNode jsonNode) {
List<String> keys = new ArrayList<>();
Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
keys.add(fieldNames.next());
}
return keys;
}
// get key value from FabricIcardLinesService
@PostMapping("/FabricIcardLines/getKeyValuePairs/{id}")
public ResponseEntity<List<Map<String, String>>> getKeyValuePairs(@PathVariable String id) {
FabricIcardLines lines = fabricIcardLinesService.getbyheaderid(id);
if (lines == null) {
String message = "No lines found for ID: " + id;
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Collections.singletonList(Collections.singletonMap("message", message)));
}
String jsonData = lines.getLayoutModel();
try {
// Parse JSON string into JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
// Extract key-value pairs based on type
List<Map<String, String>> keyValuePairs = extractKeyValuePairs(rootNode);
return ResponseEntity.ok(keyValuePairs);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
private List<Map<String, String>> extractKeyValuePairs(JsonNode rootNode) {
List<Map<String, String>> keyValuePairs = new ArrayList<>();
JsonNode objectsNode = rootNode.get("objects");
if (objectsNode == null || !objectsNode.isArray()) {
return keyValuePairs; // Return empty list if objects array is missing or not an array
}
for (JsonNode node : objectsNode) {
Map<String, String> pair = new HashMap<>();
String type = node.path("type").asText();
if (type.equals("i-text")) {
JsonNode textNode = node.path("text");
if (!textNode.isMissingNode()) {
pair.put(type, textNode.asText());
}
} else if (type.equals("image")) {
JsonNode srcNode = node.path("src");
if (!srcNode.isMissingNode()) {
pair.put(type, node.get("src").asText());
}
}
if (!pair.isEmpty()) {
keyValuePairs.add(pair);
}
}
return keyValuePairs;
}
}

View File

@@ -0,0 +1,19 @@
package com.realnet.FabricIcardLines.Entity;
import javax.persistence.Lob;
import lombok.Data;
@Data
public class Dummyfabric {
@Lob
private String json;
@Lob
private String xml;
}

View File

@@ -0,0 +1,41 @@
package com.realnet.FabricIcardLines.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.realnet.FabricIcard.Entity.FabricIcard;
import lombok.Data;
@Entity
@Data
public class FabricIcardLines {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String header_id;
private String file_path;
private String xml_file_name;
private String json_file_name;
@Lob
private String mapping_model;
@Lob
private String Model;
@Lob
private String layoutModel;
@JsonBackReference
@ManyToOne
private FabricIcard layoutBuilder_t;
}

View File

@@ -0,0 +1,15 @@
package com.realnet.FabricIcardLines.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.FabricIcardLines.Entity.FabricIcardLines;
@Repository
public interface FabricIcardLinesRepository extends JpaRepository<FabricIcardLines, Long> {
@Query(value = "select * from fabric_icard_lines where header_id=?1", nativeQuery = true)
FabricIcardLines getbyheaderId(String header_id);
}

View File

@@ -0,0 +1,109 @@
package com.realnet.FabricIcardLines.Services;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.realnet.FabricIcard.Entity.FabricIcard;
import com.realnet.FabricIcard.Repository.FabricIcardRepository;
import com.realnet.FabricIcardLines.Entity.FabricIcardLines;
import com.realnet.FabricIcardLines.Repository.FabricIcardLinesRepository;
@Service
public class FabricIcardLinesService {
@Value("${projectPath}")
private String projectpath;
@Autowired
private FabricIcardRepository fabricIcardRepository;
@Autowired
private FabricIcardLinesRepository Repository;
public FabricIcardLines Savedata(FabricIcardLines data) {
return Repository.save(data);
}
public List<FabricIcardLines> getdetails() {
return (List<FabricIcardLines>) Repository.findAll();
}
public FabricIcardLines getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public FabricIcardLines update(FabricIcardLines data, Long id) {
FabricIcardLines old = Repository.findById(id).get();
old.setHeader_id(data.getHeader_id());
old.setModel(data.getModel());
old.setLayoutModel(data.getLayoutModel());
old.setFile_path(data.getFile_path());
old.setXml_file_name(data.getXml_file_name());
old.setJson_file_name(data.getJson_file_name());
old.setMapping_model(data.getMapping_model());
final FabricIcardLines test = Repository.save(old);
return test;
}
// make xml file
public FabricIcardLines makexmlfile(String headerid, String xml, String json) throws IOException {
FabricIcard fabricIcard = fabricIcardRepository.findById(Long.valueOf(headerid)).get();
String name = fabricIcard.getName();
String xmlfileName = name + ".xml";
String jsonfileName = name + ".txt";
String filePath = Paths.get(xmlfileName).toString();
FileWriter fr = new FileWriter(filePath);
fr.write(xml);
fr.close();
String jsonfilePath = Paths.get(jsonfileName).toString();
FileWriter jsonfr = new FileWriter(jsonfilePath);
jsonfr.write(json);
jsonfr.close();
FabricIcardLines old = Repository.getbyheaderId(headerid);
old.setFile_path(projectpath);
old.setXml_file_name(xmlfileName);
old.setJson_file_name(jsonfileName);
old.setHeader_id(headerid);
final FabricIcardLines test = Repository.save(old);
return test;
}
// get by header id
public FabricIcardLines getbyheaderid(String id) {
return Repository.getbyheaderId(id);
}
// read file
public String readjson(String id) throws IOException {
FabricIcardLines fLines = Repository.getbyheaderId(id);
String file_path = fLines.getFile_path();
String json_file_name = fLines.getJson_file_name();
String pathString = file_path + File.separator + json_file_name;
String readFileToString = FileUtils.readFileToString(new File(pathString), StandardCharsets.UTF_8);
return readFileToString;
}
}

View File

@@ -0,0 +1,194 @@
package com.realnet.FileUpload.Controllers;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.realnet.FileUpload.Entity.Uploadeddocs;
import com.realnet.FileUpload.Services.FileuploadService;
import com.realnet.FileUpload.Services.UploadedFileService;
@RequestMapping(value = "/FileUpload")
//@CrossOrigin("*")
@RestController
public class UploadeddocsController {
@Autowired
private UploadedFileService Service;
@Value("${projectPath}")
private String projectPath;
@Autowired
private FileuploadService fileuploadService;
@PostMapping("/Uploadeddocs/{ref}/{table_name}")
public ResponseEntity<?> Savedata(@PathVariable String ref, @PathVariable String table_name,
@RequestParam MultipartFile file) throws JsonMappingException, JsonProcessingException {
Uploadeddocs tdata = new Uploadeddocs();
Date d = new Date();
String addString = "_" + d.getTime();
if (file.isEmpty()) {
return new ResponseEntity<>("file is empty", HttpStatus.BAD_REQUEST);
}
String UPLOAD_DIREC = File.separator + "Resources" + File.separator + "Files";
String originalFilename = file.getOriginalFilename();
String filetype = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + addString;
String replacedfilename = filename + filetype;
System.out.println("file name is ..." + replacedfilename);
Uploadeddocs save = null;
System.out.println(file.getOriginalFilename());
boolean f = fileuploadService.uploadFile(file, addString);
if (f) {
System.out.println("file uploaded successfully");
tdata.setUploadedfile_path(projectPath + UPLOAD_DIREC);
tdata.setUploadedfile_name(replacedfilename);
tdata.setRef(ref);
tdata.setRef_table_name(table_name);
save = Service.Savedata(tdata);
return new ResponseEntity<>(save, HttpStatus.OK);
}
else {
return new ResponseEntity<>("file upload failed", HttpStatus.BAD_REQUEST);
}
}
@PutMapping("/Uploadeddocs/{id}")
public Uploadeddocs update(@RequestBody Uploadeddocs data, @PathVariable Integer id) {
Uploadeddocs update = Service.update(data, id);
return update;
}
@GetMapping("/Uploadeddocs")
public List<Uploadeddocs> getdetails() {
List<Uploadeddocs> get = Service.getdetails();
return get;
}
@GetMapping("/Uploadeddocs/{id}")
public Uploadeddocs getdetailsbyId(@PathVariable Integer id) {
Uploadeddocs get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Uploadeddocs/{id}")
public void delete_by_id(@PathVariable Integer id) {
Service.delete_by_id(id);
}
// get by ref and ref table name
@GetMapping("/Uploadeddocs/{ref}/{ref_tablename}")
public List<Uploadeddocs> getbyrefandtablename(@PathVariable String ref, @PathVariable String ref_tablename) {
List<Uploadeddocs> get = Service.getbyrefandtablename(ref, ref_tablename);
return get;
}
@Autowired
private JdbcTemplate jdbcTemplate;
@PostMapping("/execute")
public ResponseEntity<String> executeDump(@RequestParam Boolean execute, @RequestParam String filePath) {
// Check if execution is allowed
if (!execute) {
return ResponseEntity.ok("Service not executed due to 'execute' flag being false.");
}
Path path = Paths.get(System.getProperty("user.dir")).resolve(filePath);
try {
// Check if file exists
if (!Files.exists(path)) {
return ResponseEntity.badRequest().body("File not found: " + filePath);
}
// File content ko read karo aur SQL commands extract karo
String sql = FileUtils.readFileToString(new File(filePath), StandardCharsets.UTF_8);
// SQL commands ko execute karo
// Split statements by semicolon
List<String> sqlStatements = Arrays.stream(sql.split(";")).map(String::trim)
.filter(statement -> !statement.isEmpty()) // Empty statements ko remove karo
.filter(statement -> !statement.startsWith("USE")) // "USE db;" ko ignore karo
.filter(statement -> !statement.startsWith("--")) // Comments ko ignore karo
.filter(statement -> !statement.startsWith("/*")) // Special MySQL commands ko ignore karo
.collect(Collectors.toList());
// Execute each statement
for (String statement : sqlStatements) {
try {
jdbcTemplate.execute(statement);
System.out.println(statement + " executed..");
} catch (DataAccessException e) {
// Specific SQL execution error ko catch karo aur log karo
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error executing statement: " + statement + " | Error: " + e.getMessage());
}
}
System.out.println("Dump executed executed..");
// File ko delete karo
Files.delete(path);
System.out.println("File delete successfully...");
return ResponseEntity.ok("Dump executed and file deleted successfully!");
} catch (IOException e) {
System.out.println("io error.." + e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("File reading/deletion error: " + e.getMessage());
} catch (DataAccessException e) {
System.out.println("DataAccessException error.." + e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("SQL execution error: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,25 @@
package com.realnet.FileUpload.Entity;
import lombok.*;
import javax.persistence.*;
import com.realnet.WhoColumn.Entity.Who_column;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Uploadeddocs extends Who_column {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String ref;
private String ref_table_name;
private String uploadedfile_name;
private String uploadedfile_path;
}

View File

@@ -0,0 +1,17 @@
package com.realnet.FileUpload.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.FileUpload.Entity.Uploadeddocs;
@Repository
public interface UploadFileRepository extends JpaRepository<Uploadeddocs, Integer> {
@Query(value = "select * from uploadeddocs where ref=?1 && ref_table_name=?2", nativeQuery = true)
List<Uploadeddocs> findbyrefAnsTableName(String ref, String ref_table_name);
}

View File

@@ -0,0 +1,66 @@
package com.realnet.FileUpload.Services;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class FileuploadService {
@Value("${projectPath}")
private String projectPath;
public boolean uploadFile(MultipartFile multipartFile, String addString) {
boolean f = false;
String UPLOAD_DIREC = File.separator + "Resources" + File.separator + "Files";
String originalFilename = multipartFile.getOriginalFilename();
String filetype = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + addString;
String replacedfilename = filename + filetype;
System.out.println("file name with replace is ..." + replacedfilename);
String Path1 = projectPath + UPLOAD_DIREC;
String filepath = Path1 + File.separator + replacedfilename;
try {
if (!UPLOAD_DIREC.isEmpty()) {
File projectdir = new File(Path1);
if (!projectdir.exists()) {
boolean mkdir = projectdir.mkdirs();
System.out.println(Path1 + " folder create = " + mkdir);
}
}
// reading data
InputStream is = multipartFile.getInputStream();
byte data[] = new byte[is.available()];
is.read(data);
// writing data
FileOutputStream fos = new FileOutputStream(filepath);
fos.write(data);
fos.close();
fos.flush();
f = true;
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
return f;
}
}

View File

@@ -0,0 +1,43 @@
package com.realnet.FileUpload.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.FileUpload.Entity.Uploadeddocs;
import com.realnet.FileUpload.Repository.UploadFileRepository;
@Service
public class UploadedFileService {
@Autowired
private UploadFileRepository Repository;
public Uploadeddocs Savedata(Uploadeddocs data) {
return Repository.save(data);
}
public List<Uploadeddocs> getdetails() {
return (List<Uploadeddocs>) Repository.findAll();
}
public Uploadeddocs getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Uploadeddocs update(Uploadeddocs data, Integer id) {
Uploadeddocs old = Repository.findById(id).get();
old.setUploadedfile_name(data.getUploadedfile_name());
final Uploadeddocs test = Repository.save(old);
return test;
}
// get by ref and table name
public List<Uploadeddocs> getbyrefandtablename(String ref, String ref_table_name) {
return (List<Uploadeddocs>) Repository.findbyrefAnsTableName(ref, ref_table_name);
}
}

View File

@@ -0,0 +1,54 @@
//package com.realnet.FileUpload.controller;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.multipart.MultipartFile;
//
//import com.realnet.fileupload.helper.Fileupload_helper;
//
//@RestController
//@RequestMapping("/sureserve/api")
//public class Filecontroller {
//
// @Autowired
// private Fileupload_helper fileuploadhelper;
//
// @PostMapping("/test")
// public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
//
// /*
// * System.out.println(file.getOriginalFilename());
// * System.out.println(file.getSize());
// * System.out.println(file.getContentType());
// */
//
// try {
//
// if (file.isEmpty()) {
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("must contain file");
// }
// /*
// * if(!file.getContentType().equals("image/png")) {
// *
// * return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).
// * body("must contain png format"); }
// */
//
// boolean f = fileuploadhelper.uploadFile(file);
// if (f) {
// return ResponseEntity.ok("File uploaded successfully");
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("something went wrong");
//
// }
//
//}

View File

@@ -0,0 +1,81 @@
package com.realnet.FileUpload.helper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class Fileupload_helper {
@Value("${projectPath}")
private String projectPath;
public final String UPLOAD_DIREC = "/Files";
public boolean uploadFile(MultipartFile multipartFile) {
boolean f = false;
try {
File path = new File(projectPath + UPLOAD_DIREC);
File FileParentDir = new File(path.toString());
if (!FileParentDir.exists()) {
FileParentDir.mkdirs();
}
// reading data
InputStream is = multipartFile.getInputStream();
byte data[] = new byte[is.available()];
is.read(data);
// writing data
FileOutputStream fos = new FileOutputStream(
projectPath + UPLOAD_DIREC + File.separator + multipartFile.getOriginalFilename());
fos.write(data);
fos.close();
fos.flush();
f = true;
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
public boolean uploadFilewithtimestamp(MultipartFile multipartFile, String timestamp) {
boolean f = false;
try {
File path = new File(projectPath + UPLOAD_DIREC);
File FileParentDir = new File(path.toString());
if (!FileParentDir.exists()) {
FileParentDir.mkdirs();
}
// reading data
InputStream is = multipartFile.getInputStream();
byte data[] = new byte[is.available()];
is.read(data);
// writing data
FileOutputStream fos = new FileOutputStream(
projectPath + UPLOAD_DIREC + File.separator + timestamp + multipartFile.getOriginalFilename());
fos.write(data);
fos.close();
fos.flush();
f = true;
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
}

View File

@@ -0,0 +1,95 @@
package com.realnet.FromExtensionJson.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.FromExtensionJson.Entity.FromExtensionJson_t;
import com.realnet.FromExtensionJson.Repository.FromExtensionJson_Repository;
import com.realnet.FromExtensionJson.Services.FromExtensionJson_Service;
@RequestMapping(value = "/FromExtensionJson")
@RestController
public class FromExtensionJson_Controller {
@Autowired
private FromExtensionJson_Service Service;
@Autowired
private FromExtensionJson_Repository extensionJson_Repository;
@PostMapping("/ExtensionJson")
public FromExtensionJson_t Savedata(@RequestBody FromExtensionJson_t data) {
FromExtensionJson_t save = Service.Savedata(data);
return save;
}
@GetMapping("/ExtensionJson")
public List<FromExtensionJson_t> getdetails() {
List<FromExtensionJson_t> get = Service.getdetails();
return get;
}
@GetMapping("/ExtensionJson/{id}")
public FromExtensionJson_t getdetailsbyId(@PathVariable Long id) {
FromExtensionJson_t get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/ExtensionJson/{id}")
public void delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
}
@PutMapping("/ExtensionJson/{id}")
public FromExtensionJson_t update(@RequestBody FromExtensionJson_t data, @PathVariable Long id) {
FromExtensionJson_t update = Service.update(data, id);
return update;
}
@GetMapping("/ExtensionJson/{formCode}")
public ResponseEntity<String> getdetailsbyFormcode(@PathVariable String formCode) {
FromExtensionJson_t get = extensionJson_Repository.getdetailsbyFormCode(formCode);
// return get;
if (get != null) {
String jsonObject = get.getJsonObject();
return ResponseEntity.ok().body(jsonObject);
} else {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/ListExtensionJson/{formCode}")
public ResponseEntity<List<String>> getJsonObjectsByFormCodeList(@PathVariable String formCode) {
List<String> jsonObjects = extensionJson_Repository.getJsonObjectsByFormCode(formCode);
if (!jsonObjects.isEmpty()) {
return ResponseEntity.ok().body(jsonObjects);
} else {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,20 @@
package com.realnet.FromExtensionJson.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class FromExtensionJson_t{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String form_code;
private String account_id;
@Lob
private String jsonObject;
}

View File

@@ -0,0 +1,23 @@
package com.realnet.FromExtensionJson.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.FromExtensionJson.Entity.FromExtensionJson_t;
@Repository
public interface FromExtensionJson_Repository extends JpaRepository<FromExtensionJson_t, Long> {
@Query(value="SELECT * FROM from_extension_json_t WHERE form_code = ?1", nativeQuery = true)
FromExtensionJson_t getdetailsbyFormCode(String formCode);
@Query(value = "SELECT json_object FROM from_extension_json_t WHERE form_code = ?1", nativeQuery = true)
List<String> getJsonObjectsByFormCode(String formCode);
}

View File

@@ -0,0 +1,39 @@
package com.realnet.FromExtensionJson.Services;
import com.realnet.FromExtensionJson.Repository.FromExtensionJson_Repository;
import com.realnet.FromExtensionJson.Entity.FromExtensionJson_t;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FromExtensionJson_Service {
@Autowired
private FromExtensionJson_Repository Repository;
public FromExtensionJson_t Savedata(FromExtensionJson_t data) {
return Repository.save(data);
}
public List<FromExtensionJson_t> getdetails() {
return (List<FromExtensionJson_t>) Repository.findAll();
}
public FromExtensionJson_t getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public FromExtensionJson_t update(FromExtensionJson_t data, Long id) {
FromExtensionJson_t old = Repository.findById(id).get();
old.setForm_code(data.getForm_code());
old.setAccount_id(data.getAccount_id());
old.setJsonObject(data.getJsonObject());
final FromExtensionJson_t test = Repository.save(old);
return test;
}
}

View File

@@ -1,9 +1,11 @@
package com.realnet.Gaurav_testing.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data

View File

@@ -0,0 +1,28 @@
package com.realnet.MultiTimeZone.Services;
import org.springframework.stereotype.Service;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
@Service
public class TimezoneService {
public ZonedDateTime convertToUserTimezone(Date date, String userTimezone) {
ZoneId targetZoneId;
// Default timezone is UTC
if (userTimezone == null || userTimezone.isEmpty()) {
targetZoneId = ZoneId.of("UTC");
} else {
targetZoneId = ZoneId.of(userTimezone);
}
// Convert Date to ZonedDateTime in UTC
ZonedDateTime utcZonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"));
// Convert to target timezone
return utcZonedDateTime.withZoneSameInstant(targetZoneId);
}
}

View File

@@ -0,0 +1,36 @@
package com.realnet.Notification.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.Notification.Entity.NotEntity;
import com.realnet.Notification.Repository.NotRepo;
@RestController
@RequestMapping("/notification")
public class NotController {
@Autowired
private NotRepo notRepo;
// @PostMapping("/save_notification")
// public NotEntity Savedata(@RequestBody NotEntity entity) {
// NotEntity dash = notRepo.save(entity) ;
// return dash;
// }
@GetMapping("/get_notification")
public List<NotEntity> getdetails() {
List<NotEntity> dash = notRepo.findTopByOrderByd();
return dash;
}
}

View File

@@ -0,0 +1,21 @@
package com.realnet.Notification.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class NotEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String notification;
private String time;
private Long user_id;
}

View File

@@ -0,0 +1,40 @@
package com.realnet.Notification.Entity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.realnet.Notification.Repository.NotRepo;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
@Service
public class NotificationService {
@Autowired
private NotRepo notRepo;
@Autowired
private AppUserServiceImpl userService;
public ResponseEntity<?> setnotification(String jobType, String wireframeName) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
AppUser loggedInUser = userService.getLoggedInUser();
NotEntity notEntity = new NotEntity();
notEntity.setTime(dateFormat.format(cal.getTime()));
notEntity.setNotification(loggedInUser.getUsername() + jobType + wireframeName);
notEntity.setUser_id(loggedInUser.getUserId());
notRepo.save(notEntity);
return new ResponseEntity<>("notification set", HttpStatus.CREATED);
}
}

View File

@@ -0,0 +1,18 @@
package com.realnet.Notification.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.Notification.Entity.NotEntity;
@Repository
public interface NotRepo extends JpaRepository<NotEntity, Long>{
@Query(value = "select * from not_entity order by id desc limit 10", nativeQuery = true)
List<NotEntity> findTopByOrderByd();
}

View File

@@ -0,0 +1,7 @@
package com.realnet.Payment.Paytm;
public class AppConfig {
public static final String MID="RHLBnF070397707073";
public static final String MKEY="BXWmXtYo858BTG";
public static final String WEBSITE="WEBSTAGING";
}

View File

@@ -0,0 +1,19 @@
//package com.realnet.Payment.Paytm;
//
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//
//@Controller
//public class PaytmPageController {
// @RequestMapping("/")
// public String homePage() {
// System.out.println("Request for home page");
// return "home";
// }
// @RequestMapping("/about")
// public String aboutPage() {
// System.out.println("Request for about page");
// return "about";
// }
//
//}

View File

@@ -0,0 +1,105 @@
package com.realnet.Payment.Paytm;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Map;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.paytm.pg.merchant.PaytmChecksum;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaytmPayment {
@PostMapping("/start")
public Map<String, Object> startPayment(@RequestBody Map<String, Object> data) {
SecureRandom random = new SecureRandom();
String orderId = "ORDER" + random.nextInt(10000000);
// param created
JSONObject paytmParams = new JSONObject();
// body information
JSONObject body = new JSONObject();
body.put("requestType", "Payment");
body.put("mid", AppConfig.MID);
body.put("websiteName", AppConfig.WEBSITE);
body.put("orderId", orderId);
body.put("callbackUrl", "http://localhost:8081/payment-success");
JSONObject txnAmount = new JSONObject();
txnAmount.put("value", data.get("amount"));
txnAmount.put("currency", "INR");
JSONObject userInfo = new JSONObject();
userInfo.put("custId", "CUST_001");
body.put("txnAmount", txnAmount);
body.put("userInfo", userInfo);
String responseData = "";
ResponseEntity<Map> response = null;
try {
String checksum = PaytmChecksum.generateSignature(body.toString(), AppConfig.MKEY);
JSONObject head = new JSONObject();
head.put("signature", checksum);
paytmParams.put("body", body);
paytmParams.put("head", head);
String post_data = paytmParams.toString();
/* for Staging */
URL url = new URL("https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=" + AppConfig.MID
+ "&orderId=" + orderId + "");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paytmParams.toMap(), headers);
// calling api
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.postForEntity(url.toString(), httpEntity, Map.class);
System.out.println(response);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
Map body1 = response.getBody();
body1.put("orderId", orderId);
body1.put("amount", txnAmount.get("value"));
return body1;
}
public void capturePayment() {
// get the data from client
// verify the payment
// database mein bhi update kar do ki payment ho chuka hai...
// allow user to access the service
}
}

View File

@@ -0,0 +1,89 @@
package com.realnet.Payment.Razorpay;
import com.razorpay.*;
import lombok.RequiredArgsConstructor;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.UUID;
@RestController
@RequiredArgsConstructor
@RequestMapping("/payment/razorpay")
public class RazorpayController {
@Autowired
private RazorpayRepo repo;
@Value("${razorpay.api.key}")
private String razorpayApiKey;
@Value("${razorpay.api.secret}")
private String razorpayApiSecret;
@PostMapping("/create-order")
public void payOrder(@RequestBody Map<String, Object> data) throws RazorpayException {
int amt = Integer.parseInt(data.get("amount").toString());
amt = 50;
RazorpayClient razorpayClient = new RazorpayClient(razorpayApiKey, razorpayApiSecret);
String trnx = UUID.randomUUID().toString();
JSONObject orderDetails = createOrderJSON(amt, "INR", "_INV/0001/2023");
Order order = razorpayClient.orders.create(orderDetails);
System.out.println(order);
// Taking record into Our database
RazorpayDTO dto = RazorpayDTO.builder().orderId(order.get("order_id")).bodyField(String.valueOf(order)).build();
repo.save(dto);
}
@PostMapping("/verify-payment")
public ResponseEntity<String> verifyPayment(@RequestParam("orderId") JSONObject orderId) {
try {
RazorpayClient razorpayClient = new RazorpayClient(razorpayApiKey, razorpayApiSecret);
Payment payment = razorpayClient.payments.fetch(orderId.get("order_id").toString());
boolean isSignatureValid = Utils.verifyPaymentSignature(orderId, razorpayApiSecret);
if (payment != null && payment.get("status").equals("captured") && isSignatureValid) {
return ResponseEntity.ok("Payment successfully verified.");
} else {
return ResponseEntity.badRequest().body("Payment verification failed.");
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred during payment verification.");
}
}
@PostMapping("update-order")
public ResponseEntity<?> updateOrder(@RequestBody Map<String, Object> data) {
RazorpayDTO current_order = repo.findByOrderId(data.get("order_id").toString());
current_order.setBodyField(data.toString());
repo.save(current_order);
// return ResponseEntity.ok(Map.of("msg", "updated"));
return ResponseEntity.ok("updated");
}
public JSONObject createOrderJSON(Integer amount, String currency, String trxnId) {
JSONObject options = new JSONObject();
options.put("amount", amount * 100); // amount in paise = Rs*100
options.put("currency", currency);
options.put("receipt", trxnId);
return options;
}
}

View File

@@ -0,0 +1,27 @@
package com.realnet.Payment.Razorpay;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.UUID;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class RazorpayDTO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String orderId;
private String bodyField;
}

View File

@@ -0,0 +1,9 @@
package com.realnet.Payment.Razorpay;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RazorpayRepo extends JpaRepository<RazorpayDTO,Long> {
RazorpayDTO findByOrderId(String orderId);
}

View File

@@ -23,13 +23,9 @@ public class RealNetApp extends SpringBootServletInitializer{
//
public static void main(String[] args) {
SpringApplication.run(RealNetApp.class, args);
}
}
/*
SpringBoot Notes
@Bean :tells Spring 'here is an instance of this class, please keep hold of it and give it back to me when I ask'.
@Autowired :says 'please give me an instance of this class, for example, one that I created with an @Bean annotation earlier'.
*/

View File

@@ -0,0 +1,229 @@
package com.realnet.Rpt_builder.Controllers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
@RestController
@RequestMapping("/rbbuilder/fileconverter")
public class FileConverterController {
// @PostMapping("/downloadCsv")
// public ResponseEntity<String> downloadCSV(@RequestBody List<Map<String, Object>> dataList) {
// try {
// // Convert dataList to CSV format and provide download
// String csvContent = convertToCSV(dataList);
//
// // Set headers for response
// HttpHeaders headers = new HttpHeaders();
// headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.csv");
//
// // Send the CSV content as a response
// return new ResponseEntity<>(csvContent, headers, HttpStatus.OK);
// } catch (IOException e) {
// // Handle exception
// return new ResponseEntity<>("Error occurred while processing data", HttpStatus.INTERNAL_SERVER_ERROR);
// }
// }
//
// private String convertToCSV(List<Map<String, Object>> dataList) throws IOException {
// StringWriter writer = new StringWriter();
// CSVWriter csvWriter = new CSVWriter(writer);
//
// // Write headers
// if (!dataList.isEmpty()) {
// Map<String, Object> firstRow = dataList.get(0);
// String[] headers = firstRow.keySet().toArray(new String[0]);
// csvWriter.writeNext(headers);
//
// // Write data
// for (Map<String, Object> data : dataList) {
// String[] rowData = new String[headers.length];
// for (int i = 0; i < headers.length; i++) {
// Object value = data.get(headers[i]);
// rowData[i] = (value != null) ? value.toString() : "";
// }
// csvWriter.writeNext(rowData);
// }
// }
//
// // Close CSV writer
// csvWriter.close();
//
// return writer.toString();
// }
@PostMapping("/downloadFile/{format}")
public ResponseEntity<?> downloadFile(@RequestBody List<Map<String, Object>> dataList,@PathVariable String format) {
try {
// Convert dataList to the requested format
byte[] fileContent;
String fileName;
String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
if ("csv".equalsIgnoreCase(format)) {
fileContent = convertToCSV(dataList).getBytes();
fileName = "data_" + timestamp + ".csv";
} else if ("excel".equalsIgnoreCase(format)) {
fileContent = convertToExcel(dataList);
fileName = "data_" + timestamp + ".xlsx";
} else if ("pdf".equalsIgnoreCase(format)) {
fileContent = convertToPDF(dataList);
fileName = "data_" + timestamp + ".pdf";
} else {
return new ResponseEntity<>("Unsupported file format", HttpStatus.BAD_REQUEST);
}
// Set headers for response
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
// Send the file content as a response
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
} catch (IOException e) {
// Handle exception
return new ResponseEntity<>("Error occurred while processing data", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private String convertToCSV(List<Map<String, Object>> dataList) throws IOException {
StringWriter writer = new StringWriter();
CSVWriter csvWriter = new CSVWriter(writer);
// Write headers
if (!dataList.isEmpty()) {
Map<String, Object> firstRow = dataList.get(0);
String[] headers = firstRow.keySet().toArray(new String[0]);
csvWriter.writeNext(headers);
// Write data
for (Map<String, Object> data : dataList) {
String[] rowData = new String[headers.length];
for (int i = 0; i < headers.length; i++) {
Object value = data.get(headers[i]);
rowData[i] = (value != null) ? value.toString() : "";
}
csvWriter.writeNext(rowData);
}
}
// Close CSV writer
csvWriter.close();
return writer.toString();
}
private byte[] convertToExcel(List<Map<String, Object>> dataList) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data");
// Write headers
if (!dataList.isEmpty()) {
Row headerRow = sheet.createRow(0);
Map<String, Object> firstRow = dataList.get(0);
int cellIndex = 0;
for (String header : firstRow.keySet()) {
Cell cell = headerRow.createCell(cellIndex++);
cell.setCellValue(header);
}
// Write data
int rowIndex = 1;
for (Map<String, Object> data : dataList) {
Row dataRow = sheet.createRow(rowIndex++);
int columnIndex = 0;
for (Object value : data.values()) {
Cell cell = dataRow.createCell(columnIndex++);
if (value != null) {
if (value instanceof Number) {
cell.setCellValue(((Number) value).doubleValue());
} else {
cell.setCellValue(value.toString());
}
}
}
}
}
// Convert workbook to byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
workbook.close();
return outputStream.toByteArray();
}
private byte[] convertToPDF(List<Map<String, Object>> dataList) throws IOException {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PDDocument document = new PDDocument()) {
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// Set font and size (you can customize these)
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
float margin = 50;
float yStart = page.getMediaBox().getHeight() - margin;
float tableWidth = page.getMediaBox().getWidth() - 2 * margin;
float yPosition = yStart;
// Write headers
Map<String, Object> firstRow = dataList.get(0);
int numberOfColumns = firstRow.size();
float tableHeight = 20f; // Height of the table (you can adjust this)
// Set column widths
float[] columnWidths = new float[numberOfColumns];
float tableHeightStart = yStart - 2 * tableHeight;
float nextXStart = margin;
for (int i = 0; i < numberOfColumns; i++) {
columnWidths[i] = tableWidth / (float) numberOfColumns;
}
// Write data
for (Map<String, Object> data : dataList) {
contentStream.beginText();
contentStream.newLineAtOffset(nextXStart, yPosition);
int columnIndex = 0;
for (Object value : data.values()) {
contentStream.showText(value != null ? value.toString() : "");
contentStream.newLineAtOffset(columnWidths[columnIndex], 0);
columnIndex++;
}
contentStream.endText();
yPosition -= tableHeight;
}
}
document.save(byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
// Handle PDF creation exception
return new byte[0];
}
}
}

Some files were not shown because too many files have changed in this diff Show More