Skip to content

Commit

Permalink
Merge pull request #57 from reneburghardt/master
Browse files Browse the repository at this point in the history
Fix printing the same document when submitting two documents with the same name at (almost) the same time
  • Loading branch information
imTigger authored Jul 25, 2024
2 parents bbbf538 + 8ea9325 commit 10ac459
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -13,6 +15,14 @@ public class PrintDocument {
String raw_content;
ArrayList<AnnotatedPrintable.AnnotatedPrintableAnnotation> extras = new ArrayList<>();

public PrintDocument() {
uuid = UUID.randomUUID();
}

public UUID getUuid() {
return uuid;
}

public String getType() {
return type;
}
Expand Down Expand Up @@ -44,7 +54,8 @@ public ArrayList<AnnotatedPrintable.AnnotatedPrintableAnnotation> getExtras() {
@Override
public String toString() {
return "PrintDocument{" +
"type='" + type + '\'' +
"uuid='" + uuid + '\'' +
", type='" + type + '\'' +
", url='" + url + '\'' +
", id='" + id + '\'' +
", qty=" + qty +
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package tigerworkshop.webapphardwarebridge.services;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.LoggerFactory;
import tigerworkshop.webapphardwarebridge.Config;
import tigerworkshop.webapphardwarebridge.responses.PrintDocument;
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());
Expand All @@ -18,38 +22,46 @@ 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.");
}
}
}

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 {
Expand All @@ -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());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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();

Expand Down

0 comments on commit 10ac459

Please sign in to comment.