You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ze...@apache.org on 2024/03/09 14:03:16 UTC

(streampipes) branch 2520-issue-with-file-cache-persistence-in-extensions-service updated: refactor(#2520): Add method to check file content in FileProtocolUtils

This is an automated email from the ASF dual-hosted git repository.

zehnder pushed a commit to branch 2520-issue-with-file-cache-persistence-in-extensions-service
in repository https://gitbox.apache.org/repos/asf/streampipes.git


The following commit(s) were added to refs/heads/2520-issue-with-file-cache-persistence-in-extensions-service by this push:
     new d9f7c05907 refactor(#2520): Add method to check file content in FileProtocolUtils
d9f7c05907 is described below

commit d9f7c059070984dc818b28f33146127f47e1f45a
Author: Philipp Zehnder <te...@users.noreply.github.com>
AuthorDate: Sat Mar 9 15:03:05 2024 +0100

    refactor(#2520): Add method to check file content in FileProtocolUtils
---
 .../apache/streampipes/client/api/IFileApi.java    |  3 ++
 .../org/apache/streampipes/client/api/FileApi.java | 19 +++++++--
 .../connect/iiot/utils/FileProtocolUtils.java      | 48 ++++++++++++++++++++--
 .../streampipes/manager/file/FileManager.java      | 14 +++++++
 .../streampipes/rest/impl/PipelineElementFile.java | 20 +++++++++
 5 files changed, 96 insertions(+), 8 deletions(-)

diff --git a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IFileApi.java b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IFileApi.java
index 97d3da062a..1fade3601f 100644
--- a/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IFileApi.java
+++ b/streampipes-client-api/src/main/java/org/apache/streampipes/client/api/IFileApi.java
@@ -24,4 +24,7 @@ public interface IFileApi {
   String getFileContentAsString(String filename);
 
   void writeToFile(String file, String fileLocation);
+
+  boolean checkFileContentChanged(String filename, String hash);
+
 }
diff --git a/streampipes-client/src/main/java/org/apache/streampipes/client/api/FileApi.java b/streampipes-client/src/main/java/org/apache/streampipes/client/api/FileApi.java
index b6e8dcbf73..321bf89955 100644
--- a/streampipes-client/src/main/java/org/apache/streampipes/client/api/FileApi.java
+++ b/streampipes-client/src/main/java/org/apache/streampipes/client/api/FileApi.java
@@ -33,9 +33,10 @@ public class FileApi extends AbstractClientApi implements IFileApi {
 
   public byte[] getFileContent(String filename, boolean isOriginalFileName) {
     return new BinaryGetRequest(clientConfig, getBaseResourcePath(filename)
-            .withQueryParameters(Map.of("isOriginalFilename", String.valueOf(isOriginalFileName))), null)
-            .executeRequest();
+        .withQueryParameters(Map.of("isOriginalFilename", String.valueOf(isOriginalFileName))), null)
+        .executeRequest();
   }
+
   @Override
   public byte[] getFileContent(String fileId) {
     return getFileContent(fileId, false);
@@ -56,9 +57,19 @@ public class FileApi extends AbstractClientApi implements IFileApi {
         .writeToFile(fileLocation);
   }
 
+  @Override
+  public boolean checkFileContentChanged(String filename, String hash) {
+    return getSingle(
+        getBaseResourcePath(filename)
+            .addToPath("checkFileContentChanged")
+            .addToPath(hash),
+        Boolean.class
+    );
+  }
+
   protected StreamPipesApiPath getBaseResourcePath(String fileName) {
     return StreamPipesApiPath.fromBaseApiPath()
-        .addToPath("files")
-        .addToPath(fileName);
+                             .addToPath("files")
+                             .addToPath(fileName);
   }
 }
diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/utils/FileProtocolUtils.java b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/utils/FileProtocolUtils.java
index 15d5266e1c..8a673ecea0 100644
--- a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/utils/FileProtocolUtils.java
+++ b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/utils/FileProtocolUtils.java
@@ -22,18 +22,26 @@ import org.apache.streampipes.client.StreamPipesClient;
 import org.apache.streampipes.commons.exceptions.connect.ParseException;
 import org.apache.streampipes.extensions.management.client.StreamPipesClientResolver;
 
+import org.apache.commons.codec.digest.DigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 
 public class FileProtocolUtils {
+  private static final Logger LOG = LoggerFactory.getLogger(FileProtocolUtils.class);
 
   public static InputStream getFileInputStream(String selectedFilename) throws FileNotFoundException {
-    if (!isFilePresent(selectedFilename)) {
+    if (!isFilePresent(selectedFilename) || checkIfFileChanged(selectedFilename)) {
       try {
         storeFileLocally(selectedFilename);
+        LOG.info("Cache file locally: %s".formatted(selectedFilename));
       } catch (IOException e) {
         throw new ParseException("Could not receive file");
       }
@@ -42,19 +50,47 @@ public class FileProtocolUtils {
     return new FileInputStream(makeFileLoc(selectedFilename));
   }
 
+  /**
+   * Checks if the file has changed in the backend since the last time it was read
+   * This prevents that the cached file is invalid, or was updated by the user
+   * @param selectedFilename name of the file
+   * @return whether the content of the file has changed or not
+   */
+  private static boolean checkIfFileChanged(String selectedFilename) {
+    try {
+      var hash = getFileHash(selectedFilename);
+      StreamPipesClient client = getStreamPipesClientInstance();
+      return client.fileApi()
+                   .checkFileContentChanged(selectedFilename, hash);
+    } catch (IOException e) {
+      throw new ParseException("Could not read file with filename: %s".formatted(selectedFilename));
+    }
+  }
+
+  private static String getFileHash(String selectedFilename) throws IOException {
+    try (InputStream is = Files.newInputStream(Paths.get(getFile(selectedFilename).toURI()))) {
+      return DigestUtils.md5Hex(is);
+    }
+  }
+
   private static boolean isFilePresent(String selectedFilename) {
-    File file = new File(makeFileLoc(selectedFilename));
+    var file = getFile(selectedFilename);
     return file.exists();
   }
 
+  private static File getFile(String selectedFilename) {
+    return new File(makeFileLoc(selectedFilename));
+  }
+
   private static void storeFileLocally(String selectedFilename) throws IOException {
     File storageDir = new File(makeServiceStorageDir());
     if (!storageDir.exists()) {
       storageDir.mkdirs();
     }
-    StreamPipesClient client = new StreamPipesClientResolver().makeStreamPipesClientInstance();
+    StreamPipesClient client = getStreamPipesClientInstance();
 
-    client.fileApi().writeToFile(selectedFilename, makeFileLoc(selectedFilename));
+    client.fileApi()
+          .writeToFile(selectedFilename, makeFileLoc(selectedFilename));
   }
 
   private static String makeServiceStorageDir() {
@@ -69,4 +105,8 @@ public class FileProtocolUtils {
     return makeServiceStorageDir() + File.separator + filename;
   }
 
+  private static StreamPipesClient getStreamPipesClientInstance() {
+    return new StreamPipesClientResolver().makeStreamPipesClientInstance();
+  }
+
 }
diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/file/FileManager.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/file/FileManager.java
index 20fece68b9..7be47cb377 100644
--- a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/file/FileManager.java
+++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/file/FileManager.java
@@ -22,11 +22,14 @@ import org.apache.streampipes.sdk.helpers.Filetypes;
 import org.apache.streampipes.storage.api.IFileMetadataStorage;
 import org.apache.streampipes.storage.management.StorageDispatcher;
 
+import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.io.input.BOMInputStream;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.Arrays;
 import java.util.List;
 import java.util.stream.Collectors;
@@ -104,6 +107,17 @@ public class FileManager {
     return fileInputStream;
   }
 
+  public static boolean checkFileContentChanged(String filename, String hash) throws IOException {
+    var fileHash = getFileHash(filename);
+    return !fileHash.equals(hash);
+  }
+
+  private static String getFileHash(String filename) throws IOException {
+    try (InputStream is = Files.newInputStream(Paths.get(getFile(filename).toURI()))) {
+      return DigestUtils.md5Hex(is);
+    }
+  }
+
   private static void storeFileMetadata(FileMetadata fileMetadata) {
     getFileMetadataStorage().addFileMetadata(fileMetadata);
   }
diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java
index bcdfb5e5e8..777e1dc548 100644
--- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java
+++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java
@@ -139,4 +139,24 @@ public class PipelineElementFile extends AbstractAuthGuardedRestResource {
                                                           .toLowerCase())
                          .toList());
   }
+
+  @GetMapping(
+      path = "/{filename}/checkFileContentChanged/{hash}",
+      produces = MediaType.APPLICATION_JSON_VALUE)
+  @PreAuthorize(AuthConstants.HAS_READ_FILE_PRIVILEGE)
+  public ResponseEntity<Boolean> checkFileContentChanged(
+      @PathVariable(value = "filename") String filename,
+      @PathVariable(value = "hash") String hash
+  ) {
+    try {
+      return ok(FileManager.checkFileContentChanged(filename, hash));
+    } catch (IOException e) {
+      throw new SpMessageException(
+          org.springframework.http.HttpStatus.NOT_FOUND,
+          Notifications.error("File not found")
+      );
+    }
+  }
+
+
 }