base_project

This commit is contained in:
2026-01-28 06:45:43 +00:00
commit 9860ff7374
1843 changed files with 119930 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
package com.realnet.Accesstype_back.Controllers;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.realnet.Accesstype_back.Entity.Accesstype;
import com.realnet.Accesstype_back.Services.AccesstypeService;
import com.realnet.fnd.response.EntityResponse;
@RequestMapping(value = "/access_type")
@RestController
public class AccesstypeController {
@Autowired
private AccesstypeService Service;
// add data
@PostMapping("/Accesstype")
public Accesstype Savedata(@RequestBody Accesstype data) throws JsonProcessingException {
Accesstype save = Service.Savedata(data);
return save;
}
// get all
@GetMapping("/Accesstype")
public List<Accesstype> getdetails() {
List<Accesstype> get = Service.getdetails();
return get;
}
// getby id
@GetMapping("/Accesstype/{id}")
public Accesstype getdetailsbyId(@PathVariable Long id) {
Accesstype get = Service.getdetailsbyId(id);
return get;
}
// update by id
@PutMapping("/Accesstype/{id}")
public Accesstype update(@RequestBody Accesstype data, @PathVariable Long id) {
Accesstype update = Service.update(data, id);
return update;
}
// delete by id
@DeleteMapping("/Accesstype/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
return new ResponseEntity<>(new EntityResponse("deleted"), HttpStatus.OK);
}
}

View File

@@ -0,0 +1,30 @@
package com.realnet.Accesstype_back.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.Accesstype_back.Entity.Agyana;
import com.realnet.Accesstype_back.Repository.AgyanaRepository;
@RequestMapping(value = "/token/access_type")
@RestController
public class AgyanaController {
@Autowired
private AgyanaRepository agyanaRepository;
@GetMapping("/agyana")
public List<Agyana> getAlldetails() {
List<Agyana> get = getdetails();
return get;
}
public List<Agyana> getdetails() {
return (List<Agyana>) agyanaRepository.findAll();
}
}

View File

@@ -0,0 +1,51 @@
package com.realnet.Accesstype_back.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.RestController;
import com.realnet.Accesstype_back.Entity.Arani;
import com.realnet.Accesstype_back.Services.AraniService;
@RestController
public class AraniController {
@Autowired
private AraniService service;
@GetMapping("/Arani")
public List<Arani> getAlldetails(){
List<Arani> get = service.getAll();
return get;
}
@GetMapping("/Arani/{id}")
public Arani getAlldetails(@PathVariable Long id) {
Arani get = service.getdetailsbyid(id);
return get;
}
@PostMapping("/Arani")
public Arani saverani(@RequestBody Arani rani) {
Arani saverani = service.saverani(rani);
return saverani;
}
@DeleteMapping("/Arani/{id}")
public void delete_by_id(@PathVariable Long id) {
service.delete_by_id(id);
}
@PutMapping("/Arani/{id}")
public Arani update(@RequestBody Arani data, @PathVariable Long id) {
Arani update = service.update(data, id);
return update;
}
}

View File

@@ -0,0 +1,68 @@
package com.realnet.Accesstype_back.Controllers;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.realnet.Accesstype_back.Entity.Accesstype;
import com.realnet.Accesstype_back.Services.AccesstypeService;
@RequestMapping(value = "/token/access_type")
@RestController
public class TokenFreeAccesstypeController {
@Autowired
private AccesstypeService Service;
// @Autowired
// private Workflow_service workflow_service;
//add data
@PostMapping("/Accesstype")
public Accesstype Savedata(@RequestBody Accesstype data) throws JsonProcessingException {
Accesstype save = Service.Savedata(data);
// workflow_service.save_webhook(data, "post", "Accesstype");
return save;
}
//get all
@GetMapping("/Accesstype")
public List<Accesstype> getdetails() {
List<Accesstype> get = Service.getdetails();
return get;
}
//getby id
@GetMapping("/Accesstype/{id}")
public Accesstype getdetailsbyId(@PathVariable Long id) {
Accesstype get = Service.getdetailsbyId(id);
return get;
}
//update by id
@PutMapping("/Accesstype/{id}")
public Accesstype update(@RequestBody Accesstype data, @PathVariable Long id) {
Accesstype update = Service.update(data, id);
return update;
}
//delete by id
@DeleteMapping("/Accesstype/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Long id) {
Service.delete_by_id(id);
return new ResponseEntity<>("deleted",HttpStatus.OK);
}
}

View File

@@ -0,0 +1,19 @@
package com.realnet.Accesstype_back.Entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Accesstype{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private boolean defaultvalue;
}

View File

@@ -0,0 +1,27 @@
package com.realnet.Accesstype_back.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Agyana {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String mark;
private Date timestamp;
private String mark2;
}

View File

@@ -0,0 +1,22 @@
package com.realnet.Accesstype_back.Entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Arani {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String address;
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,49 @@
package com.realnet.Accesstype_back.Services;
import com.realnet.Accesstype_back.Repository.AccesstypeRepository;
//import com.realnet.AudiTrail.Service.AuditrailService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.realnet.Accesstype_back.Entity.Accesstype;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccesstypeService {
@Autowired
private AccesstypeRepository Repository;
// @Autowired
// private AuditrailService auditrailService;
public Accesstype Savedata(Accesstype data) {
return Repository.save(data);
}
public List<Accesstype> getdetails() {
return (List<Accesstype>) Repository.findAll();
}
public Accesstype getdetailsbyId(Long id) {
return Repository.findById(id).get();
}
public void delete_by_id(Long id) {
Repository.deleteById(id);
}
public Accesstype update(Accesstype data, Long id) {
Accesstype old = Repository.findById(id).get();
old.setName(data.getName());
old.setDescription(data.getDescription());
final Accesstype test = Repository.save(old);
// try {
// auditrailService.saveaudiTrail_t(old, test,"Accesstype");
// } catch (JsonProcessingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
return test;
}
}

View File

