Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/prerna/engine/impl/vector/AbstractVectorDatabaseEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -496,6 +499,36 @@ public String getIndexFilesPath(String indexClass) {
+ INDEXED_FOLDER_NAME);
}

// the stored copy of a listed document, or null unless it is an existing regular file directly inside the documents folder
public static File storedDocument(File documentsDir, String fileName) {
if (documentsDir == null || fileName == null || fileName.isEmpty() || ".".equals(fileName)
|| "..".equals(fileName) || fileName.indexOf('/') >= 0 || fileName.indexOf('\\') >= 0
|| fileName.indexOf('\0') >= 0) {
return null;
}
try {
Path realDir = documentsDir.toPath().toRealPath();
Path candidate = realDir.resolve(fileName);
// the real path rules out a link that leads out of the folder
if (!Files.isRegularFile(candidate) || !realDir.equals(candidate.toRealPath().getParent())) {
return null;
}
return new File(documentsDir, fileName);
} catch (IOException | InvalidPathException e) {
return null;
}
}

// the stored copy to delete with a removed document, or null (logged) when there is none to delete safely
protected static File storedDocumentToRemove(File documentsDir, String documentName) {
File file = storedDocument(documentsDir, documentName);
if (file == null) {
classLogger.warn("Not deleting a stored copy of '{}': it is missing or not a file directly in the documents folder",
documentName);
}
return file;
}

/**
*
* @param indexClass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
for (String document : sourceNames) {
String documentName = Paths.get(document).getFileName().toString();
// remove the physical documents
File documentFile = new File(DOCUMENT_FOLDER, documentName);
if (documentFile.exists()) {
File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);
if (documentFile != null) {
try {
FileUtils.forceDelete(documentFile);
} catch (IOException e) {
Expand Down Expand Up @@ -554,8 +554,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
Map<String, Object> fileInfo = new HashMap<>();
String fileName = bucketDetails.get("value").getAsString();
fileInfo.put("fileName", fileName);
File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,9 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter

String documentName = Paths.get(fileName).getFileName().toString();
// remove the physical documents
File documentFile = new File(this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents", documentName);
File documentFile = storedDocumentToRemove(new File(this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents"), documentName);
try {
if (documentFile.exists()) {
if (documentFile != null) {
FileUtils.forceDelete(documentFile);
filesToRemoveFromCloud.add(documentFile.getAbsolutePath());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,8 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
for (String document : fileNames) {
String documentName = Paths.get(document).getFileName().toString();
// remove the physical documents
File documentFile = new File(DOCUMENT_FOLDER, documentName);
if (documentFile.exists()) {
File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);
if (documentFile != null) {
try {
FileUtils.forceDelete(documentFile);
} catch (IOException e) {
Expand Down Expand Up @@ -554,8 +554,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
String fileName = bucketDetails.get("key").getAsString();
fileInfo.put("fileName", fileName);

File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
10 changes: 5 additions & 5 deletions src/prerna/engine/impl/vector/FaissDatabaseEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -459,9 +459,9 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
}

try {
File documentFile = new File(this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass
+ FILE_SEPARATOR + "documents", document);
if (documentFile.exists() && documentFile.isFile()) {
File documentFile = storedDocumentToRemove(new File(this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR
+ indexClass + FILE_SEPARATOR + "documents"), documentName);
if (documentFile != null) {
FileUtils.forceDelete(documentFile);
filesToRemoveFromCloud.add(documentFile.getAbsolutePath());
}
Expand Down Expand Up @@ -693,8 +693,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
for (String fileName : sources) {
Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("fileName", fileName);
File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,9 +312,9 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
List<String> filesToRemoveFromCloud = new ArrayList<>();
for (String name : fileNames) {
String documentName = Paths.get(name).getFileName().toString();
File documentFile = new File(DOCUMENT_FOLDER, documentName);
File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);

if (documentFile.exists()) {
if (documentFile != null) {
try {
FileUtils.forceDelete(documentFile);
} catch (IOException e) {
Expand Down Expand Up @@ -453,8 +453,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {

Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("fileName", source);
File thisF = new File(documentsDir, source);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, source);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,8 +555,8 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
for (String document : sourceNames) {
String documentName = Paths.get(document).getFileName().toString();
// remove the physical documents
File documentFile = new File(DOCUMENT_FOLDER, documentName);
if (documentFile.exists()) {
File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);
if (documentFile != null) {
try {
FileUtils.forceDelete(documentFile);
} catch (IOException e) {
Expand Down Expand Up @@ -856,8 +856,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
for (String source : sources) {
Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("fileName", source);
File thisF = new File(documentsDir, source);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, source);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
8 changes: 4 additions & 4 deletions src/prerna/engine/impl/vector/PGVectorDatabaseEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -603,8 +603,8 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
for (String document : sourceNames) {
String documentName = Paths.get(document).getFileName().toString();
// remove the physical documents
File documentFile = new File(DOCUMENT_FOLDER, documentName);
if (documentFile.exists()) {
File documentFile = AbstractVectorDatabaseEngine.storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);
if (documentFile != null) {
FileUtils.forceDelete(documentFile);
filesToRemoveFromCloud.add(documentFile.getAbsolutePath());
}
Expand Down Expand Up @@ -837,8 +837,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
for (Map<String, Object> fileInPostgresDb : sourcesInPostgresDb) {
String fileName = (String) fileInPostgresDb.get("fileName");

File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,11 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter

String documentName = Paths.get(fileName).getFileName().toString();
// remove the physical documents
File documentFile = new File(
this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents",
File documentFile = storedDocumentToRemove(new File(
this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents"),
documentName);
try {
if (documentFile.exists()) {
if (documentFile != null) {
FileUtils.forceDelete(documentFile);
filesToRemoveFromCloud.add(documentFile.getAbsolutePath());
}
Expand Down Expand Up @@ -448,8 +448,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
for (String fileName : sources) {
Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("fileName", fileName);
File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,11 +378,11 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter

String documentName = Paths.get(sourceName).getFileName().toString();
// remove the physical documents
File documentFile = new File(
this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents",
File documentFile = storedDocumentToRemove(new File(
this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + "documents"),
documentName);
try {
if (documentFile.exists()) {
if (documentFile != null) {
FileUtils.forceDelete(documentFile);
filesToRemoveFromCloud.add(documentFile.getAbsolutePath());
}
Expand Down Expand Up @@ -517,8 +517,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {
Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("fileName", fileName);

File thisF = new File(documentsDir, fileName);
if (thisF.exists() && thisF.isFile()) {
File thisF = AbstractVectorDatabaseEngine.storedDocument(documentsDir, fileName);
if (thisF != null && thisF.isFile()) {
long fileSizeInBytes = thisF.length();
double fileSizeInMB = (double) fileSizeInBytes / (1024);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Expand Down
100 changes: 19 additions & 81 deletions src/prerna/reactor/vector/CreateEmbeddingsFromDocumentsReactor.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
Expand All @@ -59,6 +59,7 @@
import prerna.util.AssetUtility;
import prerna.util.Constants;
import prerna.util.Utility;
import prerna.util.ZipUtils;

public class CreateEmbeddingsFromDocumentsReactor extends AbstractReactor {

Expand Down Expand Up @@ -209,100 +210,37 @@ private String getRootFolder() {
}

/**
* @param insightFolder
* @param rootFolder
* @param validFiles
* @param invalidFiles
* @return
* @throws IOException
*/
private void getFiles(String rootFolder, List<String> validFiles) throws IOException {
GenRowStruct grs = this.store.getGenRowStruct(FILE_PATHS_KEY);
if (grs != null && !grs.isEmpty()) {
int size = grs.size();
for (int i = 0; i < size; i++) {
String filePath = rootFolder + "/" + grs.get(i).toString();
String relativePath = grs.get(i).toString().replace('\\', '/').replaceFirst("^/+", "");
// the file must be inside the insight or project space
String filePath;
try {
filePath = Utility.resolveContainedFile(rootFolder, relativePath).toString();
} catch (IOException e) {
throw new IllegalArgumentException(
"File path for " + relativePath + " does not exist within the insight or project space.");
}
if (isZipFile(filePath)) {
String zipFileLocation = filePath.replace('\\', '/');
File zipFileExtractFolder = new File(rootFolder, PATH_TO_UNZIP_FILES);
unzipAndFilter(zipFileLocation, zipFileExtractFolder.getAbsolutePath(), validFiles);
zipFileExtractFolder.mkdirs();
// each zip gets its own folder so zips with the same file names never overwrite each other
Path zipDir = Files.createTempDirectory(zipFileExtractFolder.toPath(), "zip-");
validFiles.addAll(ZipUtils.unzipNested(filePath, zipDir.toString()));
} else {
validFiles.add(filePath);
}
}
}
}

