DownloadController.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package es.uv.saic.web;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.math.BigInteger;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.Optional;
  12. import org.apache.commons.io.FilenameUtils;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.core.io.FileSystemResource;
  16. import org.springframework.http.HttpHeaders;
  17. import org.springframework.http.HttpStatus;
  18. import org.springframework.http.MediaType;
  19. import org.springframework.http.ResponseEntity;
  20. import org.springframework.ui.Model;
  21. import org.springframework.web.bind.annotation.GetMapping;
  22. import org.springframework.web.bind.annotation.PathVariable;
  23. import org.springframework.web.bind.annotation.PostMapping;
  24. import org.springframework.web.bind.annotation.RequestBody;
  25. import org.springframework.web.bind.annotation.RequestMapping;
  26. import org.springframework.web.bind.annotation.ResponseBody;
  27. import org.springframework.web.bind.annotation.RestController;
  28. import es.uv.saic.service.DocumentService;
  29. import es.uv.saic.service.PlantillaService;
  30. import es.uv.saic.shared.domain.Document;
  31. import es.uv.saic.shared.dto.InstanciaTascaDTO;
  32. import es.uv.saic.shared.dto.OrganDTO;
  33. import es.uv.saic.shared.dto.PdfDTO;
  34. import es.uv.saic.shared.dto.ProcesDTO;
  35. import es.uv.saic.shared.dto.TascaDTO;
  36. import es.uv.saic.shared.dto.TascaInformeTransferDTO;
  37. import es.uv.saic.shared.feign.IndicadorClient;
  38. import es.uv.saic.shared.feign.OrganClient;
  39. import es.uv.saic.shared.feign.ProceduresClient;
  40. import es.uv.saic.shared.feign.TascaClient;
  41. import fr.opensagres.xdocreport.core.XDocReportException;
  42. import fr.opensagres.xdocreport.core.io.internal.ByteArrayOutputStream;
  43. import fr.opensagres.xdocreport.document.IXDocReport;
  44. import fr.opensagres.xdocreport.document.images.FileImageProvider;
  45. import fr.opensagres.xdocreport.document.images.IImageProvider;
  46. import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
  47. import fr.opensagres.xdocreport.template.IContext;
  48. import fr.opensagres.xdocreport.template.TemplateEngineKind;
  49. import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
  50. import jakarta.servlet.http.HttpServletResponse;
  51. @RestController
  52. public class DownloadController {
  53. @Autowired
  54. private PlantillaService pls;
  55. @Autowired
  56. private DocumentService ds;
  57. @Value("${saic.data.filePath}")
  58. private String filePath;
  59. @Value("${saic.data.docsPath}")
  60. private String docsPath;
  61. @Value("${saic.data.templates.fileNotFound}")
  62. private String fileNotFound;
  63. @Value("${saic.data.templates.filePath}")
  64. private String templatePath;
  65. @Value("${saic.data.templates.logoPath}")
  66. private String logoPath;
  67. @Autowired
  68. private TascaClient tc;
  69. @Autowired
  70. private OrganClient oc;
  71. @Autowired
  72. private IndicadorClient ic;
  73. @Autowired
  74. private ProceduresClient pc;
  75. /*
  76. * Download a file associated with a task instance
  77. * @param model
  78. * @param idInstanciaTasca The ID of the task instance
  79. * @param response HttpServletResponse
  80. * @return A FileSystemResource
  81. * representing the file to download
  82. */
  83. @GetMapping(value="/download/{fileName}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  84. public ResponseEntity<byte[]> download(@PathVariable("fileName") BigInteger idInstanciaTasca, HttpServletResponse response) throws FileNotFoundException {
  85. try {
  86. InstanciaTascaDTO i = tc.findInstanciaTascaById(idInstanciaTasca);
  87. FileSystemResource file = null;
  88. if(i.getTasca().getIdTipus() == 22){
  89. file = new FileSystemResource(i.getEvidencia());
  90. String extension = "."+FilenameUtils.getExtension(i.getEvidencia());
  91. String name = "-"+i.getTasca().getNomEvidenciaCas().replace(" ", "_");
  92. response.setHeader("Content-Disposition", "attachment; filename="+i.getTasca().getCodiEvidencia()+name+extension);
  93. }
  94. else{
  95. file = new FileSystemResource(this.filePath+i.getEvidencia());
  96. response.setHeader("Content-Disposition", "attachment; filename="+i.getEvidencia());
  97. }
  98. if (!file.exists()) {
  99. return ResponseEntity.ok(new FileSystemResource(this.fileNotFound).getInputStream().readAllBytes());
  100. }
  101. return ResponseEntity.ok(file.getInputStream().readAllBytes());
  102. } catch (IOException e) {
  103. e.printStackTrace();
  104. }
  105. return null;
  106. }
  107. // PARA BORRAR
  108. /*
  109. * Download a document by its ID
  110. * @param model
  111. * @param idDocument The ID of the document to download
  112. * @param response HttpServletResponse
  113. * @return A FileSystemResource representing the document to download
  114. */
  115. @GetMapping(value="/download/document/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  116. @ResponseBody
  117. public ResponseEntity<byte[]> downloadDocument(@PathVariable("id") Integer idDocument, HttpServletResponse response) {
  118. Document document = ds.findById(idDocument);
  119. FileSystemResource file = new FileSystemResource(document.getRuta());
  120. if(!file.exists()) {
  121. return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
  122. }
  123. response.setHeader("Content-Disposition", "attachment; filename="+file.getFilename());
  124. try {
  125. return ResponseEntity.ok(file.getInputStream().readAllBytes());
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. }
  129. return null;
  130. }
  131. /*
  132. * Download the latest report for a given process and degree
  133. * @param model
  134. * @param idTitulacio The ID of the degree
  135. * @param nomProces The name of the process
  136. * @param response HttpServletResponse
  137. * @return A FileSystemResource representing the report to download
  138. */
  139. @GetMapping(value="/download/report/{t}/{p}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  140. @ResponseBody
  141. public ResponseEntity<byte[]> downloadReport(@PathVariable("t") Integer idTitulacio, @PathVariable("p") String nomProces,
  142. HttpServletResponse response) throws IOException, XDocReportException {
  143. OrganDTO titulacio = oc.findByID("T", idTitulacio);
  144. ProcesDTO procesDTO = new ProcesDTO(nomProces, titulacio.getLugar(),
  145. titulacio.getLugar2(),
  146. titulacio.getTambit());
  147. TascaInformeTransferDTO it = tc.getLastByProcName(procesDTO);
  148. if(it != null) {
  149. if((new File(this.filePath+it.getEvidencia())).exists()) {
  150. response.setHeader("Content-Disposition", "attachment; filename="+Integer.toString(idTitulacio)+"_"+nomProces+".pdf");
  151. return ResponseEntity.ok(new FileSystemResource(this.filePath+it.getEvidencia()).getInputStream().readAllBytes());
  152. }
  153. }
  154. return ResponseEntity.ok(new FileSystemResource(this.filePath+it.getEvidencia()).getInputStream().readAllBytes());
  155. }
  156. /*
  157. * Download a populated template for a given task instance
  158. * @param model
  159. * @param idTascai The ID of the task instance
  160. * @param response HttpServletResponse
  161. * @return A byte array representing the populated template to download
  162. */
  163. @GetMapping(value="/download/template/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  164. @ResponseBody
  165. public ResponseEntity<byte[]> downloadTemplate(@PathVariable("id") BigInteger idTascai, HttpServletResponse response) throws IOException, XDocReportException {
  166. XDocReportRegistry.getRegistry().clear();
  167. String reportId = "none";
  168. InstanciaTascaDTO it = tc.findInstanciaTascaById(idTascai);
  169. TascaDTO tasca = it.getTasca();
  170. /* Check if specific template exists */
  171. Integer idTitulacio = it.getInstancia().getTitulacio();
  172. String templatePath = this.templatePath+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  173. if(it.getInstancia().getTambit().equals("G") | idTitulacio == 1) {
  174. File f = new File(this.templatePath+"/T1/"+tasca.getCodiEvidencia().replace(".", "_")+".docx");
  175. if(f.exists() && !f.isDirectory()) {
  176. templatePath = this.templatePath+"/T1/"+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  177. }
  178. }
  179. else if(it.getInstancia().getTambit().equals("M") | idTitulacio == 2) {
  180. File f = new File(this.templatePath+"/T2/"+tasca.getCodiEvidencia().replace(".", "_")+".docx");
  181. if(f.exists() && !f.isDirectory()) {
  182. templatePath = this.templatePath+"/T2/"+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  183. }
  184. }
  185. File f = new File(templatePath);
  186. if(!f.exists()) {
  187. return ResponseEntity.ok(new FileSystemResource(this.fileNotFound).getInputStream().readAllBytes());
  188. }
  189. InputStream in = new FileInputStream(f);
  190. IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, reportId, TemplateEngineKind.Velocity);
  191. FieldsMetadata metadata = new FieldsMetadata();
  192. metadata.addFieldAsImage("logo");
  193. report.setFieldsMetadata(metadata);
  194. IContext context = report.createContext();
  195. IImageProvider img;
  196. if(new File(this.logoPath+"C"+Integer.toString(it.getInstancia().getCentre())+".png").exists()) {
  197. img = new FileImageProvider(new File(this.logoPath+"C"+Integer.toString(it.getInstancia().getCentre())+".png"));
  198. }
  199. else {
  200. img = new FileImageProvider(new File(this.logoPath+"C0.png"));
  201. }
  202. context.put("logo", img);
  203. context.put("centre", it.getInstancia().getNomval());
  204. context.put("titulacio", it.getInstancia().getNomcas());
  205. context.put("curs", Integer.toString(it.getInstancia().getCursAvaluat()-1)+" - "+Integer.toString(it.getInstancia().getCursAvaluat()));
  206. context.put("curs_anterior", Integer.toString(it.getInstancia().getCursAvaluat()-2)+" - "+Integer.toString(it.getInstancia().getCursAvaluat()-1));
  207. Integer idCentre = it.getInstancia().getCentre();
  208. if(tasca.getIdTipus() == 14) { // Iterable template task
  209. List<OrganDTO> titulacions = new ArrayList<OrganDTO>();
  210. Integer ambit = idTitulacio/(int)1000;
  211. titulacions = oc.getTitulacionsByTypeCentre(it.getInstancia().getLugar(), ambit);
  212. List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
  213. for(OrganDTO x : titulacions) {
  214. HashMap<String, String> t = ic.getTemplateDataArray(x.getRuct(), idCentre, it.getInstancia().getCursAvaluat(), x.getTambit());
  215. t.put("titulacio", x.getNomCas());
  216. data.add(t);
  217. }
  218. context.put("data", data);
  219. addToContext(ic.getTemplateData(idTitulacio, idCentre, it.getInstancia().getCursAvaluat()), context);
  220. }
  221. else { // NO iterable template task
  222. addToContext(ic.getTemplateData(idTitulacio, idCentre, it.getInstancia().getCursAvaluat()), context);
  223. }
  224. ByteArrayOutputStream out = new ByteArrayOutputStream();
  225. report.process(context, out);
  226. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+tasca.getCodiEvidencia()+".docx\"");
  227. return ResponseEntity.ok(out.toByteArray());
  228. }
  229. /*
  230. * Test endpoint to generate a populated template for a given task (id of task)
  231. * @param model
  232. * @param idTitulacio The ID of the degree
  233. * @param idCentre The ID of the center
  234. * @param idTascap The ID of the task
  235. * @param idProces The ID of the process
  236. * @param response HttpServletResponse
  237. * @return A byte array representing the populated template
  238. */
  239. @GetMapping(value="/download/test/template/{ruct}/{centre}/{idProces}/{idTascap}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  240. @ResponseBody
  241. public ResponseEntity<byte[]> testTemplate(@PathVariable("ruct") String ruct, @PathVariable("centre") Integer idCentre,
  242. @PathVariable("idTascap") Integer idTascap, @PathVariable("idProces") Integer idProces, HttpServletResponse response)
  243. throws IOException, XDocReportException {
  244. XDocReportRegistry.getRegistry().clear();
  245. String reportId = "none";
  246. TascaDTO tasca = tc.getByProcesTascap(idProces, idTascap);
  247. ProcesDTO proces = pc.findById(idProces);
  248. OrganDTO titulacio = oc.findByRuct(Integer.parseInt(ruct));
  249. OrganDTO centre = oc.findByID("C", idCentre);
  250. /* Check if specific template exists */
  251. String templatePath = this.templatePath+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  252. if(titulacio.getTambit().equals("G")) {
  253. File f = new File(this.templatePath+"/T1/"+tasca.getCodiEvidencia().replace(".", "_")+".docx");
  254. if(f.exists() && !f.isDirectory()) {
  255. templatePath = this.templatePath+"/T1/"+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  256. }
  257. }
  258. else if(titulacio.getTambit().equals("M")) {
  259. File f = new File(this.templatePath+"/T2/"+tasca.getCodiEvidencia().replace(".", "_")+".docx");
  260. if(f.exists() && !f.isDirectory()) {
  261. templatePath = this.templatePath+"/T2/"+tasca.getCodiEvidencia().replace(".", "_")+".docx";
  262. }
  263. }
  264. InputStream in = new FileInputStream(new File(templatePath));
  265. IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, reportId, TemplateEngineKind.Velocity);
  266. FieldsMetadata metadata = new FieldsMetadata();
  267. metadata.addFieldAsImage("logo");
  268. report.setFieldsMetadata(metadata);
  269. IContext context = report.createContext();
  270. IImageProvider img;
  271. if(new File(this.logoPath+"C"+Integer.toString(idCentre)+".png").exists()) {
  272. img = new FileImageProvider(new File(this.logoPath+"C"+Integer.toString(idCentre)+".png"));
  273. }
  274. else {
  275. img = new FileImageProvider(new File(this.logoPath+"C0.png"));
  276. }
  277. context.put("logo", img);
  278. context.put("centre", centre.getNomVal());
  279. context.put("titulacio", titulacio.getNomVal());
  280. context.put("curs", Integer.toString(proces.getCursAvaluat()-1)+" - "+Integer.toString(proces.getCursAvaluat()));
  281. context.put("curs_anterior", Integer.toString(proces.getCursAvaluat()-2)+" - "+Integer.toString(proces.getCursAvaluat()-1));
  282. if(tasca.getIdTipus() == 14) { // Iterable template task
  283. List<OrganDTO> titulacions = new ArrayList<OrganDTO>();
  284. titulacions = oc.getTitulacionsByTypeCentre(centre.getRuct(), centre.getLugar());
  285. List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
  286. for(OrganDTO x : titulacions) {
  287. HashMap<String, String> t = ic.getTemplateDataArray(Integer.parseInt(ruct), idCentre, proces.getCursAvaluat(), x.getTambit());
  288. t.put("titulacio", x.getNomCas());
  289. data.add(t);
  290. }
  291. context.put("data", data);
  292. addToContext(ic.getTemplateData(titulacio.getRuct(), idCentre, proces.getCursAvaluat()), context);
  293. }
  294. else { // NO iterable template task
  295. addToContext(ic.getTemplateData(titulacio.getRuct(), idCentre, proces.getCursAvaluat()), context);
  296. }
  297. ByteArrayOutputStream out = new ByteArrayOutputStream();
  298. report.process(context, out);
  299. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+tasca.getCodiEvidencia()+".docx\"");
  300. return ResponseEntity.ok(out.toByteArray());
  301. }
  302. /*
  303. * Test endpoint to generate a populated template for a given degree and evidence (Type of task)
  304. * @param model
  305. * @param idTitulacio The ID of the degree
  306. * @param idCentre The ID of the center
  307. * @param evidencia The name of the evidence
  308. * @param curs The academic year
  309. * @param tipusTasca The type of task
  310. * @param response HttpServletResponse
  311. * @return A byte array representing the populated template
  312. */
  313. @GetMapping(value="/download/test/template2/{ruct}/{centre}/{evidencia}/{curs}/{tipusTasca}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  314. @ResponseBody
  315. public ResponseEntity<byte[]> testTemplate(Model model, @PathVariable("ruct") Integer ruct, @PathVariable("centre") Integer idCentre,
  316. @PathVariable("evidencia") String evidencia, @PathVariable("curs") Integer curs, @PathVariable("tipusTasca") Integer tipusTasca,
  317. HttpServletResponse response) throws IOException, XDocReportException {
  318. XDocReportRegistry.getRegistry().clear();
  319. String reportId = "none";
  320. OrganDTO titulacio = oc.findByRuct(ruct);
  321. OrganDTO centre = oc.findByID("C", idCentre);
  322. /* Check if specific template exists */
  323. String templatePath = this.templatePath+evidencia.replace(".", "_").replace(" (G)", "").replace(" (M)", "")+".docx";
  324. if(titulacio.getLugar() < 2000 | titulacio.getLugar() == 1) {
  325. File f = new File(this.templatePath+"/T1/"+evidencia.replace(".", "_").replace(" (G)", "").replace(" (M)", "")+".docx");
  326. if(f.exists() && !f.isDirectory()) {
  327. templatePath = this.templatePath+"/T1/"+evidencia.replace(".", "_").replace(" (G)", "").replace(" (M)", "")+".docx";
  328. };
  329. }
  330. else if((titulacio.getLugar() >= 2000 & titulacio.getLugar() < 3000) | titulacio.getLugar() == 2) {
  331. File f = new File(this.templatePath+"/T2/"+evidencia.replace(".", "_").replace(" (G)", "").replace(" (M)", "")+".docx");
  332. if(f.exists() && !f.isDirectory()) {
  333. templatePath = this.templatePath+"/T2/"+evidencia.replace(".", "_").replace(" (G)", "").replace(" (M)", "")+".docx";
  334. }
  335. }
  336. InputStream in = new FileInputStream(new File(templatePath));
  337. IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, reportId, TemplateEngineKind.Velocity);
  338. FieldsMetadata metadata = new FieldsMetadata();
  339. metadata.addFieldAsImage("logo");
  340. report.setFieldsMetadata(metadata);
  341. IContext context = report.createContext();
  342. IImageProvider img;
  343. if(new File(this.logoPath+"C"+Integer.toString(idCentre)+".png").exists()) {
  344. img = new FileImageProvider(new File(this.logoPath+"C"+Integer.toString(idCentre)+".png"));
  345. }
  346. else {
  347. img = new FileImageProvider(new File(this.logoPath+"C0.png"));
  348. }
  349. context.put("logo", img);
  350. context.put("centre", centre.getNomVal());
  351. context.put("titulacio", titulacio.getNomVal());
  352. context.put("curs", Integer.toString(curs-1)+" - "+Integer.toString(curs));
  353. context.put("curs_anterior", Integer.toString(curs-2)+" - "+Integer.toString(curs-1));
  354. if(tipusTasca == 14) { // Iterable template task
  355. List<OrganDTO> titulacions = new ArrayList<OrganDTO>();
  356. titulacions = oc.getTitulacionsByTypeCentre(centre.getRuct(), centre.getLugar());
  357. List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
  358. for(OrganDTO x : titulacions) {
  359. HashMap<String, String> t = ic.getTemplateDataArray(x.getRuct(), idCentre, curs, x.getTambit());
  360. t.put("titulacio", x.getNomCas());
  361. data.add(t);
  362. }
  363. context.put("data", data);
  364. addToContext(ic.getTemplateData(ruct, idCentre, curs), context);
  365. }
  366. else { // NO iterable template task
  367. addToContext(ic.getTemplateData(ruct, idCentre, curs), context);
  368. }
  369. ByteArrayOutputStream out = new ByteArrayOutputStream();
  370. report.process(context, out);
  371. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+evidencia+".docx\"");
  372. response.setHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
  373. return ResponseEntity.ok(out.toByteArray());
  374. }
  375. /*
  376. * Generate a PDF from the content of a task instance (unused)
  377. * @param model
  378. * @param idTascai The ID of the task instance
  379. * @param response HttpServletResponse
  380. * @return A byte array representing the generated PDF
  381. */
  382. @GetMapping(value="/download/pdf/{idTascai}")
  383. @ResponseBody
  384. public byte[] downloadTemplatePdf(@PathVariable("idTascai") BigInteger idTascai, HttpServletResponse response) throws IOException, InterruptedException {
  385. InstanciaTascaDTO it = tc.findInstanciaTascaById(idTascai);
  386. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+it.getIdInstanciaTasca()+".pdf\"");
  387. response.setHeader(HttpHeaders.CONTENT_TYPE, "application/pdf");
  388. return pls.toPDF(it.getText(), Optional.of(idTascai));
  389. }
  390. /*
  391. * Generate a PDF preview from provided content
  392. * @param model
  393. * @param content The content to convert to PDF
  394. * @param idtascai Optional ID of the task instance for context
  395. * @param response HttpServletResponse
  396. */
  397. @PostMapping(value="/download/pdf/preview")
  398. @ResponseBody
  399. public byte[] downloadTemplatePdf(HttpServletResponse response,
  400. @RequestBody PdfDTO pdf) throws IOException, InterruptedException {
  401. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"borrador.pdf\"");
  402. response.setHeader(HttpHeaders.CONTENT_TYPE, "application/pdf");
  403. return pls.toPDF(pdf.getContent(), pdf.getIdtascai());
  404. }
  405. private void addToContext(HashMap<String,String> templateData, IContext context) {
  406. for (HashMap.Entry<String, String> entry : templateData.entrySet()) {
  407. context.put(entry.getKey(), formatValue(entry.getValue()));
  408. }
  409. }
  410. @GetMapping(value="/download/{idInstancia}/{idTascap}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  411. @ResponseBody
  412. public ResponseEntity<byte[]> downloadEvidenceByTascaP(@PathVariable("idInstancia") BigInteger idInstancia, @PathVariable("idTascap") Integer idTascap, HttpServletResponse response){
  413. try {
  414. InstanciaTascaDTO i = tc.findInstanciaTascaByInstanciaAndTascaP(idInstancia, idTascap);
  415. FileSystemResource file = null;
  416. file = new FileSystemResource(this.filePath+i.getEvidencia());
  417. response.setHeader("Content-Disposition", "attachment; filename="+i.getEvidencia());
  418. if (!file.exists()) {
  419. return ResponseEntity.ok(new FileSystemResource(this.fileNotFound).getInputStream().readAllBytes());
  420. }
  421. return ResponseEntity.ok(file.getInputStream().readAllBytes());
  422. } catch (IOException e) {
  423. e.printStackTrace();
  424. }
  425. return null;
  426. }
  427. /*
  428. * Format a value for template insertion
  429. * @param v The value to format
  430. * @return The formatted value
  431. */
  432. private String formatValue(String v) {
  433. if(v == null) return "";
  434. if(v.equals("NP")) return "NP";
  435. if(v.isEmpty() | v.isBlank()) {
  436. return "";
  437. }
  438. try{
  439. return String.format("%.2f", Float.parseFloat(v)).replace(",", ".");
  440. }
  441. catch(NumberFormatException e){ }
  442. try{
  443. return Integer.toString(Integer.parseInt(v));
  444. }
  445. catch(NumberFormatException e){ }
  446. return v;
  447. }
  448. }