diff --git a/src/main/java/de/tum/cit/aet/artemis/athena/service/AthenaRepositoryExportService.java b/src/main/java/de/tum/cit/aet/artemis/athena/service/AthenaRepositoryExportService.java
index e719a74d131b..7ff362467f8e 100644
--- a/src/main/java/de/tum/cit/aet/artemis/athena/service/AthenaRepositoryExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/athena/service/AthenaRepositoryExportService.java
@@ -2,7 +2,6 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_ATHENA;
-import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -79,11 +78,11 @@ private void checkFeedbackSuggestionsOrAutomaticFeedbackEnabledElseThrow(Exercis
* @param exerciseId the id of the exercise to export the repository for
* @param submissionId the id of the submission to export the repository for (only for student repository, otherwise pass null)
* @param repositoryType the type of repository to export. Pass null to export the student repository.
- * @return the zip file containing the exported repository
+ * @return the path to the zip file containing the exported repository
* @throws IOException if the export fails
* @throws AccessForbiddenException if the feedback suggestions are not enabled for the given exercise
*/
- public File exportRepository(long exerciseId, Long submissionId, RepositoryType repositoryType) throws IOException {
+ public Path exportRepository(long exerciseId, Long submissionId, RepositoryType repositoryType) throws IOException {
log.debug("Exporting repository for exercise {}, submission {}", exerciseId, submissionId);
var programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);
@@ -97,27 +96,27 @@ public File exportRepository(long exerciseId, Long submissionId, RepositoryType
}
Path exportDir = fileService.getTemporaryUniqueSubfolderPath(repoDownloadClonePath, 15);
- Path zipFile = null;
+ Path zipFilePath = null;
if (repositoryType == null) { // Export student repository
var submission = programmingSubmissionRepository.findById(submissionId).orElseThrow();
// Load participation with eager submissions
var participation = programmingExerciseStudentParticipationRepository.findWithSubmissionsById(submission.getParticipation().getId()).getFirst();
- zipFile = programmingExerciseExportService.getRepositoryWithParticipation(programmingExercise, participation, exportOptions, exportDir, exportDir, true);
+ zipFilePath = programmingExerciseExportService.getRepositoryWithParticipation(programmingExercise, participation, exportOptions, exportDir, exportDir, true);
}
else {
List exportErrors = List.of();
var exportFile = programmingExerciseExportService.exportInstructorRepositoryForExercise(programmingExercise.getId(), repositoryType, exportDir, exportDir,
exportErrors);
if (exportFile.isPresent()) {
- zipFile = exportFile.get().toPath();
+ zipFilePath = exportFile.get().toPath();
}
}
- if (zipFile == null) {
+ if (zipFilePath == null) {
throw new IOException("Failed to export repository");
}
- return zipFile.toFile();
+ return zipFilePath;
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildAgentDockerService.java b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildAgentDockerService.java
index f18fb0a0542a..f0d112394013 100644
--- a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildAgentDockerService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildAgentDockerService.java
@@ -2,7 +2,8 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_BUILDAGENT;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
@@ -353,8 +354,8 @@ public void checkUsableDiskSpaceThenCleanUp() {
try {
// Get the Docker root directory to check disk space.
- File dockerRootDirectory = new File(Objects.requireNonNullElse(dockerClient.infoCmd().exec().getDockerRootDir(), "/"));
- long usableSpace = dockerRootDirectory.getUsableSpace();
+ Path dockerRootDirectory = Path.of(Objects.requireNonNullElse(dockerClient.infoCmd().exec().getDockerRootDir(), "/"));
+ long usableSpace = Files.getFileStore(dockerRootDirectory).getUsableSpace();
long threshold = convertMegabytesToBytes(imageCleanupDiskSpaceThresholdMb);
@@ -385,7 +386,7 @@ public void checkUsableDiskSpaceThenCleanUp() {
log.info("Remove oldest docker image {} to cleanup disk space to avoid filling up the hard disk", oldestImage.getKey());
try {
dockerClient.removeImageCmd(oldestImage.getKey()).exec();
- usableSpace = dockerRootDirectory.getUsableSpace();
+ usableSpace = Files.getFileStore(dockerRootDirectory).getUsableSpace();
deleteAttempts--;
}
catch (NotFoundException e) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobContainerService.java b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobContainerService.java
index 76655e03aade..161e8ef30ded 100644
--- a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobContainerService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobContainerService.java
@@ -5,11 +5,10 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
@@ -18,6 +17,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
@@ -349,7 +349,7 @@ private void createScriptFile(String buildJobContainerId) {
}
private void addAndPrepareDirectoryAndReplaceContent(String containerId, Path repositoryPath, String newDirectoryName) {
- copyToContainer(repositoryPath.toString(), containerId);
+ copyToContainer(repositoryPath, containerId);
addDirectory(containerId, newDirectoryName, true);
insertRepositoryFiles(containerId, LOCALCI_WORKING_DIRECTORY + "/" + repositoryPath.getFileName().toString(), newDirectoryName);
}
@@ -363,7 +363,7 @@ private void addDirectory(String containerId, String directoryName, boolean crea
executeDockerCommand(containerId, null, false, false, true, command);
}
- private void copyToContainer(String sourcePath, String containerId) {
+ private void copyToContainer(Path sourcePath, String containerId) {
try (final var uploadStream = new ByteArrayInputStream(createTarArchive(sourcePath).toByteArray());
final var copyToContainerCommand = buildAgentConfiguration.getDockerClient().copyArchiveToContainerCmd(containerId).withRemotePath(LOCALCI_WORKING_DIRECTORY)
.withTarInputStream(uploadStream)) {
@@ -374,8 +374,7 @@ private void copyToContainer(String sourcePath, String containerId) {
}
}
- private ByteArrayOutputStream createTarArchive(String sourcePath) {
- Path path = Paths.get(sourcePath);
+ private ByteArrayOutputStream createTarArchive(Path sourcePath) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@@ -385,7 +384,7 @@ private ByteArrayOutputStream createTarArchive(String sourcePath) {
tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
try {
- addFileToTar(tarArchiveOutputStream, path.toFile(), "");
+ addFileToTar(tarArchiveOutputStream, sourcePath, "");
}
catch (IOException e) {
throw new LocalCIException("Could not create tar archive", e);
@@ -393,15 +392,15 @@ private ByteArrayOutputStream createTarArchive(String sourcePath) {
return byteArrayOutputStream;
}
- private void addFileToTar(TarArchiveOutputStream tarArchiveOutputStream, File file, String parent) throws IOException {
- TarArchiveEntry tarEntry = new TarArchiveEntry(file, parent + file.getName());
+ private void addFileToTar(TarArchiveOutputStream tarArchiveOutputStream, Path path, String parent) throws IOException {
+ TarArchiveEntry tarEntry = new TarArchiveEntry(path, parent + path.getFileName());
tarArchiveOutputStream.putArchiveEntry(tarEntry);
- if (file.isFile()) {
- try (FileInputStream fis = new FileInputStream(file)) {
+ if (Files.isRegularFile(path)) {
+ try (InputStream is = Files.newInputStream(path)) {
byte[] buffer = new byte[1024];
int count;
- while ((count = fis.read(buffer)) != -1) {
+ while ((count = is.read(buffer)) != -1) {
tarArchiveOutputStream.write(buffer, 0, count);
}
}
@@ -409,13 +408,13 @@ private void addFileToTar(TarArchiveOutputStream tarArchiveOutputStream, File fi
}
else {
tarArchiveOutputStream.closeArchiveEntry();
- File[] children = file.listFiles();
- if (children != null) {
- for (File child : children) {
- addFileToTar(tarArchiveOutputStream, child, parent + file.getName() + "/");
+ try (Stream children = Files.list(path)) {
+ for (Path child : children.toList()) {
+ addFileToTar(tarArchiveOutputStream, child, parent + path.getFileName() + "/");
}
}
}
+
}
private void executeDockerCommandWithoutAwaitingResponse(String containerId, String... command) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobExecutionService.java b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobExecutionService.java
index 2ad17adbfa3c..093bd76d6fe4 100644
--- a/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobExecutionService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/buildagent/service/BuildJobExecutionService.java
@@ -11,7 +11,6 @@
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.ArrayList;
@@ -578,7 +577,7 @@ private Path cloneRepository(VcsRepositoryUri repositoryUri, @Nullable String co
private void deleteCloneRepo(VcsRepositoryUri repositoryUri, @Nullable String commitHash, String buildJobId, Path repositoryPath) {
String msg;
try {
- Path repositoryPathForDeletion = commitHash != null ? Paths.get(CHECKED_OUT_REPOS_TEMP_DIR, commitHash, repositoryUri.folderNameForRepositoryUri()) : repositoryPath;
+ Path repositoryPathForDeletion = commitHash != null ? Path.of(CHECKED_OUT_REPOS_TEMP_DIR, commitHash, repositoryUri.folderNameForRepositoryUri()) : repositoryPath;
Repository repository = buildJobGitService.getExistingCheckedOutRepositoryByLocalPath(repositoryPathForDeletion, repositoryUri, defaultBranch);
if (repository == null) {
msg = "Repository with commit hash " + commitHash + " not found";
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/config/SAML2Configuration.java b/src/main/java/de/tum/cit/aet/artemis/core/config/SAML2Configuration.java
index f8e25073785a..03a18eff2cec 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/config/SAML2Configuration.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/config/SAML2Configuration.java
@@ -1,11 +1,10 @@
package de.tum.cit.aet.artemis.core.config;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
@@ -117,10 +116,10 @@ private boolean checkFiles(SAML2Properties.RelyingPartyProperties config) {
return false;
}
- File keyFile = new File(config.getKeyFile());
- File certFile = new File(config.getCertFile());
+ Path keyFile = Path.of(config.getKeyFile());
+ Path certFile = Path.of(config.getCertFile());
- if (!keyFile.exists() || !certFile.exists()) {
+ if (!Files.exists(keyFile) || !Files.exists(certFile)) {
log.error("Keyfile or Certfile for SAML[{}] does not exist.", config.getRegistrationId());
return false;
}
@@ -128,16 +127,16 @@ private boolean checkFiles(SAML2Properties.RelyingPartyProperties config) {
return true;
}
- private static X509Certificate readPublicCert(String file) throws IOException, CertificateException {
- try (InputStream inStream = new FileInputStream(file)) {
+ private static X509Certificate readPublicCert(String filepath) throws IOException, CertificateException {
+ try (InputStream inStream = Files.newInputStream(Path.of(filepath))) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(inStream);
}
}
- private RSAPrivateKey readPrivateKey(String file) throws IOException {
+ private RSAPrivateKey readPrivateKey(String filepath) throws IOException {
// Read PKCS#8 File!
- try (var keyReader = new FileReader(file, StandardCharsets.UTF_8); var pemParser = new PEMParser(keyReader)) {
+ try (var keyReader = Files.newBufferedReader(Path.of(filepath), StandardCharsets.UTF_8); var pemParser = new PEMParser(keyReader)) {
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(pemParser.readObject());
return (RSAPrivateKey) converter.getPrivateKey(privateKeyInfo);
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/config/WebConfigurer.java b/src/main/java/de/tum/cit/aet/artemis/core/config/WebConfigurer.java
index c7bf24bc12aa..031e4a65930f 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/config/WebConfigurer.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/config/WebConfigurer.java
@@ -3,8 +3,8 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
import static java.net.URLDecoder.decode;
-import java.io.File;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
@@ -96,9 +96,9 @@ private void setMimeMappings(WebServerFactory server) {
private void setLocationForStaticAssets(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory servletWebServer) {
String prefixPath = resolvePathPrefix();
- File root = new File(prefixPath + "build/resources/main/static/");
- if (root.exists() && root.isDirectory()) {
- servletWebServer.setDocumentRoot(root);
+ Path root = Path.of(prefixPath + "build/resources/main/static/");
+ if (Files.exists(root) && Files.isDirectory(root)) {
+ servletWebServer.setDocumentRoot(root.toFile());
}
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/service/FileService.java b/src/main/java/de/tum/cit/aet/artemis/core/service/FileService.java
index b70b5515635e..23f157af8111 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/service/FileService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/service/FileService.java
@@ -3,14 +3,9 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
import static java.nio.charset.StandardCharsets.UTF_8;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -501,12 +496,11 @@ private boolean isIgnoredDirectory(final Path filePath) {
* @throws IOException if the directory could not be renamed.
*/
public void renameDirectory(Path oldDirectoryPath, Path targetDirectoryPath) throws IOException {
- File oldDirectory = oldDirectoryPath.toFile();
- if (!oldDirectory.exists()) {
- log.error("Directory {} should be renamed but does not exist.", oldDirectoryPath);
- throw new RuntimeException("Directory " + oldDirectoryPath + " should be renamed but does not exist.");
- }
+ if (!Files.exists(oldDirectoryPath)) {
+ throw new FilePathParsingException("Directory " + oldDirectoryPath + " should be renamed but does not exist.");
+ }
+ File oldDirectory = oldDirectoryPath.toFile();
File targetDirectory = targetDirectoryPath.toFile();
FileUtils.moveDirectory(oldDirectory, targetDirectory);
@@ -521,12 +515,12 @@ public void renameDirectory(Path oldDirectoryPath, Path targetDirectoryPath) thr
public void replacePlaceholderSections(Path filePath, Map sections) {
Map patternBooleanMap = sections.entrySet().stream().collect(Collectors.toMap(e -> Pattern.compile(".*%" + e.getKey() + ".*%.*"), Map.Entry::getValue));
File file = filePath.toFile();
- File tempFile = new File(filePath + "_temp");
+ File tempFile = Path.of(filePath + "_temp").toFile();
if (!file.exists()) {
throw new FilePathParsingException("File " + filePath + " should be updated but does not exist.");
}
- try (var reader = new BufferedReader(new FileReader(file, UTF_8)); var writer = new BufferedWriter(new FileWriter(tempFile, UTF_8))) {
+ try (var reader = Files.newBufferedReader(file.toPath(), UTF_8); var writer = Files.newBufferedWriter(tempFile.toPath(), UTF_8)) {
Map.Entry matchingStartPattern = null;
String line = reader.readLine();
while (line != null) {
@@ -599,12 +593,13 @@ public void replaceVariablesInDirectoryName(Path startPath, String targetString,
if (pathString.contains(targetString)) {
log.debug("Target String found, replacing..");
String targetPath = pathString.replace(targetString, replacementString);
- renameDirectory(startPath, Path.of(targetPath));
- directory = new File(targetPath);
+ final var path = Path.of(targetPath);
+ renameDirectory(startPath, path);
+ directory = path.toFile();
}
// Get all subdirectories
- final var subDirectories = directory.list((current, name) -> new File(current, name).isDirectory());
+ final var subDirectories = directory.list((current, name) -> current.toPath().resolve(name).toFile().isDirectory());
if (subDirectories != null) {
for (String subDirectory : subDirectories) {
@@ -634,7 +629,7 @@ public void replaceVariablesInFilename(Path startPath, String targetString, Stri
try {
// We expect the strings to be clean already, so the filename shouldn't change. If it does, we are on the safe side with the sanitation.
String cleanFileName = sanitizeFilename(filePath.toString().replace(targetString, replacementString));
- FileUtils.moveFile(filePath.toFile(), new File(cleanFileName));
+ FileUtils.moveFile(filePath.toFile(), Path.of(cleanFileName).toFile());
}
catch (IOException e) {
throw new RuntimeException("File " + filePath + " should be replaced but does not exist.");
@@ -672,7 +667,7 @@ public void replaceVariablesInFileRecursive(Path startPath, Map
}
// Get all files in directory
- String[] files = directory.list((current, name) -> new File(current, name).isFile());
+ String[] files = directory.list((current, name) -> current.toPath().resolve(name).toFile().isFile());
if (files != null) {
// filter out files that should be ignored
files = Arrays.stream(files).filter(Predicate.not(filesToIgnore::contains)).toArray(String[]::new);
@@ -682,7 +677,7 @@ public void replaceVariablesInFileRecursive(Path startPath, Map
}
// Recursive call: get all subdirectories
- String[] subDirectories = directory.list((current, name) -> new File(current, name).isDirectory());
+ String[] subDirectories = directory.list((current, name) -> current.toPath().resolve(name).toFile().isDirectory());
if (subDirectories != null) {
for (String subDirectory : subDirectories) {
if (subDirectory.equalsIgnoreCase(".git")) {
@@ -1040,7 +1035,7 @@ public MultipartFile convertByteArrayToMultipart(String filename, String extensi
FileItem fileItem = new DiskFileItem(cleanFilename, Files.probeContentType(tempPath), false, outputFile.getName(), (int) outputFile.length(),
outputFile.getParentFile());
- try (InputStream input = new FileInputStream(outputFile); OutputStream fileItemOutputStream = fileItem.getOutputStream()) {
+ try (InputStream input = Files.newInputStream(outputFile.toPath()); OutputStream fileItemOutputStream = fileItem.getOutputStream()) {
IOUtils.copy(input, fileItemOutputStream);
}
return new CommonsMultipartFile(fileItem);
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderService.java b/src/main/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderService.java
index 726f573a7e97..5e2988f5fae5 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderService.java
@@ -9,7 +9,6 @@
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -216,7 +215,7 @@ public Path getResourceFilePath(Path path) throws IOException, URISyntaxExceptio
if ("file".equals(resourceUrl.getProtocol())) {
// Resource is in the file system.
- return Paths.get(resourceUrl.toURI());
+ return Path.of(resourceUrl.toURI());
}
else if ("jar".equals(resourceUrl.getProtocol())) {
// Resource is in a jar file.
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/service/export/CourseExamExportService.java b/src/main/java/de/tum/cit/aet/artemis/core/service/export/CourseExamExportService.java
index ad14a6097a26..82d9573b32b5 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/service/export/CourseExamExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/service/export/CourseExamExportService.java
@@ -2,7 +2,7 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
-import java.io.FileWriter;
+import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -429,10 +429,8 @@ private List exportExercises(String notificationTopic, Set exerc
.exportModelingExerciseWithSubmissions(modelingExercise, submissionsExportOptions, exerciseExportDir, exportErrors, reportData));
case QuizExercise quizExercise ->
exportedExercises.add(quizExerciseWithSubmissionsExportService.exportExerciseWithSubmissions(quizExercise, exerciseExportDir, exportErrors, reportData));
- default -> {
- logMessageAndAppendToList("Failed to export exercise '" + exercise.getTitle() + "' (id: " + exercise.getId() + "): Exercise type not supported for export",
- exportErrors, null);
- }
+ default -> logMessageAndAppendToList(
+ "Failed to export exercise '" + exercise.getTitle() + "' (id: " + exercise.getId() + "): Exercise type not supported for export", exportErrors, null);
}
}
catch (Exception e) {
@@ -520,7 +518,7 @@ private Path writeReport(List data, Path outputDir) throws
*/
private Path writeFile(List data, Path outputDir, String fileName) throws IOException {
Path outputFile = outputDir.resolve(fileName);
- try (FileWriter writer = new FileWriter(outputFile.toFile(), StandardCharsets.UTF_8)) {
+ try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) {
for (String line : data) {
writer.write(line);
writer.write(System.lineSeparator());
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/service/export/DataExportService.java b/src/main/java/de/tum/cit/aet/artemis/core/service/export/DataExportService.java
index c3d6f8f918e5..7726e3b31fd2 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/service/export/DataExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/service/export/DataExportService.java
@@ -2,8 +2,8 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@@ -100,11 +100,10 @@ public Resource downloadDataExport(DataExport dataExport) {
dataExport.setDataExportState(DataExportState.DOWNLOADED);
dataExport = dataExportRepository.save(dataExport);
var filePath = Path.of(dataExport.getFilePath());
- var finalZipFile = filePath.toFile();
try {
- return new InputStreamResource(new FileInputStream(finalZipFile));
+ return new InputStreamResource(Files.newInputStream(filePath));
}
- catch (FileNotFoundException e) {
+ catch (IOException e) {
log.error("Could not find data export file", e);
throw new InternalServerErrorException("Could not find data export file");
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/util/ResponseUtil.java b/src/main/java/de/tum/cit/aet/artemis/core/util/ResponseUtil.java
index 8be235aae419..559f7aa11336 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/util/ResponseUtil.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/util/ResponseUtil.java
@@ -1,8 +1,8 @@
package de.tum.cit.aet.artemis.core.util;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
@@ -18,18 +18,19 @@
public final class ResponseUtil implements tech.jhipster.web.util.ResponseUtil {
/**
- * Sends an OK response entity that contains a file. Returns a not found response
- * if the file doesn't exist.
+ * Sends an OK response entity that contains a filepath. Returns a not found response
+ * if the filepath doesn't exist.
*
- * @param file the file to send as a response
+ * @param filepath the path to the file to send as a response
* @return the response
*/
- public static ResponseEntity ok(File file) {
+ public static ResponseEntity ok(Path filepath) {
try {
- InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
- return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header("filename", file.getName()).body(resource);
+ InputStreamResource resource = new InputStreamResource(Files.newInputStream(filepath));
+ return ResponseEntity.ok().contentLength(Files.size(filepath)).contentType(MediaType.APPLICATION_OCTET_STREAM)
+ .header("filename", String.valueOf(filepath.getFileName())).body(resource);
}
- catch (FileNotFoundException e) {
+ catch (IOException e) {
throw new EntityNotFoundException("File not found");
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/core/web/CourseResource.java b/src/main/java/de/tum/cit/aet/artemis/core/web/CourseResource.java
index cc2589f5321c..dcd4f325ba68 100644
--- a/src/main/java/de/tum/cit/aet/artemis/core/web/CourseResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/core/web/CourseResource.java
@@ -5,10 +5,10 @@
import static java.time.ZonedDateTime.now;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
+import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Principal;
import java.time.ZonedDateTime;
@@ -914,7 +914,7 @@ public ResponseEntity archiveCourse(@PathVariable Long courseId) {
*/
@EnforceAtLeastInstructor
@GetMapping("courses/{courseId}/download-archive")
- public ResponseEntity downloadCourseArchive(@PathVariable Long courseId) throws FileNotFoundException {
+ public ResponseEntity downloadCourseArchive(@PathVariable Long courseId) throws IOException {
log.info("REST request to download archive of Course : {}", courseId);
final Course course = courseRepository.findByIdElseThrow(courseId);
authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);
@@ -924,9 +924,8 @@ public ResponseEntity downloadCourseArchive(@PathVariable Long courseI
// The path is stored in the course table
Path archive = Path.of(courseArchivesDirPath, course.getCourseArchivePath());
-
+ InputStreamResource resource = new InputStreamResource(Files.newInputStream(archive));
File zipFile = archive.toFile();
- InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));
ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(zipFile.getName()).build();
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(contentDisposition);
diff --git a/src/main/java/de/tum/cit/aet/artemis/exam/web/ExamResource.java b/src/main/java/de/tum/cit/aet/artemis/exam/web/ExamResource.java
index 8d0e16e4a5c7..510d28208eca 100644
--- a/src/main/java/de/tum/cit/aet/artemis/exam/web/ExamResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/exam/web/ExamResource.java
@@ -5,11 +5,10 @@
import static java.time.ZonedDateTime.now;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Principal;
import java.time.ZonedDateTime;
@@ -1239,7 +1238,7 @@ public ResponseEntity archiveExam(@PathVariable Long courseId, @PathVariab
*/
@GetMapping("courses/{courseId}/exams/{examId}/download-archive")
@EnforceAtLeastInstructor
- public ResponseEntity downloadExamArchive(@PathVariable Long courseId, @PathVariable Long examId) throws FileNotFoundException {
+ public ResponseEntity downloadExamArchive(@PathVariable Long courseId, @PathVariable Long examId) throws IOException {
log.info("REST request to download archive of exam : {}", examId);
final Exam exam = examRepository.findByIdElseThrow(examId);
@@ -1256,7 +1255,7 @@ public ResponseEntity downloadExamArchive(@PathVariable Long courseId,
ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(zipFile.getName()).build();
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(contentDisposition);
- InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));
+ InputStreamResource resource = new InputStreamResource(Files.newInputStream(archive));
return ResponseEntity.ok().headers(headers).contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header("filename", zipFile.getName())
.body(resource);
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/exercise/service/SubmissionExportService.java b/src/main/java/de/tum/cit/aet/artemis/exercise/service/SubmissionExportService.java
index 5c7557b88071..12e7ffe5bd00 100644
--- a/src/main/java/de/tum/cit/aet/artemis/exercise/service/SubmissionExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/exercise/service/SubmissionExportService.java
@@ -66,14 +66,14 @@ public SubmissionExportService(ExerciseRepository exerciseRepository, ZipFileSer
*
* @param exerciseId the id of the exercise to be exported
* @param submissionExportOptions the options for the export
- * @return the zipped file with the exported submissions
+ * @return the path to the zipped file with the exported submissions
*/
- public File exportStudentSubmissionsElseThrow(Long exerciseId, SubmissionExportOptionsDTO submissionExportOptions) {
+ public Path exportStudentSubmissionsElseThrow(Long exerciseId, SubmissionExportOptionsDTO submissionExportOptions) {
var zippedSubmissionsPaths = exportStudentSubmissions(exerciseId, submissionExportOptions);
if (zippedSubmissionsPaths.isEmpty()) {
throw new BadRequestAlertException("Failed to export student submissions.", "SubmissionExport", "noSubmissions");
}
- return zippedSubmissionsPaths.getFirst().toFile();
+ return zippedSubmissionsPaths.getFirst();
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/fileupload/web/FileUploadExerciseResource.java b/src/main/java/de/tum/cit/aet/artemis/fileupload/web/FileUploadExerciseResource.java
index 13ec36c06432..66366ac5a1d5 100644
--- a/src/main/java/de/tum/cit/aet/artemis/fileupload/web/FileUploadExerciseResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/fileupload/web/FileUploadExerciseResource.java
@@ -3,9 +3,9 @@
import static de.tum.cit.aet.artemis.core.config.Constants.FILE_ENDING_PATTERN;
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
-import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -385,8 +385,8 @@ public ResponseEntity exportSubmissions(@PathVariable long exerciseId,
authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, exercise.getCourseViaExerciseGroupOrCourseMember(), null);
}
- File zipFile = fileUploadSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
- return ResponseUtil.ok(zipFile);
+ Path zipFilePath = fileUploadSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
+ return ResponseUtil.ok(zipFilePath);
}
/**
diff --git a/src/main/java/de/tum/cit/aet/artemis/modeling/service/ModelingSubmissionExportService.java b/src/main/java/de/tum/cit/aet/artemis/modeling/service/ModelingSubmissionExportService.java
index 3daced54e48b..dac20372b93a 100644
--- a/src/main/java/de/tum/cit/aet/artemis/modeling/service/ModelingSubmissionExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/modeling/service/ModelingSubmissionExportService.java
@@ -4,9 +4,9 @@
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@@ -35,7 +35,7 @@ protected void saveSubmissionToFile(Exercise exercise, Submission submission, Fi
}
}
else {
- try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8))) {
+ try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
writer.write(((ModelingSubmission) submission).getModel()); // TODO: save explanation text
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/modeling/web/ModelingExerciseResource.java b/src/main/java/de/tum/cit/aet/artemis/modeling/web/ModelingExerciseResource.java
index 899e16a32127..4ea6da80eae6 100644
--- a/src/main/java/de/tum/cit/aet/artemis/modeling/web/ModelingExerciseResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/modeling/web/ModelingExerciseResource.java
@@ -3,9 +3,9 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
import static de.tum.cit.aet.artemis.plagiarism.web.PlagiarismResultResponseBuilder.buildPlagiarismResultResponse;
-import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -392,8 +392,8 @@ public ResponseEntity exportSubmissions(@PathVariable long exerciseId,
authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, modelingExercise.getCourseViaExerciseGroupOrCourseMember(), null);
}
- File zipFile = modelingSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
- return ResponseUtil.ok(zipFile);
+ Path zipFilePath = modelingSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
+ return ResponseUtil.ok(zipFilePath);
}
/**
diff --git a/src/main/java/de/tum/cit/aet/artemis/plagiarism/service/TextPlagiarismDetectionService.java b/src/main/java/de/tum/cit/aet/artemis/plagiarism/service/TextPlagiarismDetectionService.java
index c69d979c3640..4a912fe51778 100644
--- a/src/main/java/de/tum/cit/aet/artemis/plagiarism/service/TextPlagiarismDetectionService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/plagiarism/service/TextPlagiarismDetectionService.java
@@ -3,8 +3,8 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
import static de.tum.cit.aet.artemis.plagiarism.service.PlagiarismService.hasMinimumScore;
-import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -99,7 +99,7 @@ public TextPlagiarismResult checkPlagiarism(TextExercise textExercise, float sim
// TODO: why do we have such a strange folder name?
final var submissionsFolderName = "./tmp/submissions";
- final var submissionFolderFile = new File(submissionsFolderName);
+ final var submissionFolderFile = Path.of(submissionsFolderName).toFile();
submissionFolderFile.mkdirs();
final List textSubmissions = textSubmissionsForComparison(textExercise, minimumScore, minimumSize);
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/AbstractGitService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/AbstractGitService.java
index 950247b1976f..952b011cd002 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/AbstractGitService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/AbstractGitService.java
@@ -1,7 +1,6 @@
package de.tum.cit.aet.artemis.programming.service;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URI;
@@ -119,8 +118,8 @@ protected static SshdSessionFactoryBuilder getSshdSessionFactoryBuilder(Optional
return new SshdSessionFactoryBuilder()
.setKeyPasswordProvider(keyPasswordProvider -> new CustomKeyPasswordProvider(gitSshPrivateKeyPath, gitSshPrivateKeyPassphrase))
.setConfigStoreFactory((homeDir, configFile, localUserName) -> new CustomSshConfigStore(gitUrl))
- .setSshDirectory(new File(gitSshPrivateKeyPath.orElseThrow()))
- .setHomeDirectory(new java.io.File(System.getProperty("user.home")));
+ .setSshDirectory(Path.of(gitSshPrivateKeyPath.orElseThrow()).toFile())
+ .setHomeDirectory(Path.of(System.getProperty("user.home")).toFile());
// @formatter:on
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/JavaTemplateUpgradeService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/JavaTemplateUpgradeService.java
index 9e6a796307a0..02b646c558b1 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/JavaTemplateUpgradeService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/JavaTemplateUpgradeService.java
@@ -2,11 +2,10 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
@@ -158,14 +157,14 @@ private Resource[] getTemplateResources(ProgrammingExercise exercise, String fil
}
private void writeProjectObjectModel(Model repositoryModel, File repositoryPom) throws IOException {
- try (OutputStream outputStream = new FileOutputStream(repositoryPom)) {
+ try (OutputStream outputStream = Files.newOutputStream(repositoryPom.toPath())) {
var pomWriter = new MavenXpp3Writer();
pomWriter.write(outputStream, repositoryModel);
}
}
private Model upgradeProjectObjectModel(Resource templatePom, File repositoryPom, boolean scaEnabled) throws IOException, XmlPullParserException {
- try (InputStream templateInput = templatePom.getInputStream(); InputStream repoInput = new FileInputStream(repositoryPom)) {
+ try (InputStream templateInput = templatePom.getInputStream(); InputStream repoInput = Files.newInputStream(repositoryPom.toPath())) {
var pomReader = new MavenXpp3Reader();
Model templateModel = pomReader.read(templateInput);
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/PlantUmlService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/PlantUmlService.java
index 5a31f0a81a46..f926ba753f4c 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/PlantUmlService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/PlantUmlService.java
@@ -7,7 +7,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
@@ -35,7 +34,7 @@ public class PlantUmlService {
private static final String LIGHT_THEME_FILE_NAME = "puml-theme-artemislight.puml";
- private static final Path PATH_TMP_THEME = Paths.get(System.getProperty("java.io.tmpdir"), "artemis-puml-theme");
+ private static final Path PATH_TMP_THEME = Path.of(System.getProperty("java.io.tmpdir"), "artemis-puml-theme");
private final ResourceLoaderService resourceLoaderService;
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseExportService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseExportService.java
index 76a140eb2147..46b489138d18 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseExportService.java
@@ -853,7 +853,7 @@ public void addParticipantIdentifierToProjectName(Repository repository, Program
private void addParticipantIdentifierToMavenProjectName(Repository repo, String participantIdentifier, String pomFilePath) {
try {
- File pomFile = new File(pomFilePath);
+ File pomFile = Path.of(pomFilePath).toFile();
// check if file exists and full file name is pom.xml and not just the file ending.
if (!pomFile.exists() || !pomFile.getName().equals("pom.xml")) {
return;
@@ -889,7 +889,7 @@ private void addParticipantIdentifierToMavenProjectName(Repository repo, String
private void addParticipantIdentifierToEclipseProjectName(Repository repo, String participantIdentifier, String eclipseProjectFilePath) {
try {
- File eclipseProjectFile = new File(eclipseProjectFilePath);
+ File eclipseProjectFile = Path.of(eclipseProjectFilePath).toFile();
// Check if file exists and full file name is .project and not just the file ending.
if (!eclipseProjectFile.exists() || !eclipseProjectFile.getName().equals(".project")) {
return;
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportFromFileService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportFromFileService.java
index 784e29599185..b32a72fbbc0b 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportFromFileService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportFromFileService.java
@@ -198,7 +198,7 @@ private void importRepositoriesFromFile(ProgrammingExercise newExercise, Path ba
}
- private void replaceImportedExerciseShortName(Map replacements, List repositories) {
+ private void replaceImportedExerciseShortName(Map replacements, List repositories) throws IOException {
for (Repository repository : repositories) {
fileService.replaceVariablesInFileRecursive(repository.getLocalPath(), replacements, SHORT_NAME_REPLACEMENT_EXCLUSIONS);
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportService.java
index 0c308cc80c0a..8e049963a70a 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseImportService.java
@@ -263,7 +263,7 @@ private void adjustProjectNames(ProgrammingExercise templateExercise, Programmin
* @param user the user which performed the action (used as Git author)
* @throws GitAPIException If the checkout/push of one repository fails
*/
- private void adjustProjectName(Map replacements, String projectKey, String repositoryName, User user) throws GitAPIException {
+ private void adjustProjectName(Map replacements, String projectKey, String repositoryName, User user) throws GitAPIException, IOException {
final var repositoryUri = versionControlService.orElseThrow().getCloneRepositoryUri(projectKey, repositoryName);
Repository repository = gitService.getOrCheckoutRepository(repositoryUri, true);
fileService.replaceVariablesInFileRecursive(repository.getLocalPath().toAbsolutePath(), replacements, List.of("gradle-wrapper.jar"));
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/RepositoryService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/RepositoryService.java
index 1ca095cac600..529fbc7adea1 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/RepositoryService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/RepositoryService.java
@@ -2,7 +2,6 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
@@ -10,7 +9,6 @@
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@@ -245,7 +243,7 @@ public byte[] getFile(Repository repository, String filename) throws IOException
if (file.isEmpty()) {
throw new FileNotFoundException();
}
- InputStream inputStream = new FileInputStream(file.get());
+ InputStream inputStream = Files.newInputStream(file.get().toPath());
byte[] fileInBytes = org.apache.commons.io.IOUtils.toByteArray(inputStream);
inputStream.close();
return fileInBytes;
@@ -332,7 +330,7 @@ public void createFolder(Repository repository, String folderPath, InputStream i
*/
private Path checkIfPathIsValidAndReturnSafePath(Repository repository, String path) {
String unescapedPath = StringEscapeUtils.unescapeJava(path);
- Path unknownInputPath = Paths.get(unescapedPath).normalize();
+ Path unknownInputPath = Path.of(unescapedPath).normalize();
Path absoluteRepositoryPath = repository.getLocalPath().normalize().toAbsolutePath();
Path absoluteInputPath = absoluteRepositoryPath.resolve(unknownInputPath).normalize();
if (!absoluteInputPath.startsWith(absoluteRepositoryPath)) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/localci/scaparser/strategy/PMDCPDParser.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/localci/scaparser/strategy/PMDCPDParser.java
index b5da7a65fdf0..eaba11782d85 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/localci/scaparser/strategy/PMDCPDParser.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/localci/scaparser/strategy/PMDCPDParser.java
@@ -1,7 +1,7 @@
package de.tum.cit.aet.artemis.programming.service.localci.scaparser.strategy;
-import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -67,7 +67,7 @@ private StaticCodeAnalysisReportDTO createReportFromDuplication(PmdCpc report) {
// Iterate through the files to create on commonly used error message refering to all instances of duplication.
for (DuplicationFile file : duplication.files()) {
String unixPath = ParserStrategy.transformToUnixPath(file.path());
- String filename = new File(unixPath).getName();
+ String filename = Path.of(unixPath).toFile().getName();
messageBuilder.append("\n - ").append(filename).append(": Lines ").append(file.startLine()).append(" to ").append(file.endLine());
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCRepositoryUri.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCRepositoryUri.java
index 8103863650fa..5002a884fb8e 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCRepositoryUri.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCRepositoryUri.java
@@ -4,7 +4,6 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
-import java.nio.file.Paths;
import de.tum.cit.aet.artemis.core.exception.localvc.LocalVCInternalException;
import de.tum.cit.aet.artemis.programming.domain.VcsRepositoryUri;
@@ -73,7 +72,7 @@ public LocalVCRepositoryUri(String urlString) {
throw new LocalVCInternalException("Could not create local VC Repository URI", e);
}
- var urlPath = Paths.get(this.uri.getPath());
+ var urlPath = Path.of(this.uri.getPath());
// Find index of "git" in the path. This is needed in case the base URL contains a path.
final var startIndex = getGitPartStartIndex(urlString, urlPath);
@@ -147,12 +146,12 @@ private static int getGitPartStartIndex(String urlString, Path urlPath) throws L
*
*
* -
- * Input: Local repository path - {@code Paths.get("/local/path/projectX/my-repo/.git")}
+ * Input: Local repository path - {@code Path.of("/local/path/projectX/my-repo/.git")}
* and Local VC server URL - {@code new URI("https://artemis.tum.de").getURL()}
* Output: {@code https://artemis.tum.de/git/projectX/my-repo.git}
*
* -
- * Input: Remote repository path - {@code Paths.get("/remote/path/projectY/my-repo")}
+ * Input: Remote repository path - {@code Path.of("/remote/path/projectY/my-repo")}
* and Local VC server URL - {@code new URI("https://artemis.tum.de").getURL()}
* Output: {@code https://artemis.tum.de/git/projectY/my-repo.git}
*
@@ -291,6 +290,6 @@ public Path getLocalRepositoryPath(String localVCBasePath) {
* @return The relative Path to the repository, which includes the project key and repository slug with a ".git" suffix.
*/
public Path getRelativeRepositoryPath() {
- return Paths.get(projectKey, repositorySlug + ".git");
+ return Path.of(projectKey, repositorySlug + ".git");
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCServletService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCServletService.java
index bb33dfc715cf..0266cc51a04f 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCServletService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/LocalVCServletService.java
@@ -8,7 +8,6 @@
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.HashMap;
@@ -171,7 +170,7 @@ public Repository resolveRepository(String repositoryPath) throws RepositoryNotF
long timeNanoStart = System.nanoTime();
// Find the local repository depending on the name.
- Path repositoryDir = Paths.get(localVCBasePath, repositoryPath);
+ Path repositoryDir = Path.of(localVCBasePath, repositoryPath);
log.debug("Path to resolve repository from: {}", repositoryDir);
if (!Files.exists(repositoryDir)) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/SshGitLocationResolverService.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/SshGitLocationResolverService.java
index fbe1f6450384..94f8ae6f7ec6 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/SshGitLocationResolverService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/SshGitLocationResolverService.java
@@ -6,7 +6,6 @@
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.apache.sshd.git.GitLocationResolver;
import org.apache.sshd.server.session.ServerSession;
@@ -56,7 +55,7 @@ public Path resolveRootDirectory(String command, String[] args, ServerSession se
}
final var gitCommand = args[0];
- final var localVCRepositoryUri = new LocalVCRepositoryUri(Paths.get(repositoryPath), localVCBaseUrl);
+ final var localVCRepositoryUri = new LocalVCRepositoryUri(Path.of(repositoryPath), localVCBaseUrl);
final var projectKey = localVCRepositoryUri.getProjectKey();
final var repositoryTypeOrUserName = localVCRepositoryUri.getRepositoryTypeOrUserName();
ProgrammingExercise exercise;
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/ssh/SshConfiguration.java b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/ssh/SshConfiguration.java
index 190b1732efe1..8e494729aaab 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/ssh/SshConfiguration.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/service/localvc/ssh/SshConfiguration.java
@@ -5,7 +5,6 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Optional;
import org.apache.sshd.common.util.threads.ThreadUtils;
@@ -67,7 +66,7 @@ public SshServer sshServer() {
}
else {
// this is a simple solution for development, the host key will be generated during the first ssh operation in case it does not exist
- sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("tmp", "hostkey.ser")));
+ sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Path.of("tmp", "hostkey.ser")));
}
sshd.setCommandFactory(
sshGitCommandFactoryService.withGitLocationResolver(sshGitLocationResolverService).withExecutorServiceProvider(() -> ThreadUtils.newFixedThreadPool("git-ssh", 8)));
diff --git a/src/main/java/de/tum/cit/aet/artemis/programming/web/ProgrammingExerciseExportImportResource.java b/src/main/java/de/tum/cit/aet/artemis/programming/web/ProgrammingExerciseExportImportResource.java
index 7079d2e2994e..9f7ddb1e330d 100644
--- a/src/main/java/de/tum/cit/aet/artemis/programming/web/ProgrammingExerciseExportImportResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/programming/web/ProgrammingExerciseExportImportResource.java
@@ -4,9 +4,9 @@
import static de.tum.cit.aet.artemis.core.util.TimeLogUtil.formatDurationFrom;
import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
@@ -334,14 +334,14 @@ public ResponseEntity exportInstructorExercise(@PathVariable long exer
log.error("Error while exporting programming exercise with id {} for instructor", exerciseId, e);
throw new InternalServerErrorException("Error while exporting programming exercise with id " + exerciseId + " for instructor");
}
- var finalZipFile = path.toFile();
- InputStreamResource resource = new InputStreamResource(new FileInputStream(finalZipFile));
+ InputStreamResource resource = new InputStreamResource(Files.newInputStream(path));
log.info("Export of the programming exercise {} with title '{}' was successful in {}.", programmingExercise.getId(), programmingExercise.getTitle(),
formatDurationFrom(start));
- return ResponseEntity.ok().contentLength(finalZipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header("filename", finalZipFile.getName()).body(resource);
+ final var zipFile = path.toFile();
+ return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header("filename", zipFile.getName()).body(resource);
}
/**
@@ -402,7 +402,7 @@ private ResponseEntity returnZipFileForRepositoryExport(Optional
"There was an error on the server and the zip file could not be created.")).body(null);
}
- InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile.get()));
+ InputStreamResource resource = new InputStreamResource(Files.newInputStream(zipFile.get().toPath()));
log.info("Export of the repository of type {} programming exercise {} with title '{}' was successful in {}.", repositoryName, exercise.getId(), exercise.getTitle(),
formatDurationFrom(startTime));
@@ -511,7 +511,7 @@ private ResponseEntity provideZipForParticipations(@NotNull List checkPlagiarismWithJPlagReport(@PathVariable lon
"notEnoughSubmissions");
}
- var resource = new InputStreamResource(new FileInputStream(zipFile));
+ var resource = new InputStreamResource(Files.newInputStream(zipFile.toPath()));
return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header("filename", zipFile.getName()).body(resource);
}
catch (ProgrammingLanguageNotSupportedForPlagiarismDetectionException e) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizExerciseService.java b/src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizExerciseService.java
index 955212be3450..e529d4ae6f46 100644
--- a/src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizExerciseService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizExerciseService.java
@@ -6,7 +6,6 @@
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
@@ -292,7 +291,7 @@ public void handleDndQuizFileUpdates(QuizExercise updatedExercise, QuizExercise
}
}
- fileService.deleteFiles(filesToRemove.stream().map(Paths::get).toList());
+ fileService.deleteFiles(filesToRemove.stream().map(Path::of).toList());
}
private Set getAllPathsFromDragAndDropQuestionsOfExercise(QuizExercise quizExercise) {
diff --git a/src/main/java/de/tum/cit/aet/artemis/text/service/TextSubmissionExportService.java b/src/main/java/de/tum/cit/aet/artemis/text/service/TextSubmissionExportService.java
index 6025b30fbea2..ee83a8e5de3c 100644
--- a/src/main/java/de/tum/cit/aet/artemis/text/service/TextSubmissionExportService.java
+++ b/src/main/java/de/tum/cit/aet/artemis/text/service/TextSubmissionExportService.java
@@ -4,9 +4,10 @@
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@@ -35,7 +36,7 @@ protected void saveSubmissionToFile(Exercise exercise, Submission submission, Fi
}
}
else {
- try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8))) {
+ try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
writer.write(((TextSubmission) submission).getText());
}
}
@@ -50,14 +51,13 @@ protected void saveSubmissionToFile(Exercise exercise, Submission submission, Fi
*/
public void saveSubmissionToFile(TextSubmission submission, String studentLogin, String submissionsFolderName) throws IOException {
String submissionFileName = String.format("%s-%s%s", submission.getId(), studentLogin, this.getFileEndingForSubmission(submission));
+ Path submissionPath = Path.of(submissionsFolderName, submissionFileName);
- File submissionExportFile = new File(submissionsFolderName, submissionFileName);
-
- if (!submissionExportFile.exists()) {
- submissionExportFile.createNewFile();
+ if (!Files.exists(submissionPath)) {
+ Files.createFile(submissionPath);
}
- try (BufferedWriter writer = new BufferedWriter(new FileWriter(submissionExportFile, StandardCharsets.UTF_8))) {
+ try (BufferedWriter writer = Files.newBufferedWriter(submissionPath, StandardCharsets.UTF_8)) {
writer.write(submission.getText());
}
}
diff --git a/src/main/java/de/tum/cit/aet/artemis/text/web/TextExerciseResource.java b/src/main/java/de/tum/cit/aet/artemis/text/web/TextExerciseResource.java
index 0b72f23ba0db..6fb475c45d78 100644
--- a/src/main/java/de/tum/cit/aet/artemis/text/web/TextExerciseResource.java
+++ b/src/main/java/de/tum/cit/aet/artemis/text/web/TextExerciseResource.java
@@ -3,9 +3,9 @@
import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;
import static de.tum.cit.aet.artemis.plagiarism.web.PlagiarismResultResponseBuilder.buildPlagiarismResultResponse;
-import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
@@ -560,8 +560,8 @@ public ResponseEntity exportSubmissions(@PathVariable long exerciseId,
authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, textExercise.getCourseViaExerciseGroupOrCourseMember(), null);
}
- File zipFile = textSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
- return ResponseUtil.ok(zipFile);
+ Path zipFilePath = textSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
+ return ResponseUtil.ok(zipFilePath);
}
/**
diff --git a/src/test/java/de/tum/cit/aet/artemis/assessment/util/GradingScaleUtilService.java b/src/test/java/de/tum/cit/aet/artemis/assessment/util/GradingScaleUtilService.java
index 7053c3b96595..1c3456cb3eba 100644
--- a/src/test/java/de/tum/cit/aet/artemis/assessment/util/GradingScaleUtilService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/assessment/util/GradingScaleUtilService.java
@@ -2,8 +2,9 @@
import static org.assertj.core.api.Assertions.fail;
-import java.io.FileReader;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@@ -200,11 +201,12 @@ else if (i == gradeStepCount - 1) {
*
* @param path The path to the csv file.
* @return The list of String arrays.
- * @throws Exception if an error occurs while reading the csv file.
+ * @throws IOException if an error occurs while reading the csv file.
*/
- public List loadPercentagesAndGrades(String path) throws Exception {
+ public List loadPercentagesAndGrades(String path) throws IOException {
- try (var reader = new FileReader(ResourceUtils.getFile("classpath:" + path), StandardCharsets.UTF_8); var csvParser = CSVParser.parse(reader, CSVFormat.DEFAULT)) {
+ try (var reader = Files.newBufferedReader(ResourceUtils.getFile("classpath:" + path).toPath(), StandardCharsets.UTF_8);
+ var csvParser = CSVParser.parse(reader, CSVFormat.DEFAULT)) {
var rows = csvParser.getRecords();
rows.removeFirst(); // remove header
diff --git a/src/test/java/de/tum/cit/aet/artemis/athena/service/connectors/AthenaRepositoryExportServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/athena/service/connectors/AthenaRepositoryExportServiceTest.java
index 163d1821e1bc..f0a8f09f5260 100644
--- a/src/test/java/de/tum/cit/aet/artemis/athena/service/connectors/AthenaRepositoryExportServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/athena/service/connectors/AthenaRepositoryExportServiceTest.java
@@ -4,11 +4,9 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.BeforeEach;
@@ -79,10 +77,10 @@ void shouldExportRepository() throws Exception {
programmingExerciseUtilService.createGitRepository();
- File resultStudentRepo = athenaRepositoryExportService.exportRepository(programmingExerciseWithId.getId(), programmingSubmissionWithId.getId(), null);
- File resultSolutionRepo = athenaRepositoryExportService.exportRepository(programmingExerciseWithId.getId(), programmingSubmissionWithId.getId(), RepositoryType.SOLUTION);
+ Path resultStudentRepo = athenaRepositoryExportService.exportRepository(programmingExerciseWithId.getId(), programmingSubmissionWithId.getId(), null);
+ Path resultSolutionRepo = athenaRepositoryExportService.exportRepository(programmingExerciseWithId.getId(), programmingSubmissionWithId.getId(), RepositoryType.SOLUTION);
- assertThat(resultStudentRepo.toPath()).isEqualTo(Paths.get("repo.zip")); // The student repository ZIP is returned
+ assertThat(resultStudentRepo).isEqualTo(Path.of("repo.zip")); // The student repository ZIP is returned
assertThat(resultSolutionRepo).exists(); // The solution repository ZIP can actually be created in the test
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/communication/linkpreview/LinkPreviewIntegrationTest.java b/src/test/java/de/tum/cit/aet/artemis/communication/linkpreview/LinkPreviewIntegrationTest.java
index 02947eefc6b3..52c2eb9bea70 100644
--- a/src/test/java/de/tum/cit/aet/artemis/communication/linkpreview/LinkPreviewIntegrationTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/communication/linkpreview/LinkPreviewIntegrationTest.java
@@ -6,6 +6,7 @@
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
import java.util.Objects;
import java.util.stream.Stream;
@@ -156,8 +157,9 @@ void testLinkPreviewDataExtractionWithInvalidTld() throws Exception {
}
private static Stream provideUrls() {
- return Stream.of(Arguments.of("https://github.com/ls1intum/Artemis/pull/6615", new File(MOCK_FILE_PATH_PREFIX + "github_pull_request_6615.txt")),
- Arguments.of("https://github.com/ls1intum/Artemis/pull/6618", new File(MOCK_FILE_PATH_PREFIX + "github_pull_request_6618.txt")),
- Arguments.of("https://github.com/", new File(MOCK_FILE_PATH_PREFIX + "github_home.txt")), Arguments.of(GOOGLE_URL, new File(MOCK_FILE_PATH_PREFIX + "google.txt")));
+ var mockPath = Path.of(MOCK_FILE_PATH_PREFIX);
+ return Stream.of(Arguments.of("https://github.com/ls1intum/Artemis/pull/6615", mockPath.resolve("github_pull_request_6615.txt").toFile()),
+ Arguments.of("https://github.com/ls1intum/Artemis/pull/6618", mockPath.resolve("github_pull_request_6618.txt").toFile()),
+ Arguments.of("https://github.com/", mockPath.resolve("github_home.txt").toFile()), Arguments.of(GOOGLE_URL, mockPath.resolve("google.txt").toFile()));
}
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/communication/notification/NotificationPlaceholderSignatureTest.java b/src/test/java/de/tum/cit/aet/artemis/communication/notification/NotificationPlaceholderSignatureTest.java
index e4b0c6d70511..78caf6dca4e5 100644
--- a/src/test/java/de/tum/cit/aet/artemis/communication/notification/NotificationPlaceholderSignatureTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/communication/notification/NotificationPlaceholderSignatureTest.java
@@ -6,7 +6,7 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
-import java.nio.file.Paths;
+import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -66,7 +66,7 @@ void testSignatureHasNotChanged() throws URISyntaxException, IOException {
}
private String readPlaceholderText(URL url) throws URISyntaxException, IOException {
- return Files.readString(Paths.get(url.toURI())).strip();
+ return Files.readString(Path.of(url.toURI())).strip();
}
private record ClassSignature(String notificationType, List fieldDescriptions) implements Comparable {
diff --git a/src/test/java/de/tum/cit/aet/artemis/core/service/DataExportCreationServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/core/service/DataExportCreationServiceTest.java
index 03fc57119a21..4115500b4a3e 100644
--- a/src/test/java/de/tum/cit/aet/artemis/core/service/DataExportCreationServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/core/service/DataExportCreationServiceTest.java
@@ -12,7 +12,6 @@
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
-import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -217,7 +216,7 @@ void testDataExportCreationSuccess_containsCorrectCourseContent() throws Excepti
}
org.apache.commons.io.FileUtils.deleteDirectory(extractedZipDirPath.toFile());
- org.apache.commons.io.FileUtils.delete(new File(dataExportFromDb.getFilePath()));
+ org.apache.commons.io.FileUtils.delete(Path.of(dataExportFromDb.getFilePath()).toFile());
}
private void assertCommunicationDataCsvFile(Path courseDirPath) {
@@ -545,7 +544,7 @@ void testDataExportCreationSuccess_containsCorrectExamContent() throws Exception
}
org.apache.commons.io.FileUtils.deleteDirectory(extractedZipDirPath.toFile());
- org.apache.commons.io.FileUtils.delete(new File(dataExportFromDb.getFilePath()));
+ org.apache.commons.io.FileUtils.delete(Path.of(dataExportFromDb.getFilePath()).toFile());
}
private void addOnlyAnswerPostReactionInCourse(Course course) {
@@ -571,7 +570,7 @@ void resultsPublicationDateInTheFuture_noResultsLeaked() throws Exception {
getExerciseDirectoryPaths(examDirPath).forEach(this::assertNoResultsFile);
org.apache.commons.io.FileUtils.deleteDirectory(extractedZipDirPath.toFile());
- org.apache.commons.io.FileUtils.delete(new File(dataExportFromDb.getFilePath()));
+ org.apache.commons.io.FileUtils.delete(Path.of(dataExportFromDb.getFilePath()).toFile());
}
@Test
@@ -594,7 +593,7 @@ void testDataExportDoesntLeakResultsIfAssessmentDueDateInTheFuture() throws Exce
}
org.apache.commons.io.FileUtils.deleteDirectory(extractedZipDirPath.toFile());
- org.apache.commons.io.FileUtils.delete(new File(dataExportFromDb.getFilePath()));
+ org.apache.commons.io.FileUtils.delete(Path.of(dataExportFromDb.getFilePath()).toFile());
}
private void addOnlyAnswerPostInCourse(Course course) {
@@ -650,7 +649,7 @@ void testDataExportContainsDataAboutCourseStudentUnenrolled() throws Exception {
}
org.apache.commons.io.FileUtils.deleteDirectory(extractedZipDirPath.toFile());
- org.apache.commons.io.FileUtils.delete(new File(dataExportFromDb.getFilePath()));
+ org.apache.commons.io.FileUtils.delete(Path.of(dataExportFromDb.getFilePath()).toFile());
}
private DataExport initDataExport() {
diff --git a/src/test/java/de/tum/cit/aet/artemis/core/service/FileServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/core/service/FileServiceTest.java
index 74b85b6bf9f6..b4019258c2db 100644
--- a/src/test/java/de/tum/cit/aet/artemis/core/service/FileServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/core/service/FileServiceTest.java
@@ -69,6 +69,10 @@ class FileServiceTest extends AbstractSpringIntegrationIndependentTest {
private static final URI INVALID_DRAGITEM_PATH = URI.create("/api/uploads/images/drag-and-drop/drag-items/1/../../../exam-users/signatures/some-file.png");
+ private static final Path lineEndingsUnixPath = Path.of(".", "exportTest", "LineEndingsUnix.java");
+
+ private static final Path lineEndingsWindowsPath = Path.of(".", "exportTest", "LineEndingsWindows.java");
+
private static URI createURIWithPath(String prefix, Path path) {
String replacementForWindows = path.toString().replace('\\', '/');
return URI.create(prefix + replacementForWindows + '/');
@@ -189,36 +193,36 @@ void testCopyExistingFileToTarget_temporaryFile() {
@Test
void normalizeFileEndingsUnix_noChange() throws IOException {
writeFile("LineEndingsUnix.java", FILE_WITH_UNIX_LINE_ENDINGS);
- int size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsUnix.java")).length;
+ int size = Files.readAllBytes(lineEndingsUnixPath).length;
assertThat(size).isEqualTo(129);
}
@Test
void normalizeFileEndingsUnix_normalized() throws IOException {
writeFile("LineEndingsUnix.java", FILE_WITH_UNIX_LINE_ENDINGS);
- int size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsUnix.java")).length;
+ int size = Files.readAllBytes(lineEndingsUnixPath).length;
assertThat(size).isEqualTo(129);
- fileService.normalizeLineEndings(Path.of(".", "exportTest", "LineEndingsUnix.java"));
- size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsUnix.java")).length;
+ fileService.normalizeLineEndings(lineEndingsUnixPath);
+ size = Files.readAllBytes(lineEndingsUnixPath).length;
assertThat(size).isEqualTo(129);
}
@Test
void normalizeFileEndingsWindows_noChange() throws IOException {
writeFile("LineEndingsWindows.java", FILE_WITH_WINDOWS_LINE_ENDINGS);
- int size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsWindows.java")).length;
+ int size = Files.readAllBytes(lineEndingsWindowsPath).length;
assertThat(size).isEqualTo(136);
}
@Test
void normalizeFileEndingsWindows_normalized() throws IOException {
writeFile("LineEndingsWindows.java", FILE_WITH_WINDOWS_LINE_ENDINGS);
- int size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsWindows.java")).length;
+ int size = Files.readAllBytes(lineEndingsWindowsPath).length;
assertThat(size).isEqualTo(136);
- fileService.normalizeLineEndings(Path.of(".", "exportTest", "LineEndingsWindows.java"));
- size = Files.readAllBytes(Path.of(".", "exportTest", "LineEndingsWindows.java")).length;
+ fileService.normalizeLineEndings(lineEndingsWindowsPath);
+ size = Files.readAllBytes(lineEndingsWindowsPath).length;
assertThat(size).isEqualTo(129);
}
@@ -232,11 +236,12 @@ void normalizeEncodingUTF8() throws IOException {
@Test
void normalizeEncodingISO_8559_1() throws IOException {
copyFile("EncodingISO_8559_1.java", "EncodingISO_8559_1.java");
- Charset charset = fileService.detectCharset(Files.readAllBytes(Path.of(".", "exportTest", "EncodingISO_8559_1.java")));
+ final var exportTestPath = Path.of(".", "exportTest", "EncodingISO_8559_1.java");
+ Charset charset = fileService.detectCharset(Files.readAllBytes(exportTestPath));
assertThat(charset).isEqualTo(StandardCharsets.ISO_8859_1);
- fileService.convertToUTF8(Path.of(".", "exportTest", "EncodingISO_8559_1.java"));
- charset = fileService.detectCharset(Files.readAllBytes(Path.of(".", "exportTest", "EncodingISO_8559_1.java")));
+ fileService.convertToUTF8(exportTestPath);
+ charset = fileService.detectCharset(Files.readAllBytes(exportTestPath));
assertThat(charset).isEqualTo(StandardCharsets.UTF_8);
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderServiceTest.java
index 845c645030c9..9f7723ccd5f2 100644
--- a/src/test/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/core/service/ResourceLoaderServiceTest.java
@@ -14,7 +14,6 @@
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
@@ -175,7 +174,7 @@ void testGetResourceFilePathFromJar() throws IOException, URISyntaxException {
// Instantiate the class under test and invoke the method.
ResourceLoaderService resourceLoaderService = new ResourceLoaderService(resourceLoader);
- Path path = Paths.get("path", "to", "resource.txt");
+ Path path = Path.of("path", "to", "resource.txt");
Path resourceFilePath = resourceLoaderService.getResourceFilePath(path);
// Verify the temporary file was created.
diff --git a/src/test/java/de/tum/cit/aet/artemis/core/service/UriServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/core/service/UriServiceTest.java
index 024ae81df398..8459e3dea2ac 100644
--- a/src/test/java/de/tum/cit/aet/artemis/core/service/UriServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/core/service/UriServiceTest.java
@@ -3,8 +3,8 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import java.io.File;
import java.net.URISyntaxException;
+import java.nio.file.Path;
import org.junit.jupiter.api.Test;
@@ -23,9 +23,10 @@ class UriServiceTest extends AbstractSpringIntegrationIndependentTest {
private final VcsRepositoryUri repositoryUri3 = new VcsRepositoryUri("https://username@artemistest2gitlab.ase.in.tum.de/FTCSCAGRADING1/ftcscagrading1-username");
- private final VcsRepositoryUri fileRepositoryUri1 = new VcsRepositoryUri(new File("C:/Users/Admin/AppData/Local/Temp/studentOriginRepo1644180397872264950"));
+ private final VcsRepositoryUri fileRepositoryUri1 = new VcsRepositoryUri(Path.of("C:/Users/Admin/AppData/Local/Temp/studentOriginRepo1644180397872264950").toFile());
- private final VcsRepositoryUri fileRepositoryUri2 = new VcsRepositoryUri(new File("/var/folders/vc/sk85td_s54v7w9tjq07b0_q80000gn/T/studentTeamOriginRepo420037178325056205"));
+ private final VcsRepositoryUri fileRepositoryUri2 = new VcsRepositoryUri(
+ Path.of("/var/folders/vc/sk85td_s54v7w9tjq07b0_q80000gn/T/studentTeamOriginRepo420037178325056205").toFile());
/**
* empty constructor for exception handling
diff --git a/src/test/java/de/tum/cit/aet/artemis/exam/ExamUserIntegrationTest.java b/src/test/java/de/tum/cit/aet/artemis/exam/ExamUserIntegrationTest.java
index 99587a381c68..e38d69446467 100644
--- a/src/test/java/de/tum/cit/aet/artemis/exam/ExamUserIntegrationTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/exam/ExamUserIntegrationTest.java
@@ -5,7 +5,9 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.File;
-import java.io.FileInputStream;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashSet;
@@ -337,8 +339,9 @@ private MockHttpServletRequestBuilder buildUploadExamUserImages(long courseId, l
}
private MockMultipartFile loadFile(String path, String fileName) throws Exception {
- File signingImage = new File(ResourceUtils.getFile(path), fileName);
- FileInputStream input = new FileInputStream(signingImage);
+ Path signingPath = ResourceUtils.getFile(path).toPath().resolve(fileName);
+ File signingImage = signingPath.toFile();
+ InputStream input = Files.newInputStream(signingPath);
return new MockMultipartFile("file", signingImage.getName(), "image/png", IOUtils.toByteArray(input));
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/fileupload/util/ZipFileTestUtilService.java b/src/test/java/de/tum/cit/aet/artemis/fileupload/util/ZipFileTestUtilService.java
index 446e00ff9f9a..b83d6ad48535 100644
--- a/src/test/java/de/tum/cit/aet/artemis/fileupload/util/ZipFileTestUtilService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/fileupload/util/ZipFileTestUtilService.java
@@ -4,6 +4,7 @@
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
@@ -27,13 +28,13 @@ public class ZipFileTestUtilService {
* @throws IOException if something goes wrong
*/
public Path extractZipFileRecursively(String zipFile) throws IOException {
- File file = new File(zipFile);
+ File file = Path.of(zipFile).toFile();
try (ZipFile zip = new ZipFile(file)) {
String newPath = zipFile.substring(0, zipFile.length() - 4);
- File parentFolder = new File(newPath);
- parentFolder.mkdir();
+ Path parentFolder = Path.of(newPath);
+ Files.createDirectories(parentFolder);
Enumeration extends ZipEntry> zipFileEntries = zip.entries();
// Process each entry
@@ -41,26 +42,26 @@ public Path extractZipFileRecursively(String zipFile) throws IOException {
// grab a zip file entry
ZipEntry entry = zipFileEntries.nextElement();
String currentEntry = entry.getName();
- File destFile = new File(parentFolder, currentEntry);
+ Path destFile = parentFolder.resolve(currentEntry);
- if (!destFile.getCanonicalPath().startsWith(parentFolder.getCanonicalPath())) {
+ if (!destFile.toAbsolutePath().toString().startsWith(parentFolder.toAbsolutePath().toString())) {
fail("Bad zip entry");
}
- File destinationParent = destFile.getParentFile();
+ Path destinationParent = destFile.getParent();
// create the parent directory structure if needed
- destinationParent.mkdirs();
+ Files.createDirectories(destinationParent);
if (!entry.isDirectory()) {
- FileUtils.copyInputStreamToFile(zip.getInputStream(entry), destFile);
+ FileUtils.copyInputStreamToFile(zip.getInputStream(entry), destFile.toFile());
}
if (currentEntry.endsWith(".zip")) {
// found a zip file, try to open
- extractZipFileRecursively(destFile.getAbsolutePath());
+ extractZipFileRecursively(destFile.toAbsolutePath().toString());
}
}
- return parentFolder.toPath();
+ return parentFolder;
}
}
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/plagiarism/PlagiarismDetectionServiceTest.java b/src/test/java/de/tum/cit/aet/artemis/plagiarism/PlagiarismDetectionServiceTest.java
index 560a74a893c7..f31556b1b440 100644
--- a/src/test/java/de/tum/cit/aet/artemis/plagiarism/PlagiarismDetectionServiceTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/plagiarism/PlagiarismDetectionServiceTest.java
@@ -8,8 +8,8 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.Optional;
import org.junit.jupiter.api.Test;
@@ -120,7 +120,7 @@ void shouldExecuteChecksWithJplagReportForProgrammingExercise() throws Programmi
var programmingExercise = new ProgrammingExercise();
programmingExercise.setId(1L);
programmingExercise.setPlagiarismDetectionConfig(config);
- var zipFile = new File("");
+ var zipFile = Path.of("").toFile();
when(programmingPlagiarismDetectionService.checkPlagiarismWithJPlagReport(1L, config.getSimilarityThreshold(), config.getMinimumScore(), config.getMinimumSize()))
.thenReturn(zipFile);
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseIntegrationTestService.java b/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseIntegrationTestService.java
index f628d543c17f..70b251f6f5b6 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseIntegrationTestService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseIntegrationTestService.java
@@ -425,13 +425,13 @@ void testExportSubmissionsByParticipationIds_addParticipantIdentifierToProjectNa
// Create the eclipse .project file which will be modified.
Path projectFilePath = Path.of(repository1.getLocalPath().toString(), ".project");
- File projectFile = new File(projectFilePath.toString());
+ File projectFile = Path.of(projectFilePath.toString()).toFile();
String projectFileContents = TestResourceUtils.loadFileFromResources("test-data/repository-export/sample.project");
FileUtils.writeStringToFile(projectFile, projectFileContents, StandardCharsets.UTF_8);
// Create the maven .pom file
Path pomPath = Path.of(repository1.getLocalPath().toString(), "pom.xml");
- File pomFile = new File(pomPath.toString());
+ File pomFile = Path.of(pomPath.toString()).toFile();
String pomContents = TestResourceUtils.loadFileFromResources("test-data/repository-export/pom.xml");
FileUtils.writeStringToFile(pomFile, pomContents, StandardCharsets.UTF_8);
@@ -466,14 +466,14 @@ void testExportSubmissionsByParticipationIds_addParticipantIdentifierToProjectNa
// Create the eclipse .project file which will be modified.
Path projectFilePath = Path.of(repository1.getLocalPath().toString(), ".project");
- File projectFile = new File(projectFilePath.toString());
+ File projectFile = Path.of(projectFilePath.toString()).toFile();
if (!projectFile.exists()) {
Files.createFile(projectFilePath);
}
// Create the maven .pom file
Path pomPath = Path.of(repository1.getLocalPath().toString(), "pom.xml");
- File pomFile = new File(pomPath.toString());
+ File pomFile = Path.of(pomPath.toString()).toFile();
if (!pomFile.exists()) {
Files.createFile(pomPath);
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseTemplateIntegrationTest.java b/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseTemplateIntegrationTest.java
index b4b2e2709e20..7e35608b93cd 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseTemplateIntegrationTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/ProgrammingExerciseTemplateIntegrationTest.java
@@ -124,7 +124,7 @@ private static void findAndSetJava17UnixSystems() throws Exception {
// Use which to find all java installations on Linux
var javaInstallations = runProcess(new ProcessBuilder("which", "-a", "java"));
for (String path : javaInstallations) {
- File binFolder = new File(path).getParentFile();
+ File binFolder = Path.of(path).toFile().getParentFile();
if (checkJavaVersion(binFolder, "./java", "-version")) {
return;
}
@@ -139,8 +139,8 @@ private static void findAndSetJava17UnixSystems() throws Exception {
private static void findAndSetJava17Mac() throws Exception {
var alternativeInstallations = runProcess(new ProcessBuilder("/usr/libexec/java_home", "-v", "17"));
for (String path : alternativeInstallations) {
- File binFolder = new File(path).getParentFile();
- binFolder = new File(binFolder, "Home/bin");
+ File binFolder = Path.of(path).toFile().getParentFile();
+ binFolder = binFolder.toPath().resolve("Home/bin").toFile();
if (checkJavaVersion(binFolder, "./java", "-version")) {
return;
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/StaticCodeAnalysisParserUnitTest.java b/src/test/java/de/tum/cit/aet/artemis/programming/StaticCodeAnalysisParserUnitTest.java
index 96c23a2172cd..70980ee2710c 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/StaticCodeAnalysisParserUnitTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/StaticCodeAnalysisParserUnitTest.java
@@ -7,7 +7,6 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
@@ -22,9 +21,9 @@
*/
class StaticCodeAnalysisParserUnitTest {
- private static final Path EXPECTED_FOLDER_PATH = Paths.get("src", "test", "resources", "test-data", "static-code-analysis", "expected");
+ private static final Path EXPECTED_FOLDER_PATH = Path.of("src", "test", "resources", "test-data", "static-code-analysis", "expected");
- private static final Path REPORTS_FOLDER_PATH = Paths.get("src", "test", "resources", "test-data", "static-code-analysis", "reports");
+ private static final Path REPORTS_FOLDER_PATH = Path.of("src", "test", "resources", "test-data", "static-code-analysis", "reports");
private final ObjectMapper mapper = new ObjectMapper();
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalCIIntegrationTest.java b/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalCIIntegrationTest.java
index c59be123369d..e05dff05b589 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalCIIntegrationTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalCIIntegrationTest.java
@@ -20,7 +20,6 @@
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
@@ -464,7 +463,7 @@ void testBuildLogs() throws IOException {
assertThat(buildLogs).isNotNull();
assertThat(buildLogs.getFile().exists()).isTrue();
- String content = new String(Files.readAllBytes(Paths.get(buildLogs.getFile().getAbsolutePath())));
+ String content = new String(Files.readAllBytes(Path.of(buildLogs.getFile().getAbsolutePath())));
// Assert that the content contains the expected log entry
assertThat(content).contains("Dummy log entry");
@@ -472,7 +471,7 @@ void testBuildLogs() throws IOException {
finally {
// Delete log file
if (buildLogs != null && buildLogs.getFile().exists()) {
- Files.deleteIfExists(Paths.get(buildLogs.getFile().getAbsolutePath()));
+ Files.deleteIfExists(Path.of(buildLogs.getFile().getAbsolutePath()));
}
}
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalVCLocalCITestService.java b/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalVCLocalCITestService.java
index cb5d100e2d9f..45ca5aee6868 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalVCLocalCITestService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/icl/LocalVCLocalCITestService.java
@@ -20,7 +20,6 @@
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
@@ -313,7 +312,7 @@ public LocalRepository createAndConfigureLocalRepository(String projectKey, Stri
private Path createRepositoryFolderInTempDirectory(String projectKey, String repositorySlug) throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
- Path projectFolder = Paths.get(tempDir, projectKey);
+ Path projectFolder = Path.of(tempDir, projectKey);
// Create the project folder if it does not exist.
if (!Files.exists(projectFolder)) {
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/icl/RepositoryUriTest.java b/src/test/java/de/tum/cit/aet/artemis/programming/icl/RepositoryUriTest.java
index d1c816be5c66..110f9d1254b2 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/icl/RepositoryUriTest.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/icl/RepositoryUriTest.java
@@ -11,7 +11,6 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
@@ -61,7 +60,7 @@ void testUrlRepositorySlugWithoutGitSuffix() {
@Test
void testLocalRepositoryPath() throws Exception {
- Path repositoryPath = Paths.get("/local/path/projectX/projectX-repo/.git");
+ Path repositoryPath = Path.of("/local/path/projectX/projectX-repo/.git");
URL localVCServerUrl = new URI("https://artemis.tum.de").toURL();
LocalVCRepositoryUri uri = new LocalVCRepositoryUri(repositoryPath, localVCServerUrl);
@@ -74,7 +73,7 @@ void testLocalRepositoryPath() throws Exception {
@Test
void testRemoteRepositoryPath() throws Exception {
- Path repositoryPath = Paths.get("/remote/path/projectY/projectY-repo");
+ Path repositoryPath = Path.of("/remote/path/projectY/projectY-repo");
URL localVCServerUrl = new URI("https://artemis.tum.de").toURL();
LocalVCRepositoryUri uri = new LocalVCRepositoryUri(repositoryPath, localVCServerUrl);
@@ -87,7 +86,7 @@ void testRemoteRepositoryPath() throws Exception {
@Test
void testInvalidRepositoryPath() {
- Path repositoryPath = Paths.get("/invalid/path");
+ Path repositoryPath = Path.of("/invalid/path");
URL localVCServerUrl;
try {
localVCServerUrl = new URI("https://artemis.tum.de").toURL();
@@ -166,7 +165,7 @@ void testConstructorWithInvalidUriString() {
@Test
void testConstructorWithFile() {
- File file = new File("/path/to/repo");
+ File file = Path.of("/path/to/repo").toFile();
VcsRepositoryUri uri = new VcsRepositoryUri(file);
assertThat(uri.getURI().toString()).isEqualTo(file.toURI().toString());
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/util/GitUtilService.java b/src/test/java/de/tum/cit/aet/artemis/programming/util/GitUtilService.java
index c68c5d5cf5d6..761db3283334 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/util/GitUtilService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/util/GitUtilService.java
@@ -3,7 +3,6 @@
import static org.assertj.core.api.Fail.fail;
import java.io.File;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
@@ -165,7 +164,7 @@ private void tryToDeleteDirectory(Path path) throws Exception {
public void deleteRepo(REPOS repo) {
try {
String repoPath = getCompleteRepoPathStringByType(repo);
- FileUtils.deleteDirectory(new File(repoPath));
+ FileUtils.deleteDirectory(Path.of(repoPath).toFile());
setRepositoryToNull(repo);
}
catch (IOException ignored) {
@@ -285,7 +284,7 @@ public String getCompleteRepoPathStringByType(REPOS repo) {
}
public VcsRepositoryUri getRepoUriByType(REPOS repo) {
- return new VcsRepositoryUri(new File(getCompleteRepoPathStringByType(repo)));
+ return new VcsRepositoryUri(Path.of(getCompleteRepoPathStringByType(repo)).toFile());
}
public static final class MockFileRepositoryUri extends VcsRepositoryUri {
@@ -305,7 +304,7 @@ public VcsRepositoryUri withUser(String username) {
public void writeEmptyJsonFileToPath(Path path) throws Exception {
var fileContent = "{}";
path.toFile().getParentFile().mkdirs();
- try (FileWriter writer = new FileWriter(path.toFile(), StandardCharsets.UTF_8)) {
+ try (var writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write(fileContent);
}
}
diff --git a/src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java b/src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java
index d2a64d1a0ddd..ff4a7efca458 100644
--- a/src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java
+++ b/src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseUtilService.java
@@ -12,7 +12,6 @@
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
@@ -873,7 +872,7 @@ public void createGitRepository() throws Exception {
// Mock Git service operations
doReturn(mockRepository).when(gitService).getOrCheckoutRepository(any(), any(), any(), anyBoolean(), anyString());
doNothing().when(gitService).resetToOriginHead(any());
- doReturn(Paths.get("repo.zip")).when(gitService).getRepositoryWithParticipation(any(), anyString(), anyBoolean(), eq(true));
- doReturn(Paths.get("repo")).when(gitService).getRepositoryWithParticipation(any(), anyString(), anyBoolean(), eq(false));
+ doReturn(Path.of("repo.zip")).when(gitService).getRepositoryWithParticipation(any(), anyString(), anyBoolean(), eq(true));
+ doReturn(Path.of("repo")).when(gitService).getRepositoryWithParticipation(any(), anyString(), anyBoolean(), eq(false));
}
}