@@ -0,0 +1,44 @@
package com.realnet.Accesstype_back.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.Accesstype_back.Entity.Arani;
import com.realnet.Accesstype_back.Repository.AraniRepository;
@Service
public class AraniService {
@Autowired
private AraniRepository repo;
public List<Arani> getAll() {
return (List<Arani>) repo.findAll();
}
public Arani getdetailsbyid(Long id) {
return repo.findById(id).get();
}
public Arani saverani(Arani rani){
Arani saverani = repo.save(rani);
return saverani;
}
public void delete_by_id(Long id) {
repo.deleteById(id);
}
public Arani update(Arani data, Long id) {
Arani old = repo.findById(id).get();
old.setName(data.getName());
old.setEmail(data.getEmail());
old.setAddress(data.getAddress());
final Arani test = repo.save(old);
return test;
}
}

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 AND 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,130 @@
package com.realnet.Builders.Services;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Service;
@Service
public class SqlDumpExecutor {
/**
* Executes a massive SQL dump safely.
*
* @param connection JDBC connection
* @param sqlDump Full SQL dump string from getSql()
*/
public void executeDump(Connection connection, String sqlDump) {
Statement stmt = null;
try {
stmt = connection.createStatement();
connection.setAutoCommit(false);
// Remove MySQL backticks
sqlDump = sqlDump.replaceAll("`", "");
// Remove table-level DEFAULT COLLATE or CHARSET
sqlDump = sqlDump.replaceAll("(?i)DEFAULT\\s+CHARSET=[^;\\n]+", "");
sqlDump = sqlDump.replaceAll("(?i)COLLATE=[^;\\n]+", "");
// Convert data types
sqlDump = sqlDump.replaceAll("(?i)bigint", "INTEGER");
sqlDump = sqlDump.replaceAll("(?i)int\\([0-9]+\\)", "INTEGER");
sqlDump = sqlDump.replaceAll("(?i)varchar\\([0-9]+\\)", "TEXT");
sqlDump = sqlDump.replaceAll("(?i)bit\\([0-9]+\\)", "INTEGER");
sqlDump = sqlDump.replaceAll("(?i)longblob", "BLOB");
// Remove AUTO_INCREMENT (if any)
sqlDump = sqlDump.replaceAll("(?i)AUTO_INCREMENT", "");
// Remove MySQL-specific directives
sqlDump = sqlDump.replaceAll("(?i)SET\\s+[^;]+;", "");
sqlDump = sqlDump.replaceAll("(?i)ENGINE=\\w+\\s*", "");
sqlDump = sqlDump.replaceAll("(?i)AUTO_INCREMENT=\\d+", "");
sqlDump = sqlDump.replaceAll("(?i)CHARSET=\\w+", "");
// Remove DEFAULT NULL (SQLite allows NULL by default)
sqlDump = sqlDump.replaceAll("(?i)DEFAULT NULL", "");
// Convert UNIQUE KEY <name> to UNIQUE
sqlDump = sqlDump.replaceAll("(?i)UNIQUE KEY [^\\(]+\\(", "UNIQUE(");
// Remove double commas in CREATE TABLE (,,)
sqlDump = sqlDump.replaceAll(",\\s*,", ",");
// Remove _binary prefix in INSERT statements
sqlDump = sqlDump.replaceAll("(?i)_binary\\s+'", "'");
String delimiter = ";"; // default delimiter
StringBuilder sqlStatement = new StringBuilder();
String[] lines = sqlDump.split("\\r?\\n");
for (String line : lines) {
line = line.trim();
// Skip empty lines and comments
if (line.isEmpty() || line.startsWith("--") || line.startsWith("//") || line.startsWith("/*")) {
continue;
}
// Detect DELIMITER changes (optional, mostly MySQL)
if (line.startsWith("DELIMITER ")) {
delimiter = line.substring("DELIMITER ".length()).trim();
continue;
}
// Remove MySQL-specific comments like /*! ... */
line = line.replaceAll("/\\*!.*?\\*/", "").trim();
if (line.isEmpty())
continue;
sqlStatement.append(line).append(" ");
// Check if statement ends with current delimiter
if (sqlStatement.toString().trim().endsWith(delimiter)) {
String finalSql = sqlStatement.toString().trim();
// Remove the delimiter from the end
if (delimiter.length() > 0 && finalSql.endsWith(delimiter)) {
finalSql = finalSql.substring(0, finalSql.length() - delimiter.length()).trim();
}
try {
stmt.execute(finalSql);
} catch (SQLException e) {
System.err.println("Failed SQL: " + finalSql);
e.printStackTrace();
}
sqlStatement.setLength(0); // reset for next statement
}
}
connection.commit();
} catch (Exception e) {
System.err.println("Error executing SQL dump: " + e.getMessage());
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException ex) {
System.err.println("Rollback failed: " + ex.getMessage());
}
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

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,180 @@
package com.realnet.Communication.Services;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
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.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.realnet.config.EmailService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.utils.Port_Constant;
@Service
public class EmailNotificationService {
@Autowired
private EmailService emailService;
@Autowired
private AppUserServiceImpl userService;
public void sendDirectEmail(String email, String subject, String message) throws JsonProcessingException {
// Call the sendSimpleMessage method from EmailService
emailService.sendSimpleMessage(null, email, subject, message);
}
public void sendmailViaSetu(String email, String Name, String type) {
// Call the method from EmailCommunicationService
switch (type) {
case "TeamMember":
sendEmailTeamMember(email, Name);
break;
case "WorkSpaceUser":
sendEmailtoWorkUser(email, Name);
break;
case "AddProject":
sendEmailAfterAddPrj(email, Name);
break;
case "CopyProject":
sendEmailAfterCopyPrj(email, Name);
break;
case "CreateWireframe":
sendEmailAfterCopyPrj(email, Name);
break;
default:
break;
}
}
// for sending mail to team member
public ResponseEntity<?> sendEmailTeamMember(String email, String FullName) {
// Call the method from EmailCommunicationService
String subject = "Team Added to Workspace";
String message = "Dear " + FullName + ",\n\nYou have been added to the workspace.";
String templateName = "addproject";
String gatewayName = "ganesh";
// Sending the email via Setu
ResponseEntity<?> responseEntity = sendEmailViaSetu(email, message, templateName, gatewayName);
return responseEntity;
}
// for sending mail to Sec workspace User
public ResponseEntity<?> sendEmailtoWorkUser(String email, String FullName) {
// Call the method from EmailCommunicationService
String subject = "Workspace Access Granted";
String message = "Dear " + FullName + ",\n\nYou have been granted access to the workspace.";
String templateName = "addproject"; // Replace with actual template name
String gatewayName = "ganesh"; // Replace with actual gateway name
// Sending the email via Setu
return sendEmailViaSetu(email, message, templateName, gatewayName);
}
// for sending mail After Add project
public ResponseEntity<?> sendEmailAfterAddPrj(String email, String Name) {
// Call the method from EmailCommunicationService
String subject = "Add Project";
String message = "Project " + Name + " has been created successfully.";
String templateName = "addproject"; // Replace with actual template name
String gatewayName = "ganesh"; // Replace with actual gateway name
// Sending the email via Setu
return sendEmailViaSetu(email, message, templateName, gatewayName);
}
// for sending mail After Copy project
public ResponseEntity<?> sendEmailAfterCopyPrj(String email, String Name) {
// Call the method from EmailCommunicationService
String subject = "Copy Project";
String message = "Project " + Name + " has been Copied successfully.";
String templateName = "addproject"; // Replace with actual template name
String gatewayName = "ganesh"; // Replace with actual gateway name
// Sending the email via Setu
return sendEmailViaSetu(email, message, templateName, gatewayName);
}
// for sending mail After create Wireframe
public ResponseEntity<?> sendEmailAfterCreateWireframe(String email, String Name) {
// Call the method from EmailCommunicationService
String subject = "Create Wireframe";
String message = "A new wireframe has been successfully added to your project.";
String templateName = "addproject"; // Replace with actual template name
String gatewayName = "ganesh"; // Replace with actual gateway name
// Sending the email via Setu
return sendEmailViaSetu(email, message, templateName, gatewayName);
}
// send mail via setu
public ResponseEntity<?> sendEmailViaSetu(String email, String message, String templateName, String gatewayName)
throws ResourceAccessException {
// template name = notification_template, gateway name = email_gateway
try {
String jsonData = "{\r\n" + " \"job_type\": \"Email\",\r\n" + " \"send_to\": \"" + email.trim()
+ "\",\r\n" + " \"cc\": \"cc@example.com\",\r\n"
// + " \"attachment\": \"sample-file.txt\",\r\n"
+ " \"gatewaydone\": \"N\",\r\n" + " \"template_name\": \"" + templateName.trim() + "\",\r\n"
+ " \"replacement_string\": \"Hello, {name} " + message + "!\",\r\n" + " \"gatewayName\": \""
+ gatewayName.trim() + "\"\r\n" + "}\r\n";
HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
queryParams.add("data", jsonData);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(queryParams, headers);
String apiUrl2 = Port_Constant.SURE_SETU_DOMAIN
+ "/token/Surecommunication/communication/jobtable/Com_jobTable"; // Replace with the
// actual API URL
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl2, requestEntity, String.class);
return ResponseEntity.ok(responseEntity.getBody());
} catch (ResourceAccessException e) {
throw new ResourceAccessException("communication server no start..." + e);
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

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,48 @@
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;
@Column(length = 5000)
private String common_filter;
@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,84 @@
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());
oldline.setCommon_filter(dashbord1_Line.getCommon_filter());
final Dashbord1_Line newline = dashboard_lineRepository.save(oldline);
return newline;
}
}

View File

@@ -0,0 +1,510 @@
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.SureConnect.Entities.Sure_Connect;
import com.realnet.SureConnect.Service.SureService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequestMapping("/chart")
@RestController
public class ChartBuilder {
@Autowired
private SureService sureService;
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;
}
@GetMapping(value = "/getValue")
public ResponseEntity<?> getValue(@RequestParam String apiUrl, @RequestParam Integer sureId,
@RequestParam(required = false) String key) throws IOException {
System.out.println(" value get..");
// Step 1: Fetch all table data from API
List<Map<String, Object>> tableData = getAllDataFromApi(apiUrl, sureId);
// Step 2: Handle null or empty key
if (key == null || key.trim().isEmpty()) {
return ResponseEntity.badRequest().body("Key parameter is required");
}
// Step 3: Extract unique values for that key
Set<Object> uniqueValues = tableData.stream().map(row -> row.get(key)) // get value by key
.filter(Objects::nonNull) // remove nulls
.collect(Collectors.toCollection(LinkedHashSet::new)); // keep unique + order
// Step 4: Convert to List
List<Object> resultList = new ArrayList<>(uniqueValues);
// Step 5: Return as ResponseEntity
return ResponseEntity.ok(resultList);
}
@GetMapping(value = "/getdashjson/{job_type}")
public ResponseEntity<?> jsonretun(@PathVariable String job_type, @RequestParam String tableName,
@RequestParam(required = false) String xAxis, @RequestParam(required = false) List<String> yAxes,
@RequestParam Integer sureId, @RequestParam(required = false) String parameter,
@RequestParam(required = false) String parameterValue, @RequestParam(required = false) String filters)
throws IOException {
System.out.println(" chart data getting...");
List<Map<String, Object>> tableData = getAllDataFromApi(tableName, sureId); // Retrieve all data from the table
// ✅ Filter table data if parameter and parameterValue are provided
if (parameter != null && !parameter.trim().isEmpty() && parameterValue != null
&& !parameterValue.trim().isEmpty()) {
tableData = tableData.stream().filter(row -> {
Object paramVal = row.get(parameter);
return paramVal != null && paramVal.toString().equalsIgnoreCase(parameterValue);
}).collect(Collectors.toList());
}
ObjectMapper mapper = new ObjectMapper();
// ✅ Parse filters JSON (supports both string and array values)
if (filters != null && !filters.trim().isEmpty()) {
Map<String, Object> filtersMap;
try {
filtersMap = mapper.readValue(filters, new TypeReference<Map<String, Object>>() {
});
} catch (Exception e) {
return new ResponseEntity<>("Invalid filters JSON format", HttpStatus.BAD_REQUEST);
}
// ✅ Call reusable filter method
tableData = applyFilters(tableData, filtersMap);
}
StringBuilder jsonmap = new StringBuilder();
if (job_type.equalsIgnoreCase("Grid")) {
jsonmap.append("[\n");
for (Map<String, Object> row : tableData) {
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(tableData.get(tableData.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()) {
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 : tableData) {
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<List<Object>> yAxisValuesList = new ArrayList<>();
List<String> xAxisValues = new ArrayList<>();
List<String> parameterValues = 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 (value != null && key.equalsIgnoreCase(xAxis)) {
xAxisValues.add(value.toString());
} else {
int yIndex = yAxes.indexOf(key);
if (yIndex >= 0) {
yAxisValuesList.get(yIndex).add(value);
}
}
}
}
jsonmap = getJson(jsonmap, yAxes, xAxisValues, yAxisValuesList, parameterValues);
return new ResponseEntity<>(jsonmap.toString(), HttpStatus.CREATED);
}
/**
* ✅ Reusable filter method Supports both single-value and multi-value filters
*/
private List<Map<String, Object>> applyFilters(List<Map<String, Object>> tableData,
Map<String, Object> filtersMap) {
if (filtersMap == null || filtersMap.isEmpty())
return tableData;
return tableData.stream().filter(row -> {
for (Map.Entry<String, Object> entry : filtersMap.entrySet()) {
Object filterValue = entry.getValue();
Object rowValue = row.get(entry.getKey());
// skip empty filters
if (filterValue == null)
continue;
// ✅ Multi-value filter (List or Array)
if (filterValue instanceof List<?>) {
List<?> filterList = (List<?>) filterValue;
if (filterList.isEmpty())
continue;
if (rowValue == null
|| !filterList.stream().anyMatch(v -> v.toString().equalsIgnoreCase(rowValue.toString()))) {
return false;
}
}
// ✅ Single-value filter
else {
if (rowValue == null || !rowValue.toString().equalsIgnoreCase(filterValue.toString())) {
return false;
}
}
}
return true;
}).collect(Collectors.toList());
}
public StringBuilder getJson(StringBuilder jsonmap, List<String> yAxes, List<String> xAxisValues,
List<List<Object>> yAxisValuesList, List<String> parameterValues) {
jsonmap.append("{\n \"chartData\": [\n");
for (int j = 0; j < yAxes.size(); j++) {
String yAxis = yAxes.get(j);
jsonmap.append("{");
jsonmap.append("\"data\": [");
// --- Y-Axis Data ---
for (int i = 0; i < xAxisValues.size(); i++) {
List<Object> list = yAxisValuesList.get(j);
if (list == null || list.isEmpty() || i >= list.size()) {
continue;
}
Object yValue = list.get(i);
if (yValue instanceof Number) {
jsonmap.append(yValue);
} else if (yValue instanceof String) {
String yStr = ((String) yValue).trim();
try {
Double num = Double.parseDouble(yStr);
jsonmap.append(num);
} catch (NumberFormatException e) {
continue; // skip non-numeric
}
} else {
continue; // skip invalid
}
if (i < xAxisValues.size() - 1) {
jsonmap.append(",");
}
}
// 🧹 Remove trailing comma
int lastIndex = jsonmap.lastIndexOf(",");
if (lastIndex == jsonmap.length() - 1) {
jsonmap.deleteCharAt(lastIndex);
}
jsonmap.append("],");
jsonmap.append("\"label\": \"" + yAxis + "\"");
jsonmap.append("}");
if (j < yAxes.size() - 1) {
jsonmap.append(",");
}
}
// --- Chart Labels (X-Axis) ---
jsonmap.append("],\n \"chartLabels\": [");
for (String xValue : xAxisValues) {
jsonmap.append("\"").append(xValue).append("\",");
}
if (!xAxisValues.isEmpty()) {
jsonmap.deleteCharAt(jsonmap.lastIndexOf(","));
}
jsonmap.append("],");
// --- Parameter Values ---
jsonmap.append("\n \"parameterValues\": [");
if (parameterValues != null && !parameterValues.isEmpty()) {
for (String param : parameterValues) {
if (param != null && !param.trim().isEmpty()) {
jsonmap.append("\"").append(param.trim()).append("\",");
}
}
// Remove trailing comma
int lastComma = jsonmap.lastIndexOf(",");
if (lastComma == jsonmap.length() - 1) {
jsonmap.deleteCharAt(lastComma);
}
}
jsonmap.append("]\n}");
return jsonmap;
}
@GetMapping("/getAllKeys")
public Set<String> getAllKeys(@RequestParam String apiUrl, @RequestParam Integer sureId) {
List<Map<String, Object>> apiData = getAllKeyFromApi(apiUrl, sureId);
return getAllKeys(apiData);
}
public List<Map<String, Object>> getAllKeyFromApi(String apiUrl, Integer sureId) {
List<Map<String, Object>> apiData = new ArrayList<>();
try {
// Make a GET request using the provided URL
ResponseEntity<Object> responseEntity = GETWithObject(apiUrl, sureId);
// 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;
}
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, Integer sureId) {
List<Map<String, Object>> apiData = new ArrayList<>();
try {
// Make a GET request using the provided URL
ResponseEntity<Object> responseEntity = GETWithObject(apiUrl, sureId);
// 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> GET1(String get) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
return u;
}
public ResponseEntity<String> GET(String url, Integer sureid) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL)); // accept JSON or XML
headers.setContentType(MediaType.APPLICATION_JSON);
// 🔹 Add your token here (you can make it dynamic)
String token = getToken(sureid); // helper method (see below)
if (token != null && !token.isEmpty()) {
headers.set("Authorization", "Bearer " + token);
}
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return response;
}
public ResponseEntity<Object> GETWithObject(String url, Integer sureid) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL)); // accept JSON or XML
headers.setContentType(MediaType.APPLICATION_JSON);
// 🔹 Add your token here (you can make it dynamic)
String token = getToken(sureid); // helper method (see below)
if (token != null && !token.isEmpty()) {
headers.set("Authorization", "Bearer " + token);
}
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
return response;
}
private String getToken(Integer sureid) {
Sure_Connect connect = sureService.getbyid(sureid);
String access_token = connect.getAccess_token();
return access_token; // optional
}
}

View File

