From 45ab61575b9c75f19d18ddd3ba15a6c1a8266431 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Mon, 17 Nov 2025 12:01:39 +0530 Subject: [PATCH 01/33] resolved conflict --- .../com/health/config/SecurityConfig.java | 5 +- .../com/health/controller/HomeController.java | 222 ++++++++++++ src/main/java/com/health/model/Language.java | 11 + src/main/java/com/health/model/Topic.java | 11 + .../com/health/model/TopicLanMapping.java | 117 +++++++ .../com/health/model/TrainingResource.java | 127 +++++++ .../repository/TopicLanMappingRepository.java | 21 ++ .../TrainingResourceRepository.java | 16 + .../service/TopicLanMappingService.java | 25 ++ .../service/TrainingResourceService.java | 20 ++ .../impl/TopicLanMappingServiceImpl.java | 66 ++++ .../impl/TrainingReourceServiceImpl.java | 53 +++ .../java/com/health/utility/CommonData.java | 9 + .../com/health/utility/ServiceUtility.java | 113 +++++++ .../templates/addTrainingResource.html | 315 ++++++++++++++++++ .../resources/templates/common/sidebar.html | 18 + 16 files changed, 1148 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/health/model/TopicLanMapping.java create mode 100644 src/main/java/com/health/model/TrainingResource.java create mode 100644 src/main/java/com/health/repository/TopicLanMappingRepository.java create mode 100644 src/main/java/com/health/repository/TrainingResourceRepository.java create mode 100644 src/main/java/com/health/service/TopicLanMappingService.java create mode 100644 src/main/java/com/health/service/TrainingResourceService.java create mode 100644 src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java create mode 100644 src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java create mode 100644 src/main/resources/templates/addTrainingResource.html diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index efdf6fed..eeee32d1 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -96,6 +96,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", + "/addTrainingResource", }; @@ -155,11 +156,13 @@ protected void configure(HttpSecurity http) throws Exception { "/addTestimonial/**", "/addPromoVideo/**", "/addResearchPaper/**", "/brochure/edit/**", "/promoVideo/edit/**", "/carousel/edit/**", "/event/edit/**", "/testimonial/edit/**", "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", + "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/researchPaper/edit/**", "/enableDisableBrouchure/**", "/enableDisableConsultant/**", "/enableDisableTestimonial/**", "/addCitation/**", "/citation/edit/**", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", - "/updateCourseName") + "/updateCourseName", "/addTrainingResource") + .hasAnyAuthority("SUPER_USER", "CONTRIBUTOR").antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest() .authenticated().and().exceptionHandling().accessDeniedPage("/access-denied"); diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 66347547..7736d7ee 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -116,8 +116,10 @@ import com.health.model.Testimonial; import com.health.model.Topic; import com.health.model.TopicCategoryMapping; +import com.health.model.TopicLanMapping; import com.health.model.TraineeInformation; import com.health.model.TrainingInformation; +import com.health.model.TrainingResource; import com.health.model.TrainingTopic; import com.health.model.Tutorial; import com.health.model.TutorialWithWeekAndPackage; @@ -161,9 +163,11 @@ import com.health.service.StateService; import com.health.service.TestimonialService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TopicLanMappingService; import com.health.service.TopicService; import com.health.service.TraineeInformationService; import com.health.service.TrainingInformationService; +import com.health.service.TrainingResourceService; import com.health.service.TrainingTopicService; import com.health.service.TutorialService; import com.health.service.TutorialWithWeekAndPackageService; @@ -281,6 +285,12 @@ public class HomeController { @Autowired private WeekTitleVideoService weekTitleVideoService; + @Autowired + private TopicLanMappingService topicLanMapiingService; + + @Autowired + private TrainingResourceService trainingResourceService; + @Autowired private TopicCategoryMappingService topicCatService; @@ -5300,6 +5310,218 @@ private List getEnglishTrainingMouduleFirst(List * Assign Tutorial on Week And Package End ********************/ + @GetMapping("/addTrainingResource") + public String addTrainingResourceGet(HttpServletRequest req, Principal principal, Model model) { + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + List languages = getLanguages(); + + languages.sort(Comparator.comparing(Language::getLangName)); + + model.addAttribute("languages", languages); + + List topics = getTopics(); + model.addAttribute("topics", topics); + + return "addTrainingResource"; + } + + @PostMapping("/addTrainingResource") + public String addTrainingResourcePost(HttpServletRequest req, Model model, Principal principal, + @RequestParam(name = "topicId") int topicId, @RequestParam("langName") List lanIds, + @RequestParam(name = "file") List files) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + boolean viewSection = false; + + if (topicId == 0) { + model.addAttribute("error_msg", "Topic should not be null"); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + if (lanIds.isEmpty() || files.isEmpty()) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", "Language and Files should not be null"); + return addTrainingResourceGet(req, principal, model); + } + +// for (MultipartFile uniquefile : files) { +// if (!uniquefile.isEmpty()) { +// if (!ServiceUtility.checkFileExtensionZip(uniquefile)) { +// model.addAttribute("error_msg", "Only zip files are supported"); +// return addTrainingResourceGet(req, principal, model); +// } +// } +// +// } + + Topic topic = topicService.findById(topicId); + + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + List trainingResources = new ArrayList<>(); + + Set addedLan = new HashSet<>(); + + try { + + for (int i = 0; i < lanIds.size(); i++) { + if (i < files.size()) + logger.info("File: {}", files.get(i)); + if (lanIds.get(i) != 0 && !files.get(i).isEmpty()) { + Language language = lanService.getById(lanIds.get(i)); + + if (language != null) { + String langName = language.getLangName(); + TopicLanMapping topicLanMapping = topicLanMapiingService.findByTopicAndLan(topic, language); + + boolean addedLanFlag = addedLan.add(language); + + if (topicLanMapping == null && addedLanFlag) { + topicLanMapping = new TopicLanMapping(dateAdded, topic, language); + + topicLanMapiingService.save(topicLanMapping); + logger.info(" iter:{} TopicLanMapping :{}", i, topicLanMapping); + } + + // String zipOriginalFilename = zipFile.getOriginalFilename(); + + // Save the zip file temporarily to extract contents + // Path tempZipPath = Files.createTempFile("uploaded-", ".zip"); + // Files.write(tempZipPath, zipFile.getBytes()); + + List trList = trainingResourceService.findByTopicLanMapping(topicLanMapping); + TrainingResource tr = null; + + if (trList.isEmpty()) { + tr = new TrainingResource(); + logger.info("iter:{} TrainingResource :{}", i, tr); + + } else { + tr = trList.get(0); + } + int trId = tr.getTrainingResourceId(); + + Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); + String docFolder = Paths.get(rootPath.toString(), "docs").toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); + String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + + Set extentions = new HashSet<>(); + String document = ""; + + MultipartFile file = files.get(i); + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file Error at language:" + langName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + tr.setPdfPath(document); + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + tr.setDocPath(document); + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + tr.setExcelPath(document); + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + tr.setImgPath(document); + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + // ZipFile zip=new ZipFile(file.getOriginalFilename()); + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + tr.setPdfPath(document); + } + + else if (ext.equals(CommonData.DOC_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + tr.setDocPath(document); + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + tr.setExcelPath(document); + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + tr.setImgPath(document); + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", + "Unsupported file Error at language:" + langName); + + return addTrainingResourceGet(req, principal, model); + } + + } + } + + else { + model.addAttribute("error_msg", + "Zip contains different types of files Error at language:" + langName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addTrainingResourceGet(req, principal, model); + } + + } + + tr.setDateAdded(dateAdded); + tr.setTopicLanMapping(topicLanMapping); + trainingResources.add(tr); + // Files.deleteIfExists(tempZipPath); + + } + + } + + } + + trainingResourceService.saveAll(trainingResources); + + } catch (Exception e) { + model.addAttribute("error_msg", "Some errors occurred, please contact the Admin"); + logger.error("Error:", e); + return addTrainingResourceGet(req, principal, model); + } + + model.addAttribute("viewSection", viewSection); + model.addAttribute("success_msg", CommonData.RECORD_SAVE_SUCCESS_MSG); + return addTrainingResourceGet(req, principal, model); + } + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/java/com/health/model/Language.java b/src/main/java/com/health/model/Language.java index 1c791ed1..8d8b1f92 100644 --- a/src/main/java/com/health/model/Language.java +++ b/src/main/java/com/health/model/Language.java @@ -94,6 +94,17 @@ public class Language implements Comparable, Serializable { @OneToMany(mappedBy = "lan", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set packageLanguages = new HashSet(); + @OneToMany(mappedBy = "lan", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set topicLanMappings = new HashSet(); + + public Set getTopicLanMappings() { + return topicLanMappings; + } + + public void setTopicLanMappings(Set topicLanMappings) { + this.topicLanMappings = topicLanMappings; + } + public Set getLiveTutorial() { return liveTutorial; } diff --git a/src/main/java/com/health/model/Topic.java b/src/main/java/com/health/model/Topic.java index ce5f1f2c..d30c449a 100644 --- a/src/main/java/com/health/model/Topic.java +++ b/src/main/java/com/health/model/Topic.java @@ -67,6 +67,17 @@ public class Topic implements Comparable, Serializable { @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set courseCatTopicMappings = new HashSet(); + @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set topicLanMappingd = new HashSet(); + + public Set getTopicLanMappingd() { + return topicLanMappingd; + } + + public void setTopicLanMappingd(Set topicLanMappingd) { + this.topicLanMappingd = topicLanMappingd; + } + public int getTopicId() { return topicId; } diff --git a/src/main/java/com/health/model/TopicLanMapping.java b/src/main/java/com/health/model/TopicLanMapping.java new file mode 100644 index 00000000..a1cf0216 --- /dev/null +++ b/src/main/java/com/health/model/TopicLanMapping.java @@ -0,0 +1,117 @@ +package com.health.model; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "topic_lan_mapping") +public class TopicLanMapping implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "topic_lan_id", nullable = false, updatable = false) + private int topicLanId; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @ManyToOne + @JoinColumn(name = "topic_id") + private Topic topic; + + @ManyToOne + @JoinColumn(name = "lang_id") + private Language lan; + + @OneToMany(mappedBy = "topicLanMapping", cascade = CascadeType.ALL) + private Set trainingResources = new HashSet(); + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public Topic getTopic() { + return topic; + } + + public void setTopic(Topic topic) { + this.topic = topic; + } + + public int getTopicLanId() { + return topicLanId; + } + + public void setTopicLanId(int topicLanId) { + this.topicLanId = topicLanId; + } + + public Language getLan() { + return lan; + } + + public void setLan(Language lan) { + this.lan = lan; + } + + public Set getTrainingResources() { + return trainingResources; + } + + public void setTrainingResources(Set trainingResources) { + this.trainingResources = trainingResources; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public TopicLanMapping() { + + } + + public TopicLanMapping(Timestamp dateAdded, Topic topic, Language lan) { + + this.dateAdded = dateAdded; + this.topic = topic; + this.lan = lan; + } + + public static Comparator SortByTopicName = new Comparator() { + + @Override + public int compare(TopicLanMapping t1, TopicLanMapping t2) { + + return t1.getTopic().getTopicName().compareTo(t2.getTopic().getTopicName()); + + } + }; + +} diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java new file mode 100644 index 00000000..6e8cf011 --- /dev/null +++ b/src/main/java/com/health/model/TrainingResource.java @@ -0,0 +1,127 @@ +package com.health.model; + +import java.io.Serializable; +import java.sql.Timestamp; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "training_resource") +public class TrainingResource implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "training_res_id", nullable = false, updatable = false) + private int trainingResourceId; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @ManyToOne + @JoinColumn(name = "topic_lan_id") + private TopicLanMapping topicLanMapping; + + @Column(name = "pdf_path", length = 1000) + private String pdfPath; + + @Column(name = "doc_path", length = 1000) + private String docPath; + + @Column(name = "excel_path", length = 1000) + private String excelPath; + + @Column(name = "img_path", length = 1000) + private String imgPath; + + public int getTrainingResourceId() { + return trainingResourceId; + } + + public void setTrainingResourceId(int trainingResourceId) { + this.trainingResourceId = trainingResourceId; + } + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public TopicLanMapping getTopicLanMapping() { + return topicLanMapping; + } + + public void setTopicLanMapping(TopicLanMapping topicLanMapping) { + this.topicLanMapping = topicLanMapping; + } + + public String getPdfPath() { + return pdfPath; + } + + public void setPdfPath(String pdfPath) { + this.pdfPath = pdfPath; + } + + public String getDocPath() { + return docPath; + } + + public void setDocPath(String docPath) { + this.docPath = docPath; + } + + public String getExcelPath() { + return excelPath; + } + + public void setExcelPath(String excelPath) { + this.excelPath = excelPath; + } + + public String getImgPath() { + return imgPath; + } + + public void setImgPath(String imgPath) { + this.imgPath = imgPath; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, String pdfPath, String docPath, + String excelPath, String imgPath) { + + this.dateAdded = dateAdded; + this.topicLanMapping = topicLanMapping; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + } + + public TrainingResource() { + + } + +} diff --git a/src/main/java/com/health/repository/TopicLanMappingRepository.java b/src/main/java/com/health/repository/TopicLanMappingRepository.java new file mode 100644 index 00000000..ffd2204c --- /dev/null +++ b/src/main/java/com/health/repository/TopicLanMappingRepository.java @@ -0,0 +1,21 @@ +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; + +public interface TopicLanMappingRepository extends JpaRepository { + + TopicLanMapping findByTopicLanId(int topicLanId); + + List findByLan(Language lan); + + List findByTopic(Topic topic); + + TopicLanMapping findByTopicAndLan(Topic topic, Language lan); + +} diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java new file mode 100644 index 00000000..6a0c63cc --- /dev/null +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -0,0 +1,16 @@ +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; + +public interface TrainingResourceRepository extends JpaRepository { + + TrainingResource findByTrainingResourceId(int trainingResourceId); + + List findByTopicLanMapping(TopicLanMapping topicLanMapping); + +} diff --git a/src/main/java/com/health/service/TopicLanMappingService.java b/src/main/java/com/health/service/TopicLanMappingService.java new file mode 100644 index 00000000..24f00fc8 --- /dev/null +++ b/src/main/java/com/health/service/TopicLanMappingService.java @@ -0,0 +1,25 @@ +package com.health.service; + +import java.util.List; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; + +public interface TopicLanMappingService { + + TopicLanMapping findBTopicLanId(int topicLanId); + + List findByLan(Language lan); + + List findByTopic(Topic topic); + + TopicLanMapping findByTopicAndLan(Topic topic, Language lan); + + List findAll(); + + void save(TopicLanMapping topicLanMapping); + + void saveAll(List topicLanMappingList); + +} diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java new file mode 100644 index 00000000..9046550c --- /dev/null +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -0,0 +1,20 @@ +package com.health.service; + +import java.util.List; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; + +public interface TrainingResourceService { + + TrainingResource findBTrainingResourceId(int trainingResourceId); + + List findByTopicLanMapping(TopicLanMapping topicLanMapping); + + List findAll(); + + void save(TrainingResource trainingResource); + + void saveAll(List trainingResourceList); + +} diff --git a/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java b/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java new file mode 100644 index 00000000..88f5cbf3 --- /dev/null +++ b/src/main/java/com/health/service/impl/TopicLanMappingServiceImpl.java @@ -0,0 +1,66 @@ +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.Language; +import com.health.model.Topic; +import com.health.model.TopicLanMapping; +import com.health.repository.TopicLanMappingRepository; +import com.health.service.TopicLanMappingService; + +@Service +public class TopicLanMappingServiceImpl implements TopicLanMappingService { + + private static final Logger logger = LoggerFactory.getLogger(TopicLanMappingServiceImpl.class); + + @Autowired + private TopicLanMappingRepository repo; + + @Override + public TopicLanMapping findBTopicLanId(int topicLanId) { + + return repo.findByTopicLanId(topicLanId); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public void save(TopicLanMapping topicLanMapping) { + repo.save(topicLanMapping); + + } + + @Override + public void saveAll(List topicLanMappingList) { + repo.saveAll(topicLanMappingList); + + } + + @Override + public List findByLan(Language lan) { + + return repo.findByLan(lan); + } + + @Override + public List findByTopic(Topic topic) { + + return repo.findByTopic(topic); + } + + @Override + public TopicLanMapping findByTopicAndLan(Topic topic, Language lan) { + + return repo.findByTopicAndLan(topic, lan); + } + +} diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java new file mode 100644 index 00000000..04b23e06 --- /dev/null +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -0,0 +1,53 @@ +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.TopicLanMapping; +import com.health.model.TrainingResource; +import com.health.repository.TrainingResourceRepository; +import com.health.service.TrainingResourceService; + +@Service +public class TrainingReourceServiceImpl implements TrainingResourceService { + + private static final Logger logger = LoggerFactory.getLogger(TrainingReourceServiceImpl.class); + + @Autowired + private TrainingResourceRepository repo; + + @Override + public TrainingResource findBTrainingResourceId(int trainingResourceId) { + + return repo.findByTrainingResourceId(trainingResourceId); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public void save(TrainingResource trainingResource) { + repo.save(trainingResource); + + } + + @Override + public void saveAll(List trainingResourceList) { + repo.saveAll(trainingResourceList); + + } + + @Override + public List findByTopicLanMapping(TopicLanMapping topicLanMapping) { + + return repo.findByTopicLanMapping(topicLanMapping); + } + +} diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 4b9541b1..46e157aa 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -163,6 +163,8 @@ public class CommonData { public static String uploadBrouchure = "Media/Content/Brochure/"; + public static String uploadTrainingResource = "Media/Content/TrainingResource/"; + public static String uploadPromoVideo = "Media/Content/PromoVideo/"; public static String uploadVersion = "Media/Content/Version/"; @@ -270,6 +272,13 @@ public class CommonData { public int HANDLER_DATA = 10000000; + public static final String PDF_EXTENSION = "pdf"; + public static final String EXCEL_EXTENSION = "excel"; + public static final String DOC_EXTENSION = "doc"; + public static final String IMAGE_EXTENSION = "img"; + public static final String ZIP_EXTENSION = "zip"; + public static final String UNSUPPORTED_EXTENSION = "unsupported"; + public static final String STATUS = "status"; public static final String STATUS_QUEUED = "queued"; public static final String STATUS_PROCESSING = "processing"; diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index cb49d229..a67584e8 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -4,6 +4,7 @@ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -22,12 +23,17 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; +import java.util.Enumeration; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.imageio.ImageIO; @@ -37,6 +43,7 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.io.FilenameUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; @@ -378,6 +385,112 @@ public static boolean checkFileExtensionImage(MultipartFile temp) { // validate return true; } + /* + * check FileExtention of Training Resource + * + */ + + public static String checkFileExtensions(MultipartFile file) { + String filename = file.getOriginalFilename(); + if (filename == null) { + return CommonData.UNSUPPORTED_EXTENSION; + } + + String lowerCaseFilename = filename.toLowerCase(); + + if (lowerCaseFilename.endsWith(".pdf")) { + return CommonData.PDF_EXTENSION; + } else if (lowerCaseFilename.endsWith(".csv") || lowerCaseFilename.endsWith(".ods") + || lowerCaseFilename.endsWith(".xlsx")) { + return CommonData.EXCEL_EXTENSION; + } else if (lowerCaseFilename.endsWith(".docx") || lowerCaseFilename.endsWith(".odt") + || lowerCaseFilename.endsWith(".rtf")) { + return CommonData.DOC_EXTENSION; + } else if (lowerCaseFilename.endsWith(".png") || lowerCaseFilename.endsWith(".jpg") + || lowerCaseFilename.endsWith(".jpeg")) { + return CommonData.IMAGE_EXTENSION; + } else if (lowerCaseFilename.endsWith(".zip")) { + return CommonData.ZIP_EXTENSION; + } else { + return CommonData.UNSUPPORTED_EXTENSION; + } + } + + /** + * Check file extentions of zip for training Resource + * + * @throws IOException + * @throws FileNotFoundException + * + */ + + public static Set checkFileExtentionsInZip(MultipartFile file) { + Set extensions = new HashSet<>(); + + try (ZipInputStream zis = new ZipInputStream(file.getInputStream())) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (!entry.isDirectory()) { + String ext = FilenameUtils.getExtension(entry.getName()).toLowerCase(); + if (ext.equals("pdf")) { + extensions.add(CommonData.PDF_EXTENSION); + } else if (ext.equals("csv") || ext.equals("ods") || ext.equals("xlsx")) { + extensions.add(CommonData.EXCEL_EXTENSION); + } else if (ext.equals("png") || ext.equals("jpg") || ext.equals("jpeg")) { + extensions.add(CommonData.IMAGE_EXTENSION); + } else if (ext.equals("docx") || ext.equals("odt") || ext.equals("rtf")) { + extensions.add(CommonData.DOC_EXTENSION); + } + + else { + extensions.add(CommonData.UNSUPPORTED_EXTENSION); + } + } + } + } catch (Exception e) { + logger.error("Exception Error in checkFileExtentionsINZip", e); + } + + logger.info("Extensions found in zip: {}", extensions); + + return extensions; + + } + + public static Set checkFileExtentionsInZip(ZipFile zip) { + Set extensions = new HashSet<>(); + + try { + + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + ZipEntry entry = (ZipEntry) e.nextElement(); + if (!entry.isDirectory()) { + String ext = FilenameUtils.getExtension(entry.getName()).toLowerCase(); + if (ext.equals("pdf")) { + extensions.add(CommonData.PDF_EXTENSION); + } else if (ext.equals("csv") || ext.equals("ods") || ext.equals("xlsx")) { + extensions.add(CommonData.EXCEL_EXTENSION); + } else if (ext.equals("png") || ext.equals("jpg") || ext.equals("jpeg")) { + extensions.add(CommonData.IMAGE_EXTENSION); + } else if (ext.equals("docx") || ext.equals("odt") || ext.equals("rtf")) { + extensions.add(CommonData.DOC_EXTENSION); + } + + else { + extensions.add(CommonData.UNSUPPORTED_EXTENSION); + } + } + } + } catch (Exception e) { + logger.error("Exception Error in checkFileExtentionsINZip", e); + } + + logger.info("Extensions found in zip: {}", extensions); + + return extensions; + + } + /** * to check whether MP4 file or not * diff --git a/src/main/resources/templates/addTrainingResource.html b/src/main/resources/templates/addTrainingResource.html new file mode 100644 index 00000000..3d362c58 --- /dev/null +++ b/src/main/resources/templates/addTrainingResource.html @@ -0,0 +1,315 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+ +
+
+
+
+

Add Training Resource

+
+
+
+
+ +
+
+ +
+ + + + +
+ + +
+ + + + + + +
+ +
+ +
+
+ +
+ + +
+ +
+ + + +
+ +
+ + + + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) + Max file size : 700 MB + +
+ +
+
+
+ + + + + + +
+
+
+ + + + +
+ + +
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Date AddedTopicLanguageEnable/DisableFiles
+ +
+ +
+
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + Edit + + Edit + + +
PNG FilePDF FileDOC FileExcel File
+ Edit + Edit
+
+
+
+ + + + + +
+ + + +
+ +
+ + +
+ + +
+ + + + + + diff --git a/src/main/resources/templates/common/sidebar.html b/src/main/resources/templates/common/sidebar.html index ca30f3c6..c3afe394 100644 --- a/src/main/resources/templates/common/sidebar.html +++ b/src/main/resources/templates/common/sidebar.html @@ -296,10 +296,19 @@ + + + @@ -510,10 +519,19 @@ + + + From 2d84499c4fa1df8ecedf918b9904ca860071d54b Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Fri, 2 May 2025 12:13:53 +0530 Subject: [PATCH 02/33] add Training Resource post and template --- .../com/health/controller/HomeController.java | 28 +-- .../com/health/model/TrainingResource.java | 33 +++ .../templates/addTrainingResource.html | 220 +++++++++++++----- 3 files changed, 200 insertions(+), 81 deletions(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 7736d7ee..1367a187 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5323,7 +5323,9 @@ public String addTrainingResourceGet(HttpServletRequest req, Principal principal model.addAttribute("languages", languages); List topics = getTopics(); + List trainingResourceList = trainingResourceService.findAll(); model.addAttribute("topics", topics); + model.addAttribute("trainingResourceList", trainingResourceList); return "addTrainingResource"; } @@ -5353,22 +5355,10 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ return addTrainingResourceGet(req, principal, model); } -// for (MultipartFile uniquefile : files) { -// if (!uniquefile.isEmpty()) { -// if (!ServiceUtility.checkFileExtensionZip(uniquefile)) { -// model.addAttribute("error_msg", "Only zip files are supported"); -// return addTrainingResourceGet(req, principal, model); -// } -// } -// -// } - Topic topic = topicService.findById(topicId); Timestamp dateAdded = ServiceUtility.getCurrentTime(); - List trainingResources = new ArrayList<>(); - Set addedLan = new HashSet<>(); try { @@ -5392,12 +5382,6 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ logger.info(" iter:{} TopicLanMapping :{}", i, topicLanMapping); } - // String zipOriginalFilename = zipFile.getOriginalFilename(); - - // Save the zip file temporarily to extract contents - // Path tempZipPath = Files.createTempFile("uploaded-", ".zip"); - // Files.write(tempZipPath, zipFile.getBytes()); - List trList = trainingResourceService.findByTopicLanMapping(topicLanMapping); TrainingResource tr = null; @@ -5452,7 +5436,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { - // ZipFile zip=new ZipFile(file.getOriginalFilename()); + extentions = ServiceUtility.checkFileExtentionsInZip(file); if (extentions.size() == 1) { for (String ext : extentions) { @@ -5500,8 +5484,8 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { tr.setDateAdded(dateAdded); tr.setTopicLanMapping(topicLanMapping); - trainingResources.add(tr); - // Files.deleteIfExists(tempZipPath); + + trainingResourceService.save(tr); } @@ -5509,8 +5493,6 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { } - trainingResourceService.saveAll(trainingResources); - } catch (Exception e) { model.addAttribute("error_msg", "Some errors occurred, please contact the Admin"); logger.error("Error:", e); diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 6e8cf011..8d9a2a87 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -1,6 +1,7 @@ package com.health.model; import java.io.Serializable; +import java.nio.file.Paths; import java.sql.Timestamp; import javax.persistence.Column; @@ -101,6 +102,38 @@ public void setImgPath(String imgPath) { this.imgPath = imgPath; } + public String getPdfFileNameWithorWitoutZip() { + if (pdfPath == null || pdfPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(pdfPath).getFileName().toString(); + return fileName; + } + + public String getDocFileNameWithorWitoutZip() { + if (docPath == null || docPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(docPath).getFileName().toString(); + return fileName; + } + + public String getExcelFileNameWithorWitoutZip() { + if (excelPath == null || excelPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(excelPath).getFileName().toString(); + return fileName; + } + + public String getImageFileNameWithorWitoutZip() { + if (imgPath == null || imgPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(imgPath).getFileName().toString(); + return fileName; + } + public Timestamp getDateAdded() { return dateAdded; } diff --git a/src/main/resources/templates/addTrainingResource.html b/src/main/resources/templates/addTrainingResource.html index 3d362c58..d1bd4ff9 100644 --- a/src/main/resources/templates/addTrainingResource.html +++ b/src/main/resources/templates/addTrainingResource.html @@ -13,23 +13,7 @@ font-weight:bold!important; } - .trainingResourceTable { - background-color: #f8f9fa; /* Light gray background */ - color: #333; /* Dark text color */ - } - - .trainingResourceTable th { - background-color: #007bff; /* Blue header background */ - color: white; /* White header text */ - } - - .trainingResourceTable td { - background-color: #ffffff; /* White cell background */ - } - - .trainingResourceTable tr:nth-child(even) td { - background-color: #f2f2f2; /* Light gray for even rows */ - } + @@ -133,7 +117,7 @@