/**
* Recursively go through all the zips, directories and files in a zip file and
* save the paths of valid file types
*
* @param zipFilePath
* @param destDirectory
* @param validFiles
* @param invalidFiles
* @throws IOException
*/
private void unzipAndFilter(String zipFilePath, String destDirectory, List<String> validFiles) throws IOException {
File destDir = new File(Utility.normalizePath(destDirectory));
if (!destDir.exists()) {
destDir.mkdir();
}

try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(Utility.normalizePath(zipFilePath)))) {
ZipEntry entry = zipIn.getNextEntry();

while (entry != null) {
String filePath = destDirectory + "/" + entry.getName();
if (!entry.isDirectory()) {
validFiles.add(filePath);
} else if (entry.isDirectory()) {
File dir = new File(Utility.normalizePath(filePath));
dir.mkdirs();
} else if (isZipFile(filePath)) {
// Handle nested zip file
this.extractFile(zipIn, filePath);

// Check if the entry is not in the root directory
String parentPath = null;
if (filePath.contains("/")) { // ZIP entries use "/" as a separator
parentPath = filePath.substring(0, filePath.lastIndexOf('/'));
}

// Extract the last part of the path (file name + extension)
String fileNameWithExtension = filePath.contains("/")
? filePath.substring(filePath.lastIndexOf('/') + 1)
: filePath;

// Remove the extension
String baseName = fileNameWithExtension.contains(".")
? fileNameWithExtension.substring(0, fileNameWithExtension.lastIndexOf('.'))
: fileNameWithExtension;

unzipAndFilter(filePath, parentPath + "/" + baseName, validFiles);
}

zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
}
}

/**
*
* @param zipIn
* @param filePath
* @throws IOException
*/
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
try (FileOutputStream fos = new FileOutputStream(Utility.normalizePath(filePath))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipIn.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}

/**
*
* @param filePath
Expand All @@ -314,7 +252,7 @@ private boolean isZipFile(String filePath) {

if (dotIndex > 0 && dotIndex < filePath.length() - 1) {
// Extract the extension and convert it to lower case
String extension = filePath.substring(dotIndex + 1).toLowerCase();
String extension = filePath.substring(dotIndex + 1).toLowerCase(Locale.ROOT);

return extension.equals("zip");
} else {
Expand Down
Loading
Loading