@@ -0,0 +1,49 @@
package com.realnet.Dashboard_builder.Controllers;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.*;
@RestController
public class DashboardMockController {
@GetMapping("/api/getDummyDashboardData")
public ResponseEntity<List<Map<String, Object>>> getDummyDashboardData() {
List<Map<String, Object>> dataList = new ArrayList<>();
String[] salesReps = { "Gaurav", "Ravi", "Ankit", "Neha", "Kiran" };
String[] partners = { "IBM", "Microsoft", "TCS", "Infosys", "Wipro" };
String[] regions = { "Asia", "Europe", "North America", "South America", "Africa" };
String[] channels = { "Online", "Retail", "Direct", "Distributor", "Reseller" };
String[] products = { "Laptops", "Servers", "Networking", "Cloud", "AI" };
for (int i = 1; i <= 50; i++) {
Map<String, Object> row = new LinkedHashMap<>();
// 🧩 Fixed pattern numeric data
row.put("leadCount", 100 + (i * 10));
row.put("dealValue", 5000 + (i * 750));
row.put("conversionRate", (i % 100));
row.put("activeUsers", 50 + (i * 5));
row.put("visits", 200 + (i * 15));
// 🧠 Repeated pattern text data
row.put("salesRep", salesReps[i % salesReps.length]);
row.put("partner", partners[i % partners.length]);
row.put("region", regions[i % regions.length]);
row.put("channel", channels[i % channels.length]);
row.put("productLine", products[i % products.length]);
// 📅 Sequential date data
row.put("createdDate", LocalDate.of(2024, (i % 12) + 1, ((i % 28) + 1)));
row.put("lastUpdated", LocalDate.of(2025, ((i + 2) % 12) + 1, ((i + 3) % 28) + 1));
dataList.add(row);
}
return ResponseEntity.ok(dataList);
}
}

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,143 @@
package com.realnet.DataLake.Controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.DataLake.Entity.Data_lake;
import com.realnet.DataLake.Services.DataLakeActionService;
import com.realnet.DataLake.Services.Data_lakeService;
import com.realnet.fnd.response.EntityResponse;
@RequestMapping(value = "/Data_lake")
@CrossOrigin("*")
@RestController
public class Data_lakeController {
@Autowired
private Data_lakeService Service;
@Autowired
private DataLakeActionService lakeActionService;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Data_lake")
public Data_lake Savedata(@RequestBody Data_lake data) {
Data_lake save = Service.Savedata(data);
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Data_lake/{id}")
public Data_lake update(@RequestBody Data_lake data, @PathVariable Integer id) {
Data_lake update = Service.update(data, id);
System.out.println("data update..." + update);
return update;
}
@GetMapping("/Data_lake/webhook/{id}")
public Data_lake enableWebhook(@PathVariable Integer id) {
Data_lake update = Service.enableWebHook(id);
System.out.println("webhook enabled..." + update);
return update;
}
@GetMapping("/Data_lake/keys/{lakeid}")
public Map<String, Object> getAllKeys(@PathVariable Integer lakeid) throws JsonProcessingException {
Map<String, Object> update = lakeActionService.getAllKeys(lakeid);
System.out.println("get all keys and header successfully...");
return update;
}
// get all with pagination
@GetMapping("/Data_lake/getall/page")
public Page<Data_lake> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Data_lake> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Data_lake")
public List<Data_lake> getdetails() {
List<Data_lake> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Data_lake")
public List<Data_lake> getallwioutsec() {
List<Data_lake> get = Service.getdetails();
return get;
}
@GetMapping("/Data_lake/{id}")
public Data_lake getdetailsbyId(@PathVariable Integer id) {
Data_lake get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Data_lake/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Integer id) {
Service.delete_by_id(id);
return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);
}
// json Upadted
@PutMapping("/Data_lake/json/{id}")
public Data_lake update(@PathVariable Integer id) throws JsonProcessingException {
Data_lake update = lakeActionService.applyCalculation(id);
System.out.println("clculation applied..." + update);
return update;
}
@GetMapping("/Data_lake/merge/{id}")
public ResponseEntity<?> mergeBatchData(@PathVariable Integer id) {
try {
// Get merged JSON string from service
String mergedJson = lakeActionService.mergeBatchData(id);
// Parse the merged JSON string back into JSON structure
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(mergedJson);
// Return as actual JSON (not as string)
return ResponseEntity.ok(jsonNode);
} catch (Exception e) {
// Build error response manually (Map.of() not available in Java 8)
Map<String, String> error = new HashMap<>();
error.put("error", e.getMessage());
return ResponseEntity.status(500).body(error);
}
}
}

View File

@@ -0,0 +1,57 @@
package com.realnet.DataLake.Controllers;
import javax.xml.bind.annotation.XmlRootElement;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@RequestMapping("/token/api")
public class XmlApiExample {
@GetMapping(value = "/getUser", produces = MediaType.APPLICATION_XML_VALUE)
public User getUser() {
User user = new User();
user.setId(101);
user.setName("John Doe");
user.setEmail("john.doe@example.com");
return user;
}
// Dummy XML model class
@XmlRootElement(name = "user")
public static class User {
private int id;
private String name;
private String email;
// Getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}

View File

@@ -0,0 +1,119 @@
package com.realnet.DataLake.Controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.DataLake.Entity.Data_lake;
import com.realnet.DataLake.Services.DataLakeActionService;
import com.realnet.DataLake.Services.Data_lakeService;
import com.realnet.fnd.response.EntityResponse;
@RequestMapping(value = "/token/Data_lake")
@CrossOrigin("*")
@RestController
public class tokenFree_Data_lakeController {
@Autowired
private Data_lakeService Service;
@Autowired
private DataLakeActionService lakeActionService;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Data_lake")
public Data_lake Savedata(@RequestBody Data_lake data) {
Data_lake save = Service.Savedata(data);
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Data_lake/{id}")
public Data_lake update(@RequestBody Data_lake data, @PathVariable Integer id) {
Data_lake update = Service.update(data, id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Data_lake/getall/page")
public Page<Data_lake> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Data_lake> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Data_lake")
public List<Data_lake> getdetails() {
List<Data_lake> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Data_lake")
public List<Data_lake> getallwioutsec() {
List<Data_lake> get = Service.getdetails();
return get;
}
@GetMapping("/Data_lake/{id}")
public Data_lake getdetailsbyId(@PathVariable Integer id) {
Data_lake get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Data_lake/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Integer id) {
Service.delete_by_id(id);
return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);
}
@GetMapping("/Data_lake/merge/{id}")
public ResponseEntity<?> mergeBatchData(@PathVariable Integer id) {
try {
// Get merged JSON string from service
String mergedJson = lakeActionService.mergeBatchData(id);
// Parse the merged JSON string back into JSON structure
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(mergedJson);
// Return as actual JSON (not as string)
return ResponseEntity.ok(jsonNode);
} catch (Exception e) {
// Build error response manually (Map.of() not available in Java 8)
Map<String, String> error = new HashMap<>();
error.put("error", e.getMessage());
return ResponseEntity.status(500).body(error);
}
}
}

View File

@@ -0,0 +1,26 @@
package com.realnet.DataLake.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import lombok.Data;
@Entity
@Data
public class BatchData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer datalake_id;
@Lob
@Column(columnDefinition = "TEXT")
private String batchjson;
}

View File

@@ -0,0 +1,73 @@
package com.realnet.DataLake.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import com.realnet.WhoColumn.Entity.Extension;
import lombok.Data;
@Entity
@Data
public class Data_lake extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String url;
private String schedule;
private String cron_job;
private String randomnumber;
private String webhook_url;
@Lob
@Column(columnDefinition = "TEXT")
private String json;
private Integer batch_volume;
private Integer sure_connect_id;
private String sureconnect_name;
private String url_endpoint;
private Integer ref_datalake_id;
private String datalake_type;
private String blending_lakeids;
@Lob
@Column(columnDefinition = "TEXT")
private String calculated_field_json;
@Lob
@Column(columnDefinition = "TEXT")
private String groupby_json;
@Lob
@Column(columnDefinition = "TEXT")
private String sqlquery_json;
@Lob
@Column(columnDefinition = "TEXT")
private String mapping_json;
private Boolean iscalculatedfield;
}

View File

@@ -0,0 +1,24 @@
package com.realnet.DataLake.Repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.DataLake.Entity.BatchData;
@Repository
public interface BatchDataRepository extends JpaRepository<BatchData, Integer> {
@Query(value = "select * from batch_data where created_by=?1", nativeQuery = true)
List<BatchData> findAll(Long creayedBy);
@Query(value = "select * from batch_data where created_by=?1", nativeQuery = true)
Page<BatchData> findAll(Long creayedBy, Pageable page);
@Query(value = "select * from batch_data", nativeQuery = true)
List<BatchData> findByDatalake_id(Integer datalake_id);
}

View File

@@ -0,0 +1,24 @@
package com.realnet.DataLake.Repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.realnet.DataLake.Entity.Data_lake;
@Repository
public interface Data_lakeRepository extends JpaRepository<Data_lake, Integer> {
@Query(value = "select * from data_lake where created_by=?1", nativeQuery = true)
List<Data_lake> findAll(Long creayedBy);
@Query(value = "select * from data_lake where created_by=?1", nativeQuery = true)
Page<Data_lake> findAll(Long creayedBy, Pageable page);
@Query(value = "select * from data_lake where created_by=?1 && ref_datalake_id=?2", nativeQuery = true)
List<Data_lake> findAllByRefDatlakeId(Long creayedBy, Integer ref_datalake_id);
}

View File

@@ -0,0 +1,963 @@
package com.realnet.DataLake.Services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.springframework.beans.factory.annotation.Autowired;
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.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.realnet.DataLake.Entity.BatchData;
import com.realnet.DataLake.Entity.Data_lake;
import com.realnet.DataLake.Repository.BatchDataRepository;
import com.realnet.DataLake.Repository.Data_lakeRepository;
import com.realnet.SureConnect.Entities.Sure_Connect;
import com.realnet.SureConnect.Service.SureService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.utils.Port_Constant;
@Service
public class DataLakeActionService {
@Autowired
private Data_lakeRepository Repository;
@Autowired
private BatchDataRepository batchRepo;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private SureService sureService;
// sql to json
public Object sqltojson(Integer lakeid) {
Data_lake lake = Repository.findById(lakeid).get();
String datalake_type = lake.getDatalake_type();
Object responseBody = null; // 👈 this is what well return
if (datalake_type.equalsIgnoreCase("blending") && lake.getBlending_lakeids() != null
&& lake.getSqlquery_json() != null) {
String blending_lakeids = lake.getBlending_lakeids(); // e.g. "12,13"
String sqlquery_json = lake.getSqlquery_json(); // e.g. "select * from gtest, gtest2"
// Step 1⃣: Collect all child lakes
String[] lakeIds = blending_lakeids.split(",");
Map<String, JsonNode> lakeDataMap = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
for (String idStr : lakeIds) {
int id = Integer.parseInt(idStr.trim());
Data_lake child = Repository.findById(id).orElse(null);
if (child == null)
continue;
String url = child.getUrl_endpoint();
// ResponseEntity<String> response = GETWithString(url, child.getSure_connect_id());
ResponseEntity<Object> response = GETWithObject(url, child.getSure_connect_id());
Object body = response.getBody();
try {
String rawBody = mapper.writeValueAsString(body);
JsonNode data = mapper.readTree(rawBody);
// Normalize to array
if (!data.isArray()) {
ArrayNode arr = mapper.createArrayNode();
arr.add(data);
data = arr;
}
lakeDataMap.put(child.getName().toLowerCase(), data);
System.out.println("Loaded data for: " + child.getName());
} catch (Exception e) {
System.err.println("Error parsing data from " + child.getName() + ": " + e.getMessage());
}
}
// Step 2⃣: Parse SQL for table names
List<String> tables = extractTableNames(sqlquery_json);
System.out.println("Tables in query: " + tables);
// Step 3⃣: Perform JOIN or UNION based on query type
ArrayNode result = mapper.createArrayNode();
if (sqlquery_json.toLowerCase().contains("join") || sqlquery_json.toLowerCase().contains("where")) {
// Perform naive JOIN on common field names
result = performJoin(mapper, lakeDataMap, tables);
} else {
// Perform simple UNION of all tables (cross merge)
result = performUnion(mapper, lakeDataMap, tables);
}
System.out.println("✅ Final blended JSON:");
System.out.println(result.toPrettyString());
// Step 4⃣: Convert ArrayNode → Object for return
try {
responseBody = mapper.readValue(mapper.writeValueAsString(result), Object.class);
} catch (Exception e) {
throw new RuntimeException("Error converting result to Object: " + e.getMessage());
}
}
return responseBody;
}
/** Extract table names from SQL query like "select * from gtest, gtest2" */
private List<String> extractTableNames(String sql) {
List<String> tables = new ArrayList<>();
String lower = sql.toLowerCase();
String regex = "from\\s+([a-zA-Z0-9_,\\s]+)";
Matcher m = Pattern.compile(regex).matcher(lower);
if (m.find()) {
String group = m.group(1);
for (String name : group.split(",")) {
tables.add(name.trim());
}
}
return tables;
}
/** Simple union of all tables */
private ArrayNode performUnion(ObjectMapper mapper, Map<String, JsonNode> lakeDataMap, List<String> tables) {
ArrayNode result = mapper.createArrayNode();
for (String table : tables) {
JsonNode data = lakeDataMap.get(table.toLowerCase());
if (data == null)
continue;
for (JsonNode row : data) {
ObjectNode newRow = mapper.createObjectNode();
Iterator<String> fields = row.fieldNames();
while (fields.hasNext()) {
String field = fields.next();
newRow.put(table + "." + field, row.get(field).asText());
}
result.add(newRow);
}
}
return result;
}
/** Simple JOIN based on common keys */
private ArrayNode performJoin(ObjectMapper mapper, Map<String, JsonNode> lakeDataMap, List<String> tables) {
ArrayNode result = mapper.createArrayNode();
if (tables.size() < 2)
return result;
JsonNode first = lakeDataMap.get(tables.get(0).toLowerCase());
JsonNode second = lakeDataMap.get(tables.get(1).toLowerCase());
if (first == null || second == null)
return result;
// Find common key (like "id" or "emp_id")
String joinKey = findCommonKey(first, second);
for (JsonNode row1 : first) {
for (JsonNode row2 : second) {
if (joinKey != null && row1.has(joinKey) && row2.has(joinKey)
&& row1.get(joinKey).asText().equals(row2.get(joinKey).asText())) {
ObjectNode merged = mapper.createObjectNode();
row1.fieldNames().forEachRemaining(f -> merged.put(tables.get(0) + "." + f, row1.get(f).asText()));
row2.fieldNames().forEachRemaining(f -> merged.put(tables.get(1) + "." + f, row2.get(f).asText()));
result.add(merged);
}
}
}
return result;
}
/** Finds a likely common join key between two datasets */
private String findCommonKey(JsonNode a, JsonNode b) {
Set<String> aKeys = new HashSet<>();
a.get(0).fieldNames().forEachRemaining(aKeys::add);
Set<String> bKeys = new HashSet<>();
b.get(0).fieldNames().forEachRemaining(bKeys::add);
for (String k : aKeys) {
if (bKeys.contains(k))
return k;
}
return null;
}
// get all keys of url endpoint
public Map<String, Object> getAllKeys(Integer lakeid) throws JsonProcessingException {
Data_lake old = Repository.findById(lakeid).get();
String url = old.getUrl_endpoint();
ResponseEntity<String> response = GETMethodAsString(url, old.getSure_connect_id());
String rawBody = response.getBody();
ObjectMapper jsonMapper = new ObjectMapper();
Object responseBody;
// Detect and convert if XML
if (isXml(rawBody)) {
try {
XmlMapper xmlMapper = new XmlMapper();
JsonNode xmlNode = xmlMapper.readTree(rawBody.getBytes());
String jsonFromXml = jsonMapper.writeValueAsString(xmlNode);
responseBody = jsonMapper.readValue(jsonFromXml, Object.class);
System.out.println("XML detected and converted to JSON successfully.");
} catch (Exception e) {
throw new RuntimeException("Failed to convert XML to JSON: " + e.getMessage());
}
} else {
try {
responseBody = jsonMapper.readValue(rawBody, Object.class);
System.out.println("JSON response detected.");
} catch (Exception e) {
throw new RuntimeException("Invalid JSON format: " + e.getMessage());
}
}
Map<String, Object> result = new HashMap<>();
extractTableAndHeaders(result, responseBody);
// Add table name from database
result.put("tableName", old.getName());
System.out.println("Keys extracted successfully.");
return result;
}
public static Map<String, Object> extractTableAndHeaders(Map<String, Object> result, Object responseBody) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode root = mapper.valueToTree(responseBody);
JsonNode firstNode = root.isArray() && root.size() > 0 ? root.get(0) : root;
Set<String> headers = new LinkedHashSet<>();
Iterator<String> fieldNames = firstNode.fieldNames();
while (fieldNames.hasNext()) {
String field = fieldNames.next();
if (!field.equalsIgnoreCase("tableName")) {
headers.add(field);
}
}
result.put("headers", headers);
} catch (Exception e) {
result.put("error", "Invalid JSON: " + e.getMessage());
}
return result;
}
// apply calculated json
public Data_lake applyCalculation(Integer id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Data_lake old = Repository.findById(id).get();
String datalake_type = old.getDatalake_type();
if (datalake_type != null && datalake_type.equalsIgnoreCase("blending") && old.getBlending_lakeids() != null
&& old.getSqlquery_json() != null) {
Object sqltojson = sqltojson(id);
String jsonString = mapper.writeValueAsString(sqltojson);
old.setJson(jsonString);
// Process and insert into BatchData as before
// Process and insert into BatchData
processBatchData(old, sqltojson, mapper);
String Url = Port_Constant.LOCALHOST + ":9292" + "/Data_lake/Data_lake/merge/" + old.getId();
old.setUrl_endpoint(Url);
old.setUpdatedBy(getUser().getUserId());
final Data_lake saved = Repository.save(old);
return saved;
}
String url = old.getUrl();
ResponseEntity<Object> response = GETWithObject(url, old.getSure_connect_id());
Object data = response.getBody();
String rawBody = mapper.writeValueAsString(data);
try {
List<Data_lake> datlakes = Repository.findAllByRefDatlakeId(getUser().getUserId(), id);
if (datlakes != null) {
datlakes.forEach(lake -> {
try {
Updatejson(lake.getId(), rawBody);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
} catch (Exception e2) {
System.out.println(" exception " + e2);
// TODO: handle exception
}
Data_lake saved = Updatejson(id, rawBody);
System.out.println(" json updated..");
return saved;
}
public Data_lake Updatejson(Integer id, String rawBody) throws JsonProcessingException {
Data_lake lake = Repository.findById(id).get();
// String url = old.getUrl();
//
// ResponseEntity<String> response = GETAsString(url);
// String rawBody = response.getBody();
// Convert the JSON object (ArrayList, Map, etc.) to a String
// Object responseBody = response.getBody();
ObjectMapper mapper = new ObjectMapper();
// String jsonString = mapper.writeValueAsString(rawBody);
ObjectMapper jsonMapper = new ObjectMapper();
Object responseBody;
// Detect and convert if XML
if (isXml(rawBody)) {
try {
// Convert XML → JSON tree
XmlMapper xmlMapper = new XmlMapper();
JsonNode xmlNode = xmlMapper.readTree(rawBody.getBytes());
// Convert to standard JSON structure
String jsonFromXml = jsonMapper.writeValueAsString(xmlNode);
responseBody = jsonMapper.readValue(jsonFromXml, Object.class);
System.out.println("XML detected and converted to JSON successfully.");
} catch (Exception e) {
throw new RuntimeException("Failed to convert XML to JSON: " + e.getMessage());
}
} else {
// Normal JSON response
try {
responseBody = jsonMapper.readValue(rawBody, Object.class);
System.out.println("JSON response detected.");
} catch (Exception e) {
throw new RuntimeException("Invalid JSON format: " + e.getMessage());
}
}
// Step 2⃣: Apply mapping if available
String mapping_json = lake.getMapping_json();
if (mapping_json != null && !mapping_json.trim().isEmpty()) {
try {
Map<String, String> keyMapping = mapper.readValue(mapping_json,
new TypeReference<Map<String, String>>() {
});
responseBody = applyFieldMapping(responseBody, keyMapping);
System.out.println("✅ Applied header mapping successfully.");
} catch (Exception e) {
throw new RuntimeException("Failed to apply mapping JSON: " + e.getMessage());
}
}
// ✅ Handle calculated fields before batch processing
if (Boolean.TRUE.equals(lake.getIscalculatedfield()) && lake.getCalculated_field_json() != null) {
try {
responseBody = applyCalculatedFields(responseBody, lake.getCalculated_field_json(), mapper, lake);
System.out.println("Calculated fields applied successfully.");
} catch (Exception e) {
System.err.println("Failed to process calculated fields: " + e.getMessage());
}
}
String jsonString = mapper.writeValueAsString(responseBody);
lake.setJson(jsonString);
// Process and insert into BatchData as before
// Process and insert into BatchData
processBatchData(lake, responseBody, mapper);
String Url = Port_Constant.LOCALHOST + ":9292" + "/Data_lake/Data_lake/merge/" + lake.getId();
lake.setUrl_endpoint(Url);
lake.setUpdatedBy(getUser().getUserId());
final Data_lake saved = Repository.save(lake);
System.out.println(" json updated..");
return saved;
}
private Object applyFieldMapping(Object input, Map<String, String> keyMapping) {
ObjectMapper mapper = new ObjectMapper();
if (input instanceof List) {
ArrayNode newArray = mapper.createArrayNode();
for (Object obj : (List<?>) input) {
JsonNode newNode = renameFields(mapper.valueToTree(obj), keyMapping, mapper);
newArray.add(newNode);
}
return newArray;
} else {
return renameFields(mapper.valueToTree(input), keyMapping, mapper);
}
}
private JsonNode renameFields(JsonNode node, Map<String, String> keyMapping, ObjectMapper mapper) {
ObjectNode updated = mapper.createObjectNode();
node.fieldNames().forEachRemaining(key -> {
JsonNode value = node.get(key);
String newKey = keyMapping.getOrDefault(key, key);
updated.set(newKey, value);
});
return updated;
}
@SuppressWarnings("unchecked")
private Object applyCalculatedFields(Object responseBody, String calculatedFieldJson, ObjectMapper mapper,
Data_lake old) throws JsonProcessingException {
// Parse the calculated field JSON
List<Map<String, Object>> calcFields = mapper.readValue(calculatedFieldJson, List.class);
// if (!(responseBody instanceof List)) {
// responseBody = Arrays.asList(responseBody);
// }
// ✅ Case 1: Already a Java List
if (responseBody instanceof List) {
// Do nothing
}
// ✅ Case 2: Jackson ArrayNode (convert to List)
else if (responseBody instanceof com.fasterxml.jackson.databind.node.ArrayNode) {
responseBody = mapper.convertValue(responseBody, List.class);
}
// ✅ Case 3: Jackson ObjectNode (convert to single object inside list)
else if (responseBody instanceof com.fasterxml.jackson.databind.node.ObjectNode) {
Map<String, Object> obj = mapper.convertValue(responseBody, Map.class);
responseBody = Collections.singletonList(obj);
}
// ✅ Case 4: JSON String input
else if (responseBody instanceof String) {
String json = ((String) responseBody).trim();
if (json.startsWith("[")) {
responseBody = mapper.readValue(json, List.class);
} else if (json.startsWith("{")) {
Map<String, Object> singleObject = mapper.readValue(json, Map.class);
responseBody = Collections.singletonList(singleObject);
} else {
throw new IllegalArgumentException("Invalid JSON format: " + json);
}
}
// ✅ Case 5: Single map
else if (responseBody instanceof Map) {
responseBody = Collections.singletonList(responseBody);
}
// ❌ Anything else — throw error
else {
throw new IllegalArgumentException("Unexpected response body type: " + responseBody.getClass());
}
List<Map<String, Object>> records = (List<Map<String, Object>>) responseBody;
for (Map<String, Object> calc : calcFields) {
String type = (String) calc.get("type");
if ("groupby".equalsIgnoreCase(type)) {
// ✅ Handle group-by aggregation
List<Map<String, Object>> groupbyrecords = applyGroupBy(records, calc);
String groupByRecord = mapper.writeValueAsString(groupbyrecords);
old.setGroupby_json(groupByRecord);
} else {
// ✅ Handle calculated / complex operations (as before)
for (Map<String, Object> record : records) {
String fieldName = (String) calc.get("fieldName");
String operation = (String) calc.get("operation");
List<Map<String, Object>> components = (List<Map<String, Object>>) calc.get("fieldComponents");
// Handle constant fields
if (components != null) {
for (Map<String, Object> comp : components) {
String subField = (String) comp.get("field");
Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
Object constantValue = comp.get("constant");
if (isConstant && subField != null) {
record.put(subField, parseNumberOrString(constantValue));
}
}
}
// Handle complex expression
if ("complex".equalsIgnoreCase(operation) && calc.get("complexEquation") != null) {
String equation = (String) calc.get("complexEquation");
Object result = evaluateComplexExpression(equation, record);
record.put(fieldName, result);
continue;
}
// Handle normal arithmetic
List<Object> values = new ArrayList<>();
if (components != null) {
for (Map<String, Object> comp : components) {
Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
Object val = isConstant ? comp.get("constant") : record.get(comp.get("field"));
if (val != null) {
values.add(val);
}
}
}
Object result = performOperation(values, operation);
record.put(fieldName, result);
}
}
}
return records;
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> applyGroupBy(List<Map<String, Object>> records, Map<String, Object> groupConfig) {
List<String> groupFields = (List<String>) groupConfig.get("groupFields");
List<Map<String, Object>> aggregations = (List<Map<String, Object>>) groupConfig.get("aggregations");
// Group records by key
Map<String, List<Map<String, Object>>> grouped = new LinkedHashMap<>();
for (Map<String, Object> record : records) {
String key = groupFields.stream().map(f -> String.valueOf(record.getOrDefault(f, "")))
.collect(Collectors.joining("|"));
grouped.computeIfAbsent(key, k -> new ArrayList<>()).add(record);
}
// Aggregate results per group
List<Map<String, Object>> result = new ArrayList<>();
for (Map.Entry<String, List<Map<String, Object>>> entry : grouped.entrySet()) {
Map<String, Object> groupRecord = new LinkedHashMap<>();
// Add group fields
String[] parts = entry.getKey().split("\\|");
for (int i = 0; i < groupFields.size(); i++) {
groupRecord.put(groupFields.get(i), parts[i]);
}
List<Map<String, Object>> groupRows = entry.getValue();
// Apply each aggregation
for (Map<String, Object> agg : aggregations) {
String field = (String) agg.get("field");
String operation = ((String) agg.get("operation")).toLowerCase();
List<Double> numericValues = groupRows.stream().map(r -> toDouble(r.get(field)))
.filter(v -> !Double.isNaN(v)).collect(Collectors.toList());
Object aggResult;
switch (operation) {
case "count":
aggResult = groupRows.size();
break;
case "sum":
aggResult = numericValues.stream().mapToDouble(Double::doubleValue).sum();
break;
case "avg":
aggResult = numericValues.isEmpty() ? 0.0
: numericValues.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
break;
case "min":
aggResult = numericValues.isEmpty() ? null
: numericValues.stream().mapToDouble(Double::doubleValue).min().orElse(0.0);
break;
case "max":
aggResult = numericValues.isEmpty() ? null
: numericValues.stream().mapToDouble(Double::doubleValue).max().orElse(0.0);
break;
case "median":
aggResult = calculateMedian(numericValues);
break;
case "mode":
aggResult = calculateMode(numericValues);
break;
case "stdev":
aggResult = calculateStdDev(numericValues);
break;
default:
aggResult = null;
}
groupRecord.put(field + "_" + operation, aggResult);
}
result.add(groupRecord);
}
return result;
}
// --- Statistical helpers ---
private Double calculateMedian(List<Double> values) {
if (values == null || values.isEmpty())
return null;
List<Double> sorted = new ArrayList<>(values);
Collections.sort(sorted);
int n = sorted.size();
if (n % 2 == 1) {
return sorted.get(n / 2);
} else {
return (sorted.get(n / 2 - 1) + sorted.get(n / 2)) / 2.0;
}
}
private Double calculateMode(List<Double> values) {
if (values == null || values.isEmpty())
return null;
Map<Double, Long> freq = values.stream().collect(Collectors.groupingBy(v -> v, Collectors.counting()));
return freq.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse(null);
}
private Double calculateStdDev(List<Double> values) {
if (values == null || values.isEmpty())
return null;
double mean = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
double variance = values.stream().mapToDouble(v -> Math.pow(v - mean, 2)).average().orElse(0.0);
return Math.sqrt(variance);
}
private Object evaluateComplexExpression(String expression, Map<String, Object> record) {
try {
// Replace field names with values dynamically
for (Map.Entry<String, Object> e : record.entrySet()) {
String field = e.getKey();
Object val = e.getValue();
expression = expression.replaceAll("\\b" + field + "\\b", String.valueOf(val != null ? val : 0));
}
// Evaluate using ScriptEngine (works on Java 1.8)
javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("JavaScript");
Object result = engine.eval(expression);
return result;
} catch (Exception e) {
System.err.println("Complex expression error: " + e.getMessage());
return null;
}
}
// perform normal operation
private Object performOperation(List<Object> values, String operation) {
if (values.isEmpty())
return null;
switch (operation.toLowerCase()) {
case "add":
double sum = 0;
for (Object v : values)
sum += toDouble(v);
return sum;
case "subtract":
double result = toDouble(values.get(0));
for (int i = 1; i < values.size(); i++)
result -= toDouble(values.get(i));
return result;
case "multiply":
double prod = 1;
for (Object v : values)
prod *= toDouble(v);
return prod;
case "divide":
double div = toDouble(values.get(0));
for (int i = 1; i < values.size(); i++) {
double val = toDouble(values.get(i));
if (val != 0)
div /= val;
}
return div;
case "percentage":
if (values.size() < 2)
return null;
double num = toDouble(values.get(0));
double den = toDouble(values.get(1));
return den == 0 ? null : (num * den) / 100;
case "concat":
return values.stream().map(Object::toString).collect(Collectors.joining("_"));
default:
return null;
}
}
/**
* ✅ Evaluates complex equations using JavaScript engine Supports math
* operations, parentheses, and string concatenation.
*/
private Object evaluateComplexEquation(String expression, Map<String, Object> record,
List<Map<String, Object>> fieldComponents) {
if (expression == null || expression.trim().isEmpty())
return null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
try {
// 🔹 Replace constants
if (fieldComponents != null) {
for (Map<String, Object> comp : fieldComponents) {
String field = (String) comp.get("field");
Object constant = comp.get("constant");
Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
if (isConstant && constant != null) {
String constVal = constant.toString();
expression = expression.replaceAll("\\b" + field + "\\b", constVal);
}
}
}
// 🔹 Replace field values from record
for (Map.Entry<String, Object> entry : record.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (val != null) {
String safeValue = val.toString();
// If it's a string containing letters, wrap it in quotes for JS
if (!safeValue.matches("^-?\\d+(\\.\\d+)?$")) {
safeValue = "'" + safeValue.replace("'", "\\'") + "'";
}
expression = expression.replaceAll("\\b" + key + "\\b", safeValue);
}
}
// Evaluate the expression safely
Object result = engine.eval(expression);
System.out.println(" exoression is : " + expression + " and " + result);
return result;
} catch (Exception e) {
System.err.println("❌ Error evaluating complex equation: " + e.getMessage());
return null;
}
}
private double toDouble(Object val) {
if (val == null)
return 0.0;
try {
return Double.parseDouble(val.toString().trim());
} catch (NumberFormatException e) {
return 0.0;
}
}
private Object parseNumberOrString(Object val) {
if (val == null)
return null;
String str = val.toString().trim();
try {
return Double.parseDouble(str);
} catch (NumberFormatException e) {
return str;
}
}
private boolean isXml(String content) {
if (content == null)
return false;
String trimmed = content.trim();
// XML usually starts with '<' and ends with '>'
return trimmed.startsWith("<") && trimmed.endsWith(">");
}
private void processBatchData(Data_lake dataLake, Object responseBody, ObjectMapper mapper)
throws JsonProcessingException {
int batchVolume = (dataLake.getBatch_volume() != null && dataLake.getBatch_volume() > 0)
? dataLake.getBatch_volume()
: 100; // default batch size if not given
// Convert to JsonNode
JsonNode jsonNode = mapper.valueToTree(responseBody);
if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
int total = arrayNode.size();
System.out.println("Total records: " + total);
for (int i = 0; i < total; i += batchVolume) {
int end = Math.min(i + batchVolume, total);
// Create a sub-array manually
ArrayNode subArray = mapper.createArrayNode();
for (int j = i; j < end; j++) {
subArray.add(arrayNode.get(j));
}
String subJson = mapper.writeValueAsString(subArray);
BatchData batch = new BatchData();
batch.setDatalake_id(dataLake.getId());
batch.setBatchjson(subJson);
batchRepo.save(batch);
}
System.out.println("Inserted " + (int) Math.ceil((double) total / batchVolume) + " batch records.");
} else {
// Single object → one record
BatchData batch = new BatchData();
batch.setDatalake_id(dataLake.getId());
batch.setBatchjson(mapper.writeValueAsString(jsonNode));
batchRepo.save(batch);
System.out.println("Inserted single batch record.");
}
}
public String mergeBatchData(Integer datalakeId) throws Exception {
List<BatchData> batchList = batchRepo.findByDatalake_id(datalakeId);
if (batchList.isEmpty()) {
throw new RuntimeException("No batch data found for datalake_id: " + datalakeId);
}
ObjectMapper mapper = new ObjectMapper();
ArrayNode mergedArray = mapper.createArrayNode();
for (BatchData batch : batchList) {
String json = batch.getBatchjson();
JsonNode node = mapper.readTree(json);
if (node.isArray()) {
// Add each element to merged array
for (JsonNode item : node) {
mergedArray.add(item);
}
} else {
// Single object, just add directly
mergedArray.add(node);
}
}
String mergedJson = mapper.writeValueAsString(mergedArray);
System.out.println("Merged JSON size: " + mergedArray.size());
return mergedJson;
}
public ResponseEntity<Object> GET(String get) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
return u;
}
public ResponseEntity<String> GETAsString1(String url) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForEntity(url, String.class);
}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}
public ResponseEntity<String> GETMethodAsString(String url, Integer sureid) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL)); // accept JSON or XML
headers.setContentType(MediaType.APPLICATION_JSON);
// 🔹 Add your token here (you can make it dynamic)
String token = getToken(sureid); // helper method (see below)
if (token != null && !token.isEmpty()) {
headers.set("Authorization", "Bearer " + token);
}
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return response;
}
public ResponseEntity<Object> GETWithObject(String url, Integer sureid) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL)); // accept JSON or XML
headers.setContentType(MediaType.APPLICATION_JSON);
// 🔹 Add your token here (you can make it dynamic)
String token = getToken(sureid); // helper method (see below)
if (token != null && !token.isEmpty()) {
headers.set("Authorization", "Bearer " + token);
}
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
return response;
}
private String getToken(Integer sureid) {
Sure_Connect connect = sureService.getbyid(sureid);
String access_token = connect.getAccess_token();
return access_token; // optional
}
}

