From e74abc704ee0ce33b1c02232efe526d7d19019ff Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Thu, 5 Mar 2026 12:01:50 +0530 Subject: [PATCH 01/21] token --- .../com/health/controller/HomeController.java | 59 +++++++++++++++--- .../com/health/model/TrainingResource.java | 62 +++++++++++++++++++ .../TrainingResourceRepository.java | 11 ++++ .../service/TrainingResourceService.java | 11 ++++ .../impl/TrainingReourceServiceImpl.java | 31 ++++++++++ .../com/health/utility/ServiceUtility.java | 13 ++++ 6 files changed, 179 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 3ee7205a..3d66ec95 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5365,6 +5365,22 @@ private List getEnglishTrainingMouduleFirst(List * Assign Tutorial on Week And Package End ********************/ + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + @GetMapping("/addTrainingResource") public String addTrainingResourceGet(HttpServletRequest req, Principal principal, Model model) { User usr = getUser(principal); @@ -5480,10 +5496,11 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String token = generateUniqueTokenForTrainingResource(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); Set extentions = new HashSet<>(); String document = ""; @@ -5509,6 +5526,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { @@ -5521,6 +5539,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { @@ -5533,6 +5552,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { @@ -5545,6 +5565,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { @@ -5562,6 +5583,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (ext.equals(CommonData.DOC_EXTENSION)) { @@ -5574,6 +5596,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (ext.equals(CommonData.EXCEL_EXTENSION)) { @@ -5586,6 +5609,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (ext.equals(CommonData.IMAGE_EXTENSION)) { @@ -5598,6 +5622,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { @@ -5900,11 +5925,13 @@ public String updateTrainingResourcePost(HttpServletRequest req, Model model, Pr } boolean fileMatch = false; + String token = ""; if (fileType.equals("Doc")) { originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getDocPath(); + token = oldTrainingResource.getDocToken(); } } @@ -5912,6 +5939,7 @@ else if (fileType.equals("Pdf")) { originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getPdfPath(); + token = oldTrainingResource.getPdfToken(); } } @@ -5919,12 +5947,14 @@ else if (fileType.equals("Image")) { originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getImgPath(); + token = oldTrainingResource.getImgToken(); } } else if (fileType.equals("Excel")) { originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getExcelPath(); + token = oldTrainingResource.getExcelToken(); } } @@ -5976,6 +6006,7 @@ else if (fileType.equals("Image")) { trainingResourceService.save(newTrainingResource); trIdInt = newTrainingResource.getTrainingResourceId(); + token = generateUniqueTokenForTrainingResource(); } @@ -5985,10 +6016,10 @@ else if (fileType.equals("Image")) { Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); boolean fileFlag = false; if (!file.isEmpty()) { @@ -6009,6 +6040,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) oldTrainingResource.setPdfPath(""); fileMatch = true; @@ -6018,6 +6050,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) oldTrainingResource.setDocPath(""); fileMatch = true; @@ -6027,6 +6060,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) oldTrainingResource.setExcelPath(""); fileMatch = true; @@ -6036,6 +6070,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) oldTrainingResource.setImgPath(""); fileMatch = true; @@ -6050,6 +6085,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) { oldTrainingResource.setPdfPath(""); } @@ -6062,6 +6098,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) { oldTrainingResource.setDocPath(""); } @@ -6073,6 +6110,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) { oldTrainingResource.setExcelPath(""); } @@ -6084,6 +6122,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) { oldTrainingResource.setImgPath(""); } @@ -6155,6 +6194,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); oldTrainingResource.setDocPath(""); } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { @@ -6163,6 +6203,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { env); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); oldTrainingResource.setExcelPath(""); } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { @@ -6170,6 +6211,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); oldTrainingResource.setPdfPath(""); } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { @@ -6177,6 +6219,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, env); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); oldTrainingResource.setImgPath(""); } diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 33664880..8f14b5f9 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -50,6 +50,18 @@ public class TrainingResource implements Serializable { @Column(name = "img_path", length = 1000) private String imgPath; + @Column(unique = true, length = 1000) + private String pdfToken; + + @Column(unique = true, length = 1000) + private String docToken; + + @Column(unique = true, length = 1000) + private String imgToken; + + @Column(unique = true, length = 1000) + private String excelToken; + @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User user; @@ -126,6 +138,38 @@ public void setUser(User user) { this.user = user; } + public String getPdfToken() { + return pdfToken; + } + + public void setPdfToken(String pdfToken) { + this.pdfToken = pdfToken; + } + + public String getDocToken() { + return docToken; + } + + public void setDocToken(String docToken) { + this.docToken = docToken; + } + + public String getImgToken() { + return imgToken; + } + + public void setImgToken(String imgToken) { + this.imgToken = imgToken; + } + + public String getExcelToken() { + return excelToken; + } + + public void setExcelToken(String excelToken) { + this.excelToken = excelToken; + } + public String getPdfFileNameWithorWitoutZip() { if (pdfPath == null || pdfPath.trim().isEmpty()) { return "NA"; @@ -166,6 +210,24 @@ public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, Category category, String pdfPath, + String docPath, String excelPath, String imgPath, String pdfToken, String docToken, String imgToken, + String excelToken, User user) { + super(); + this.dateAdded = dateAdded; + this.topicLanMapping = topicLanMapping; + this.category = category; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + this.pdfToken = pdfToken; + this.docToken = docToken; + this.imgToken = imgToken; + this.excelToken = excelToken; + this.user = user; + } + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, String pdfPath, String docPath, String excelPath, String imgPath) { diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java index ac83a2fd..643f03a2 100644 --- a/src/main/java/com/health/repository/TrainingResourceRepository.java +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -17,4 +17,15 @@ public interface TrainingResourceRepository extends JpaRepository findAllByStatusTrue(); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String docToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java index c82f9b29..4a7f7691 100644 --- a/src/main/java/com/health/service/TrainingResourceService.java +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -21,4 +21,15 @@ public interface TrainingResourceService { void saveAll(List trainingResourceList); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String imgToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java index 5fcf20a1..c2814063 100644 --- a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -62,4 +62,35 @@ public List findAllByStatusTrue() { return repo.findAllByStatusTrue(); } + @Override + public TrainingResource findByPdfToken(String pdfToken) { + + return repo.findByPdfToken(pdfToken); + } + + @Override + public TrainingResource findByDocToken(String docToken) { + + return repo.findByDocToken(docToken); + } + + @Override + public TrainingResource findByExcelToken(String excelToken) { + + return repo.findByExcelToken(excelToken); + } + + @Override + public TrainingResource findByImgToken(String imgToken) { + + return repo.findByImgToken(imgToken); + } + + @Override + public boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken) { + + return repo.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(pdfToken, docToken, excelToken, imgToken); + } + } diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index 35545363..60101215 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -18,12 +18,14 @@ import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; +import java.security.SecureRandom; import java.sql.Timestamp; import java.text.Normalizer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -77,6 +79,7 @@ import com.health.model.TrainingResource; import com.health.model.User; import com.health.repository.UserRepository; +import com.health.service.TrainingResourceService; import com.health.threadpool.TimeoutOutputStream; /** @@ -100,6 +103,9 @@ public class ServiceUtility { @Autowired private JavaMailSender mailSender; + @Autowired + private TrainingResourceService trainingResourceService; + public static Timestamp getCurrentTime() { // Current Date Date date = new Date(); @@ -1261,6 +1267,13 @@ public static String copyFileAndGetRelativePath(File sourceFile, String destinat return resultantPath; } + public static String generateToken() { + byte[] bytes = new byte[8]; + new SecureRandom().nextBytes(bytes); + + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, 10); + } + public static boolean hasAnyResourceFile(TrainingResource tr) { boolean hasData = true; if ((tr.getPdfPath() == null || tr.getPdfPath().isEmpty()) From 1a4e023f57a10eda113d0442f36952c8dbc516db Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Thu, 5 Mar 2026 15:15:32 +0530 Subject: [PATCH 02/21] token in shared resources --- src/main/java/com/health/HealthNutrition.java | 1 + .../com/health/controller/HomeController.java | 101 ++++++++++++++++-- .../com/health/model/TrainingResource.java | 10 ++ .../threadpool/TaskProcessingService.java | 52 +++++++++ .../java/com/health/utility/CommonData.java | 3 + .../templates/trainingResources.html | 8 +- 6 files changed, 163 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/health/HealthNutrition.java b/src/main/java/com/health/HealthNutrition.java index 32383c52..21234a26 100644 --- a/src/main/java/com/health/HealthNutrition.java +++ b/src/main/java/com/health/HealthNutrition.java @@ -59,6 +59,7 @@ public void run(String... args) throws Exception { try { taskProcessingService.createOutlineFile(); + taskProcessingService.addTokenInTrainingResource(); taskProcessingService.addAllBrochureToQueue(); taskProcessingService.addAllResearchPapertoQueue(); taskProcessingService.addAllTuttorialsToQueue(); diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 3d66ec95..d1c0cacc 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5996,14 +5996,13 @@ else if (fileType.equals("Image")) { } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); // To get exact Id of new trainining Resource Data if (newTrainingData) { - + newTrainingResource.setDateAdded(dateAdded); trainingResourceService.save(newTrainingResource); trIdInt = newTrainingResource.getTrainingResourceId(); token = generateUniqueTokenForTrainingResource(); @@ -6157,14 +6156,18 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { FileUtils.deleteDirectory(extractDirPath.toFile()); } + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); if (fileMatch) { - newTrainingResource.setDateAdded(dateAdded); + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } newTrainingResource.setTopicLanMapping(topicLan); trainingResourceService.save(newTrainingResource); if (newTrainingData) { @@ -6247,13 +6250,23 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } - private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, int trId, + private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, String token, Principal principal, Model model) { int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); logger.info("FileType:{}", fileType); logger.info("intFileType:{}", intFileType); - TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + + TrainingResource tr = null; + if (intFileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (intFileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (intFileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (intFileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } boolean isZipFile = false; String filePath = ""; @@ -6306,10 +6319,39 @@ public String getShareLinkofTrainingResource(HttpServletRequest req, @PathVariab @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceByToken(req, topicName, fileType, langName, token, principal, model); + } + + } + + @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Image") || fileType.equals("Pdf")) { return res; } else { @@ -6323,10 +6365,40 @@ public String getShareLinkofTrainingResourceDoc_Excel(HttpServletRequest req, @P @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceDoc_ExcelByToken(req, topicName, fileType, langName, token, principal, + model); + } + + } + + @GetMapping("/shared-training-resource-file/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceDoc_ExcelByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Doc") || fileType.equals("Excel")) { return "sharedTrainingResource"; } else { @@ -6416,6 +6488,19 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, TrainingResource tr = trList.get(0); int trId = tr.getTrainingResourceId(); model.addAttribute("trId", trId); + + String token = ""; + if (fileTypeString.equals("Doc")) { + token = tr.getDocToken(); + } else if (fileTypeString.equals("Excel")) { + token = tr.getExcelToken(); + } else if (fileTypeString.equals("Pdf")) { + token = tr.getPdfToken(); + } else if (fileTypeString.equals("Image")) { + token = tr.getImgToken(); + } + model.addAttribute("token", token); + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, inputFileType); if (filePath.isEmpty()) { getModelTrainingResource(model); diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 8f14b5f9..1fff2802 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.nio.file.Paths; import java.sql.Timestamp; +import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,6 +14,8 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; +import com.health.utility.CommonData; + @Entity @Table(name = "training_resource") public class TrainingResource implements Serializable { @@ -210,6 +213,13 @@ public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } + public boolean isAfterImplementationDate() { + + LocalDate resourceDate = this.dateAdded.toLocalDateTime().toLocalDate(); + + return !resourceDate.isBefore(CommonData.IMPL_DATE_TRAINING_RESOURCE); + } + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, Category category, String pdfPath, String docPath, String excelPath, String imgPath, String pdfToken, String docToken, String imgToken, String excelToken, User user) { diff --git a/src/main/java/com/health/threadpool/TaskProcessingService.java b/src/main/java/com/health/threadpool/TaskProcessingService.java index 7034d12e..16065329 100644 --- a/src/main/java/com/health/threadpool/TaskProcessingService.java +++ b/src/main/java/com/health/threadpool/TaskProcessingService.java @@ -43,6 +43,7 @@ import com.health.model.QueueManagement; import com.health.model.ResearchPaper; import com.health.model.TopicCategoryMapping; +import com.health.model.TrainingResource; import com.health.model.Tutorial; import com.health.model.Version; import com.health.repository.QueueManagementRepository; @@ -55,6 +56,7 @@ import com.health.service.QueueManagementService; import com.health.service.ResearchPaperService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TrainingResourceService; import com.health.service.TutorialService; import com.health.utility.CommonData; import com.health.utility.ServiceUtility; @@ -79,6 +81,9 @@ public class TaskProcessingService { @Autowired private ThreadPoolTaskExecutor taskExecutor; + @Autowired + private TrainingResourceService trainingResourceService; + @Autowired private QueueManagementService queueService; @@ -962,4 +967,51 @@ public void stop() { logger.info("stopping QueueProcessor thread"); taskExecutor.shutdown(); } + + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + + public void addTokenInTrainingResource() { + + List trList = trainingResourceService.findAll(); + + for (TrainingResource temp : trList) { + + if ((temp.getPdfToken() == null || temp.getPdfToken().isEmpty()) + && (temp.getPdfPath() != null && !temp.getPdfPath().isEmpty())) { + temp.setPdfToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getDocToken() == null || temp.getDocToken().isEmpty()) + && (temp.getDocPath() != null && !temp.getDocPath().isEmpty())) { + temp.setDocToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getExcelToken() == null || temp.getExcelToken().isEmpty()) + && (temp.getExcelPath() != null && !temp.getExcelPath().isEmpty())) { + temp.setExcelToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getImgToken() == null || temp.getImgToken().isEmpty()) + && (temp.getImgPath() != null && !temp.getImgPath().isEmpty())) { + temp.setImgToken(generateUniqueTokenForTrainingResource()); + } + + trainingResourceService.save(temp); + } + } + } diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 33a013fe..7424114a 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -1,5 +1,7 @@ package com.health.utility; +import java.time.LocalDate; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -312,6 +314,7 @@ public class CommonData { public static final String image_OR_ZIP_OF_IMAGES = "imageOrZipOfImages"; public static final String PDF_OR_ZIP_OF_PDFS = "pdfOrZipOfPdfs"; public static final String Excel_OR_ZIP_OF_EXCELS = "excelOrZipOfexcels"; + public static final LocalDate IMPL_DATE_TRAINING_RESOURCE = LocalDate.of(2026, 3, 5); public static final String DOCUMENT_ID_TUTORIAL_TIMESCRIPT = "Tts"; public static final String DOCUMENT_ID_TUTORIAL_ORIGINAL_SCRIPT = "Tos"; diff --git a/src/main/resources/templates/trainingResources.html b/src/main/resources/templates/trainingResources.html index 8685c704..17114dd0 100644 --- a/src/main/resources/templates/trainingResources.html +++ b/src/main/resources/templates/trainingResources.html @@ -228,8 +228,8 @@ ? @{${baseUrl} + '/shared-Training-Resource/' + ${topicName} + '/' + ${fileTypeString} + '/' - + ${langName} + '/' - + ${trId}} + + ${langName} + + '?token=' + ${token}} : ''"> @@ -242,8 +242,8 @@ ? @{${baseUrl} + '/shared-training-resource-file/' + ${topicName} + '/' + ${fileTypeString} + '/' - + ${langName} + '/' - + ${trId}} + + ${langName} + + '?token=' + ${token}} : ''"> From e11d4044b6f570c92bf0f18cda5187d97fe1f361 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Thu, 5 Mar 2026 16:36:20 +0530 Subject: [PATCH 03/21] token in download --- .../com/health/controller/AjaxController.java | 73 ++++++++++++++++++- .../com/health/controller/HomeController.java | 14 ++-- .../templates/sharedTrainingResource.html | 2 +- 3 files changed, 81 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 06647767..ed051064 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -2133,11 +2133,80 @@ public ResponseEntity deleteTrainingResource(@RequestParam("trainingReso } + /* + * @GetMapping("/downloadTrainingResource") public ResponseEntity + * downloadTrainingResourcePost(@RequestParam(name = "filePath") String + * filePath) { + * + * try { + * + * String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + * + * Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), + * finalUrl); + * + * if (!Files.exists(path)) { return + * ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); } + * + * Resource resource = new UrlResource(path.toUri()); + * + * String contentType = Files.probeContentType(path); if (contentType == null) { + * contentType = "application/octet-stream"; } + * + * String originalFilename = path.getFileName().toString(); + * + * String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + * + * String encodedFilename = URLEncoder.encode(safeFilename, + * "UTF-8").replace("+", "%20"); + * + * return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + * .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + + * encodedFilename) .body(resource); + * + * } catch (Exception e) { logger.error("Error in download", e); return + * ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } + */ + @GetMapping("/downloadTrainingResource") - public ResponseEntity downloadTrainingResourcePost(@RequestParam(name = "filePath") String filePath) { + public ResponseEntity downloadTrainingResource(@RequestParam(name = "fileType") String fileTypeString, + @RequestParam(name = "token") String token) { try { + int fileType = ServiceUtility.getFileTypeIdByValue(fileTypeString); + TrainingResource tr = null; + + if (fileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (fileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (fileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + + String filePath = null; + + if (fileType == CommonData.DOC) { + filePath = tr.getDocPath(); + } else if (fileType == CommonData.EXCEL) { + filePath = tr.getExcelPath(); + } else if (fileType == CommonData.PDF) { + filePath = tr.getPdfPath(); + } else if (fileType == CommonData.IMAGE) { + filePath = tr.getImgPath(); + } + + if (filePath == null || filePath.trim().isEmpty()) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalUrl); @@ -2164,7 +2233,7 @@ public ResponseEntity downloadTrainingResourcePost(@RequestParam(name .body(resource); } catch (Exception e) { - logger.error("Error in download", e); + logger.error("Error while downloading training resource", e); return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index d1c0cacc..c6f46be3 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -4,8 +4,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -6285,6 +6283,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("topicName", topic_name); model.addAttribute("langName", lang_name); model.addAttribute("fileTypeString", fileType); + model.addAttribute("token", token); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), filePath); String fileName = path.getFileName().toString(); @@ -6522,9 +6521,14 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; - return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?filePath=" - + URLEncoder.encode(finalUrl, "UTF-8"); - } catch (UnsupportedEncodingException e) { + // return "redirect:" + normalizedBaseUrl + + // "/downloadTrainingResource?filePath=" + // + URLEncoder.encode(finalUrl, "UTF-8"); + + return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?fileType=" + fileTypeString + + "&token=" + token; + + } catch (Exception e) { logger.error("Error in Download Package", e); } } diff --git a/src/main/resources/templates/sharedTrainingResource.html b/src/main/resources/templates/sharedTrainingResource.html index 690f320c..f78916c8 100644 --- a/src/main/resources/templates/sharedTrainingResource.html +++ b/src/main/resources/templates/sharedTrainingResource.html @@ -90,7 +90,7 @@

Download From 5a768c658d608a9139cec64b7febf4d5396f5915 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Fri, 6 Mar 2026 12:41:52 +0530 Subject: [PATCH 04/21] token-security in share view --- .../com/health/config/SecurityConfig.java | 2 +- .../com/health/controller/AjaxController.java | 75 +++++++++++++++++++ .../com/health/controller/HomeController.java | 55 ++++++++++++-- .../templates/sharedTrainingResource.html | 55 ++++++++++++++ .../templates/trainingResources.html | 39 ++++++---- 5 files changed, 203 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 89a57846..3ee25ff3 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -59,7 +59,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/Training-Resource/**", "/Training-Resources/**", "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", "/loadTopicAndLanByFileType/**", "/downloadTrainingResource/**", "/shared-Training-Resource/**", - "/shared-training-resource-file/**", "/check-deployment" }; + "/shared-training-resource-file/**", "/check-deployment", "/training-resources/view-share/**" }; /** * url matcher for SUPERADMIN diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index ed051064..5f03aa6f 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -32,6 +32,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; +import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; @@ -42,6 +43,7 @@ import org.springframework.stereotype.Controller; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -2238,6 +2240,79 @@ public ResponseEntity downloadTrainingResource(@RequestParam(name = "f } } + @GetMapping("/training-resources/view-share/{topic}/{lang}/{fileType}/{token}/{page}/{fileName}") + public ResponseEntity viewOrSharePdfOrImage(@PathVariable String topic, @PathVariable String lang, + @PathVariable String fileType, @PathVariable String token, @PathVariable int page, + @PathVariable String fileName) { + + try { + + int fileTypeId = ServiceUtility.getFileTypeIdByValue(fileType); + + TrainingResource tr = null; + if (fileTypeId == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileTypeId == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.notFound().build(); + } + + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, fileTypeId); + + List filePaths = new ArrayList<>(); + if (filePath.toLowerCase().endsWith(".zip")) { + List extracted = ServiceUtility.extractZipIfNeeded(filePath, env); + List sorted = ServiceUtility.sortFilePathsNumericOtherwiseLexical(extracted); + + if (fileType.equalsIgnoreCase("Pdf")) { + for (String str : sorted) { + if (!str.endsWith(".png")) { + filePaths.add(str); + } + } + } else { + filePaths.addAll(sorted); + } + + } else { + filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); + } + + if (page < 0 || page >= filePaths.size()) { + return ResponseEntity.badRequest().build(); + } + + String finalFilePath = filePaths.get(page); + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalFilePath); + + if (!Files.exists(path)) { + return ResponseEntity.notFound().build(); + } + + String contentType = Files.probeContentType(path); + if (contentType == null) { + contentType = "application/octet-stream"; + } + + String originalFilename = path.getFileName().toString(); + String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + String encodedFilename = URLEncoder.encode(safeFilename, "UTF-8").replace("+", "%20"); + + InputStreamResource resource = new InputStreamResource(Files.newInputStream(path)); + + return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename*=UTF-8''" + encodedFilename) + .body(resource); + + } catch (Exception e) { + logger.error("Error viewing shared file", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); + } + } + @RequestMapping("/loadTopicByCategoryforTR") public @ResponseBody TreeMap loadTopicByCategoryforTR(@RequestParam(value = "catId") int catId) { TreeMap topicMaps = new TreeMap<>(); diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index c6f46be3..ed0cb2d0 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -4,6 +4,9 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -27,6 +30,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; +import java.util.stream.IntStream; import javax.servlet.http.HttpServletRequest; @@ -6300,7 +6304,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("isZipFile", isZipFile); String res = ServiceUtility.convertFilePathToUrl(filePath); - model.addAttribute("filePath", res); + // model.addAttribute("filePath", res); if (res == null || res.trim().isEmpty()) { @@ -6310,7 +6314,17 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, return "sharedTrainingResource"; } res = ServiceUtility.convertFilePathToUrlWithUTFforBrowserRedirect(filePath); - return "redirect:/files/" + res; + String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + String encodedFileName = ""; + try { + encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + + logger.error("Exception", e); + } + + return "redirect:" + normalizedBaseUrl + "/training-resources/view-share/" + topicName + "/" + langName + "/" + + fileType + "/" + token + "/" + 0 + "/" + encodedFileName; } @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}/{trId}") @@ -6498,7 +6512,6 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, } else if (fileTypeString.equals("Image")) { token = tr.getImgToken(); } - model.addAttribute("token", token); String filePath = ServiceUtility.getTrainingResourceFilePath(tr, inputFileType); if (filePath.isEmpty()) { @@ -6508,10 +6521,23 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, } String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + boolean allowed = true; + + if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + + allowed = false; + + } + + if (allowed) { + model.addAttribute("token", token); + } else { + model.addAttribute("token", ""); + } if (action != null && !action.isEmpty() && action.equals("download")) { model.addAttribute("action", action); - if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + if (!allowed) { model.addAttribute("error_msg", "Authentication Error"); @@ -6573,7 +6599,22 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); } - model.addAttribute("filePaths", filePaths); + List fileNames = new ArrayList<>(); + for (String str : filePaths) { + + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), str); + String fileName = path.getFileName().toString(); + + fileNames.add(fileName); + + } + List pageIndexes = IntStream.range(0, filePaths.size()).boxed().collect(Collectors.toList()); + + if (allowed) { + model.addAttribute("pageIndexes", pageIndexes); + // model.addAttribute("filePaths", filePaths); + model.addAttribute("fileNames", fileNames); + } model.addAttribute("action", action); } @@ -6581,8 +6622,8 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, if (action != null && !action.isEmpty() && action.equals("share")) { model.addAttribute("action", action); - - model.addAttribute("shareUrl", finalUrl); + if (allowed) + model.addAttribute("shareUrl", finalUrl); } diff --git a/src/main/resources/templates/sharedTrainingResource.html b/src/main/resources/templates/sharedTrainingResource.html index f78916c8..cd1026bb 100644 --- a/src/main/resources/templates/sharedTrainingResource.html +++ b/src/main/resources/templates/sharedTrainingResource.html @@ -119,6 +119,61 @@

+ +
+ +
+
+
+
+
+
+
+
+ + +
+ +
+
+
+
+

Add Project Report

+
+
+
+
+ +
+
+ +
+ +
+ + +
+ + + + + + + + + +
+ +
+ +
+
+ +
+ + +
+ +
+ + + +
+ +
+ + + + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) + Max file size : 700 MB + +
+ +
+
+
+ + + + + + +
+
+
+ + + + +
+ + +
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Date AddedStateDistrictEnable/DisablePdf FileDoc FileExcel FileImage File
+ +
+ +
+
+ +
+ +
+
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Pdf available +
+
+
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Doc available +
+
+ +
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Excel available +
+
+ + +
+
+
+ + + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Image available +
+
+ + +
+
+ + + + + +
+ + + +
+ +
+ + +
+ + +
+ + + + + + + From d4da5deef38fb5edd900612802bf8d0e1bcdaa50 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Wed, 25 Feb 2026 09:49:24 +0530 Subject: [PATCH 11/21] state district maping repo method --- .../com/health/repository/StateDistrictMappingRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/health/repository/StateDistrictMappingRepository.java b/src/main/java/com/health/repository/StateDistrictMappingRepository.java index 9c333b35..4813039a 100644 --- a/src/main/java/com/health/repository/StateDistrictMappingRepository.java +++ b/src/main/java/com/health/repository/StateDistrictMappingRepository.java @@ -11,7 +11,7 @@ public interface StateDistrictMappingRepository extends JpaRepository { - StateDistrictMapping findByStateDisId(int topicLanId); + StateDistrictMapping findByStateDisId(int stateDisId); List findByDistrict(District district); From a88863f220b2a944354c8f18f8e7303b430f3505 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Wed, 25 Feb 2026 10:14:39 +0530 Subject: [PATCH 12/21] all districts --- src/main/java/com/health/controller/HomeController.java | 4 ++++ src/main/java/com/health/repository/DistrictRepository.java | 3 +++ src/main/java/com/health/service/DistrictService.java | 3 +++ .../java/com/health/service/impl/DistrictServiceImpl.java | 6 ++++++ src/main/resources/templates/addProjectReport.html | 2 +- 5 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 162ec67f..9d62f715 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -6671,6 +6671,10 @@ public String addProjectReportGet(HttpServletRequest req, Principal principal, M states.sort(Comparator.comparing(State::getStateName)); model.addAttribute("states", states); + Optional allDis = districtService.findByDistrictNameIgnoreCase(CommonData.ALL_DISTRICTS); + + allDis.ifPresent(dis -> model.addAttribute("allDisId", dis.getId())); + List projectReportList = new ArrayList<>(); List tempProjectReportList = projectReportService.findAll(); for (ProjectReport temp : tempProjectReportList) { diff --git a/src/main/java/com/health/repository/DistrictRepository.java b/src/main/java/com/health/repository/DistrictRepository.java index d804173c..554e0139 100644 --- a/src/main/java/com/health/repository/DistrictRepository.java +++ b/src/main/java/com/health/repository/DistrictRepository.java @@ -1,6 +1,7 @@ package com.health.repository; import java.util.List; +import java.util.Optional; import org.springframework.data.repository.CrudRepository; @@ -41,4 +42,6 @@ public interface DistrictRepository extends CrudRepository { */ List findAllBystate(State state); + Optional findByDistrictNameIgnoreCase(String districtName); + } diff --git a/src/main/java/com/health/service/DistrictService.java b/src/main/java/com/health/service/DistrictService.java index 911b696c..9e46cb9c 100644 --- a/src/main/java/com/health/service/DistrictService.java +++ b/src/main/java/com/health/service/DistrictService.java @@ -1,6 +1,7 @@ package com.health.service; import java.util.List; +import java.util.Optional; import com.health.model.District; import com.health.model.State; @@ -45,4 +46,6 @@ public interface DistrictService { */ List findAllByState(State state); + Optional findByDistrictNameIgnoreCase(String districtName); + } diff --git a/src/main/java/com/health/service/impl/DistrictServiceImpl.java b/src/main/java/com/health/service/impl/DistrictServiceImpl.java index 7e45986f..5a7777fd 100644 --- a/src/main/java/com/health/service/impl/DistrictServiceImpl.java +++ b/src/main/java/com/health/service/impl/DistrictServiceImpl.java @@ -77,4 +77,10 @@ public List findAllByState(State state) { return local; } + @Override + public Optional findByDistrictNameIgnoreCase(String districtName) { + + return distRepo.findByDistrictNameIgnoreCase(districtName); + } + } diff --git a/src/main/resources/templates/addProjectReport.html b/src/main/resources/templates/addProjectReport.html index 4d33ae18..314fb9c3 100644 --- a/src/main/resources/templates/addProjectReport.html +++ b/src/main/resources/templates/addProjectReport.html @@ -99,7 +99,7 @@

Add Project Report

- +
From 516c1fabf6f839dcddd3987ef5d45b467d396dc2 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Wed, 25 Feb 2026 14:29:22 +0530 Subject: [PATCH 13/21] addProject ajax controller, state and district --- .../com/health/config/SecurityConfig.java | 5 ++ .../com/health/controller/AjaxController.java | 32 +++++++++++++ .../com/health/controller/HomeController.java | 6 ++- src/main/java/com/health/model/City.java | 2 +- src/main/java/com/health/model/District.java | 4 +- src/main/java/com/health/model/State.java | 10 ++-- .../health/repository/DistrictRepository.java | 8 +++- .../health/repository/StateRepository.java | 6 +++ .../service/impl/DistrictServiceImpl.java | 13 ++--- .../health/service/impl/StateServiceImpl.java | 8 ++-- src/main/resources/static/js/ajaxSupport.js | 48 +++++++++++++++++++ .../resources/templates/addProjectReport.html | 23 +++------ .../resources/templates/common/sidebar.html | 15 ++++++ 13 files changed, 139 insertions(+), 41 deletions(-) diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 3ee25ff3..c724d703 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -74,6 +74,9 @@ public static BCryptPasswordEncoder passwordEncoder() { "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", + "/addProjectReport", "/projectReportAdminView/**", "/projectReport/edit/**", "/enableDisableProjectReport", + "/delete-projectReport", + // "/unpublishTutorial/**" }; @@ -102,6 +105,8 @@ public static BCryptPasswordEncoder passwordEncoder() { "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", "/addTrainingResource", "/trainingReource/view/**", "/trainingReourceAdminView/**", "/trainingReource/edit/**", "/enableDisableTrainingResource", "/delete-trainingResource", + "/addProjectReport", "/projectReportAdminView/**", "/projectReport/edit/**", "/enableDisableProjectReport", + "/delete-projectReport", }; diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 5f03aa6f..dffdefb6 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -2336,6 +2336,38 @@ public ResponseEntity viewOrSharePdfOrImage(@PathVariable String topic * Training Resource End *************************************************************/ + /********************************** + * Projet Report Start + *************************/ + + @RequestMapping("/loadDistrictByStateforPR") + public @ResponseBody TreeMap loadDistrictByStateforPR(@RequestParam(value = "stateId") int stateId, + @RequestParam(value = "allDisId") int allDisId) { + TreeMap districtMaps = new TreeMap<>(); + + if (allDisId != 0) { + District allDistrict = disService.findById(allDisId); + if (allDistrict != null) + districtMaps.put(allDistrict.getDistrictName(), allDistrict.getId()); + + } + + State state = stateService.findById(stateId); + if (state != null) { + List disList = disService.findAllByState(state); + for (District temp : disList) { + + districtMaps.put(temp.getDistrictName(), temp.getId()); + + } + + } + + return districtMaps; + } + + /********************************** Projet Report End *************************/ + @RequestMapping("/loadTopicByCategoryInAssignContri") public @ResponseBody HashMap getTopicByCategoryAssignContri(@RequestParam(value = "id") int id) { diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 9d62f715..fc6bca7e 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -6673,7 +6673,9 @@ public String addProjectReportGet(HttpServletRequest req, Principal principal, M Optional allDis = districtService.findByDistrictNameIgnoreCase(CommonData.ALL_DISTRICTS); - allDis.ifPresent(dis -> model.addAttribute("allDisId", dis.getId())); + int allDisId = allDis.map(District::getId).orElse(0); + + model.addAttribute("allDisId", allDisId); List projectReportList = new ArrayList<>(); List tempProjectReportList = projectReportService.findAll(); @@ -6727,7 +6729,7 @@ public String addProjectReportPost(HttpServletRequest req, Model model, Principa for (int i = 0; i < districtIds.size(); i++) { if (i < files.size()) - logger.info("File: {}", files.get(i)); + logger.info("File: {}", files.get(i).getOriginalFilename()); if (districtIds.get(i) != 0 && !files.get(i).isEmpty()) { District district = districtService.findById(districtIds.get(i)); diff --git a/src/main/java/com/health/model/City.java b/src/main/java/com/health/model/City.java index 9a697fe3..f3efbd5f 100644 --- a/src/main/java/com/health/model/City.java +++ b/src/main/java/com/health/model/City.java @@ -46,7 +46,7 @@ public class City implements Comparable, Serializable { @JoinColumn(name = "district_id") private District district; - @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set events = new HashSet(); public int getId() { diff --git a/src/main/java/com/health/model/District.java b/src/main/java/com/health/model/District.java index c244cdba..a9a03bbb 100644 --- a/src/main/java/com/health/model/District.java +++ b/src/main/java/com/health/model/District.java @@ -50,10 +50,10 @@ public class District implements Comparable, Serializable { @JoinColumn(name = "state_id") private State state; - @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set cities = new HashSet(); - @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set events = new HashSet(); @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) diff --git a/src/main/java/com/health/model/State.java b/src/main/java/com/health/model/State.java index 4417be5d..83eedac2 100644 --- a/src/main/java/com/health/model/State.java +++ b/src/main/java/com/health/model/State.java @@ -41,10 +41,10 @@ public class State implements Comparable, Serializable { */ private Timestamp dateAdded; - @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set Districts = new HashSet(); + @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set districts = new HashSet(); - @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set events = new HashSet(); @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @@ -83,11 +83,11 @@ public void setDateAdded(Timestamp dateAdded) { } public Set getDistricts() { - return Districts; + return districts; } public void setDistricts(Set districts) { - Districts = districts; + this.districts = districts; } @Override diff --git a/src/main/java/com/health/repository/DistrictRepository.java b/src/main/java/com/health/repository/DistrictRepository.java index 554e0139..509e11c6 100644 --- a/src/main/java/com/health/repository/DistrictRepository.java +++ b/src/main/java/com/health/repository/DistrictRepository.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.Optional; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.health.model.District; @@ -40,8 +41,13 @@ public interface DistrictRepository extends CrudRepository { * @param state state object * @return list of District object */ - List findAllBystate(State state); + List findAllByState(State state); Optional findByDistrictNameIgnoreCase(String districtName); + @Query("SELECT d FROM District d ORDER BY d.districtName") + List findAllOrderByName(); + + List findAllByStateOrderByDistrictNameAsc(State state); + } diff --git a/src/main/java/com/health/repository/StateRepository.java b/src/main/java/com/health/repository/StateRepository.java index 8cc3d62a..3daef706 100644 --- a/src/main/java/com/health/repository/StateRepository.java +++ b/src/main/java/com/health/repository/StateRepository.java @@ -1,5 +1,8 @@ package com.health.repository; +import java.util.List; + +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.health.model.State; @@ -22,4 +25,7 @@ public interface StateRepository extends CrudRepository { */ State findBystateName(String name); + @Query("SELECT s FROM State s ORDER BY s.stateName") + List findAllOrderByName(); + } diff --git a/src/main/java/com/health/service/impl/DistrictServiceImpl.java b/src/main/java/com/health/service/impl/DistrictServiceImpl.java index 5a7777fd..0195b302 100644 --- a/src/main/java/com/health/service/impl/DistrictServiceImpl.java +++ b/src/main/java/com/health/service/impl/DistrictServiceImpl.java @@ -1,6 +1,5 @@ package com.health.service.impl; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -60,10 +59,8 @@ public District findById(int id) { */ @Override public List findAll() { - // TODO Auto-generated method stub - List local = (List) distRepo.findAll(); - Collections.sort(local); - return local; + + return distRepo.findAllOrderByName(); } /** @@ -71,10 +68,8 @@ public List findAll() { */ @Override public List findAllByState(State state) { - // TODO Auto-generated method stub - List local = distRepo.findAllBystate(state); - Collections.sort(local); - return local; + + return distRepo.findAllByStateOrderByDistrictNameAsc(state); } @Override diff --git a/src/main/java/com/health/service/impl/StateServiceImpl.java b/src/main/java/com/health/service/impl/StateServiceImpl.java index ad6523cd..fed25c24 100644 --- a/src/main/java/com/health/service/impl/StateServiceImpl.java +++ b/src/main/java/com/health/service/impl/StateServiceImpl.java @@ -1,6 +1,5 @@ package com.health.service.impl; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; @@ -60,10 +59,9 @@ public State findById(int id) { */ @Override public List findAll() { - // TODO Auto-generated method stub - List local = (List) stateRepo.findAll(); - Collections.sort(local); - return local; + + return stateRepo.findAllOrderByName(); + } /** diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 6679e6e0..cc79d734 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -3356,6 +3356,54 @@ $(document).ready(function () { /******************************** Training Resource End ****************************************/ + + +/******************************** Project Report Start *****************************/ + + $("#stateIdPR").change(function() { + + var stateId = $(this).find(":selected").val(); + var allDisId = $("#allDistrict").val(); + + + $.ajax({ + type : "GET", + url : projectPath+"loadDistrictByStateforPR", + data : { + "stateId" : stateId, + "allDisId" : allDisId, + + + }, + contentType : "application/json", + success : function(result) { + + var html = ''; + html += ''; + var len = result.length; + $.each(result , function( key, value ) { + html += ''; + }) + + $(".district-select-pr").prop('disabled',false); + $('.district-select-pr').html(html); + + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + + } + + }); + + }); + + + +/******************************** Project Report End *******************************/ /***************** changes made by om prakash *********************************************/ diff --git a/src/main/resources/templates/addProjectReport.html b/src/main/resources/templates/addProjectReport.html index 314fb9c3..8fbfd476 100644 --- a/src/main/resources/templates/addProjectReport.html +++ b/src/main/resources/templates/addProjectReport.html @@ -48,7 +48,7 @@ aria-selected="true">Add + aria-selected="false">Project Report View @@ -73,7 +73,7 @@

Add Project Report

- @@ -86,23 +86,14 @@

Add Project Report

- + - + -
+
@@ -111,9 +102,9 @@

Add Project Report

- - +
diff --git a/src/main/resources/templates/common/sidebar.html b/src/main/resources/templates/common/sidebar.html index c3afe394..8c562d4d 100644 --- a/src/main/resources/templates/common/sidebar.html +++ b/src/main/resources/templates/common/sidebar.html @@ -312,6 +312,14 @@ + + +