Skip to content

Commit

Permalink
use Tika to check for zip file
Browse files Browse the repository at this point in the history
  • Loading branch information
Aqua-sc committed Mar 6, 2024
1 parent 8398c6e commit 871ce4a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
2 changes: 2 additions & 0 deletions backend/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ dependencies {
implementation 'com.auth0:jwks-rsa:0.18.0'
implementation 'javax.servlet:javax.servlet-api:4.0.1'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.apache.tika:tika-core:1.27'
runtimeOnly 'org.postgresql:postgresql'


implementation "org.springframework.boot:spring-boot-devtools"
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
Expand Down
23 changes: 10 additions & 13 deletions backend/app/src/main/java/com/ugent/pidgeon/util/Filehandler.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.ugent.pidgeon.util;

import org.apache.tika.Tika;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
Expand Down Expand Up @@ -48,29 +49,25 @@ public static String saveSubmission(Path directory, MultipartFile file) throws I

return filePath.getFileName().toString();
} catch (IOException e) {
throw new IOException("Error while saving file" + e.getMessage());
throw new IOException(e.getMessage());
}
}

static public Path getSubmissionPath(long projectid, long groupid, long submissionid) {
return Path.of(BASEPATH,"projects", String.valueOf(projectid), String.valueOf(groupid), String.valueOf(submissionid));
}

static boolean isZipFile(File file) throws IOException {
try (InputStream inputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
public static boolean isZipFile(File file) throws IOException {
// Create a Tika instance
Tika tika = new Tika();

byte[] signature = new byte[4];
bufferedInputStream.mark(4);
int bytesRead = bufferedInputStream.read(signature);
// Detect the file type
String fileType = tika.detect(file);

if (bytesRead != 4) {
throw new IOException("Error while reading file");
}
// Check if the detected file type is a ZIP file
Logger.getGlobal().info("File type: " + fileType);
return fileType.equals("application/zip") || fileType.equals("application/x-zip-compressed");

// Check if the file signature matches the ZIP format
return (signature[0] == 0x50 && signature[1] == 0x4b && signature[2] == 0x03 && signature[3] == 0x04);
}
}

public static Resource getSubmissionAsResource(Path path) throws IOException {
Expand Down

0 comments on commit 871ce4a

Please sign in to comment.