View File

@@ -0,0 +1,948 @@
package com.realnet.DataLake.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.realnet.DataLake.Entity.Data_lake;
import com.realnet.DataLake.Repository.BatchDataRepository;
import com.realnet.DataLake.Repository.Data_lakeRepository;
import com.realnet.SureConnect.Service.SureService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.utils.Port_Constant;
@Service
public class Data_lakeService {
@Autowired
private Data_lakeRepository Repository;
@Autowired
private BatchDataRepository batchRepo;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private DataLakeActionService lakeActionService;
@Autowired
private SureService sureService;
public Data_lake Savedata(Data_lake data) {
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
if (data.getSure_connect_id() != null) {
data.setSureconnect_name(sureService.getbyid(data.getSure_connect_id()).getConnection_name());
}
Data_lake save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Data_lake> getAllWithPagination(Pageable page) {
return Repository.findAll(getUser().getUserId(), page);
}
public List<Data_lake> getdetails() {
List<Data_lake> all = Repository.findAll(getUser().getUserId());
return all;
}
public Data_lake getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Data_lake enableWebHook(Integer id) {
Data_lake old = Repository.findById(id).get();
String Url = Port_Constant.LOCALHOST + ":9292" + "/Data_lake/Data_lake/json/" + id;
old.setWebhook_url(Url);
final Data_lake test = Repository.save(old);
return test;
}
public Data_lake update(Data_lake data, Integer id) {
Data_lake old = Repository.findById(id).get();
// id auto-generated hai → update nahi karenge
if (data.getName() != null) {
old.setName(data.getName());
}
if (data.getUrl() != null) {
old.setUrl(data.getUrl());
}
if (data.getSchedule() != null) {
old.setSchedule(data.getSchedule());
}
if (data.getCron_job() != null) {
old.setCron_job(data.getCron_job());
}
if (data.getJson() != null) {
old.setJson(data.getJson());
}
if (data.getBatch_volume() != null) {
old.setBatch_volume(data.getBatch_volume());
}
if (data.getSure_connect_id() != null) {
old.setSure_connect_id(data.getSure_connect_id());
old.setSureconnect_name(sureService.getbyid(data.getSure_connect_id()).getConnection_name());
}
if (data.getUrl_endpoint() != null) {
old.setUrl_endpoint(data.getUrl_endpoint());
}
if (data.getCalculated_field_json() != null) {
old.setCalculated_field_json(data.getCalculated_field_json());
}
if (data.getIscalculatedfield() != null) {
old.setIscalculatedfield(data.getIscalculatedfield());
}
if (data.getGroupby_json() != null) {
old.setGroupby_json(data.getGroupby_json());
}
if (data.getRef_datalake_id() != null) {
old.setRef_datalake_id(data.getRef_datalake_id());
}
if (data.getDatalake_type() != null) {
old.setDatalake_type(data.getDatalake_type());
}
if (data.getBlending_lakeids() != null) {
old.setBlending_lakeids(data.getBlending_lakeids());
}
if (data.getSqlquery_json() != null) {
old.setSqlquery_json(data.getSqlquery_json());
}
if (data.getMapping_json() != null) {
old.setMapping_json(data.getMapping_json());
}
final Data_lake test = Repository.save(old);
return test;
}
// public Object sqltojson(Integer lakeid) {
// Data_lake lake = Repository.findById(lakeid).get();
// String datalake_type = lake.getDatalake_type();
//
// Object responseBody = null; // 👈 this is what well return
//
// if (datalake_type.equalsIgnoreCase("blending") && lake.getBlending_lakeids() != null
// && lake.getSqlquery_json() != null) {
//
// String blending_lakeids = lake.getBlending_lakeids(); // e.g. "12,13"
// String sqlquery_json = lake.getSqlquery_json(); // e.g. "select * from gtest, gtest2"
//
// // Step 1⃣: Collect all child lakes
// String[] lakeIds = blending_lakeids.split(",");
// Map<String, JsonNode> lakeDataMap = new HashMap<>();
// ObjectMapper mapper = new ObjectMapper();
//
// for (String idStr : lakeIds) {
// int id = Integer.parseInt(idStr.trim());
// Data_lake child = Repository.findById(id).orElse(null);
// if (child == null)
// continue;
//
// String url = child.getUrl_endpoint();
// ResponseEntity<String> response = GETWithString(url, child.getSure_connect_id());
// String rawBody = response.getBody();
//
// try {
// JsonNode data = mapper.readTree(rawBody);
// // Normalize to array
// if (!data.isArray()) {
// ArrayNode arr = mapper.createArrayNode();
// arr.add(data);
// data = arr;
// }
// lakeDataMap.put(child.getName().toLowerCase(), data);
// System.out.println("Loaded data for: " + child.getName());
// } catch (Exception e) {
// System.err.println("Error parsing data from " + child.getName() + ": " + e.getMessage());
// }
// }
//
// // Step 2⃣: Parse SQL for table names
// List<String> tables = extractTableNames(sqlquery_json);
// System.out.println("Tables in query: " + tables);
//
// // Step 3⃣: Perform JOIN or UNION based on query type
// ArrayNode result = mapper.createArrayNode();
//
// if (sqlquery_json.toLowerCase().contains("join") || sqlquery_json.toLowerCase().contains("where")) {
// // Perform naive JOIN on common field names
// result = performJoin(mapper, lakeDataMap, tables);
// } else {
// // Perform simple UNION of all tables (cross merge)
// result = performUnion(mapper, lakeDataMap, tables);
// }
//
// System.out.println("✅ Final blended JSON:");
// System.out.println(result.toPrettyString());
// // Step 4⃣: Convert ArrayNode → Object for return
// try {
// responseBody = mapper.readValue(mapper.writeValueAsString(result), Object.class);
// } catch (Exception e) {
// throw new RuntimeException("Error converting result to Object: " + e.getMessage());
// }
// }
//
// return responseBody;
//
// }
//
// /** Extract table names from SQL query like "select * from gtest, gtest2" */
// private List<String> extractTableNames(String sql) {
// List<String> tables = new ArrayList<>();
// String lower = sql.toLowerCase();
// String regex = "from\\s+([a-zA-Z0-9_,\\s]+)";
// Matcher m = Pattern.compile(regex).matcher(lower);
// if (m.find()) {
// String group = m.group(1);
// for (String name : group.split(",")) {
// tables.add(name.trim());
// }
// }
// return tables;
// }
//
// /** Simple union of all tables */
// private ArrayNode performUnion(ObjectMapper mapper, Map<String, JsonNode> lakeDataMap, List<String> tables) {
// ArrayNode result = mapper.createArrayNode();
//
// for (String table : tables) {
// JsonNode data = lakeDataMap.get(table.toLowerCase());
// if (data == null)
// continue;
//
// for (JsonNode row : data) {
// ObjectNode newRow = mapper.createObjectNode();
// Iterator<String> fields = row.fieldNames();
// while (fields.hasNext()) {
// String field = fields.next();
// newRow.put(table + "." + field, row.get(field).asText());
// }
// result.add(newRow);
// }
// }
// return result;
// }
//
// /** Simple JOIN based on common keys */
// private ArrayNode performJoin(ObjectMapper mapper, Map<String, JsonNode> lakeDataMap, List<String> tables) {
// ArrayNode result = mapper.createArrayNode();
// if (tables.size() < 2)
// return result;
//
// JsonNode first = lakeDataMap.get(tables.get(0).toLowerCase());
// JsonNode second = lakeDataMap.get(tables.get(1).toLowerCase());
//
// if (first == null || second == null)
// return result;
//
// // Find common key (like "id" or "emp_id")
// String joinKey = findCommonKey(first, second);
//
// for (JsonNode row1 : first) {
// for (JsonNode row2 : second) {
// if (joinKey != null && row1.has(joinKey) && row2.has(joinKey)
// && row1.get(joinKey).asText().equals(row2.get(joinKey).asText())) {
//
// ObjectNode merged = mapper.createObjectNode();
// row1.fieldNames().forEachRemaining(f -> merged.put(tables.get(0) + "." + f, row1.get(f).asText()));
// row2.fieldNames().forEachRemaining(f -> merged.put(tables.get(1) + "." + f, row2.get(f).asText()));
// result.add(merged);
// }
// }
// }
// return result;
// }
//
// /** Finds a likely common join key between two datasets */
// private String findCommonKey(JsonNode a, JsonNode b) {
// Set<String> aKeys = new HashSet<>();
// a.get(0).fieldNames().forEachRemaining(aKeys::add);
//
// Set<String> bKeys = new HashSet<>();
// b.get(0).fieldNames().forEachRemaining(bKeys::add);
//
// for (String k : aKeys) {
// if (bKeys.contains(k))
// return k;
// }
// return null;
// }
// public Map<String, Object> getAllKeys(Integer lakeid) throws JsonProcessingException {
// Data_lake old = Repository.findById(lakeid).get();
// String url = old.getUrl_endpoint();
//
// ResponseEntity<String> response = GETWithString(url, old.getSure_connect_id());
//
// String rawBody = response.getBody();
//
// ObjectMapper jsonMapper = new ObjectMapper();
// Object responseBody;
//
// // Detect and convert if XML
// if (isXml(rawBody)) {
// try {
// XmlMapper xmlMapper = new XmlMapper();
// JsonNode xmlNode = xmlMapper.readTree(rawBody.getBytes());
// String jsonFromXml = jsonMapper.writeValueAsString(xmlNode);
// responseBody = jsonMapper.readValue(jsonFromXml, Object.class);
// System.out.println("XML detected and converted to JSON successfully.");
// } catch (Exception e) {
// throw new RuntimeException("Failed to convert XML to JSON: " + e.getMessage());
// }
// } else {
// try {
// responseBody = jsonMapper.readValue(rawBody, Object.class);
// System.out.println("JSON response detected.");
// } catch (Exception e) {
// throw new RuntimeException("Invalid JSON format: " + e.getMessage());
// }
// }
//
// Map<String, Object> result = new HashMap<>();
// extractTableAndHeaders(result, responseBody);
//
// // Add table name from database
// result.put("tableName", old.getName());
//
// System.out.println("Keys extracted successfully.");
// return result;
// }
//
// public static Map<String, Object> extractTableAndHeaders(Map<String, Object> result, Object responseBody) {
// ObjectMapper mapper = new ObjectMapper();
//
// try {
// JsonNode root = mapper.valueToTree(responseBody);
// JsonNode firstNode = root.isArray() && root.size() > 0 ? root.get(0) : root;
//
// Set<String> headers = new LinkedHashSet<>();
// Iterator<String> fieldNames = firstNode.fieldNames();
// while (fieldNames.hasNext()) {
// String field = fieldNames.next();
// if (!field.equalsIgnoreCase("tableName")) {
// headers.add(field);
// }
// }
//
// result.put("headers", headers);
// } catch (Exception e) {
// result.put("error", "Invalid JSON: " + e.getMessage());
// }
//
// return result;
// }
//
//// apply calculated json
// public Data_lake applyCalculation(Integer id) throws JsonProcessingException {
//
// ObjectMapper mapper = new ObjectMapper();
//
// Data_lake old = Repository.findById(id).get();
// String datalake_type = old.getDatalake_type();
// if (datalake_type.equalsIgnoreCase("blending") && old.getBlending_lakeids() != null
// && old.getSqlquery_json() != null) {
//
// Object sqltojson = lakeActionService.sqltojson(id);
//
// String jsonString = mapper.writeValueAsString(sqltojson);
// old.setJson(jsonString);
//
// // Process and insert into BatchData as before
//
// // Process and insert into BatchData
// processBatchData(old, sqltojson, mapper);
//
// String Url = Port_Constant.LOCALHOST + ":9292" + "/Data_lake/Data_lake/merge/" + old.getId();
// old.setUrl_endpoint(Url);
//
// old.setUpdatedBy(getUser().getUserId());
//
// final Data_lake saved = Repository.save(old);
// return saved;
// }
//
// String url = old.getUrl();
//
// ResponseEntity<String> response = GETAsString(url);
// String rawBody = response.getBody();
//
// List<Data_lake> datlakes = Repository.findAllByRefDatlakeId(getUser().getUserId(), id);
//
// datlakes.forEach(lake -> {
// try {
// Updatejson(lake.getId(), rawBody);
// } catch (JsonProcessingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// });
//
// Data_lake saved = Updatejson(id, rawBody);
//
// System.out.println(" json updated..");
// return saved;
//
// }
// public Data_lake Updatejson(Integer id, String rawBody) throws JsonProcessingException {
//
// Data_lake old = Repository.findById(id).get();
//
//// String url = old.getUrl();
////
//// ResponseEntity<String> response = GETAsString(url);
//// String rawBody = response.getBody();
//
// // Convert the JSON object (ArrayList, Map, etc.) to a String
//// Object responseBody = response.getBody();
// ObjectMapper mapper = new ObjectMapper();
//
//// String jsonString = mapper.writeValueAsString(rawBody);
// ObjectMapper jsonMapper = new ObjectMapper();
// Object responseBody;
//
// // Detect and convert if XML
// if (isXml(rawBody)) {
// try {
// // Convert XML → JSON tree
//
// XmlMapper xmlMapper = new XmlMapper();
//
// JsonNode xmlNode = xmlMapper.readTree(rawBody.getBytes());
// // Convert to standard JSON structure
// String jsonFromXml = jsonMapper.writeValueAsString(xmlNode);
// responseBody = jsonMapper.readValue(jsonFromXml, Object.class);
// System.out.println("XML detected and converted to JSON successfully.");
// } catch (Exception e) {
// throw new RuntimeException("Failed to convert XML to JSON: " + e.getMessage());
// }
// } else {
// // Normal JSON response
// try {
// responseBody = jsonMapper.readValue(rawBody, Object.class);
// System.out.println("JSON response detected.");
// } catch (Exception e) {
// throw new RuntimeException("Invalid JSON format: " + e.getMessage());
// }
// }
//
// // ✅ Handle calculated fields before batch processing
// if (Boolean.TRUE.equals(old.getIscalculatedfield()) && old.getCalculated_field_json() != null) {
// try {
// responseBody = applyCalculatedFields(responseBody, old.getCalculated_field_json(), mapper, old);
// System.out.println("Calculated fields applied successfully.");
// } catch (Exception e) {
// System.err.println("Failed to process calculated fields: " + e.getMessage());
// }
// }
//
// String jsonString = mapper.writeValueAsString(responseBody);
// old.setJson(jsonString);
//
// // Process and insert into BatchData as before
//
// // Process and insert into BatchData
// processBatchData(old, responseBody, mapper);
//
// String Url = Port_Constant.LOCALHOST + ":9292" + "/Data_lake/Data_lake/merge/" + old.getId();
// old.setUrl_endpoint(Url);
//
// old.setUpdatedBy(getUser().getUserId());
//
// final Data_lake saved = Repository.save(old);
//
// System.out.println(" json updated..");
// return saved;
//
// }
//
// @SuppressWarnings("unchecked")
// private Object applyCalculatedFields(Object responseBody, String calculatedFieldJson, ObjectMapper mapper,
// Data_lake old) throws JsonProcessingException {
//
// // Parse the calculated field JSON
// List<Map<String, Object>> calcFields = mapper.readValue(calculatedFieldJson, List.class);
//
// if (!(responseBody instanceof List)) {
// responseBody = Arrays.asList(responseBody);
// }
//
// List<Map<String, Object>> records = (List<Map<String, Object>>) responseBody;
//
// for (Map<String, Object> calc : calcFields) {
// String type = (String) calc.get("type");
// if ("groupby".equalsIgnoreCase(type)) {
// // ✅ Handle group-by aggregation
// List<Map<String, Object>> groupbyrecords = applyGroupBy(records, calc);
// String groupByRecord = mapper.writeValueAsString(groupbyrecords);
//
// old.setGroupby_json(groupByRecord);
//
// } else {
// // ✅ Handle calculated / complex operations (as before)
// for (Map<String, Object> record : records) {
// String fieldName = (String) calc.get("fieldName");
// String operation = (String) calc.get("operation");
// List<Map<String, Object>> components = (List<Map<String, Object>>) calc.get("fieldComponents");
//
// // Handle constant fields
// if (components != null) {
// for (Map<String, Object> comp : components) {
// String subField = (String) comp.get("field");
// Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
// Object constantValue = comp.get("constant");
// if (isConstant && subField != null) {
// record.put(subField, parseNumberOrString(constantValue));
// }
// }
// }
//
// // Handle complex expression
// if ("complex".equalsIgnoreCase(operation) && calc.get("complexEquation") != null) {
// String equation = (String) calc.get("complexEquation");
// Object result = evaluateComplexExpression(equation, record);
// record.put(fieldName, result);
// continue;
// }
//
// // Handle normal arithmetic
// List<Object> values = new ArrayList<>();
// if (components != null) {
// for (Map<String, Object> comp : components) {
// Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
// Object val = isConstant ? comp.get("constant") : record.get(comp.get("field"));
// if (val != null) {
// values.add(val);
// }
// }
// }
//
// Object result = performOperation(values, operation);
// record.put(fieldName, result);
// }
// }
// }
//
// return records;
// }
//
// @SuppressWarnings("unchecked")
// private List<Map<String, Object>> applyGroupBy(List<Map<String, Object>> records, Map<String, Object> groupConfig) {
// List<String> groupFields = (List<String>) groupConfig.get("groupFields");
// List<Map<String, Object>> aggregations = (List<Map<String, Object>>) groupConfig.get("aggregations");
//
// // Group records by key
// Map<String, List<Map<String, Object>>> grouped = new LinkedHashMap<>();
// for (Map<String, Object> record : records) {
// String key = groupFields.stream().map(f -> String.valueOf(record.getOrDefault(f, "")))
// .collect(Collectors.joining("|"));
// grouped.computeIfAbsent(key, k -> new ArrayList<>()).add(record);
// }
//
// // Aggregate results per group
// List<Map<String, Object>> result = new ArrayList<>();
//
// for (Map.Entry<String, List<Map<String, Object>>> entry : grouped.entrySet()) {
// Map<String, Object> groupRecord = new LinkedHashMap<>();
//
// // Add group fields
// String[] parts = entry.getKey().split("\\|");
// for (int i = 0; i < groupFields.size(); i++) {
// groupRecord.put(groupFields.get(i), parts[i]);
// }
//
// List<Map<String, Object>> groupRows = entry.getValue();
//
// // Apply each aggregation
// for (Map<String, Object> agg : aggregations) {
// String field = (String) agg.get("field");
// String operation = ((String) agg.get("operation")).toLowerCase();
// List<Double> numericValues = groupRows.stream().map(r -> toDouble(r.get(field)))
// .filter(v -> !Double.isNaN(v)).collect(Collectors.toList());
//
// Object aggResult;
// switch (operation) {
// case "count":
// aggResult = groupRows.size();
// break;
// case "sum":
// aggResult = numericValues.stream().mapToDouble(Double::doubleValue).sum();
// break;
// case "average":
// aggResult = numericValues.isEmpty() ? 0.0
// : numericValues.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
// break;
// case "minimum":
// aggResult = numericValues.isEmpty() ? null
// : numericValues.stream().mapToDouble(Double::doubleValue).min().orElse(0.0);
// break;
// case "maximum":
// aggResult = numericValues.isEmpty() ? null
// : numericValues.stream().mapToDouble(Double::doubleValue).max().orElse(0.0);
// break;
// case "median":
// aggResult = calculateMedian(numericValues);
// break;
// case "mode":
// aggResult = calculateMode(numericValues);
// break;
// case "standard deviation":
// aggResult = calculateStdDev(numericValues);
// break;
// default:
// aggResult = null;
// }
//
// groupRecord.put(field + "_" + operation, aggResult);
// }
//
// result.add(groupRecord);
// }
//
// return result;
// }
//
// // --- Statistical helpers ---
//
// private Double calculateMedian(List<Double> values) {
// if (values == null || values.isEmpty())
// return null;
// List<Double> sorted = new ArrayList<>(values);
// Collections.sort(sorted);
// int n = sorted.size();
// if (n % 2 == 1) {
// return sorted.get(n / 2);
// } else {
// return (sorted.get(n / 2 - 1) + sorted.get(n / 2)) / 2.0;
// }
// }
//
// private Double calculateMode(List<Double> values) {
// if (values == null || values.isEmpty())
// return null;
// Map<Double, Long> freq = values.stream().collect(Collectors.groupingBy(v -> v, Collectors.counting()));
// return freq.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse(null);
// }
//
// private Double calculateStdDev(List<Double> values) {
// if (values == null || values.isEmpty())
// return null;
// double mean = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
// double variance = values.stream().mapToDouble(v -> Math.pow(v - mean, 2)).average().orElse(0.0);
// return Math.sqrt(variance);
// }
//
// private Object evaluateComplexExpression(String expression, Map<String, Object> record) {
// try {
// // Replace field names with values dynamically
// for (Map.Entry<String, Object> e : record.entrySet()) {
// String field = e.getKey();
// Object val = e.getValue();
// expression = expression.replaceAll("\\b" + field + "\\b", String.valueOf(val != null ? val : 0));
// }
//
// // Evaluate using ScriptEngine (works on Java 1.8)
// javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("JavaScript");
// Object result = engine.eval(expression);
// return result;
// } catch (Exception e) {
// System.err.println("Complex expression error: " + e.getMessage());
// return null;
// }
// }
//
//// perform normal operation
// private Object performOperation(List<Object> values, String operation) {
// if (values.isEmpty())
// return null;
//
// switch (operation.toLowerCase()) {
// case "add":
// double sum = 0;
// for (Object v : values)
// sum += toDouble(v);
// return sum;
//
// case "subtract":
// double result = toDouble(values.get(0));
// for (int i = 1; i < values.size(); i++)
// result -= toDouble(values.get(i));
// return result;
//
// case "multiply":
// double prod = 1;
// for (Object v : values)
// prod *= toDouble(v);
// return prod;
//
// case "divide":
// double div = toDouble(values.get(0));
// for (int i = 1; i < values.size(); i++) {
// double val = toDouble(values.get(i));
// if (val != 0)
// div /= val;
// }
// return div;
//
// case "percentage":
// if (values.size() < 2)
// return null;
// double num = toDouble(values.get(0));
// double den = toDouble(values.get(1));
// return den == 0 ? null : (num / den) * 100;
//
// case "concat":
// return values.stream().map(Object::toString).collect(Collectors.joining("_"));
//
// default:
// return null;
// }
// }
//
// /**
// * ✅ Evaluates complex equations using JavaScript engine Supports math
// * operations, parentheses, and string concatenation.
// */
// private Object evaluateComplexEquation(String expression, Map<String, Object> record,
// List<Map<String, Object>> fieldComponents) {
//
// if (expression == null || expression.trim().isEmpty())
// return null;
//
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
//
// try {
// // 🔹 Replace constants
// if (fieldComponents != null) {
// for (Map<String, Object> comp : fieldComponents) {
// String field = (String) comp.get("field");
// Object constant = comp.get("constant");
// Boolean isConstant = comp.get("isConstant") != null && (Boolean) comp.get("isConstant");
//
// if (isConstant && constant != null) {
// String constVal = constant.toString();
// expression = expression.replaceAll("\\b" + field + "\\b", constVal);
// }
// }
// }
//
// // 🔹 Replace field values from record
// for (Map.Entry<String, Object> entry : record.entrySet()) {
// String key = entry.getKey();
// Object val = entry.getValue();
// if (val != null) {
// String safeValue = val.toString();
//
// // If it's a string containing letters, wrap it in quotes for JS
// if (!safeValue.matches("^-?\\d+(\\.\\d+)?$")) {
// safeValue = "'" + safeValue.replace("'", "\\'") + "'";
// }
//
// expression = expression.replaceAll("\\b" + key + "\\b", safeValue);
// }
// }
//
// // Evaluate the expression safely
// Object result = engine.eval(expression);
// System.out.println(" exoression is : " + expression + " and " + result);
// return result;
//
// } catch (Exception e) {
// System.err.println("❌ Error evaluating complex equation: " + e.getMessage());
// return null;
// }
// }
//
// private double toDouble(Object val) {
// if (val == null)
// return 0.0;
// try {
// return Double.parseDouble(val.toString().trim());
// } catch (NumberFormatException e) {
// return 0.0;
// }
// }
//
// private Object parseNumberOrString(Object val) {
// if (val == null)
// return null;
// String str = val.toString().trim();
// try {
// return Double.parseDouble(str);
// } catch (NumberFormatException e) {
// return str;
// }
// }
//
// private boolean isXml(String content) {
// if (content == null)
// return false;
// String trimmed = content.trim();
// // XML usually starts with '<' and ends with '>'
// return trimmed.startsWith("<") && trimmed.endsWith(">");
// }
//
// private void processBatchData(Data_lake dataLake, Object responseBody, ObjectMapper mapper)
// throws JsonProcessingException {
//
// int batchVolume = (dataLake.getBatch_volume() != null && dataLake.getBatch_volume() > 0)
// ? dataLake.getBatch_volume()
// : 100; // default batch size if not given
//
// // Convert to JsonNode
// JsonNode jsonNode = mapper.valueToTree(responseBody);
//
// if (jsonNode.isArray()) {
// ArrayNode arrayNode = (ArrayNode) jsonNode;
// int total = arrayNode.size();
// System.out.println("Total records: " + total);
//
// for (int i = 0; i < total; i += batchVolume) {
// int end = Math.min(i + batchVolume, total);
//
// // Create a sub-array manually
// ArrayNode subArray = mapper.createArrayNode();
// for (int j = i; j < end; j++) {
// subArray.add(arrayNode.get(j));
// }
//
// String subJson = mapper.writeValueAsString(subArray);
//
// BatchData batch = new BatchData();
// batch.setDatalake_id(dataLake.getId());
// batch.setBatchjson(subJson);
// batchRepo.save(batch);
// }
//
// System.out.println("Inserted " + (int) Math.ceil((double) total / batchVolume) + " batch records.");
//
// } else {
// // Single object → one record
// BatchData batch = new BatchData();
// batch.setDatalake_id(dataLake.getId());
// batch.setBatchjson(mapper.writeValueAsString(jsonNode));
// batchRepo.save(batch);
//
// System.out.println("Inserted single batch record.");
// }
// }
//
// public String mergeBatchData(Integer datalakeId) throws Exception {
// List<BatchData> batchList = batchRepo.findByDatalake_id(datalakeId);
//
// if (batchList.isEmpty()) {
// throw new RuntimeException("No batch data found for datalake_id: " + datalakeId);
// }
//
// ObjectMapper mapper = new ObjectMapper();
// ArrayNode mergedArray = mapper.createArrayNode();
//
// for (BatchData batch : batchList) {
// String json = batch.getBatchjson();
// JsonNode node = mapper.readTree(json);
//
// if (node.isArray()) {
// // Add each element to merged array
// for (JsonNode item : node) {
// mergedArray.add(item);
// }
// } else {
// // Single object, just add directly
// mergedArray.add(node);
// }
// }
//
// String mergedJson = mapper.writeValueAsString(mergedArray);
// System.out.println("Merged JSON size: " + mergedArray.size());
// return mergedJson;
// }
//
// public ResponseEntity<Object> GET(String get) {
// RestTemplate restTemplate = new RestTemplate();
//
// ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);
//
// return u;
//
// }
//
// public ResponseEntity<String> GETAsString(String url) {
// RestTemplate restTemplate = new RestTemplate();
// return restTemplate.getForEntity(url, String.class);
// }
//
// public ResponseEntity<String> GETWithString(String url, Integer sureid) {
// RestTemplate restTemplate = new RestTemplate();
//
// HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Collections.singletonList(MediaType.ALL)); // accept JSON or XML
// headers.setContentType(MediaType.APPLICATION_JSON);
//
// // 🔹 Add your token here (you can make it dynamic)
// String token = getToken(sureid); // helper method (see below)
// if (token != null && !token.isEmpty()) {
// headers.set("Authorization", "Bearer " + token);
// }
//
// HttpEntity<String> entity = new HttpEntity<>(headers);
//
// ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
//
// return response;
// }
//
// private String getToken(Integer sureid) {
// Sure_Connect connect = sureService.getbyid(sureid);
// String access_token = connect.getAccess_token();
//
// return access_token; // optional
// }
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}
}