Add Training Resource

- + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) Max file size : 700 MB @@ -173,59 +157,182 @@

Add Training Resource

Date Added Topic - Language Enable/Disable - Files + Pdf File + Doc File + Excel File + Image File - + - - + +
- +
- +
+ + +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Pdf available +
+
+ + + + + +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Doc available +
+
+ + + + + +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Excel available +
+
+ + + + + +
+
+ + + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Image available +
+
+ + + - -
- - - - - - - - - - - - - - - - - - Edit - - Edit - - -
PNG FilePDF FileDOC FileExcel File
- Edit - Edit
-
- + @@ -253,11 +360,8 @@

Add Training Resource

+ +
+ + + + + + + + + + \ No newline at end of file From 586199b72d94a24b400a8c4600a8067f7d10b15b Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Tue, 3 Jun 2025 17:38:53 +0530 Subject: [PATCH 05/33] doc and excel to pdf --- .../com/health/controller/HomeController.java | 53 ++++- .../java/com/health/utility/CommonData.java | 1 + .../health/utility/FileConversionUtility.java | 198 ++++++++++++++++++ .../templates/trainingResourceViewAdmin.html | 14 +- 4 files changed, 262 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/health/utility/FileConversionUtility.java diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 15d2f047..43a4aba2 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -182,6 +182,7 @@ import com.health.threadpool.ZipCreationThreadService; import com.health.threadpool.ZipHealthTutorialThreadService; import com.health.utility.CommonData; +import com.health.utility.FileConversionUtility; import com.health.utility.MailConstructor; import com.health.utility.SecurityUtility; import com.health.utility.ServiceUtility; @@ -216,6 +217,9 @@ public class HomeController { @Autowired private CommonData commonData; + @Autowired + private FileConversionUtility fileConversionUtility; + @Autowired private LiveTutorialService liveTutorialService; @@ -393,6 +397,9 @@ public class HomeController { @Value("${scriptmanager_path}") private String scriptmanager_path; + @Value("${doc_to_pdf.command}") + private String doctoPdfCommand; + private static YouTube youtube; private static final String VIDEO_FILE_FORMAT = "video/*"; @@ -5558,8 +5565,52 @@ else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { } + // Conversion of doc/excel to pdf and pdf to thumbnails. + List finalFilePath = new ArrayList<>(); + + if (!fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + for (String str : filePaths) { + + /* + * Here we check png beacuse parent folder may have alreday created thumnails + * and their paths have been added in filePaths from extractZipIfNeeded function + * if zip is alreday extracted then that folder is used for pdf and thumnails + * too. + * + */ + if (!str.endsWith(".png")) { + finalFilePath.add(str); + fileConversionUtility.generateThumbnailFromPdfAndSave(str); + } + + } + } + + else { + // Intially we convert both doc and excel using same libreoffice cmd + for (String str : filePaths) { + /* + * Here we check png and pdf beacuse parent folder may have alreday created + * thumnails and pdfs and their respective paths have been added in filePaths + * from extractZipIfNeeded function if zip is alreday extracted then that folder + * is used for pdf and thumnails too. + * + */ + if (!str.endsWith(".png") && !str.endsWith(".pdf")) { + finalFilePath.add(str); + String pdfPath = fileConversionUtility.convertDoctoPdf(str, doctoPdfCommand); + fileConversionUtility.generateThumbnailFromPdfAndSave(pdfPath); + } + + } + } + } else { + finalFilePath.addAll(filePaths); + } + model.addAttribute("trainingResource", tr); - model.addAttribute("filePaths", filePaths); + model.addAttribute("filePaths", finalFilePath); logger.info("Alok Kumar"); for (String str : filePaths) { logger.info("file Path :{}", str); diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 2099d78b..e8f72ee7 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -330,6 +330,7 @@ public class CommonData { public static final Long TASK_SLEEP_TIME = 10L * 1000; public static final Long NO_TASK_SLEEP_TIME_FOR_DELETE = 60L * 1000 * 60; public static final Long TASK_SLEEP_TIME_FOR_DELETE = 60L * 1000 * 60; + public static final int TIME_UNIT_FOR_WAIT = 60; // public static String SCRIPT_MANAGER_VIEW= "view/healthnutrition"; diff --git a/src/main/java/com/health/utility/FileConversionUtility.java b/src/main/java/com/health/utility/FileConversionUtility.java new file mode 100644 index 00000000..c724410f --- /dev/null +++ b/src/main/java/com/health/utility/FileConversionUtility.java @@ -0,0 +1,198 @@ +package com.health.utility; + +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import javax.imageio.ImageIO; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class FileConversionUtility { + + private static final Logger logger = LoggerFactory.getLogger(FileConversionUtility.class); + + @Value("${spring.applicationexternalPath.name}") + private String mediaRoot; + + @Value("${doc_to_pdf.command}") + private String doctoPdfCommand; + + public String convertDoctoPdf(String inputFilePath, String libreOfficeCommand) { + String document = ""; + boolean shouldConvert = true; + + Path docPath = Paths.get(mediaRoot, inputFilePath); + Path pdfDirPath = docPath.getParent(); + + try { + if (docPath == null || pdfDirPath == null || !Files.exists(docPath)) { + logger.warn("Invalid document or directory path."); + return ""; + } + + String fileNameWithoutExt = docPath.getFileName().toString().replaceFirst("[.][^.]+$", ""); + Path pdfPath = Paths.get(pdfDirPath.toString(), fileNameWithoutExt + ".pdf"); + + if (Files.exists(pdfPath)) { + if (Files.getLastModifiedTime(pdfPath).toMillis() > Files.getLastModifiedTime(docPath).toMillis()) { + shouldConvert = false; + } + } + + if (shouldConvert) { + // Replace placeholders + String commandStr = libreOfficeCommand.replace("{input}", docPath.toString()).replace("{outdir}", + pdfDirPath.toString()); + + logger.debug("Resolved command: {}", commandStr); + + List commandTokens = tokenizeCommand(commandStr); + + ProcessBuilder processBuilder = new ProcessBuilder(commandTokens); + Process process = processBuilder.start(); + + // Read standard output + try (InputStream inputStream = process.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = reader.readLine()) != null) { + logger.info("LibreOffice Output: {}", line); + } + } + + // Read error output + try (InputStream errorStream = process.getErrorStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { + String line; + while ((line = reader.readLine()) != null) { + logger.warn("LibreOffice Error: {}", line); + } + } + + boolean finished = process.waitFor(CommonData.TIME_UNIT_FOR_WAIT, TimeUnit.SECONDS); + int exitCode = finished ? process.exitValue() : 1; + + if (!finished) { + logger.warn("LibreOffice process did not finish in time. Destroying process..."); + process.destroy(); + } + + if (exitCode == 0 && Files.exists(pdfPath)) { + String absolutePath = pdfPath.toString(); + int indexToStart = absolutePath.indexOf("Media"); + document = (indexToStart != -1) ? absolutePath.substring(indexToStart) : absolutePath; + } else { + logger.error("Document conversion failed or timed out: {}", docPath); + } + } + + } catch (IOException | InterruptedException e) { + logger.error("Exception during document conversion", e); + Thread.currentThread().interrupt(); // preserve interrupt status + } + + return document; + } + + /** + * Tokenizes a command string into individual arguments, respecting quoted + * segments that may contain spaces. + */ + private List tokenizeCommand(String commandTemplate) { + List tokens = new ArrayList<>(); + boolean inQuotes = false; + StringBuilder current = new StringBuilder(); + + for (char c : commandTemplate.toCharArray()) { + if (c == '"') { + inQuotes = !inQuotes; + } else if (c == ' ' && !inQuotes) { + if (current.length() > 0) { + tokens.add(current.toString()); + current.setLength(0); + } + } else { + current.append(c); + } + } + + if (current.length() > 0) { + tokens.add(current.toString()); + } + + return tokens; + } + + public String generateThumbnailFromPdfAndSave(String pdfFilePath) { + Path pdfPath = Paths.get(mediaRoot, pdfFilePath); + Path thumbnailDirPath = pdfPath.getParent(); + String fileNameWithoutExt = pdfPath.getFileName().toString().replaceFirst("[.][^.]+$", ""); + boolean shouldConvert = true; + String resultPathofThumbnail = ""; + + // Check if the PDF path is valid + if (pdfFilePath.isEmpty() || pdfFilePath.equals("") || pdfPath == null || !Files.exists(pdfPath)) { + logger.warn("PDF file does not exist: {}", pdfPath); + return ""; + } + if (!Files.isReadable(pdfPath)) { + logger.error("PDF file is not readable (access denied): {}", pdfPath); + return ""; + } + + // Define thumbnail path + Path thumbnailPath = Paths.get(thumbnailDirPath.toString(), fileNameWithoutExt + ".png"); + String thumbnailPathStr = thumbnailPath.toString(); + + try (PDDocument document = PDDocument.load(pdfPath.toFile())) { + if (Files.exists(thumbnailPath)) { + if (Files.getLastModifiedTime(thumbnailPath).toMillis() > Files.getLastModifiedTime(pdfPath) + .toMillis()) { + shouldConvert = false; + } + } + + if (shouldConvert) { + PDFRenderer pdfRenderer = new PDFRenderer(document); + BufferedImage image = pdfRenderer.renderImageWithDPI(0, 15); // Render first page at 15 DPI + + if (image.getHeight() > 200) { + int newDPI = (int) Math.ceil(15.0 * 200 / image.getHeight()); + if (newDPI > 2 && newDPI < 15) { + image = pdfRenderer.renderImageWithDPI(0, newDPI); + } + } + + // Save thumbnail image + File outputFile = thumbnailPath.toFile(); + ImageIO.write(image, "png", outputFile); + } + + int indexToStart = thumbnailPathStr.indexOf("Media"); + resultPathofThumbnail = (indexToStart != -1) ? thumbnailPathStr.substring(indexToStart) : thumbnailPathStr; + + ServiceUtility.convertFilePathToUrl(resultPathofThumbnail); + + } catch (Exception e) { + logger.error("Error in thumbnail creation for file: {}", pdfPath, e); + } + + return resultPathofThumbnail; + } +} diff --git a/src/main/resources/templates/trainingResourceViewAdmin.html b/src/main/resources/templates/trainingResourceViewAdmin.html index e2eb7162..cb62eabc 100644 --- a/src/main/resources/templates/trainingResourceViewAdmin.html +++ b/src/main/resources/templates/trainingResourceViewAdmin.html @@ -65,7 +65,7 @@
-
+
@@ -73,8 +73,10 @@
- - + + Thumbnail + @@ -87,6 +89,9 @@
+ + Thumbnail
Download Word @@ -98,6 +103,9 @@
+ + Thumbnail
Download Excel From 22ea9ffa2eff0dabe73b87b763aed5504fc8cf05 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Mon, 29 Sep 2025 13:50:56 +0530 Subject: [PATCH 06/33] resolved conflict --- .../com/health/config/SecurityConfig.java | 1 + .../com/health/controller/HomeController.java | 62 +++++++++ .../templates/updateTrainingResource.html | 120 ++++++++++++++++++ 3 files changed, 183 insertions(+) create mode 100644 src/main/resources/templates/updateTrainingResource.html diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index f1140f71..684ae8b6 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -98,6 +98,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", "/addTrainingResource", "/trainingReource/view/**", "/trainingReourceAdminView/**", + "/trainingReource/edit/**", }; diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 43a4aba2..aa1b3f79 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5619,6 +5619,68 @@ else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { return "trainingResourceViewAdmin"; } + @GetMapping("/trainingReource/edit/{fileType}/{id}") + public String TrainingResourceEditGet(@PathVariable String fileType, @PathVariable int id, HttpServletRequest req, + Model model, Principal principal) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + TrainingResource tr = trainingResourceService.findByTrainingResourceId(id); + + if (tr == null) { + + return "redirect:/addTrainingResource"; + } + Topic topic = tr.getTopicLanMapping().getTopic(); + Language lan = tr.getTopicLanMapping().getLan(); + List languages = getLanguages(); + languages.sort(Comparator.comparing(Language::getLangName)); + List topics = getTopics(); + List trainingResourceList = trainingResourceService.findAll(); + model.addAttribute("languages", languages); + model.addAttribute("topics", topics); + model.addAttribute("trainingResourceList", trainingResourceList); + model.addAttribute("trainingResource", tr); + model.addAttribute("topic", topic); + model.addAttribute("language", lan); + model.addAttribute("id", id); + String filePath = ""; + + if (fileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + filePath = tr.getDocPath(); + model.addAttribute("fileType", "Doc"); + + } + + else if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + filePath = tr.getPdfPath(); + model.addAttribute("fileType", "Pdf"); + } + + else if (fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + filePath = tr.getImgPath(); + model.addAttribute("fileType", "Image"); + } + + else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + filePath = tr.getExcelPath(); + model.addAttribute("fileType", "Excel"); + } + + if (filePath.toLowerCase().endsWith(".zip")) { + model.addAttribute("zipFile", filePath); + } + + else { + model.addAttribute("nonZipFile", filePath); + + } + + return "updateTrainingResource"; + } + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/resources/templates/updateTrainingResource.html b/src/main/resources/templates/updateTrainingResource.html new file mode 100644 index 00000000..2f479430 --- /dev/null +++ b/src/main/resources/templates/updateTrainingResource.html @@ -0,0 +1,120 @@ + + + + + + +
+
+ +
+ + + + + + + + \ No newline at end of file From 99bb8e825c65d1a65aad05fd875faddc20d197b5 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Tue, 24 Jun 2025 11:51:36 +0530 Subject: [PATCH 07/33] update Training Resource Post --- .../com/health/controller/HomeController.java | 249 +++++++++++++++++- .../templates/updateTrainingResource.html | 1 + 2 files changed, 248 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index aa1b3f79..666450b7 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5611,7 +5611,7 @@ else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { model.addAttribute("trainingResource", tr); model.addAttribute("filePaths", finalFilePath); - logger.info("Alok Kumar"); + for (String str : filePaths) { logger.info("file Path :{}", str); } @@ -5620,7 +5620,7 @@ else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { } @GetMapping("/trainingReource/edit/{fileType}/{id}") - public String TrainingResourceEditGet(@PathVariable String fileType, @PathVariable int id, HttpServletRequest req, + public String trainingResourceEditGet(@PathVariable String fileType, @PathVariable int id, HttpServletRequest req, Model model, Principal principal) { User usr = getUser(principal); @@ -5681,6 +5681,251 @@ else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { return "updateTrainingResource"; } + @PostMapping("/updateTrainingResource") + public String updateTrainingResourcePost(HttpServletRequest req, Model model, Principal principal, + @RequestParam("file") MultipartFile file) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + + model.addAttribute("userInfo", usr); + + String trId = req.getParameter("trId"); + String topicId = req.getParameter("topicId"); + String lanId = req.getParameter("lanId"); + String fileType = req.getParameter("fileType"); + int trIdInt = Integer.parseInt(trId); + int topicIdInt = Integer.parseInt(topicId); + int lanIdInt = Integer.parseInt(lanId); + + Topic topic = topicService.findById(topicIdInt); + Language lan = lanService.getById(lanIdInt); + + TopicLanMapping topicLan = topicLanMapiingService.findByTopicAndLan(topic, lan); + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + String originalFileType = ""; + String oldPath = ""; + TrainingResource oldTrainingResource = trainingResourceService.findByTrainingResourceId(trIdInt); + boolean fileMatch = false; + + if (fileType.equals("Doc")) { + originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getDocPath(); + } + } + + else if (fileType.equals("Pdf")) { + originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getPdfPath(); + } + } + + else if (fileType.equals("Image")) { + originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getImgPath(); + } + + } else if (fileType.equals("Excel")) { + originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; + if (oldTrainingResource != null) { + oldPath = oldTrainingResource.getExcelPath(); + } + } + +// if (topicLan == null) { +// model.addAttribute("error_msg", "Please select Topic and Laguage"); +// return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); +// } + + if (oldTrainingResource == null) { + model.addAttribute("error_msg", "TrainingResource doesn't exist"); + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + if (file.isEmpty()) { + model.addAttribute("error_msg", "Please upolad File"); + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + /* + * Since trainingResource have doc, image, pdf and excel path. If someone wants + * to modify any path with new topic and lan then new trainingResource will be + * created and we update file path in it and respected file path will be empty + * in oldTraining Resource. + */ + List trList = trainingResourceService.findByTopicLanMapping(topicLan); + TrainingResource newTrainingResource; + boolean newTrainingData = true; + if (trList.isEmpty()) { + newTrainingResource = new TrainingResource(); + } else if (!trList.contains(oldTrainingResource)) { + newTrainingResource = trList.get(0); + } else { + newTrainingData = false; + newTrainingResource = oldTrainingResource; // or some appropriate fallback + } + + try { + + if (!file.isEmpty()) { + + if (topicLan == null) { + topicLan = new TopicLanMapping(dateAdded, topic, lan); + + topicLanMapiingService.save(topicLan); + + } + + String langName = lan.getLangName(); + + Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); + String docFolder = Paths.get(rootPath.toString(), "docs").toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); + String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + + Set extentions = new HashSet<>(); + String document = ""; + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file"); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newTrainingResource.setPdfPath(document); + oldTrainingResource.setPdfPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newTrainingResource.setDocPath(document); + oldTrainingResource.setDocPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newTrainingResource.setExcelPath(document); + oldTrainingResource.setExcelPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newTrainingResource.setImgPath(document); + oldTrainingResource.setImgPath(""); + fileMatch = true; + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newTrainingResource.setPdfPath(document); + oldTrainingResource.setPdfPath(""); + fileMatch = true; + + } + + else if (ext.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newTrainingResource.setDocPath(document); + oldTrainingResource.setDocPath(""); + fileMatch = true; + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newTrainingResource.setExcelPath(document); + oldTrainingResource.setExcelPath(""); + fileMatch = true; + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newTrainingResource.setImgPath(document); + oldTrainingResource.setImgPath(""); + fileMatch = true; + + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + + model.addAttribute("error_msg", "Unsupported file Error "); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + } + } + + else { + model.addAttribute("error_msg", "Zip contains different types of files Error"); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + } + + if (oldPath.endsWith(".zip")) { + + String extractDir = oldPath.replace(".zip", ""); + + Path extractDirPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), extractDir); + FileUtils.deleteDirectory(extractDirPath.toFile()); + + } + + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); + + if (fileMatch) { + trainingResourceService.save(newTrainingResource); + if (newTrainingData) { + trainingResourceService.save(oldTrainingResource); + } + } else { + model.addAttribute("error_msg", + "Please upload the ZIP or non-ZIP file of the same type that you want to edit. For example, if you want to edit a DOC file, do not upload an image, Excel, or PDF file."); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + } + + } catch (Exception e) { + logger.error("Exception while updating Training Resource: {} {} {}", topic, lan, file, e); + model.addAttribute("error_msg", CommonData.RECORD_ERROR); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + + model.addAttribute("success_msg", CommonData.RECORD_UPDATE_SUCCESS_MSG); + + return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + } + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/resources/templates/updateTrainingResource.html b/src/main/resources/templates/updateTrainingResource.html index 2f479430..c53464e9 100644 --- a/src/main/resources/templates/updateTrainingResource.html +++ b/src/main/resources/templates/updateTrainingResource.html @@ -43,6 +43,7 @@

Update Training Resource

+
From 50d9d6fd8271b876ef048736d66b322ed47cb6cf Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Mon, 17 Nov 2025 12:03:05 +0530 Subject: [PATCH 08/33] resolved conflict --- .../com/health/controller/HomeController.java | 217 +++++++++++++----- .../com/health/utility/ServiceUtility.java | 49 +++- .../templates/addTrainingResource.html | 16 +- .../templates/trainingResourceViewAdmin.html | 13 +- .../templates/updateTrainingResource.html | 5 +- 5 files changed, 221 insertions(+), 79 deletions(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 666450b7..d518ebed 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5330,7 +5330,13 @@ public String addTrainingResourceGet(HttpServletRequest req, Principal principal model.addAttribute("languages", languages); List topics = getTopics(); - List trainingResourceList = trainingResourceService.findAll(); + List trainingResourceList = new ArrayList<>(); + List tempResourceList = trainingResourceService.findAll(); + for (TrainingResource temp : tempResourceList) { + if (ServiceUtility.hasAnyResourceFile(temp)) { + trainingResourceList.add(temp); + } + } model.addAttribute("topics", topics); model.addAttribute("trainingResourceList", trainingResourceList); @@ -5399,6 +5405,10 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ } else { tr = trList.get(0); } + + tr.setDateAdded(dateAdded); + tr.setTopicLanMapping(topicLanMapping); + trainingResourceService.save(tr); // Saved first to get exact Id int trId = tr.getTrainingResourceId(); Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); @@ -5489,9 +5499,6 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { } - tr.setDateAdded(dateAdded); - tr.setTopicLanMapping(topicLanMapping); - trainingResourceService.save(tr); } @@ -5638,7 +5645,13 @@ public String trainingResourceEditGet(@PathVariable String fileType, @PathVariab List languages = getLanguages(); languages.sort(Comparator.comparing(Language::getLangName)); List topics = getTopics(); - List trainingResourceList = trainingResourceService.findAll(); + List trainingResourceList = new ArrayList<>(); + List tempTrainingResourceList = trainingResourceService.findAll(); + for (TrainingResource temp : tempTrainingResourceList) { + if (ServiceUtility.hasAnyResourceFile(temp)) { + trainingResourceList.add(temp); + } + } model.addAttribute("languages", languages); model.addAttribute("topics", topics); model.addAttribute("trainingResourceList", trainingResourceList); @@ -5697,6 +5710,7 @@ public String updateTrainingResourcePost(HttpServletRequest req, Model model, Pr int trIdInt = Integer.parseInt(trId); int topicIdInt = Integer.parseInt(topicId); int lanIdInt = Integer.parseInt(lanId); + int oldtrId = trIdInt; Topic topic = topicService.findById(topicIdInt); Language lan = lanService.getById(lanIdInt); @@ -5707,6 +5721,12 @@ public String updateTrainingResourcePost(HttpServletRequest req, Model model, Pr String originalFileType = ""; String oldPath = ""; TrainingResource oldTrainingResource = trainingResourceService.findByTrainingResourceId(trIdInt); + + if (oldTrainingResource == null) { + model.addAttribute("error_msg", "TrainingResource doesn't exist"); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); + } + boolean fileMatch = false; if (fileType.equals("Doc")) { @@ -5736,57 +5756,69 @@ else if (fileType.equals("Image")) { } } -// if (topicLan == null) { -// model.addAttribute("error_msg", "Please select Topic and Laguage"); -// return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); -// } - - if (oldTrainingResource == null) { - model.addAttribute("error_msg", "TrainingResource doesn't exist"); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + if (oldPath == null || oldPath.isEmpty()) { + model.addAttribute("error_msg", + "The data has already moved to another Training Resource. Please check the View section to edit."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } - if (file.isEmpty()) { - model.addAttribute("error_msg", "Please upolad File"); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + + if (topic == null || lan == null) { + model.addAttribute("error_msg", "Topic or Language not found."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } - /* - * Since trainingResource have doc, image, pdf and excel path. If someone wants - * to modify any path with new topic and lan then new trainingResource will be - * created and we update file path in it and respected file path will be empty - * in oldTraining Resource. - */ - List trList = trainingResourceService.findByTopicLanMapping(topicLan); TrainingResource newTrainingResource; boolean newTrainingData = true; - if (trList.isEmpty()) { - newTrainingResource = new TrainingResource(); - } else if (!trList.contains(oldTrainingResource)) { - newTrainingResource = trList.get(0); + + if (topicLan != null) { + List trList = trainingResourceService.findByTopicLanMapping(topicLan); + + if (trList.isEmpty()) { + newTrainingResource = new TrainingResource(); + logger.info("new Training Resource Data"); + + } else if (!trList.contains(oldTrainingResource)) { + newTrainingResource = trList.get(0); + logger.info("new Training Resource Data from trList"); + } else { + newTrainingData = false; + newTrainingResource = oldTrainingResource; // or some appropriate fallback + logger.info("old Training resource data"); + } } else { - newTrainingData = false; - newTrainingResource = oldTrainingResource; // or some appropriate fallback + + topicLan = new TopicLanMapping(dateAdded, topic, lan); + + topicLanMapiingService.save(topicLan); + newTrainingResource = new TrainingResource(); + } - try { + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); - if (!file.isEmpty()) { + // To get exact Id of new trainining Resource Data + if (newTrainingData) { - if (topicLan == null) { - topicLan = new TopicLanMapping(dateAdded, topic, lan); + trainingResourceService.save(newTrainingResource); + trIdInt = newTrainingResource.getTrainingResourceId(); - topicLanMapiingService.save(topicLan); + } - } + try { + + String langName = lan.getLangName(); - String langName = lan.getLangName(); + Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); - Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); + String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); + String docFolder = Paths.get(rootPath.toString(), "docs").toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); + String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + boolean fileFlag = false; - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docs").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + if (!file.isEmpty()) { + fileFlag = true; Set extentions = new HashSet<>(); String document = ""; @@ -5796,14 +5828,15 @@ else if (fileType.equals("Image")) { if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { model.addAttribute("error_msg", "Unsupported file"); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } else if (fileExtention.equals(CommonData.PDF_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); - oldTrainingResource.setPdfPath(""); + if (newTrainingData) + oldTrainingResource.setPdfPath(""); fileMatch = true; } @@ -5811,7 +5844,8 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); - oldTrainingResource.setDocPath(""); + if (newTrainingData) + oldTrainingResource.setDocPath(""); fileMatch = true; } @@ -5819,7 +5853,8 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); - oldTrainingResource.setExcelPath(""); + if (newTrainingData) + oldTrainingResource.setExcelPath(""); fileMatch = true; } @@ -5827,7 +5862,8 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); - oldTrainingResource.setImgPath(""); + if (newTrainingData) + oldTrainingResource.setImgPath(""); fileMatch = true; } @@ -5840,7 +5876,10 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); - oldTrainingResource.setPdfPath(""); + if (newTrainingData) { + oldTrainingResource.setPdfPath(""); + } + fileMatch = true; } @@ -5849,7 +5888,10 @@ else if (ext.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); - oldTrainingResource.setDocPath(""); + if (newTrainingData) { + oldTrainingResource.setDocPath(""); + } + fileMatch = true; } @@ -5857,7 +5899,10 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); - oldTrainingResource.setExcelPath(""); + if (newTrainingData) { + oldTrainingResource.setExcelPath(""); + } + fileMatch = true; } @@ -5865,7 +5910,10 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); - oldTrainingResource.setImgPath(""); + if (newTrainingData) { + oldTrainingResource.setImgPath(""); + } + fileMatch = true; } @@ -5874,7 +5922,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { model.addAttribute("error_msg", "Unsupported file Error "); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } } @@ -5883,12 +5931,12 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { else { model.addAttribute("error_msg", "Zip contains different types of files Error"); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } } - if (oldPath.endsWith(".zip")) { + if (oldPath != null && oldPath.endsWith(".zip")) { String extractDir = oldPath.replace(".zip", ""); @@ -5901,29 +5949,80 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { newTrainingResource.setTopicLanMapping(topicLan); if (fileMatch) { + newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setTopicLanMapping(topicLan); trainingResourceService.save(newTrainingResource); if (newTrainingData) { + logger.info("1st old data save is called"); trainingResourceService.save(oldTrainingResource); } } else { - model.addAttribute("error_msg", - "Please upload the ZIP or non-ZIP file of the same type that you want to edit. For example, if you want to edit a DOC file, do not upload an image, Excel, or PDF file."); - - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + model.addAttribute("error_msg", "Please upload a file of the same type. E.g., DOC for DOC type."); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } + } + // File Empty + else { + if (newTrainingData && !fileFlag && oldPath != null && !oldPath.isEmpty()) { + + Path sourcePath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), oldPath); + File sourceFile = sourcePath.toFile(); + String fileName = sourcePath.getFileName().toString(); + + String document = ""; + + if (sourceFile.exists()) { + if (originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); + + newTrainingResource.setDocPath(document); + oldTrainingResource.setDocPath(""); + + } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, excelFolder, fileName, + env); + + newTrainingResource.setExcelPath(document); + oldTrainingResource.setExcelPath(""); + + } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); + + newTrainingResource.setPdfPath(document); + oldTrainingResource.setPdfPath(""); + + } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, + env); + newTrainingResource.setImgPath(document); + oldTrainingResource.setImgPath(""); + + } + + newTrainingResource.setDateAdded(dateAdded); + trainingResourceService.save(newTrainingResource); + logger.info("2nd old data save is called"); + trainingResourceService.save(oldTrainingResource); + } + + } } } catch (Exception e) { logger.error("Exception while updating Training Resource: {} {} {}", topic, lan, file, e); model.addAttribute("error_msg", CommonData.RECORD_ERROR); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } model.addAttribute("success_msg", CommonData.RECORD_UPDATE_SUCCESS_MSG); - return trainingResourceEditGet(originalFileType, trIdInt, req, model, principal); + return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } @GetMapping("/trainingModules") diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index 704cd21b..3c122686 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -43,6 +43,7 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; @@ -65,6 +66,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.health.model.TrainingResource; import com.health.model.User; import com.health.repository.UserRepository; import com.health.threadpool.TimeoutOutputStream; @@ -1082,11 +1084,6 @@ public static void deleteFilesOlderThanNDays(int days, Environment env, String d }); } - /* - * dowanload Manager - * - */ - public static String downloadManager(String zipUrl, AtomicInteger downloadCount, int downloadLimit, long downloadTimeOut, Environment env, HttpServletResponse response) { String message = "Please try again after 30 minutes."; @@ -1154,6 +1151,48 @@ public static String getVideoResolutionPath(String VideoPath, String resolution) } + public static String copyFileAndGetRelativePath(File sourceFile, String destinationFolder, String fileName, + Environment env) throws IOException { + + logger.info("destination Folder: {}", destinationFolder); + logger.info("fileName: {}", fileName); + + Path destinationFolderPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), + destinationFolder); + boolean flag = createFolder(destinationFolderPath); + + Path destinationPath = destinationFolderPath.resolve(fileName); + + File destinationFile = destinationPath.toFile(); + + if (flag && sourceFile.exists() && sourceFile.isFile()) { + FileUtils.copyFile(sourceFile, destinationFile); + logger.info("file is copied"); + } + + String temp = destinationPath.toString(); + int indexToStart = temp.indexOf("Media"); + String document = temp.substring(indexToStart, temp.length()); + String resultantPath = convertFilePathToUrl(document); + logger.info("resultant Path: {}", resultantPath); + + return resultantPath; + } + + public static boolean hasAnyResourceFile(TrainingResource tr) { + boolean hasData = true; + if ((tr.getPdfPath() == null || tr.getPdfPath().isEmpty()) + && (tr.getDocPath() == null || tr.getDocPath().isEmpty()) + && (tr.getExcelPath() == null || tr.getExcelPath().isEmpty()) + && (tr.getImgPath() == null || tr.getImgPath().isEmpty())) { + + hasData = false; + } + + return hasData; + + } + /** * to validate email * diff --git a/src/main/resources/templates/addTrainingResource.html b/src/main/resources/templates/addTrainingResource.html index 81554ca1..93636de6 100644 --- a/src/main/resources/templates/addTrainingResource.html +++ b/src/main/resources/templates/addTrainingResource.html @@ -197,7 +197,7 @@

Add Training Resource

+ title="Edit Pdf"> Edit   @@ -206,7 +206,7 @@

Add Training Resource

th:data-topicName="${temp.getTopicLanMapping().getTopic().getTopicName()}" th:data-langName="${temp.getTopicLanMapping().getLan().getLangName()}" th:data-fileName="${temp.getPdfFileNameWithorWitoutZip()}" - title="Delete"> + title="Delete Pdf"> Delete
@@ -234,7 +234,7 @@

Add Training Resource

+ title="Edit Doc"> Edit   @@ -243,7 +243,7 @@

Add Training Resource

th:data-topicName="${temp.getTopicLanMapping().getTopic().getTopicName()}" th:data-langName="${temp.getTopicLanMapping().getLan().getLangName()}" th:data-fileName="${temp.getDocFileNameWithorWitoutZip()}" - title="Delete"> + title="Delete Doc"> Delete
@@ -271,7 +271,7 @@

Add Training Resource

+ title="Edit Excel"> Edit   @@ -280,7 +280,7 @@

Add Training Resource

th:data-topicName="${temp.getTopicLanMapping().getTopic().getTopicName()}" th:data-langName="${temp.getTopicLanMapping().getLan().getLangName()}" th:data-fileName="${temp.getExcelFileNameWithorWitoutZip()}" - title="Delete"> + title="Delete Excel"> Delete
@@ -309,7 +309,7 @@

Add Training Resource

+ title="Edit Image"> Edit   @@ -318,7 +318,7 @@

Add Training Resource

th:data-topicName="${temp.getTopicLanMapping().getTopic().getTopicName()}" th:data-langName="${temp.getTopicLanMapping().getLan().getLangName()}" th:data-fileName="${temp.getImageFileNameWithorWitoutZip()}" - title="Delete"> + title="Delete Image"> Delete
diff --git a/src/main/resources/templates/trainingResourceViewAdmin.html b/src/main/resources/templates/trainingResourceViewAdmin.html index cb62eabc..b5d09422 100644 --- a/src/main/resources/templates/trainingResourceViewAdmin.html +++ b/src/main/resources/templates/trainingResourceViewAdmin.html @@ -34,11 +34,14 @@
-
-

-
-
-
+
+
+

+
+
+
+ Add Training Resource +
diff --git a/src/main/resources/templates/updateTrainingResource.html b/src/main/resources/templates/updateTrainingResource.html index c53464e9..f1a55547 100644 --- a/src/main/resources/templates/updateTrainingResource.html +++ b/src/main/resources/templates/updateTrainingResource.html @@ -34,8 +34,9 @@
-
-

Update Training Resource

+
+

Update Training Resource

+ Add Training Resource
From c8a491847f37490ab840fa23bc23fee267f3f2a0 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Fri, 25 Jul 2025 14:56:34 +0530 Subject: [PATCH 09/33] delete and enable/disable training Resource --- .../com/health/config/SecurityConfig.java | 2 +- .../com/health/controller/AjaxController.java | 65 +++++++++ .../com/health/controller/HomeController.java | 7 +- .../com/health/model/TrainingResource.java | 12 ++ src/main/java/com/health/model/User.java | 12 ++ src/main/resources/static/js/ajaxSupport.js | 126 ++++++++++++++++++ .../templates/addTrainingResource.html | 57 ++++---- .../common/commonItemsTrainingResource.html | 84 ++++++++++++ 8 files changed, 337 insertions(+), 28 deletions(-) create mode 100644 src/main/resources/templates/common/commonItemsTrainingResource.html diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 684ae8b6..0eb5f7fd 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -98,7 +98,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", "/addTrainingResource", "/trainingReource/view/**", "/trainingReourceAdminView/**", - "/trainingReource/edit/**", + "/trainingReource/edit/**", "/enableDisableTrainingResource", "/delete-trainingResource", }; diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 0655115a..9dd22d1e 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -72,6 +72,7 @@ import com.health.model.TopicCategoryMapping; import com.health.model.TraineeInformation; import com.health.model.TrainingInformation; +import com.health.model.TrainingResource; import com.health.model.TrainingTopic; import com.health.model.Tutorial; import com.health.model.TutorialWithWeekAndPackage; @@ -109,6 +110,7 @@ import com.health.service.TopicService; import com.health.service.TraineeInformationService; import com.health.service.TrainingInformationService; +import com.health.service.TrainingResourceService; import com.health.service.TrainingTopicService; import com.health.service.TutorialService; import com.health.service.TutorialWithWeekAndPackageService; @@ -161,6 +163,8 @@ public class AjaxController { @Autowired private PackageLanguageService packLanService; + @Autowired + private TrainingResourceService trainingResourceService; @Autowired private PackLanTutorialResourceService packLanTutorialResourceService; @@ -654,6 +658,31 @@ private HashMap setResponse(Integer status) { } + @GetMapping("/enableDisableTrainingResource") + public @ResponseBody boolean enableDisableTrainingResource(int trainingResourceId) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trainingResourceId); + + try { + if (tr.isStatus()) { + tr.setStatus(false); + trainingResourceService.save(tr); + return true; + + } else { + tr.setStatus(true); + trainingResourceService.save(tr); + return true; + + } + + } catch (Exception e) { + + logger.error("Error in Enable Disbale Training Resource: {}", tr, e); + return false; + } + + } + @GetMapping("/enableDisableResearchPaper") public @ResponseBody boolean enableDisableResearchPaper(int id) { ResearchPaper res = researchPaperService.findById(id); @@ -1494,6 +1523,42 @@ public ResponseEntity deleteTutorialFromCourse( /******************* Course End *****************************/ + @RequestMapping("/delete-trainingResource") + public ResponseEntity deleteTrainingResource(@RequestParam("trainingResourceId") int trainingResourceId, + @RequestParam("fileType") String fileType) { + + try { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trainingResourceId); + if (tr != null) { + switch (fileType.toLowerCase()) { + case "image": + tr.setImgPath(""); + break; + case "pdf": + tr.setPdfPath(""); + break; + case "doc": + tr.setDocPath(""); + break; + case "excel": + tr.setExcelPath(""); + break; + default: + return ResponseEntity.badRequest().body("Unsupported file type: " + fileType); + } + + trainingResourceService.save(tr); + return ResponseEntity.ok("Deleted successfully"); + } else { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).body("Training resource not found"); + } + + } catch (Exception e) { + logger.error("Error in deleting training resource", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).body("Error in deleting!"); + } + } + @RequestMapping("/loadPromoVideoByLanguage") public @ResponseBody String getPathofPromoVideo(@RequestParam(value = "lanId") int lanId, @RequestParam(value = "promoId") int promoId) { diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index d518ebed..b4819f9e 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -5408,6 +5408,7 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ tr.setDateAdded(dateAdded); tr.setTopicLanMapping(topicLanMapping); + tr.setUser(usr); trainingResourceService.save(tr); // Saved first to get exact Id int trId = tr.getTrainingResourceId(); @@ -5498,7 +5499,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { } } - + tr.setUser(usr); trainingResourceService.save(tr); } @@ -5796,6 +5797,7 @@ else if (fileType.equals("Image")) { newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); + newTrainingResource.setUser(usr); // To get exact Id of new trainining Resource Data if (newTrainingData) { @@ -5947,6 +5949,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); + newTrainingResource.setUser(usr); if (fileMatch) { newTrainingResource.setDateAdded(dateAdded); @@ -5954,6 +5957,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { trainingResourceService.save(newTrainingResource); if (newTrainingData) { logger.info("1st old data save is called"); + oldTrainingResource.setUser(usr); trainingResourceService.save(oldTrainingResource); } } else { @@ -6005,6 +6009,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { } newTrainingResource.setDateAdded(dateAdded); + newTrainingResource.setUser(usr); trainingResourceService.save(newTrainingResource); logger.info("2nd old data save is called"); trainingResourceService.save(oldTrainingResource); diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 8d9a2a87..a44f0826 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -46,6 +46,10 @@ public class TrainingResource implements Serializable { @Column(name = "img_path", length = 1000) private String imgPath; + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private User user; + public int getTrainingResourceId() { return trainingResourceId; } @@ -102,6 +106,14 @@ public void setImgPath(String imgPath) { this.imgPath = imgPath; } + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + public String getPdfFileNameWithorWitoutZip() { if (pdfPath == null || pdfPath.trim().isEmpty()) { return "NA"; diff --git a/src/main/java/com/health/model/User.java b/src/main/java/com/health/model/User.java index ecdce179..64f261c5 100644 --- a/src/main/java/com/health/model/User.java +++ b/src/main/java/com/health/model/User.java @@ -179,6 +179,10 @@ public void setOrgRolev(OrganizationRole orgRolev) { @JsonIgnore private Set weekTitleVideos = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JsonIgnore + private Set trainingResources = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonIgnore private Set topics = new HashSet(); @@ -332,6 +336,14 @@ public void setUserRoles(Set userRoles) { this.userRoles = userRoles; } + public Set getTrainingResources() { + return trainingResources; + } + + public void setTrainingResources(Set trainingResources) { + this.trainingResources = trainingResources; + } + @Override public Collection getAuthorities() { Set authorites = new HashSet<>(); diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 919d84dd..661b94bd 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -2806,6 +2806,132 @@ $(".deleteTrainingModuleTutorial-btn").click(function(){ /************************************Assign Video End ********************************************** */ + +/******************************** Trainig Resource Start ***************************************/ + +$('.enableTrainingResource').click(function() { + + var test_id=$(this).attr('value'); + + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableTrainingResource", + data : { + "trainingResourceId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + $('#'+test_id).addClass('fas fa-times-circle'); + $('#'+test_id).removeClass('fas fa-check-circle'); + $('#'+test_id).css({"color": "red"}); + $('#Success').css({"display": "block"}); + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + $('.disableTrainingResource').click(function() { + + var test_id=$(this).attr('value'); + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableTrainingResource", + data : { + "trainingResourceId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + + $('#'+test_id).addClass('fas fa-check-circle'); + $('#'+test_id).removeClass('fas fa-times-circle'); + $('#'+test_id).css({"color": "green"}); + $('#Success').css({"display": "block"}); + + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + + +$(".deleteTrainingResource-btn").click(function(){ + var row = $(this).closest("tr"); + var trainingResourceId = $(this).data("trainingresourceid"); + var topicName = $(this).data("topicname"); + var langName = $(this).data("langname"); + var fileName = $(this).data("filename"); + var fileType = $(this).data("filetype"); + + + Swal.fire({ + title: "Are you sure?", + html: "Do you want to delete this Training Resource?

" + + "Topic: " + topicName + "
" + + "Language: " + langName + "
" + + "file Type: " + fileType + "
" + + "file Name: " + fileName, + + icon: "warning", + showCancelButton: true, + confirmButtonText: "Yes", + cancelButtonText: "No", + dangerMode: true + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: "/delete-trainingResource/", + data: { + + + "trainingResourceId": trainingResourceId, + "fileType": fileType + }, + type: "DELETE", + success: function(result) { + Swal.fire("Deleted!", "Deleted successfully!", "success"); + $("#" + fileType + trainingResourceId).text("Deleted"); + }, + error: function(err) { + Swal.fire("Error!", "Error in deleting!", "error"); + } + }); + } + }); +}); + + + +/******************************** Training Resource End ****************************************/ /***************** changes made by om prakash *********************************************/ diff --git a/src/main/resources/templates/addTrainingResource.html b/src/main/resources/templates/addTrainingResource.html index 93636de6..0abdf98b 100644 --- a/src/main/resources/templates/addTrainingResource.html +++ b/src/main/resources/templates/addTrainingResource.html @@ -175,16 +175,16 @@

Add Training Resource

- +
- +
-
+

@@ -201,11 +201,12 @@

Add Training Resource

Edit   - @@ -221,7 +222,7 @@

Add Training Resource

-
+

@@ -238,11 +239,12 @@

Add Training Resource

Edit   - @@ -258,7 +260,7 @@

Add Training Resource

-
+

@@ -275,11 +277,12 @@

Add Training Resource

Edit   - @@ -295,7 +298,7 @@

Add Training Resource

-
+

@@ -313,11 +316,12 @@

Add Training Resource

Edit   - @@ -358,6 +362,7 @@

Add Training Resource

+ +
+
+ +
+ + +
+ + +
+ +
+ +
+ + + +
+ +
+ + +
+ + +
+
+ +
+ +
+
+ + +
+ +
  + + + + + +
+ + + \ No newline at end of file From cb7d11083869b6ff3dbb772f9d614c98f31ca6b9 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Tue, 25 Nov 2025 14:01:55 +0530 Subject: [PATCH 10/33] trainingResource template and common Elements --- .../com/health/config/SecurityConfig.java | 2 +- .../com/health/controller/HomeController.java | 57 ++++++ .../common/commonItemsTrainingResource.html | 192 ++++++++++++------ .../templates/trainingResources.html | 129 ++++++++++++ 4 files changed, 316 insertions(+), 64 deletions(-) create mode 100644 src/main/resources/templates/trainingResources.html diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 0eb5f7fd..174cb531 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -56,7 +56,7 @@ public static BCryptPasswordEncoder passwordEncoder() { "/api/scriptPublished/**", "/loadLanguageByPackage/**", "/promoVideoView/**", "/trainingModules/**", "/downloadTrainingModules", "/loadMessageByPackageAndLan/**", "/loadLanguageByWeek/**", "/loadWeekByLanguage/**", "/trainingTutorials/**", "/hstTrainingModuleView/**", "/downloadManager/**", - "/downloadManagerforhst/**", "/downloadHealthTutorials/**" }; + "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/trainingResource/**" }; /** * url matcher for SUPERADMIN diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index b4819f9e..039862ef 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -6030,6 +6030,63 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } + @GetMapping("/trainingResource") + public String viewAndDownloadTrainingResource(HttpServletRequest req, + @RequestParam(name = "topicName", required = false, defaultValue = "0") int topicId, + @RequestParam(name = "langName", required = false, defaultValue = "0") int lanId, + @RequestParam(name = "inputFileType", required = false, defaultValue = "0") int inputFileType, + + @RequestParam(name = "action", required = false, defaultValue = "") String action, + + Principal principal, Model model) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + + model.addAttribute("topic", topicId); + model.addAttribute("lanId", lanId); + model.addAttribute("inputFileType", inputFileType); + + if (action != null && !action.isEmpty() && action.equals("download")) { + + model.addAttribute("action", action); + } + + if (action != null && !action.isEmpty() && action.equals("view")) { + + model.addAttribute("action", action); + } + + if (action != null && !action.isEmpty() && action.equals("share")) { + + model.addAttribute("action", action); + } + + Topic localTopic = null; + Language localLan = null; + String localFile = null; + + model.addAttribute("userInfo", usr); + + // getModelData(model, cat, topic, lan, query, false); + navigationLinkCheck(model); + + if (topicId != 0) { + localTopic = topicService.findById(topicId); + model.addAttribute("topicforQuery", localTopic); + } + if (lanId != 0) { + localLan = lanService.getById(lanId); + model.addAttribute("lanforQuery", localLan); + } + if (inputFileType != 0) { + // add some code + model.addAttribute("fileTypeQuery", localFile); + } + + return "trainingResources"; + } + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/resources/templates/common/commonItemsTrainingResource.html b/src/main/resources/templates/common/commonItemsTrainingResource.html index c36747c5..bb270774 100644 --- a/src/main/resources/templates/common/commonItemsTrainingResource.html +++ b/src/main/resources/templates/common/commonItemsTrainingResource.html @@ -1,84 +1,150 @@ -
-

-
-
-
- \ No newline at end of file + diff --git a/src/main/resources/templates/trainingResources.html b/src/main/resources/templates/trainingResources.html new file mode 100644 index 00000000..9cb87d95 --- /dev/null +++ b/src/main/resources/templates/trainingResources.html @@ -0,0 +1,129 @@ + + + + + +Training Resource - Health And Nutrition + + + + +
+
+
+
+ +
+ +
+
+
+ +
+
+ +
+
+
+ + + + +
+
+ + + + +
+ +
+ + + +
+ + + +
+

+

+ + + + + + + + + + +
+ + + + + + \ No newline at end of file From 00f74255f523166718a338c6d1cdcb271ded2347 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Wed, 26 Nov 2025 17:17:55 +0530 Subject: [PATCH 11/33] AjaxController to load by topic, lan and fileType --- .../com/health/controller/AjaxController.java | 237 ++++++++++++++++++ .../com/health/controller/HomeController.java | 23 ++ .../TrainingResourceRepository.java | 2 + .../service/TrainingResourceService.java | 2 + .../impl/TrainingReourceServiceImpl.java | 6 + .../java/com/health/utility/CommonData.java | 5 + 6 files changed, 275 insertions(+) diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 9dd22d1e..1cfde010 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -70,6 +70,7 @@ import com.health.model.Testimonial; import com.health.model.Topic; import com.health.model.TopicCategoryMapping; +import com.health.model.TopicLanMapping; import com.health.model.TraineeInformation; import com.health.model.TrainingInformation; import com.health.model.TrainingResource; @@ -107,6 +108,7 @@ import com.health.service.StateService; import com.health.service.TestimonialService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TopicLanMappingService; import com.health.service.TopicService; import com.health.service.TraineeInformationService; import com.health.service.TrainingInformationService; @@ -166,6 +168,9 @@ public class AjaxController { @Autowired private TrainingResourceService trainingResourceService; + @Autowired + private TopicLanMappingService topicLanMappingService; + @Autowired private PackLanTutorialResourceService packLanTutorialResourceService; @@ -1887,6 +1892,238 @@ public ResponseEntity deleteTrainingResource(@RequestParam("trainingReso } + /*************************************** + * Training Resource Start + **********************************************************/ + private Map getFileTypeIdAndValue(int fileTypeId) { + Map result = new HashMap<>(); + + switch (fileTypeId) { + case CommonData.DOC: + result.put(fileTypeId, "Doc"); + break; + case CommonData.EXCEL: + result.put(fileTypeId, "Excel"); + break; + case CommonData.IMAGE: + result.put(fileTypeId, "Image"); + break; + case CommonData.PDF: + result.put(fileTypeId, "Pdf"); + break; + default: + return null; + } + + return result; + } + + private Map getFileTypeIdAndValue(TrainingResource tr) { + Map result = new HashMap<>(); + + if (isNotBlank(tr.getDocPath())) { + result.put(CommonData.DOC, "Doc"); + + } + if (isNotBlank(tr.getExcelPath())) { + result.put(CommonData.EXCEL, "Excel"); + + } + if (isNotBlank(tr.getImgPath())) { + result.put(CommonData.IMAGE, "Image"); + + } + if (isNotBlank(tr.getPdfPath())) { + result.put(CommonData.PDF, "Pdf"); + + } + + return Collections.emptyMap(); + } + + private boolean isTrainingResourceFilePresent(TrainingResource tr, int id) { + if (tr == null) { + return false; + } + + switch (id) { + case CommonData.DOC: + return isNotBlank(tr.getDocPath()); + case CommonData.EXCEL: + return isNotBlank(tr.getExcelPath()); + case CommonData.IMAGE: + return isNotBlank(tr.getImgPath()); + case CommonData.PDF: + return isNotBlank(tr.getPdfPath()); + default: + return false; + } + } + + private boolean isNotBlank(String s) { + return s != null && !s.isEmpty(); + } + + @RequestMapping("/loadLanAndFileTypeByTopic") + public @ResponseBody ArrayList> getLanAndFileTypeByTopic( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + + ArrayList> arlist = new ArrayList<>(); + + Map fileTypes = new TreeMap<>(); + + Map languages = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + Map fileTypeIdAndValue = fileTypeId != 0 ? getFileTypeIdAndValue(fileTypeId) : null; + + List localTopicList = new ArrayList<>(); + if (topic != null && language != null) { + TopicLanMapping tlm = topicLanMappingService.findByTopicAndLan(topic, language); + if (tlm != null) + localTopicList.add(tlm); + } else if (topic != null) { + localTopicList = topicLanMappingService.findByTopic(topic); + } else { + localTopicList = topicLanMappingService.findAll(); + } + + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(localTopicList); + + if (!trList.isEmpty()) { + + for (TrainingResource temp : trList) { + // To find languages + Language lan = temp.getTopicLanMapping().getLan(); + languages.put(lan.getLangName(), lan.getLanId()); + + // To find FileType + getFileTypeIdAndValue(temp).forEach((id, type) -> fileTypes.put(type, id)); + + } + } + arlist.add(languages); + arlist.add(fileTypes); + + return arlist; + + } + + /* + * Function to load Topic and FileType by Lan Author: Alok Kumar + */ + + @RequestMapping("/loadTopicAndFileTypeByLan") + public @ResponseBody ArrayList> getTopicAndFileTypeByLan( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + ArrayList> arlist = new ArrayList<>(); + + Map topics = new TreeMap<>(); + Map fileTypes = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + Map fileTypeIdAndValue = fileTypeId != 0 ? getFileTypeIdAndValue(fileTypeId) : null; + + List tlm = language != null ? topicLanMappingService.findByLan(language) + : topicLanMappingService.findAll(); + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(tlm); + List newtrList = new ArrayList<>(); + if (fileTypeIdAndValue != null && !fileTypeIdAndValue.isEmpty()) { + Map.Entry entry = fileTypeIdAndValue.entrySet().iterator().next(); + int id = entry.getKey(); + for (TrainingResource temp : trList) { + if (isTrainingResourceFilePresent(temp, id)) { + newtrList.add(temp); + } + } + } + + if (!newtrList.isEmpty()) + trList = newtrList; + + for (TrainingResource tr : trList) { + // To find Topic + Topic topicTemp = tr.getTopicLanMapping().getTopic(); + topics.put(topicTemp.getTopicName(), topicTemp.getTopicId()); + + // To find FileType + getFileTypeIdAndValue(tr).forEach((id, type) -> fileTypes.put(type, id)); + + } + + arlist.add(topics); + arlist.add(fileTypes); + + return arlist; + + } + + /* + * Function to load Topic and Language by FileType Author: Alok Kumar + */ + + @RequestMapping("/loadTopicAndLanByFileType") + public @ResponseBody ArrayList> getTopicAndLanByFileType( + @RequestParam(value = "topicId") int topicId, @RequestParam(value = "lanId") int lanId, + @RequestParam(value = "fileTypeId") int fileTypeId) { + + ArrayList> arlist = new ArrayList<>(); + Map topics = new TreeMap<>(); + Map languages = new TreeMap<>(); + + Topic topic = topicId != 0 ? topicService.findById(topicId) : null; + Language language = lanId != 0 ? langService.getById(lanId) : null; + + Map fileTypeIdAndValue = fileTypeId != 0 ? getFileTypeIdAndValue(fileTypeId) : null; + + List localTopicList = new ArrayList<>(); + if (language != null) { + localTopicList = topicLanMappingService.findByLan(language); + } else { + localTopicList = topicLanMappingService.findAll(); + } + + List trList = trainingResourceService.findByTopicLanMappingInAndStatusTrue(localTopicList); + List newtrList = new ArrayList<>(); + if (fileTypeIdAndValue != null && !fileTypeIdAndValue.isEmpty()) { + Map.Entry entry = fileTypeIdAndValue.entrySet().iterator().next(); + int id = entry.getKey(); + for (TrainingResource temp : trList) { + if (isTrainingResourceFilePresent(temp, id)) { + newtrList.add(temp); + } + } + } + + if (!newtrList.isEmpty()) + trList = newtrList; + + for (TrainingResource tr : trList) { + // To find Topic + Topic topicTemp = tr.getTopicLanMapping().getTopic(); + topics.put(topicTemp.getTopicName(), topicTemp.getTopicId()); + + // To find languages + Language lan = tr.getTopicLanMapping().getLan(); + languages.put(lan.getLangName(), lan.getLanId()); + + } + + arlist.add(topics); + arlist.add(languages); + + return arlist; + + } + + /*************************************** + * Training Resource 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 039862ef..42e7f581 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -878,6 +878,29 @@ private void getPackageAndLanguageData(Model model) { getPackageAndLanguageData(model, "", ""); } + private void getModelTrainingResource(Model model, int topicId, int lanId, int fileTypeId) { + + ArrayList> arlist = ajaxController.getLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + ArrayList> arlist1 = ajaxController.getTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + Map topic = arlist1.get(0); + Map fileType = arlist1.get(1); + Map lan = arlist.get(0); + + model.addAttribute("topics", topic); + model.addAttribute("languages", lan); + model.addAttribute("fileTypes", fileType); + + model.addAttribute("localTopic", topicId); + model.addAttribute("localLan", lanId); + model.addAttribute("localFile", fileTypeId); + model.addAttribute("languageCount", lan.size()); + + } + + private void getModelTrainingResource(Model model) { + getModelTrainingResource(model, 0, 0, 0); + } + @RequestMapping("/") public String index(Model model) { diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java index 6a0c63cc..f59898d9 100644 --- a/src/main/java/com/health/repository/TrainingResourceRepository.java +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -13,4 +13,6 @@ public interface TrainingResourceRepository extends JpaRepository findByTopicLanMapping(TopicLanMapping topicLanMapping); + List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList); + } diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java index c46e5051..b4222992 100644 --- a/src/main/java/com/health/service/TrainingResourceService.java +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -11,6 +11,8 @@ public interface TrainingResourceService { List findByTopicLanMapping(TopicLanMapping topicLanMapping); + List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList); + List findAll(); void save(TrainingResource trainingResource); diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java index 5d7b543c..78be35c4 100644 --- a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -50,4 +50,10 @@ public List findByTopicLanMapping(TopicLanMapping topicLanMapp return repo.findByTopicLanMapping(topicLanMapping); } + @Override + public List findByTopicLanMappingInAndStatusTrue(List topicLanMappingList) { + + return repo.findByTopicLanMappingInAndStatusTrue(topicLanMappingList); + } + } diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index e8f72ee7..33a013fe 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -279,6 +279,11 @@ public class CommonData { public static final String ZIP_EXTENSION = "zip"; public static final String UNSUPPORTED_EXTENSION = "unsupported"; + public static final int DOC = 1; + public static final int EXCEL = 2; + public static final int IMAGE = 3; + public static final int PDF = 4; + public static final String STATUS = "status"; public static final String STATUS_QUEUED = "queued"; public static final String STATUS_PROCESSING = "processing"; From 4cf6408236aa6b10b47147373e7822a27bc22906 Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Tue, 2 Dec 2025 14:25:33 +0530 Subject: [PATCH 12/33] ajaxsuport Tr dopdown data and submit restriction --- .../com/health/config/SecurityConfig.java | 3 +- .../com/health/controller/AjaxController.java | 2 +- .../com/health/controller/HomeController.java | 6 +- src/main/resources/static/js/ajaxSupport.js | 262 ++++++++++++++++++ .../common/commonItemsTrainingResource.html | 67 ++--- .../templates/trainingResources.html | 49 ++++ 6 files changed, 346 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 174cb531..52fc737b 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -56,7 +56,8 @@ public static BCryptPasswordEncoder passwordEncoder() { "/api/scriptPublished/**", "/loadLanguageByPackage/**", "/promoVideoView/**", "/trainingModules/**", "/downloadTrainingModules", "/loadMessageByPackageAndLan/**", "/loadLanguageByWeek/**", "/loadWeekByLanguage/**", "/trainingTutorials/**", "/hstTrainingModuleView/**", "/downloadManager/**", - "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/trainingResource/**" }; + "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/trainingResource/**", + "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", "/loadTopicAndLanByFileType/**" }; /** * 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 1cfde010..c37185a7 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -1938,7 +1938,7 @@ private Map getFileTypeIdAndValue(TrainingResource tr) { } - return Collections.emptyMap(); + return result; } private boolean isTrainingResourceFilePresent(TrainingResource tr, int id) { diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 42e7f581..bbd2faa9 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -6055,8 +6055,8 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { @GetMapping("/trainingResource") public String viewAndDownloadTrainingResource(HttpServletRequest req, - @RequestParam(name = "topicName", required = false, defaultValue = "0") int topicId, - @RequestParam(name = "langName", required = false, defaultValue = "0") int lanId, + @RequestParam(name = "topicNameTR", required = false, defaultValue = "0") int topicId, + @RequestParam(name = "langNameTR", required = false, defaultValue = "0") int lanId, @RequestParam(name = "inputFileType", required = false, defaultValue = "0") int inputFileType, @RequestParam(name = "action", required = false, defaultValue = "") String action, @@ -6091,7 +6091,7 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, model.addAttribute("userInfo", usr); - // getModelData(model, cat, topic, lan, query, false); + getModelTrainingResource(model, topicId, lanId, inputFileType); navigationLinkCheck(model); if (topicId != 0) { diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 661b94bd..6b88efd3 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -2931,6 +2931,268 @@ $(".deleteTrainingResource-btn").click(function(){ + /** + function to load language and fileType by topic + author: Alok Kumar + + */ + + function loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId) { + $.ajax({ + type : "GET", + url : projectPath+"loadLanAndFileTypeByTopic", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + + $.each(result, function (value, key) { + var selected = (lanId == key) ? "selected" : ""; + html += ``; + }); + + $("#langNameTR").prop('disabled', false); + $('#langNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value ,key ) { + var selected=(fileTypeId==key)?"selected":""; + html += ``; + }) + $("#inputFileType").prop('disabled',false); + $('#inputFileType').html(html); + if (topicId != 0) { + $("#topicResetDivTR").show(); + } else { + $("#topicResetDivTR").hide(); + } + + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + } + + $( "#topicNameTR" ).change(function() { + + var topicId = $(this).val(); + var lanId = $("#langNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + + }); + + $( "#topicResetTR" ).click(function() { + + var topicId = 0; + + $("#topicNameTR").val("0"); + var lanId = $("#langNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + return false; + + }); + + + + + + /* + Function to load Topic and FileType by language + author:Alok Kumar + + */ + + function loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId){ + $.ajax({ + type : "GET", + url : projectPath+"loadTopicAndFileTypeByLan", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + $.each(result , function( value ,key) { + var selected=(topicId==key)?"selected":""; + html += ``; + }) + $("#topicNameTR").prop('disabled',false); + $('#topicNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value,key ) { + var selected=(fileTypeId==key)?"selected":""; + html += ``; + }) + $("#inputFileType").prop('disabled',false); + $('#inputFileType').html(html); + if (lanId != 0) { + $("#lanResetDivTR").show(); + } else { + $("#lanResetDivTR").hide(); + } + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + + } + + $( "#langNameTR" ).change(function() { + var lanId = $(this).val(); + var topicId = $("#topicNameTR").val(); + var fileTypeId=$("#inputFileType").val(); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + + }); + + $( "#lanResetTR" ).click(function() { + var lanId = 0; + $("#langNameTR").val("0"); + var fileTypeId = $("#inputFileType").val(); + var topicId=$("#topicNameTR").val(); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + return false; + + }); + + + + /* + Function to load Topic and Language by FileType + author:Alok Kumar + + */ + + function loadTopicAndLanByFileType(topicId, lanId, fileTypeId){ + + $.ajax({ + type : "GET", + url : projectPath+"loadTopicAndLanByFileType", + data : { + "topicId" : topicId, + "lanId":lanId, + "fileTypeId":fileTypeId + + }, + contentType : "application/json", + success : function(resultarlist) { + var result= resultarlist[0]; + + console.log(result); + var html = ''; + html += ''; + $.each(result , function( value ,key ) { + var selected=(topicId==key)?"selected":""; + html += ``; + }) + $("#topicNameTR").prop('disabled',false); + $('#topicNameTR').html(html); + + result= resultarlist[1]; + + console.log(result); + var html = ''; + html += ''; + $.each(result, function( value ,key ) { + var selected=(lanId==key)?"selected":""; + html += ``; + }) + $("#langNameTR").prop('disabled',false); + $('#langNameTR').html(html); + + if (fileTypeId != 0) { + $("#fileResetDivTR").show(); + } else { + $("#fileResetDivTR").hide(); + } + + }, + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + }); + + } + + $('#inputFileType').change(function() { + var fileTypeId = $(this).val(); + var topicId = $("#topicNameTR").val(); + var lanId=$("#langNameTR").val(); + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + + + }); + + $( "#fileResetTR" ).click(function() { + + var fileTypeId = 0; + $("#inputFileType").val("0"); + var lanId = $("#langNameTR").val(); + var topicId=$("#topicNameTR").val(); + + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + + return false; + + }); + + $( "#btnClearTriningResource" ).click(function() { + + // Reset radio buttons + $("input[name='action']").prop("checked", false); + + var fileTypeId = 0; + $("#inputFileType").val("0"); + var lanId =0; + $("#langNameTR").val("0"); + var topicId=0; + $("#topicNameTR").val("0"); + + + + loadTopicAndLanByFileType(topicId, lanId, fileTypeId); + loadLanAndFileTypeByTopic(topicId, lanId, fileTypeId); + loadTopicAndFileTypeByLan(topicId, lanId, fileTypeId); + + return false; + + }); + + + + + + /******************************** Training Resource End ****************************************/ diff --git a/src/main/resources/templates/common/commonItemsTrainingResource.html b/src/main/resources/templates/common/commonItemsTrainingResource.html index bb270774..a696115f 100644 --- a/src/main/resources/templates/common/commonItemsTrainingResource.html +++ b/src/main/resources/templates/common/commonItemsTrainingResource.html @@ -8,15 +8,22 @@
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + Only authorized users can access Doc or Excel files. + + + + +
+ +
+ +
+ +
+ + + + + + + +
+ diff --git a/src/main/resources/templates/trainingResources.html b/src/main/resources/templates/trainingResources.html index a622dec4..a674182d 100644 --- a/src/main/resources/templates/trainingResources.html +++ b/src/main/resources/templates/trainingResources.html @@ -1,409 +1,467 @@ - - + - - Training Resource - Health And Nutrition + - + Training Resource - Health And Nutrition - - -
-
-
-
+ -
-
- + + +
+
+
+
+ +
+
-
- -
-
-
-
-
+
+ +
+
+
+
+
-
-
+
+
-
+
-
+
- -

-

+ +

+

- - + } + .topic-title { + color: #0d6efd; + font-weight: 600; + } -
+ .meta-title { + color: #000; + font-weight: 500; + } + - -
+ +
- +
+
+ - + - + - - - let topic = document.getElementById("topicNameTR").value; - let lang = document.getElementById("langNameTR").value; - let file = document.getElementById("inputFileType").value; - let action = document.querySelector('input[name="action"]:checked'); - let errorBox = document.getElementById("formError"); + - function showError(message) { - errorBox.textContent = message; - errorBox.classList.remove("d-none"); - errorBox.scrollIntoView({behavior: "smooth"}); - setTimeout(() => { - errorBox.classList.add("d-none"); - }, 8000); - } + + errorBox.classList.add("d-none"); + this.submit(); + }); + - + - \ No newline at end of file + \ No newline at end of file From e66280e24b0585eb2ceba66b0ca9b01172cee6cb Mon Sep 17 00:00:00 2001 From: Alok Kumar <59380269+AlokSP@users.noreply.github.com> Date: Wed, 17 Dec 2025 15:29:23 +0530 Subject: [PATCH 18/33] doc and Excel view, download and share --- .../com/health/controller/HomeController.java | 19 ++++--- src/main/resources/static/js/ajaxSupport.js | 16 +++++- .../common/commonItemsTrainingResource.html | 2 +- src/main/resources/templates/index.html | 2 +- .../templates/trainingResources.html | 52 +++++++++---------- .../resources/templates/tutorialList.html | 2 +- 6 files changed, 55 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index c4a89698..df3073a7 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -6105,9 +6105,9 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - model.addAttribute("userInfo", usr); + model.addAttribute("usr", usr.getUsername()); boolean authorizedUsr = false; - if (usr != null) { + if (usr.getUsername() != null) { Role role = roleService.findByname(CommonData.contributorRole); int roleId = role.getRoleId(); Set usrRoles = usr.getUserRoles(); @@ -6171,12 +6171,19 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, if (action != null && !action.isEmpty() && action.equals("download")) { model.addAttribute("action", action); - try { + if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { - return "redirect:/downloadTrainingResource?filePath=" + URLEncoder.encode(finalUrl, "UTF-8"); - } catch (UnsupportedEncodingException e) { - logger.error("Error in Download Package", e); + model.addAttribute("error_msg", "Authentication Error"); + + } else { + try { + + return "redirect:/downloadTrainingResource?filePath=" + URLEncoder.encode(finalUrl, "UTF-8"); + } catch (UnsupportedEncodingException e) { + logger.error("Error in Download Package", e); + } } + } if (action != null && !action.isEmpty() && action.equals("view")) { diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 6c723687..a79aa3ce 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -3201,6 +3201,9 @@ $(document).ready(function () { var langId = $("#langNameTR").val(); var fileType = $("#inputFileType").val(); var action = $("input[name='action']:checked").val(); + const usrLoggedIn =$("#usrValue").val() == "true"; + const authorizedUsr =$("#authorizedUsrValue").val() == "true"; + var fileTypeString=$("#fileTypeString").val(); $("#formError").addClass("d-none").text(""); @@ -3232,9 +3235,18 @@ $(document).ready(function () { if (action === "download") { - e.preventDefault(); + if (fileTypeString === "Pdf" || fileTypeString === "Image") { + e.preventDefault(); window.location.href = baseUrl + "&action=download"; - + } + + if (fileTypeString === "Doc" || fileTypeString === "Excel") { + if (usrLoggedIn && authorizedUsr) { + e.preventDefault(); + window.location.href = baseUrl + "&action=download"; + } + + } } }); diff --git a/src/main/resources/templates/common/commonItemsTrainingResource.html b/src/main/resources/templates/common/commonItemsTrainingResource.html index eb3b226c..73501cf4 100644 --- a/src/main/resources/templates/common/commonItemsTrainingResource.html +++ b/src/main/resources/templates/common/commonItemsTrainingResource.html @@ -10,7 +10,7 @@
- -
- You are not authorized to access Doc or Excel files -
- - -
@@ -266,8 +261,8 @@
- -