From 8ea9325c7810eff401e5058dc6ea211571c1d71f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Burghardt?= Date: Thu, 25 Jul 2024 12:47:14 +0200 Subject: [PATCH] do not print the same document twice when submitting multiple documents at (almost) the same time --- .../responses/PrintDocument.java | 13 +++++- .../services/DocumentService.java | 44 ++++++++++++------- .../utils/DownloadUtil.java | 18 +++----- .../PrinterWebSocketService.java | 6 +-- 4 files changed, 49 insertions(+), 32 deletions(-) diff --git a/src/main/java/tigerworkshop/webapphardwarebridge/responses/PrintDocument.java b/src/main/java/tigerworkshop/webapphardwarebridge/responses/PrintDocument.java index 9908a66..7fc4ec0 100644 --- a/src/main/java/tigerworkshop/webapphardwarebridge/responses/PrintDocument.java +++ b/src/main/java/tigerworkshop/webapphardwarebridge/responses/PrintDocument.java @@ -3,8 +3,10 @@ import tigerworkshop.webapphardwarebridge.utils.AnnotatedPrintable; import java.util.ArrayList; +import java.util.UUID; public class PrintDocument { + private final UUID uuid; String type; String url; String id; @@ -13,6 +15,14 @@ public class PrintDocument { String raw_content; ArrayList extras = new ArrayList<>(); + public PrintDocument() { + uuid = UUID.randomUUID(); + } + + public UUID getUuid() { + return uuid; + } + public String getType() { return type; } @@ -44,7 +54,8 @@ public ArrayList getExtras() { @Override public String toString() { return "PrintDocument{" + - "type='" + type + '\'' + + "uuid='" + uuid + '\'' + + ", type='" + type + '\'' + ", url='" + url + '\'' + ", id='" + id + '\'' + ", qty=" + qty + diff --git a/src/main/java/tigerworkshop/webapphardwarebridge/services/DocumentService.java b/src/main/java/tigerworkshop/webapphardwarebridge/services/DocumentService.java index e6cb867..17a7145 100644 --- a/src/main/java/tigerworkshop/webapphardwarebridge/services/DocumentService.java +++ b/src/main/java/tigerworkshop/webapphardwarebridge/services/DocumentService.java @@ -1,5 +1,6 @@ package tigerworkshop.webapphardwarebridge.services; +import org.apache.commons.io.FileUtils; import org.bouncycastle.util.encoders.Base64; import org.slf4j.LoggerFactory; import tigerworkshop.webapphardwarebridge.Config; @@ -7,8 +8,11 @@ import tigerworkshop.webapphardwarebridge.utils.DownloadUtil; import java.io.File; -import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; public class DocumentService { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DocumentService.class.getName()); @@ -18,7 +22,10 @@ public class DocumentService { private DocumentService() { File directory = new File(Config.DOCUMENT_PATH); if (!directory.exists()) { - directory.mkdir(); + boolean result = directory.mkdir(); + if (!result) { + logger.error("Directory for documents doesn't exist and can't be created."); + } } } @@ -26,30 +33,35 @@ public static DocumentService getInstance() { return instance; } - public static void extract(String base64, String urlString) throws Exception { + public static void extract(String base64, String uuid, String urlString) throws Exception { byte[] bytes = Base64.decode(base64); - try (OutputStream stream = new FileOutputStream(getPathFromUrl(urlString))) { + Path filePath = getPathFromUrl(uuid, urlString); + Files.createDirectories(filePath.getParent()); + try (OutputStream stream = Files.newOutputStream(filePath)) { stream.write(bytes); } } - public static void download(String urlString) throws Exception { - DownloadUtil.file(urlString, getPathFromUrl(urlString), true, settingService.getSetting().getIgnoreTLSCertificateErrorEnabled(), settingService.getSetting().getDownloadTimeout()); + public static void download(String uuid, String urlString) throws Exception { + Path filePath = getPathFromUrl(uuid, urlString); + Files.createDirectories(filePath.getParent()); + DownloadUtil.file(urlString, filePath, settingService.getSetting().getIgnoreTLSCertificateErrorEnabled(), settingService.getSetting().getDownloadTimeout()); } - public static File getFileFromUrl(String urlString) { - return new File(getPathFromUrl(urlString)); - } - - public static void deleteFileFromUrl(String urlString) { - getFileFromUrl(urlString).delete(); + public static void deleteFileFromUrl(String uuid, String urlString) { + Path filePath = getPathFromUrl(uuid, urlString); + try { + FileUtils.deleteDirectory(filePath.getParent().toFile()); + } catch (IOException e) { + logger.error("Couldn't delete downloaded document."); + } } - public static String getPathFromUrl(String urlString) { + public static Path getPathFromUrl(String uuid, String urlString) { urlString = urlString.replace(" ", "%20"); String filename = urlString.substring(urlString.lastIndexOf("/") + 1); - return Config.DOCUMENT_PATH + filename; + return Paths.get(Config.DOCUMENT_PATH + uuid + "/" + filename); } public void prepareDocument(PrintDocument printDocument) throws Exception { @@ -62,9 +74,9 @@ public void prepareDocument(PrintDocument printDocument) throws Exception { } if (printDocument.getFileContent() != null) { - extract(printDocument.getFileContent(), printDocument.getUrl()); + extract(printDocument.getFileContent(), printDocument.getUuid().toString(), printDocument.getUrl()); } else { - download(printDocument.getUrl()); + download(printDocument.getUuid().toString(), printDocument.getUrl()); } } } diff --git a/src/main/java/tigerworkshop/webapphardwarebridge/utils/DownloadUtil.java b/src/main/java/tigerworkshop/webapphardwarebridge/utils/DownloadUtil.java index dd8366f..1fc4e57 100644 --- a/src/main/java/tigerworkshop/webapphardwarebridge/utils/DownloadUtil.java +++ b/src/main/java/tigerworkshop/webapphardwarebridge/utils/DownloadUtil.java @@ -12,27 +12,21 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.cert.X509Certificate; public class DownloadUtil { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DownloadUtil.class.getName()); - public static long file(String urlString, String path, Boolean overwrite, Boolean ignoreCertError, double downloadTimeout) throws Exception { + public static long file(String urlString, Path path, Boolean ignoreCertError, double downloadTimeout) throws Exception { logger.info("Downloading file from: " + urlString); long timeStart = System.currentTimeMillis(); - urlString.replace(" ", "%20"); + urlString = urlString.replace(" ", "%20"); - File outputFile = new File(path); try { - // File Exist, return - if (!overwrite && outputFile.exists()) { - long timeFinish = System.currentTimeMillis(); - logger.info("File " + path + " found on local disk in " + (timeFinish - timeStart) + "ms"); - return timeStart; - } - - // Otherwise download it + // Download it URL url = new URL(urlString); if (ignoreCertError) { @@ -77,7 +71,7 @@ public void checkServerTrusted(X509Certificate[] certs, String authType) { throw new IOException("HTTP Status Code: " + responseCode); } - FileUtils.copyInputStreamToFile(urlConnection.getInputStream(), outputFile); + FileUtils.copyInputStreamToFile(urlConnection.getInputStream(), path.toFile()); long timeFinish = System.currentTimeMillis(); logger.info("File " + path + " downloaded in " + (timeFinish - timeStart) + "ms"); diff --git a/src/main/java/tigerworkshop/webapphardwarebridge/websocketservices/PrinterWebSocketService.java b/src/main/java/tigerworkshop/webapphardwarebridge/websocketservices/PrinterWebSocketService.java index d158b4c..dcad487 100644 --- a/src/main/java/tigerworkshop/webapphardwarebridge/websocketservices/PrinterWebSocketService.java +++ b/src/main/java/tigerworkshop/webapphardwarebridge/websocketservices/PrinterWebSocketService.java @@ -99,7 +99,7 @@ public void printDocument(PrintDocument printDocument) throws Exception { server.onDataReceived(getChannel(), gson.toJson(new PrintResult(0, printDocument.getId(), "Success"))); } catch (Exception e) { logger.error("Document Print Error, deleting downloaded document"); - DocumentService.deleteFileFromUrl(printDocument.getUrl()); + DocumentService.deleteFileFromUrl(printDocument.getUuid().toString(), printDocument.getUrl()); if (notificationListener != null) { notificationListener.notify("Printing Error " + printDocument.getType(), e.getMessage(), TrayIcon.MessageType.ERROR); @@ -169,7 +169,7 @@ private void printRaw(PrintDocument printDocument) throws PrinterException, Prin private void printImage(PrintDocument printDocument) throws PrinterException, IOException { logger.debug("printImage::" + printDocument); - String filename = DocumentService.getFileFromUrl(printDocument.getUrl()).getPath(); + String filename = DocumentService.getPathFromUrl(printDocument.getUuid().toString(), printDocument.getUrl()).toString(); long timeStart = System.currentTimeMillis(); @@ -205,7 +205,7 @@ private void printImage(PrintDocument printDocument) throws PrinterException, IO private void printPDF(PrintDocument printDocument) throws PrinterException, IOException { logger.debug("printPDF::" + printDocument); - String filename = DocumentService.getFileFromUrl(printDocument.getUrl()).getPath(); + String filename = DocumentService.getPathFromUrl(printDocument.getUuid().toString(), printDocument.getUrl()).toString(); long timeStart = System.currentTimeMillis();