View File

@@ -0,0 +1,90 @@
package com.realnet.DynamicDashbard.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.realnet.DynamicDashbard.entities.ChartTemplate;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.services.ChartTemplateService;
import com.realnet.DynamicDashbard.services.ChartTypeService;
@RestController
@RequestMapping("/api/chart-templates")
@CrossOrigin(origins = "*")
public class ChartTemplateController {
@Autowired
private ChartTemplateService chartTemplateService;
@Autowired
private ChartTypeService chartTypeService;
@GetMapping("/all")
public List<ChartTemplate> getAllChartTemplates() {
return chartTemplateService.getAllChartTemplates();
}
@GetMapping("/chart-type/{chartTypeId}")
public List<ChartTemplate> getChartTemplatesByChartType(@PathVariable Long chartTypeId) {
return chartTemplateService.getChartTemplatesByChartType(chartTypeId);
}
@GetMapping("/{id}")
public ResponseEntity<ChartTemplate> getChartTemplateById(@PathVariable Long id) {
Optional<ChartTemplate> chartTemplate = chartTemplateService.getChartTemplateById(id);
return chartTemplate.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<ChartTemplate> createChartTemplate(@RequestParam Long chartTypeId,
@RequestBody ChartTemplate chartTemplate) {
try {
// If chartType is provided as ID only, fetch the full ChartType object
if (chartTypeId != null) {
ChartType chartType = chartTypeService.getChartTypeById(chartTypeId)
.orElseThrow(() -> new RuntimeException(
"ChartType not found with id: " + chartTemplate.getChartType().getId()));
chartTemplate.setChartType(chartType);
}
ChartTemplate createdChartTemplate = chartTemplateService.saveChartTemplate(chartTemplate);
return ResponseEntity.ok(createdChartTemplate);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@PutMapping("/{id}")
public ResponseEntity<ChartTemplate> updateChartTemplate(@PathVariable Long id,
@RequestBody ChartTemplate chartTemplateDetails) {
try {
ChartTemplate updatedChartTemplate = chartTemplateService.updateChartTemplate(id, chartTemplateDetails);
return ResponseEntity.ok(updatedChartTemplate);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteChartTemplate(@PathVariable Long id) {
try {
chartTemplateService.deleteChartTemplate(id);
return ResponseEntity.ok().build();
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,83 @@
package com.realnet.DynamicDashbard.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.services.ChartTypeService;
@RestController
@RequestMapping("/api/chart-types")
@CrossOrigin(origins = "*")
public class ChartTypeController {
@Autowired
private ChartTypeService chartTypeService;
@GetMapping
public List<ChartType> getAllChartTypes() {
return chartTypeService.getAllChartTypes();
}
@GetMapping("/byname")
public ResponseEntity<ChartType> getAllChartTypes(@RequestParam String chartName) {
Optional<ChartType> chartType = chartTypeService.getChartTypeByName(chartName);
if (!chartType.isPresent()) {
System.out.println(" chart not found");
}
System.out.println(chartName + " found :\n");
return chartType.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@GetMapping("/active")
public List<ChartType> getActiveChartTypes() {
return chartTypeService.getActiveChartTypes();
}
@GetMapping("/{id}")
public ResponseEntity<ChartType> getChartTypeById(@PathVariable Long id) {
Optional<ChartType> chartType = chartTypeService.getChartTypeById(id);
return chartType.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ChartType createChartType(@RequestBody ChartType chartType) {
return chartTypeService.saveChartType(chartType);
}
@PutMapping("/{id}")
public ResponseEntity<ChartType> updateChartType(@PathVariable Long id, @RequestBody ChartType chartTypeDetails) {
try {
ChartType updatedChartType = chartTypeService.updateChartType(id, chartTypeDetails);
return ResponseEntity.ok(updatedChartType);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteChartType(@PathVariable Long id) {
try {
chartTypeService.deleteChartType(id);
return ResponseEntity.ok().build();
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,92 @@
package com.realnet.DynamicDashbard.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.DynamicDashbard.entities.ComponentProperty;
import com.realnet.DynamicDashbard.entities.UiComponent;
import com.realnet.DynamicDashbard.services.ComponentPropertyService;
import com.realnet.DynamicDashbard.services.UiComponentService;
@RestController
@RequestMapping("/api/component-properties")
@CrossOrigin(origins = "*")
public class ComponentPropertyController {
@Autowired
private ComponentPropertyService componentPropertyService;
@Autowired
private UiComponentService uiComponentService;
@GetMapping
public List<ComponentProperty> getAllComponentProperties() {
return componentPropertyService.getAllComponentProperties();
}
@GetMapping("/component/{componentId}")
public List<ComponentProperty> getComponentPropertiesByComponent(@PathVariable Long componentId) {
return componentPropertyService.getComponentPropertiesByComponent(componentId);
}
@GetMapping("/{id}")
public ResponseEntity<ComponentProperty> getComponentPropertyById(@PathVariable Long id) {
Optional<ComponentProperty> componentProperty = componentPropertyService.getComponentPropertyById(id);
return componentProperty.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<ComponentProperty> createComponentProperty(@RequestBody ComponentProperty componentProperty) {
try {
// If component is provided as ID only, fetch the full UiComponent object
if (componentProperty.getComponent() != null && componentProperty.getComponent().getId() != null
&& (componentProperty.getComponent().getComponentName() == null
|| componentProperty.getComponent().getComponentName().isEmpty())) {
UiComponent component = uiComponentService.getUiComponentById(componentProperty.getComponent().getId())
.orElseThrow(() -> new RuntimeException(
"UiComponent not found with id: " + componentProperty.getComponent().getId()));
componentProperty.setComponent(component);
}
ComponentProperty createdComponentProperty = componentPropertyService
.saveComponentProperty(componentProperty);
return ResponseEntity.ok(createdComponentProperty);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@PutMapping("/{id}")
public ResponseEntity<ComponentProperty> updateComponentProperty(@PathVariable Long id,
@RequestBody ComponentProperty componentPropertyDetails) {
try {
ComponentProperty updatedComponentProperty = componentPropertyService.updateComponentProperty(id,
componentPropertyDetails);
return ResponseEntity.ok(updatedComponentProperty);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteComponentProperty(@PathVariable Long id) {
try {
componentPropertyService.deleteComponentProperty(id);
return ResponseEntity.ok().build();
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,90 @@
package com.realnet.DynamicDashbard.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.entities.DynamicField;
import com.realnet.DynamicDashbard.services.ChartTypeService;
import com.realnet.DynamicDashbard.services.DynamicFieldService;
@RestController
@RequestMapping("/api/dynamic-fields")
@CrossOrigin(origins = "*")
public class DynamicFieldController {
@Autowired
private DynamicFieldService dynamicFieldService;
@Autowired
private ChartTypeService chartTypeService;
@GetMapping
public List<DynamicField> getAllDynamicFields() {
return dynamicFieldService.getAllDynamicFields();
}
@GetMapping("/chart-type/{chartTypeId}")
public List<DynamicField> getDynamicFieldsByChartType(@PathVariable Long chartTypeId) {
return dynamicFieldService.getDynamicFieldsByChartType(chartTypeId);
}
@GetMapping("/{id}")
public ResponseEntity<DynamicField> getDynamicFieldById(@PathVariable Long id) {
Optional<DynamicField> dynamicField = dynamicFieldService.getDynamicFieldById(id);
return dynamicField.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<DynamicField> createDynamicField(@RequestParam Long chartTypeId,
@RequestBody DynamicField dynamicField) {
try {
// If chartType is provided as ID only, fetch the full ChartType object
if (chartTypeId != null) {
ChartType chartType = chartTypeService.getChartTypeById(chartTypeId)
.orElseThrow(() -> new RuntimeException(
"ChartType not found with id: " + dynamicField.getChartType().getId()));
dynamicField.setChartType(chartType);
}
DynamicField createdDynamicField = dynamicFieldService.saveDynamicField(dynamicField);
return ResponseEntity.ok(createdDynamicField);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@PutMapping("/{id}")
public ResponseEntity<DynamicField> updateDynamicField(@PathVariable Long id,
@RequestBody DynamicField dynamicFieldDetails) {
try {
DynamicField updatedDynamicField = dynamicFieldService.updateDynamicField(id, dynamicFieldDetails);
return ResponseEntity.ok(updatedDynamicField);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteDynamicField(@PathVariable Long id) {
try {
dynamicFieldService.deleteDynamicField(id);
return ResponseEntity.ok().build();
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,91 @@
package com.realnet.DynamicDashbard.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.entities.UiComponent;
import com.realnet.DynamicDashbard.services.ChartTypeService;
import com.realnet.DynamicDashbard.services.UiComponentService;
@RestController
@RequestMapping("/api/ui-components")
@CrossOrigin(origins = "*")
public class UiComponentController {
@Autowired
private UiComponentService uiComponentService;
@Autowired
private ChartTypeService chartTypeService;
@GetMapping
public List<UiComponent> getAllUiComponents() {
return uiComponentService.getAllUiComponents();
}
@GetMapping("/chart-type/{chartTypeId}")
public List<UiComponent> getUiComponentsByChartType(@PathVariable Long chartTypeId) {
return uiComponentService.getUiComponentsByChartType(chartTypeId);
}
@GetMapping("/{id}")
public ResponseEntity<UiComponent> getUiComponentById(@PathVariable Long id) {
Optional<UiComponent> uiComponent = uiComponentService.getUiComponentById(id);
return uiComponent.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<UiComponent> createUiComponent(@RequestBody UiComponent uiComponent) {
try {
// If chartType is provided as ID only, fetch the full ChartType object
if (uiComponent.getChartType() != null && uiComponent.getChartType().getId() != null
&& (uiComponent.getChartType().getName() == null
|| uiComponent.getChartType().getName().isEmpty())) {
ChartType chartType = chartTypeService.getChartTypeById(uiComponent.getChartType().getId())
.orElseThrow(() -> new RuntimeException(
"ChartType not found with id: " + uiComponent.getChartType().getId()));
uiComponent.setChartType(chartType);
}
UiComponent createdUiComponent = uiComponentService.saveUiComponent(uiComponent);
System.out.println(createdUiComponent.getComponentName() + " ui component created successfully..");
return ResponseEntity.ok(createdUiComponent);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@PutMapping("/{id}")
public ResponseEntity<UiComponent> updateUiComponent(@PathVariable Long id,
@RequestBody UiComponent uiComponentDetails) {
try {
UiComponent updatedUiComponent = uiComponentService.updateUiComponent(id, uiComponentDetails);
return ResponseEntity.ok(updatedUiComponent);
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUiComponent(@PathVariable Long id) {
try {
uiComponentService.deleteUiComponent(id);
return ResponseEntity.ok().build();
} catch (RuntimeException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,149 @@
package com.realnet.DynamicDashbard.entities;
import java.time.LocalDateTime;
import java.util.Date;
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.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Data;
@Data
@Entity
@Table(name = "chart_templates")
public class ChartTemplate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chart_type_id", nullable = false)
@JsonBackReference
private ChartType chartType;
@Column(name = "template_name", nullable = false, length = 100)
private String templateName;
@Column(name = "template_html", columnDefinition = "TEXT")
private String templateHtml;
@Column(name = "template_css", columnDefinition = "TEXT")
private String templateCss;
@Column(name = "is_default")
private Boolean isDefault = false;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
@LastModifiedDate
private Date updatedAt;
//
// @PrePersist
// protected void onCreate() {
// createdAt = LocalDateTime.now();
// updatedAt = LocalDateTime.now();
// }
//
// @PreUpdate
// protected void onUpdate() {
// updatedAt = LocalDateTime.now();
// }
//
// // Constructors
// public ChartTemplate() {
// }
//
// public ChartTemplate(ChartType chartType, String templateName, String templateHtml, String templateCss) {
// this.chartType = chartType;
// this.templateName = templateName;
// this.templateHtml = templateHtml;
// this.templateCss = templateCss;
// }
//
// // Getters and Setters
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public ChartType getChartType() {
// return chartType;
// }
//
// public void setChartType(ChartType chartType) {
// this.chartType = chartType;
// }
//
// public String getTemplateName() {
// return templateName;
// }
//
// public void setTemplateName(String templateName) {
// this.templateName = templateName;
// }
//
// public String getTemplateHtml() {
// return templateHtml;
// }
//
// public void setTemplateHtml(String templateHtml) {
// this.templateHtml = templateHtml;
// }
//
// public String getTemplateCss() {
// return templateCss;
// }
//
// public void setTemplateCss(String templateCss) {
// this.templateCss = templateCss;
// }
//
// public Boolean getIsDefault() {
// return isDefault;
// }
//
// public void setIsDefault(Boolean isDefault) {
// this.isDefault = isDefault;
// }
//
// public LocalDateTime getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(LocalDateTime createdAt) {
// this.createdAt = createdAt;
// }
//
// public LocalDateTime getUpdatedAt() {
// return updatedAt;
// }
//
// public void setUpdatedAt(LocalDateTime updatedAt) {
// this.updatedAt = updatedAt;
// }
}

View File

@@ -0,0 +1,168 @@
package com.realnet.DynamicDashbard.entities;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
@Data
@Entity
@Table(name = "chart_types")
public class ChartType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false, length = 50)
private String name;
@Column(name = "display_name", length = 100)
private String displayName;
@Column(name = "description", columnDefinition = "TEXT")
private String description;
@Column(name = "is_active")
private Boolean isActive = true;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
@LastModifiedDate
private Date updatedAt;
@OneToMany(mappedBy = "chartType", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonManagedReference
private List<UiComponent> uiComponents;
@OneToMany(mappedBy = "chartType", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonManagedReference
private List<ChartTemplate> chartTemplates;
@OneToMany(mappedBy = "chartType", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonManagedReference
private List<DynamicField> dynamicFields;
// @PrePersist
// protected void onCreate() {
// createdAt = LocalDateTime.now();
// updatedAt = LocalDateTime.now();
// }
//
// @PreUpdate
// protected void onUpdate() {
// updatedAt = LocalDateTime.now();
// }
//
// // Constructors
// public ChartType() {
// }
//
// public ChartType(String name, String displayName, String description) {
// this.name = name;
// this.displayName = displayName;
// this.description = description;
// }
//
// // Getters and Setters
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Boolean getIsActive() {
// return isActive;
// }
//
// public void setIsActive(Boolean isActive) {
// this.isActive = isActive;
// }
//
// public LocalDateTime getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(LocalDateTime createdAt) {
// this.createdAt = createdAt;
// }
//
// public LocalDateTime getUpdatedAt() {
// return updatedAt;
// }
//
// public void setUpdatedAt(LocalDateTime updatedAt) {
// this.updatedAt = updatedAt;
// }
//
// public List<UiComponent> getUiComponents() {
// return uiComponents;
// }
//
// public void setUiComponents(List<UiComponent> uiComponents) {
// this.uiComponents = uiComponents;
// }
//
// public List<ChartTemplate> getChartTemplates() {
// return chartTemplates;
// }
//
// public void setChartTemplates(List<ChartTemplate> chartTemplates) {
// this.chartTemplates = chartTemplates;
// }
//
// public List<DynamicField> getDynamicFields() {
// return dynamicFields;
// }
//
// public void setDynamicFields(List<DynamicField> dynamicFields) {
// this.dynamicFields = dynamicFields;
// }
}

View File

@@ -0,0 +1,134 @@
package com.realnet.DynamicDashbard.entities;
import java.util.Date;
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.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Data;
@Data
@Entity
@Table(name = "component_properties")
public class ComponentProperty {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "component_id", nullable = false)
@JsonBackReference
private UiComponent component;
@Column(name = "property_name", nullable = false, length = 100)
private String propertyName;
@Column(name = "property_value", columnDefinition = "TEXT")
private String propertyValue;
@Column(name = "property_type", length = 50)
private String propertyType;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
@LastModifiedDate
private Date updatedAt;
//
// @PrePersist
// protected void onCreate() {
// createdAt = LocalDateTime.now();
// updatedAt = LocalDateTime.now();
// }
//
// @PreUpdate
// protected void onUpdate() {
// updatedAt = LocalDateTime.now();
// }
//
// // Constructors
// public ComponentProperty() {}
//
// public ComponentProperty(UiComponent component, String propertyName, String propertyValue, String propertyType) {
// this.component = component;
// this.propertyName = propertyName;
// this.propertyValue = propertyValue;
// this.propertyType = propertyType;
// }
//
// // Getters and Setters
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public UiComponent getComponent() {
// return component;
// }
//
// public void setComponent(UiComponent component) {
// this.component = component;
// }
//
// public String getPropertyName() {
// return propertyName;
// }
//
// public void setPropertyName(String propertyName) {
// this.propertyName = propertyName;
// }
//
// public String getPropertyValue() {
// return propertyValue;
// }
//
// public void setPropertyValue(String propertyValue) {
// this.propertyValue = propertyValue;
// }
//
// public String getPropertyType() {
// return propertyType;
// }
//
// public void setPropertyType(String propertyType) {
// this.propertyType = propertyType;
// }
//
// public LocalDateTime getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(LocalDateTime createdAt) {
// this.createdAt = createdAt;
// }
//
// public LocalDateTime getUpdatedAt() {
// return updatedAt;
// }
//
// public void setUpdatedAt(LocalDateTime updatedAt) {
// this.updatedAt = updatedAt;
// }
}

View File

@@ -0,0 +1,179 @@
package com.realnet.DynamicDashbard.entities;
import java.time.LocalDateTime;
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.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@Entity
@Table(name = "dynamic_fields")
public class DynamicField {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chart_type_id", nullable = false)
@JsonBackReference
private ChartType chartType;
@Column(name = "field_name", nullable = false, length = 100)
private String fieldName;
@Column(name = "field_label", length = 100)
private String fieldLabel;
@Column(name = "field_type", length = 50)
private String fieldType;
@Column(name = "field_options", columnDefinition = "TEXT")
private String fieldOptions;
@Column(name = "is_required")
private Boolean isRequired = false;
@Column(name = "show_in_ui")
private Boolean showInUi = true;
@Column(name = "sort_order")
private Integer sortOrder;
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
@Column(name = "created_at")
private LocalDateTime createdAt;
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
// Constructors
public DynamicField() {
}
public DynamicField(ChartType chartType, String fieldName, String fieldLabel, String fieldType) {
this.chartType = chartType;
this.fieldName = fieldName;
this.fieldLabel = fieldLabel;
this.fieldType = fieldType;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ChartType getChartType() {
return chartType;
}
public void setChartType(ChartType chartType) {
this.chartType = chartType;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldLabel() {
return fieldLabel;
}
public void setFieldLabel(String fieldLabel) {
this.fieldLabel = fieldLabel;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getFieldOptions() {
return fieldOptions;
}
public void setFieldOptions(String fieldOptions) {
this.fieldOptions = fieldOptions;
}
public Boolean getIsRequired() {
return isRequired;
}
public void setIsRequired(Boolean isRequired) {
this.isRequired = isRequired;
}
public Boolean getShowInUi() {
return showInUi;
}
public void setShowInUi(Boolean showInUi) {
this.showInUi = showInUi;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -0,0 +1,94 @@
package com.realnet.DynamicDashbard.entities;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
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.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
@Data
@Entity
@Table(name = "ui_components")
public class UiComponent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chart_type_id", nullable = false)
@JsonBackReference
private ChartType chartType;
@Column(name = "component_name", nullable = false, length = 100)
private String componentName;
@Column(name = "component_type", length = 50)
private String componentType;
@Column(name = "display_label", length = 100)
private String displayLabel;
@Column(name = "placeholder", columnDefinition = "TEXT")
private String placeholder;
@Column(name = "is_required")
private Boolean isRequired = false;
@Column(name = "sort_order")
private Integer sortOrder;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
@LastModifiedDate
private Date updatedAt;
@OneToMany(mappedBy = "component", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonManagedReference
private List<ComponentProperty> componentProperties;
// @PrePersist
// protected void onCreate() {
// createdAt = LocalDateTime.now();
// updatedAt = LocalDateTime.now();
// }
//
// @PreUpdate
// protected void onUpdate() {
// updatedAt = LocalDateTime.now();
// }
// Constructors
public UiComponent() {
}
public UiComponent(ChartType chartType, String componentName, String componentType) {
this.chartType = chartType;
this.componentName = componentName;
this.componentType = componentType;
}
}

View File

@@ -0,0 +1,19 @@
package com.realnet.DynamicDashbard.repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.DynamicDashbard.entities.ChartTemplate;
import com.realnet.DynamicDashbard.entities.ChartType;
@Repository
public interface ChartTemplateRepository extends JpaRepository<ChartTemplate, Long> {
List<ChartTemplate> findByChartType(ChartType chartType);
Optional<ChartTemplate> findByChartTypeAndIsDefaultTrue(ChartType chartType);
List<ChartTemplate> findByChartTypeAndTemplateNameContainingIgnoreCase(ChartType chartType, String templateName);
}

View File

@@ -0,0 +1,18 @@
package com.realnet.DynamicDashbard.repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.DynamicDashbard.entities.ChartType;
@Repository
public interface ChartTypeRepository extends JpaRepository<ChartType, Long> {
List<ChartType> findByIsActiveTrue();
Optional<ChartType> findByName(String name);
}

View File

@@ -0,0 +1,15 @@
package com.realnet.DynamicDashbard.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.DynamicDashbard.entities.ComponentProperty;
import com.realnet.DynamicDashbard.entities.UiComponent;
@Repository
public interface ComponentPropertyRepository extends JpaRepository<ComponentProperty, Long> {
List<ComponentProperty> findByComponent(UiComponent component);
List<ComponentProperty> findByComponentAndPropertyName(UiComponent component, String propertyName);
}

View File

@@ -0,0 +1,18 @@
package com.realnet.DynamicDashbard.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.entities.DynamicField;
@Repository
public interface DynamicFieldRepository extends JpaRepository<DynamicField, Long> {
List<DynamicField> findByChartType(ChartType chartType);
List<DynamicField> findByChartTypeAndIsRequiredTrue(ChartType chartType);
List<DynamicField> findByChartTypeAndShowInUiTrueOrderBySortOrder(ChartType chartType);
List<DynamicField> findByChartTypeOrderBySortOrder(ChartType chartType);
}

View File

@@ -0,0 +1,18 @@
package com.realnet.DynamicDashbard.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.entities.UiComponent;
@Repository
public interface UiComponentRepository extends JpaRepository<UiComponent, Long> {
List<UiComponent> findByChartType(ChartType chartType);
List<UiComponent> findByChartTypeAndIsRequiredTrue(ChartType chartType);
List<UiComponent> findByChartTypeOrderBySortOrder(ChartType chartType);
}

View File

@@ -0,0 +1,58 @@
package com.realnet.DynamicDashbard.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.DynamicDashbard.entities.ChartTemplate;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.repositories.ChartTemplateRepository;
import com.realnet.DynamicDashbard.repositories.ChartTypeRepository;
@Service
public class ChartTemplateService {
@Autowired
private ChartTemplateRepository chartTemplateRepository;
@Autowired
private ChartTypeRepository chartTypeRepository;
public List<ChartTemplate> getAllChartTemplates() {
return chartTemplateRepository.findAll();
}
public List<ChartTemplate> getChartTemplatesByChartType(Long chartTypeId) {
ChartType chartType = chartTypeRepository.findById(chartTypeId)
.orElseThrow(() -> new RuntimeException("ChartType not found with id: " + chartTypeId));
return chartTemplateRepository.findByChartType(chartType);
}
public Optional<ChartTemplate> getChartTemplateById(Long id) {
return chartTemplateRepository.findById(id);
}
public ChartTemplate saveChartTemplate(ChartTemplate chartTemplate) {
return chartTemplateRepository.save(chartTemplate);
}
public ChartTemplate updateChartTemplate(Long id, ChartTemplate chartTemplateDetails) {
ChartTemplate chartTemplate = chartTemplateRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ChartTemplate not found with id: " + id));
chartTemplate.setTemplateName(chartTemplateDetails.getTemplateName());
chartTemplate.setTemplateHtml(chartTemplateDetails.getTemplateHtml());
chartTemplate.setTemplateCss(chartTemplateDetails.getTemplateCss());
chartTemplate.setIsDefault(chartTemplateDetails.getIsDefault());
return chartTemplateRepository.save(chartTemplate);
}
public void deleteChartTemplate(Long id) {
ChartTemplate chartTemplate = chartTemplateRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ChartTemplate not found with id: " + id));
chartTemplateRepository.delete(chartTemplate);
}
}

View File

@@ -0,0 +1,55 @@
package com.realnet.DynamicDashbard.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.repositories.ChartTypeRepository;
@Service
public class ChartTypeService {
@Autowired
private ChartTypeRepository chartTypeRepository;
public List<ChartType> getAllChartTypes() {
return chartTypeRepository.findAll();
}
public List<ChartType> getActiveChartTypes() {
return chartTypeRepository.findByIsActiveTrue();
}
public Optional<ChartType> getChartTypeById(Long id) {
return chartTypeRepository.findById(id);
}
public Optional<ChartType> getChartTypeByName(String name) {
return chartTypeRepository.findByName(name);
}
public ChartType saveChartType(ChartType chartType) {
return chartTypeRepository.save(chartType);
}
public ChartType updateChartType(Long id, ChartType chartTypeDetails) {
ChartType chartType = chartTypeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ChartType not found with id: " + id));
chartType.setName(chartTypeDetails.getName());
chartType.setDisplayName(chartTypeDetails.getDisplayName());
chartType.setDescription(chartTypeDetails.getDescription());
chartType.setIsActive(chartTypeDetails.getIsActive());
return chartTypeRepository.save(chartType);
}
public void deleteChartType(Long id) {
ChartType chartType = chartTypeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ChartType not found with id: " + id));
chartTypeRepository.delete(chartType);
}
}

View File

@@ -0,0 +1,57 @@
package com.realnet.DynamicDashbard.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.realnet.DynamicDashbard.entities.ComponentProperty;
import com.realnet.DynamicDashbard.entities.UiComponent;
import com.realnet.DynamicDashbard.repositories.ComponentPropertyRepository;
import com.realnet.DynamicDashbard.repositories.UiComponentRepository;
@Service
public class ComponentPropertyService {
@Autowired
private ComponentPropertyRepository componentPropertyRepository;
@Autowired
private UiComponentRepository uiComponentRepository;
public List<ComponentProperty> getAllComponentProperties() {
return componentPropertyRepository.findAll();
}
public List<ComponentProperty> getComponentPropertiesByComponent(Long componentId) {
UiComponent component = uiComponentRepository.findById(componentId)
.orElseThrow(() -> new RuntimeException("UiComponent not found with id: " + componentId));
return componentPropertyRepository.findByComponent(component);
}
public Optional<ComponentProperty> getComponentPropertyById(Long id) {
return componentPropertyRepository.findById(id);
}
public ComponentProperty saveComponentProperty(ComponentProperty componentProperty) {
return componentPropertyRepository.save(componentProperty);
}
public ComponentProperty updateComponentProperty(Long id, ComponentProperty componentPropertyDetails) {
ComponentProperty componentProperty = componentPropertyRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ComponentProperty not found with id: " + id));
componentProperty.setPropertyName(componentPropertyDetails.getPropertyName());
componentProperty.setPropertyValue(componentPropertyDetails.getPropertyValue());
componentProperty.setPropertyType(componentPropertyDetails.getPropertyType());
return componentPropertyRepository.save(componentProperty);
}
public void deleteComponentProperty(Long id) {
ComponentProperty componentProperty = componentPropertyRepository.findById(id)
.orElseThrow(() -> new RuntimeException("ComponentProperty not found with id: " + id));
componentPropertyRepository.delete(componentProperty);
}
}

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