You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2025/05/15 11:55:01 UTC
(camel) branch main updated: CAMEL-21996: Replace java.io.File with Java NIO Path API in camel-jbang (#18044)
This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new e732f61286f CAMEL-21996: Replace java.io.File with Java NIO Path API in camel-jbang (#18044)
e732f61286f is described below
commit e732f61286f69bd9aec5802cff8ececf51a78377
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Thu May 15 13:54:55 2025 +0200
CAMEL-21996: Replace java.io.File with Java NIO Path API in camel-jbang (#18044)
This commit replaces the usage of java.io.File with the Java NIO Path API in the camel-jbang module. This modernizes the code to use the more robust and flexible NIO API instead of the legacy java.io.File API.
---
.../camel/jbang/console/SourceDirDevConsole.java | 155 +++++----
.../apache/camel/jbang/console/VersionHelper.java | 19 +-
.../dsl/jbang/core/commands/CamelCommand.java | 30 +-
.../dsl/jbang/core/commands/CommandHelper.java | 36 +-
.../camel/dsl/jbang/core/commands/Debug.java | 32 +-
.../dsl/jbang/core/commands/DependencyList.java | 44 ++-
.../dsl/jbang/core/commands/DependencyUpdate.java | 30 +-
.../camel/dsl/jbang/core/commands/Export.java | 24 +-
.../dsl/jbang/core/commands/ExportBaseCommand.java | 382 ++++++++++++---------
.../dsl/jbang/core/commands/ExportCamelMain.java | 131 +++----
.../dsl/jbang/core/commands/ExportQuarkus.java | 83 ++---
.../dsl/jbang/core/commands/ExportSpringBoot.java | 70 ++--
.../apache/camel/dsl/jbang/core/commands/Init.java | 67 ++--
.../apache/camel/dsl/jbang/core/commands/Run.java | 308 ++++++++++-------
.../camel/dsl/jbang/core/commands/RunHelper.java | 52 +--
.../dsl/jbang/core/commands/SBOMGenerator.java | 17 +-
.../dsl/jbang/core/commands/TransformRoute.java | 17 +-
.../core/commands/action/ActionBaseCommand.java | 49 ++-
.../jbang/core/commands/action/CamelBeanDump.java | 23 +-
.../core/commands/action/CamelBrowseAction.java | 17 +-
.../jbang/core/commands/action/CamelGCAction.java | 8 +-
.../jbang/core/commands/action/CamelLogAction.java | 29 +-
.../core/commands/action/CamelReceiveAction.java | 37 +-
.../core/commands/action/CamelReloadAction.java | 8 +-
.../commands/action/CamelResetStatsAction.java | 8 +-
.../core/commands/action/CamelRouteAction.java | 8 +-
.../core/commands/action/CamelRouteDumpAction.java | 17 +-
.../core/commands/action/CamelSendAction.java | 35 +-
.../core/commands/action/CamelSourceAction.java | 31 +-
.../jbang/core/commands/action/CamelSourceTop.java | 18 +-
.../action/CamelStartupRecorderAction.java | 18 +-
.../core/commands/action/CamelStubAction.java | 18 +-
.../core/commands/action/CamelThreadDump.java | 18 +-
.../core/commands/action/CamelTraceAction.java | 36 +-
.../jbang/core/commands/action/LoggerAction.java | 8 +-
.../commands/action/RouteControllerAction.java | 18 +-
.../commands/action/TransformMessageAction.java | 48 ++-
.../dsl/jbang/core/commands/infra/InfraGet.java | 23 +-
.../dsl/jbang/core/commands/infra/InfraLog.java | 42 ++-
.../dsl/jbang/core/commands/infra/InfraPs.java | 21 +-
.../dsl/jbang/core/commands/infra/InfraRun.java | 16 +-
.../dsl/jbang/core/commands/infra/InfraStop.java | 26 +-
.../dsl/jbang/core/commands/process/ListKafka.java | 23 +-
.../core/commands/process/ProcessBaseCommand.java | 13 +-
.../jbang/core/commands/process/StopProcess.java | 11 +-
.../jbang/core/commands/update/CamelUpdate.java | 8 +-
.../dsl/jbang/core/common/CommandLineHelper.java | 78 ++---
.../camel/dsl/jbang/core/common/PathUtils.java | 153 +++++++++
.../camel/dsl/jbang/core/common/PluginHelper.java | 21 +-
.../camel/dsl/jbang/core/common/RuntimeUtil.java | 23 +-
.../camel/dsl/jbang/core/common/SourceHelper.java | 15 +-
.../camel/dsl/jbang/core/common/VersionHelper.java | 16 +-
.../commands/ExportMainApplicationProperties.java | 2 +-
.../camel/dsl/jbang/core/commands/ExportTest.java | 5 +-
.../camel/dsl/jbang/core/commands/InitTest.java | 49 ++-
.../dsl/jbang/core/commands/TransformTest.java | 28 +-
.../core/commands/kubernetes/KubernetesExport.java | 28 +-
.../core/commands/kubernetes/KubernetesHelper.java | 33 ++
.../core/commands/kubernetes/KubernetesRun.java | 21 +-
.../commands/kubernetes/traits/RouteTrait.java | 13 +-
60 files changed, 1518 insertions(+), 1099 deletions(-)
diff --git a/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/SourceDirDevConsole.java b/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/SourceDirDevConsole.java
index dd9c0f783bb..d91a2acfc36 100644
--- a/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/SourceDirDevConsole.java
+++ b/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/SourceDirDevConsole.java
@@ -16,12 +16,15 @@
*/
package org.apache.camel.jbang.console;
-import java.io.File;
-import java.io.FileReader;
import java.io.LineNumberReader;
-import java.util.Arrays;
+import java.io.Reader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.camel.Exchange;
import org.apache.camel.impl.console.ConsoleHelper;
@@ -29,7 +32,6 @@ import org.apache.camel.spi.annotations.DevConsole;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.support.RouteOnDemandReloadStrategy;
import org.apache.camel.support.console.AbstractDevConsole;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonArray;
@@ -60,50 +62,54 @@ public class SourceDirDevConsole extends AbstractDevConsole {
if (reload != null) {
sb.append(String.format("Directory: %s%n", reload.getFolder()));
// list files in this directory
- File dir = new File(reload.getFolder());
- if (dir.exists() && dir.isDirectory()) {
- File[] files = dir.listFiles();
- if (files != null) {
- sb.append("Files:\n");
- // sort files by name (ignore case)
- Arrays.sort(files, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
- for (File f : files) {
- boolean skip = f.getName().startsWith(".") || f.isHidden();
- if (skip) {
- continue;
- }
- boolean match = subPath == null || f.getName().startsWith(subPath) || f.getName().endsWith(subPath)
- || PatternHelper.matchPattern(f.getName(), subPath);
- if (match) {
- long size = f.length();
- long ts = f.lastModified();
- String age = ts > 0 ? TimeUtils.printSince(ts) : "n/a";
- sb.append(String.format(" %s (size: %d age: %s)%n", f.getName(), size, age));
- if ("true".equals(source)) {
- StringBuilder code = new StringBuilder();
- try {
- LineNumberReader reader = new LineNumberReader(new FileReader(f));
- int i = 0;
- String t;
- do {
- t = reader.readLine();
- if (t != null) {
- i++;
- code.append(String.format("\n #%s %s", i, t));
- }
- } while (t != null);
- IOHelper.close(reader);
- } catch (Exception e) {
- // ignore
- }
- if (!code.isEmpty()) {
- sb.append(" ").append("-".repeat(40));
- sb.append(code);
- sb.append("\n\n");
+ Path dir = Paths.get(reload.getFolder());
+ if (Files.exists(dir) && Files.isDirectory(dir)) {
+ try {
+ List<Path> files = Files.list(dir).collect(Collectors.toList());
+ if (!files.isEmpty()) {
+ sb.append("Files:\n");
+ // sort files by name (ignore case)
+ files.sort((o1, o2) -> o1.getFileName().toString().compareToIgnoreCase(o2.getFileName().toString()));
+ for (Path f : files) {
+ String fileName = f.getFileName().toString();
+ boolean skip = fileName.startsWith(".") || Files.isHidden(f);
+ if (skip) {
+ continue;
+ }
+ boolean match = subPath == null || fileName.startsWith(subPath) || fileName.endsWith(subPath)
+ || PatternHelper.matchPattern(fileName, subPath);
+ if (match) {
+ long size = Files.size(f);
+ long ts = Files.getLastModifiedTime(f).toMillis();
+ String age = ts > 0 ? TimeUtils.printSince(ts) : "n/a";
+ sb.append(String.format(" %s (size: %d age: %s)%n", fileName, size, age));
+ if ("true".equals(source)) {
+ StringBuilder code = new StringBuilder();
+ try (Reader fileReader = Files.newBufferedReader(f, StandardCharsets.UTF_8);
+ LineNumberReader reader = new LineNumberReader(fileReader)) {
+ int i = 0;
+ String t;
+ do {
+ t = reader.readLine();
+ if (t != null) {
+ i++;
+ code.append(String.format("\n #%s %s", i, t));
+ }
+ } while (t != null);
+ } catch (Exception e) {
+ // ignore
+ }
+ if (!code.isEmpty()) {
+ sb.append(" ").append("-".repeat(40));
+ sb.append(code);
+ sb.append("\n\n");
+ }
}
}
}
}
+ } catch (Exception e) {
+ // ignore
}
}
}
@@ -123,39 +129,44 @@ public class SourceDirDevConsole extends AbstractDevConsole {
if (reload != null) {
root.put("dir", reload.getFolder());
// list files in this directory
- File dir = new File(reload.getFolder());
- if (dir.exists() && dir.isDirectory()) {
- File[] files = dir.listFiles();
- if (files != null) {
- // sort files by name (ignore case)
- Arrays.sort(files, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
- JsonArray arr = new JsonArray();
- root.put("files", arr);
- for (File f : files) {
- boolean skip = f.getName().startsWith(".") || f.isHidden();
- if (skip) {
- continue;
- }
- boolean match = subPath == null || f.getName().startsWith(subPath) || f.getName().endsWith(subPath)
- || PatternHelper.matchPattern(f.getName(), subPath);
- if (match) {
- JsonObject jo = new JsonObject();
- jo.put("name", f.getName());
- jo.put("size", f.length());
- jo.put("lastModified", f.lastModified());
- if ("true".equals(source)) {
- try {
- List<JsonObject> code = ConsoleHelper.loadSourceAsJson(new FileReader(f), null);
- if (code != null) {
- jo.put("code", code);
+ Path dir = Paths.get(reload.getFolder());
+ if (Files.exists(dir) && Files.isDirectory(dir)) {
+ try {
+ List<Path> files = Files.list(dir).collect(Collectors.toList());
+ if (!files.isEmpty()) {
+ // sort files by name (ignore case)
+ files.sort((o1, o2) -> o1.getFileName().toString().compareToIgnoreCase(o2.getFileName().toString()));
+ JsonArray arr = new JsonArray();
+ root.put("files", arr);
+ for (Path f : files) {
+ String fileName = f.getFileName().toString();
+ boolean skip = fileName.startsWith(".") || Files.isHidden(f);
+ if (skip) {
+ continue;
+ }
+ boolean match = subPath == null || fileName.startsWith(subPath) || fileName.endsWith(subPath)
+ || PatternHelper.matchPattern(fileName, subPath);
+ if (match) {
+ JsonObject jo = new JsonObject();
+ jo.put("name", fileName);
+ jo.put("size", Files.size(f));
+ jo.put("lastModified", Files.getLastModifiedTime(f).toMillis());
+ if ("true".equals(source)) {
+ try (Reader fileReader = Files.newBufferedReader(f, StandardCharsets.UTF_8)) {
+ List<JsonObject> code = ConsoleHelper.loadSourceAsJson(fileReader, null);
+ if (code != null) {
+ jo.put("code", code);
+ }
+ } catch (Exception e) {
+ // ignore
}
- } catch (Exception e) {
- // ignore
}
+ arr.add(jo);
}
- arr.add(jo);
}
}
+ } catch (Exception e) {
+ // ignore
}
}
}
diff --git a/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/VersionHelper.java b/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/VersionHelper.java
index ba1351cf128..1b22ca35851 100644
--- a/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/VersionHelper.java
+++ b/dsl/camel-jbang/camel-jbang-console/src/main/java/org/apache/camel/jbang/console/VersionHelper.java
@@ -16,8 +16,10 @@
*/
package org.apache.camel.jbang.console;
-import java.io.File;
-import java.io.FileInputStream;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import org.apache.camel.util.IOHelper;
@@ -28,13 +30,12 @@ public final class VersionHelper {
public static String getJBangVersion() {
try {
- File file = new File(System.getProperty("user.home"), ".jbang/cache/version.txt");
- if (file.exists() && file.isFile()) {
- FileInputStream fis = new FileInputStream(file);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
- text = text.trim();
- return text;
+ Path path = Paths.get(System.getProperty("user.home"), ".jbang/cache/version.txt");
+ if (Files.exists(path) && Files.isRegularFile(path)) {
+ try (InputStream is = Files.newInputStream(path)) {
+ String text = IOHelper.loadText(is);
+ return text.trim();
+ }
}
} catch (Exception e) {
// ignore
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
index 188c9abd295..03b2aa69ad6 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
@@ -16,7 +16,7 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -93,32 +93,32 @@ public abstract class CamelCommand implements Callable<Integer> {
public abstract Integer doCall() throws Exception;
- public File getStatusFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-status.json");
+ public Path getStatusFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-status.json");
}
- public File getActionFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-action.json");
+ public Path getActionFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-action.json");
}
- public File getOutputFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-output.json");
+ public Path getOutputFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-output.json");
}
- public File getTraceFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-trace.json");
+ public Path getTraceFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-trace.json");
}
- public File getReceiveFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-receive.json");
+ public Path getReceiveFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-receive.json");
}
- public File getDebugFile(String pid) {
- return new File(CommandLineHelper.getCamelDir(), pid + "-debug.json");
+ public Path getDebugFile(String pid) {
+ return CommandLineHelper.getCamelDir().resolve(pid + "-debug.json");
}
- public File getRunBackgroundLogFile(String uuid) {
- return new File(CommandLineHelper.getCamelDir(), uuid + "-run.log");
+ public Path getRunBackgroundLogFile(String uuid) {
+ return CommandLineHelper.getCamelDir().resolve(uuid + "-run.log");
}
protected Printer printer() {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CommandHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CommandHelper.java
index c14cf3bfc24..3755ec2df9e 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CommandHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CommandHelper.java
@@ -16,10 +16,14 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.Printer;
-import org.apache.camel.util.FileUtil;
public final class CommandHelper {
@@ -41,16 +45,26 @@ public final class CommandHelper {
}
public static void cleanExportDir(String dir, boolean keepHidden) {
- File target = new File(dir);
- File[] files = target.listFiles();
- if (files != null) {
- for (File f : files) {
- if (f.isDirectory() && (!keepHidden || !f.isHidden())) {
- FileUtil.removeDir(f);
- } else if (f.isFile() && (!keepHidden || !f.isHidden())) {
- FileUtil.deleteFile(f);
+ Path targetPath = Paths.get(dir);
+ if (!Files.exists(targetPath)) {
+ return;
+ }
+
+ try (Stream<Path> paths = Files.list(targetPath)) {
+ paths.forEach(path -> {
+ try {
+ boolean isHidden = Files.isHidden(path);
+ if (Files.isDirectory(path) && (!keepHidden || !isHidden)) {
+ PathUtils.deleteDirectory(path);
+ } else if (Files.isRegularFile(path) && (!keepHidden || !isHidden)) {
+ Files.deleteIfExists(path);
+ }
+ } catch (IOException e) {
+ // Ignore
}
- }
+ });
+ } catch (IOException e) {
+ // Ignore
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Debug.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Debug.java
index 5f9edb0b773..035676fbb0c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Debug.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Debug.java
@@ -18,12 +18,12 @@ package org.apache.camel.dsl.jbang.core.commands;
import java.io.BufferedReader;
import java.io.Console;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -34,6 +34,7 @@ import java.util.concurrent.atomic.AtomicLong;
import org.apache.camel.dsl.jbang.core.commands.action.MessageTableHelper;
import org.apache.camel.dsl.jbang.core.common.CamelCommandHelper;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.VersionHelper;
import org.apache.camel.main.KameletMain;
import org.apache.camel.util.FileUtil;
@@ -318,8 +319,8 @@ public class Debug extends Run {
private void sendDebugCommand(long pid, String command, String breakpoint) {
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "debug");
@@ -329,9 +330,10 @@ public class Debug extends Run {
if (breakpoint != null) {
root.put("breakpoint", breakpoint);
}
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ String text = root.toJson();
+ Files.writeString(f, text);
} catch (Exception e) {
// ignore
}
@@ -479,8 +481,8 @@ public class Debug extends Run {
if (b != null) {
b = CamelCommandHelper.valueAsStringPretty(b, false);
try {
- File f = new File(output);
- IOHelper.writeText(b, f);
+ Path f = Path.of(output);
+ Files.writeString(f, b);
} catch (IOException e) {
// ignore
}
@@ -735,10 +737,10 @@ public class Debug extends Run {
private void handleHangup() {
if (spawnPid > 0) {
- File pidFile = new File(CommandLineHelper.getCamelDir(), Long.toString(spawnPid));
- if (pidFile.exists()) {
+ Path pidPath = CommandLineHelper.getCamelDir().resolve(Long.toString(spawnPid));
+ if (Files.exists(pidPath)) {
printer().println("Shutting down Camel integration (PID: " + spawnPid + ")");
- FileUtil.deleteFile(pidFile);
+ PathUtils.deleteFile(pidPath);
}
}
}
@@ -751,11 +753,9 @@ public class Debug extends Run {
JsonObject loadDebug(long pid) {
try {
- File f = getDebugFile(Long.toString(pid));
- if (f != null && f.exists()) {
- FileInputStream fis = new FileInputStream(f);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ Path p = getDebugFile(Long.toString(pid));
+ if (p != null && Files.exists(p)) {
+ String text = Files.readString(p);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (Exception e) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyList.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyList.java
index 88ea5b7efe0..bef37e35fa7 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyList.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyList.java
@@ -16,7 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
+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.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -30,11 +34,9 @@ import org.w3c.dom.NodeList;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.apache.camel.dsl.jbang.core.common.RuntimeType;
-import org.apache.camel.dsl.jbang.core.common.RuntimeUtil;
import org.apache.camel.dsl.jbang.core.common.XmlHelper;
import org.apache.camel.tooling.maven.MavenGav;
import org.apache.camel.util.CamelCaseOrderedProperties;
-import org.apache.camel.util.FileUtil;
import picocli.CommandLine;
@CommandLine.Command(name = "list",
@@ -66,9 +68,9 @@ public class DependencyList extends Export {
// automatic detect maven/gradle based projects and use that
if (files.isEmpty()) {
- if (new File("pom.xml").exists()) {
+ if (Files.exists(Paths.get("pom.xml"))) {
files.add("pom.xml");
- } else if (new File("build.gradle").exists()) {
+ } else if (Files.exists(Paths.get("build.gradle"))) {
files.add("build.gradle");
}
}
@@ -76,11 +78,11 @@ public class DependencyList extends Export {
Integer answer = doExport();
if (answer == 0) {
// read pom.xml
- File pom = new File(EXPORT_DIR, "pom.xml");
- if (pom.exists()) {
+ Path pom = Paths.get(EXPORT_DIR).resolve("pom.xml");
+ if (Files.exists(pom)) {
DocumentBuilderFactory dbf = XmlHelper.createDocumentBuilderFactory();
DocumentBuilder db = dbf.newDocumentBuilder();
- Document dom = db.parse(pom);
+ Document dom = db.parse(Files.newInputStream(pom));
NodeList nl = dom.getElementsByTagName("dependency");
List<MavenGav> gavs = new ArrayList<>();
String camelVersion = null;
@@ -172,8 +174,20 @@ public class DependencyList extends Export {
}
}
// cleanup dir after complete
- File buildDir = new File(EXPORT_DIR);
- FileUtil.removeDir(buildDir);
+ Path buildDir = Paths.get(EXPORT_DIR);
+ try {
+ Files.walk(buildDir)
+ .sorted(java.util.Comparator.reverseOrder())
+ .forEach(p -> {
+ try {
+ Files.deleteIfExists(p);
+ } catch (IOException e) {
+ // ignore
+ }
+ });
+ } catch (IOException e) {
+ // ignore
+ }
}
return answer;
}
@@ -201,10 +215,14 @@ public class DependencyList extends Export {
protected Integer doExport() throws Exception {
// read runtime and gav from properties if not configured
- File profile = new File("application.properties");
- if (profile.exists()) {
+ Path profile = Paths.get("application.properties");
+ if (Files.exists(profile)) {
Properties prop = new CamelCaseOrderedProperties();
- RuntimeUtil.loadProperties(prop, profile);
+ try (InputStream is = Files.newInputStream(profile)) {
+ prop.load(is);
+ } catch (IOException e) {
+ // ignore
+ }
if (this.runtime == null && prop.containsKey("camel.jbang.runtime")) {
this.runtime = RuntimeType.fromValue(prop.getProperty("camel.jbang.runtime"));
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyUpdate.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyUpdate.java
index 08ee70f79dd..6dc09757745 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyUpdate.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DependencyUpdate.java
@@ -16,9 +16,9 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileInputStream;
import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -44,7 +44,7 @@ public class DependencyUpdate extends DependencyList {
@CommandLine.Parameters(description = "Maven pom.xml or Java source files (JBang Style with //DEPS) to have dependencies updated",
arity = "1")
- public File file;
+ public Path file;
@CommandLine.Option(names = { "--clean" },
description = "Regenerate list of dependencies (do not keep existing dependencies). Not supported for pom.xml")
@@ -60,12 +60,12 @@ public class DependencyUpdate extends DependencyList {
@Override
public Integer doCall() throws Exception {
// source file must exist
- if (!file.exists()) {
+ if (!Files.exists(file)) {
printer().printErr("Source file does not exist: " + file);
return -1;
}
- boolean maven = "pom.xml".equals(file.getName());
+ boolean maven = "pom.xml".equals(file.getFileName().toString());
if (clean && !maven) {
// remove DEPS in source file first
@@ -78,7 +78,7 @@ public class DependencyUpdate extends DependencyList {
@Override
protected void outputGav(MavenGav gav, int index, int total) {
try {
- boolean maven = "pom.xml".equals(file.getName());
+ boolean maven = "pom.xml".equals(file.getFileName().toString());
if (maven) {
outputGavMaven(gav, index, total);
} else {
@@ -118,7 +118,7 @@ public class DependencyUpdate extends DependencyList {
private void updateJBangSource() {
try {
- List<String> lines = Files.readAllLines(file.toPath());
+ List<String> lines = Files.readAllLines(file);
List<String> answer = new ArrayList<>();
// find position of where the old DEPS was
@@ -150,7 +150,7 @@ public class DependencyUpdate extends DependencyList {
}
String text = String.join(System.lineSeparator(), answer);
- IOHelper.writeText(text, file);
+ Files.writeString(file, text);
} catch (Exception e) {
printer().printErr("Error updating source file: " + file + " due to: " + e.getMessage());
}
@@ -162,10 +162,10 @@ public class DependencyUpdate extends DependencyList {
Node camelClone = null;
int targetLineNumber = -1;
- File pom = new File(file.getName());
- if (pom.exists()) {
+ Path pom = Paths.get(file.getFileName().toString());
+ if (Files.exists(pom)) {
// use line number parser as we want to find where to add new Camel JARs after the existing Camel JARs
- Document dom = XmlLineNumberParser.parseXml(new FileInputStream(pom));
+ Document dom = XmlLineNumberParser.parseXml(Files.newInputStream(pom));
String camelVersion = null;
NodeList nl = dom.getElementsByTagName("dependency");
for (int i = 0; i < nl.getLength(); i++) {
@@ -253,11 +253,11 @@ public class DependencyUpdate extends DependencyList {
if (changes > 0) {
// respect indent from existing GAVs
- String line = IOHelper.loadTextLine(new FileInputStream(file), targetLineNumber);
+ String line = IOHelper.loadTextLine(Files.newInputStream(file), targetLineNumber);
line = StringHelper.before(line, "<");
int indent = StringHelper.countChar(line, ' ');
String pad = Strings.repeat(" ", indent);
- line = IOHelper.loadTextLine(new FileInputStream(file), targetLineNumber - 1);
+ line = IOHelper.loadTextLine(Files.newInputStream(file), targetLineNumber - 1);
line = StringHelper.before(line, "<");
int indent2 = StringHelper.countChar(line, ' ');
String pad2 = Strings.repeat(" ", indent2);
@@ -275,7 +275,7 @@ public class DependencyUpdate extends DependencyList {
}
StringJoiner out = new StringJoiner("\n");
- String[] lines = IOHelper.loadText(new FileInputStream(file)).split("\n");
+ String[] lines = IOHelper.loadText(Files.newInputStream(file)).split("\n");
for (int i = 0; i < lines.length; i++) {
String txt = lines[i];
out.add(txt);
@@ -288,7 +288,7 @@ public class DependencyUpdate extends DependencyList {
} else {
outPrinter().println("Updating pom.xml with 1 dependency added");
}
- IOHelper.writeText(out.toString(), file);
+ Files.writeString(file, out.toString());
} else {
outPrinter().println("No updates to pom.xml");
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Export.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Export.java
index 3c80237fe69..597c6f3b514 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Export.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Export.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Comparator;
@@ -60,10 +60,10 @@ public class Export extends ExportBaseCommand {
protected Integer doExport() throws Exception {
// application.properties
- doLoadAndInitProfileProperties(new File("application.properties"));
+ doLoadAndInitProfileProperties(Paths.get("application.properties"));
if (profile != null) {
// override from profile specific configuration
- doLoadAndInitProfileProperties(new File("application-" + profile + ".properties"));
+ doLoadAndInitProfileProperties(Paths.get("application-" + profile + ".properties"));
}
if (runtime == null) {
@@ -116,17 +116,17 @@ public class Export extends ExportBaseCommand {
if (fn.endsWith("/*")) {
fn = fn.substring(0, fn.length() - 2);
}
- if (!Paths.get(fn).toFile().exists()) {
+ if (!Files.exists(Paths.get(fn))) {
throw new FileNotFoundException("Path does not exist: " + fn);
}
}
}
}
- private void doLoadAndInitProfileProperties(File file) throws Exception {
- if (file.exists()) {
+ private void doLoadAndInitProfileProperties(Path path) throws Exception {
+ if (Files.exists(path)) {
Properties props = new CamelCaseOrderedProperties();
- RuntimeUtil.loadProperties(props, file);
+ RuntimeUtil.loadProperties(props, path);
// read runtime and gav from profile if not configured
String rt = props.getProperty("camel.jbang.runtime");
if (rt != null) {
@@ -312,8 +312,8 @@ public class Export extends ExportBaseCommand {
// Copy the dockerfile into the same Maven project root directory.
protected void copyDockerFiles(String buildDir) throws Exception {
- File docker = new File(buildDir, "src/main/docker");
- docker.mkdirs();
+ Path docker = Path.of(buildDir).resolve("src/main/docker");
+ Files.createDirectories(docker);
String[] ids = gav.split(":");
InputStream is = ExportCamelMain.class.getClassLoader().getResourceAsStream("templates/Dockerfile.tmpl");
String context = IOHelper.loadText(is);
@@ -321,7 +321,7 @@ public class Export extends ExportBaseCommand {
String appJar = ids[1] + "-" + ids[2] + ".jar";
context = context.replaceAll("\\{\\{ \\.AppJar }}", appJar);
- IOHelper.writeText(context, new FileOutputStream(new File(docker, "Dockerfile"), false));
+ Files.writeString(docker.resolve("Dockerfile"), context);
}
// Copy the readme.md into the same Maven project root directory.
@@ -334,6 +334,6 @@ public class Export extends ExportBaseCommand {
context = context.replaceAll("\\{\\{ \\.ArtifactId }}", ids[1]);
context = context.replaceAll("\\{\\{ \\.Version }}", ids[2]);
context = context.replaceAll("\\{\\{ \\.AppRuntimeJar }}", appJar);
- IOHelper.writeText(context, new FileOutputStream(new File(buildDir, "readme.md"), false));
+ Files.writeString(Path.of(buildDir).resolve("readme.md"), context);
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportBaseCommand.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportBaseCommand.java
index 7e7d3c3c2ab..b3c268420f6 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportBaseCommand.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportBaseCommand.java
@@ -16,15 +16,15 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -378,7 +378,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
return context;
}
- protected Set<String> resolveDependencies(File settings, File profile) throws Exception {
+ protected Set<String> resolveDependencies(Path settings, Path profile) throws Exception {
Set<String> answer = new TreeSet<>((o1, o2) -> {
// favour org.apache.camel first
boolean c1 = o1.contains("org.apache.camel:");
@@ -516,7 +516,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
// include custom dependencies defined in profile
- if (profile != null && profile.exists()) {
+ if (profile != null && Files.exists(profile)) {
Properties prop = new CamelCaseOrderedProperties();
RuntimeUtil.loadProperties(prop, profile);
for (String d : RuntimeUtil.getDependenciesAsArray(prop)) {
@@ -555,8 +555,8 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
protected void copySourceFiles(
- File settings, File profile, File srcJavaDirRoot, File srcJavaDir, File srcResourcesDir, File srcCamelResourcesDir,
- File srcKameletsResourcesDir, String packageName)
+ Path settings, Path profile, Path srcJavaDirRoot, Path srcJavaDir, Path srcResourcesDir, Path srcCamelResourcesDir,
+ Path srcKameletsResourcesDir, String packageName)
throws Exception {
// read the settings file and find the files to copy
@@ -587,7 +587,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
if (scheme != null) {
f = f.substring(scheme.length() + 1);
}
- boolean skip = profile.getName().equals(f); // skip copying profile
+ boolean skip = profile.getFileName().toString().equals(f); // skip copying profile
if (skip) {
continue;
}
@@ -607,7 +607,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
boolean script = "camel.jbang.scriptFiles".equals(k);
boolean tls = "camel.jbang.tlsFiles".equals(k);
boolean web = ext != null && List.of("css", "html", "ico", "jpeg", "jpg", "js", "png").contains(ext);
- File targetDir;
+ Path targetDir;
if (java) {
targetDir = srcJavaDir;
} else if (camel) {
@@ -615,15 +615,15 @@ public abstract class ExportBaseCommand extends CamelCommand {
} else if (kamelet) {
targetDir = srcKameletsResourcesDir;
} else if (script) {
- targetDir = new File(srcJavaDirRoot.getParentFile(), "scripts");
+ targetDir = srcJavaDirRoot.getParent().resolve("scripts");
} else if (tls) {
- targetDir = new File(srcJavaDirRoot.getParentFile(), "tls");
+ targetDir = srcJavaDirRoot.getParent().resolve("tls");
} else if (web) {
- targetDir = new File(srcResourcesDir, "META-INF/resources");
+ targetDir = srcResourcesDir.resolve("META-INF/resources");
} else {
targetDir = srcResourcesDir;
}
- targetDir.mkdirs();
+ Files.createDirectories(targetDir);
Path source;
if ("kamelet".equals(k) && localKameletDir != null) {
@@ -632,45 +632,44 @@ public abstract class ExportBaseCommand extends CamelCommand {
} else {
source = Paths.get(f);
}
- File out;
- File srcFile = source.toFile();
- if (srcFile.isDirectory()) {
+ Path out;
+ if (Files.isDirectory(source)) {
out = targetDir;
} else {
- out = new File(targetDir, srcFile.getName());
+ out = targetDir.resolve(source.getFileName());
}
if (!java) {
if (kamelet) {
- safeCopy(srcFile, out, true);
+ safeCopy(source, out, true);
} else if (jkube) {
// file should be renamed and moved into src/main/jkube
f = f.replace(".jkube.yaml", ".yaml");
f = f.replace(".jkube.yml", ".yml");
- out = new File(srcCamelResourcesDir.getParentFile().getParentFile(), "jkube/" + f);
- out.getParentFile().mkdirs();
- safeCopy(srcFile, out, true);
+ out = srcCamelResourcesDir.getParent().getParent().resolve("jkube/" + f);
+ Files.createDirectories(out.getParent());
+ safeCopy(source, out, true);
} else {
- out.getParentFile().mkdirs();
+ Files.createDirectories(out.getParent());
safeCopy(scheme, source, out, true);
}
} else {
// need to append package name in java source file
List<String> lines = Files.readAllLines(source);
Optional<String> hasPackage = lines.stream().filter(l -> l.trim().startsWith("package ")).findFirst();
- FileOutputStream fos;
+ OutputStream fos;
if (hasPackage.isPresent()) {
String pn = determinePackageName(hasPackage.get());
if (pn != null) {
- File dir = new File(srcJavaDirRoot, pn.replace('.', File.separatorChar));
- dir.mkdirs();
- out = new File(dir, srcFile.getName());
+ Path dir = srcJavaDirRoot.resolve(pn.replace('.', '/'));
+ Files.createDirectories(dir);
+ out = dir.resolve(source.getFileName());
} else {
throw new IOException("Cannot determine package name from source: " + source);
}
} else {
if (javaLiveReload) {
- out = new File(srcJavaDirRoot, srcFile.getName());
+ out = srcJavaDirRoot.resolve(source.getFileName());
} else {
if (packageName != null && !"false".equalsIgnoreCase(packageName)) {
lines.add(0, "");
@@ -679,9 +678,9 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
}
if (javaLiveReload) {
- safeCopy(srcFile, out, true);
+ safeCopy(source, out, true);
} else {
- fos = new FileOutputStream(out);
+ fos = Files.newOutputStream(out);
for (String line : lines) {
adjustJavaSourceFileLine(line, fos);
fos.write(line.getBytes(StandardCharsets.UTF_8));
@@ -695,7 +694,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
}
- protected void adjustJavaSourceFileLine(String line, FileOutputStream fos) throws Exception {
+ protected void adjustJavaSourceFileLine(String line, OutputStream fos) throws Exception {
// noop
}
@@ -721,14 +720,14 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
protected void copySettingsAndProfile(
- File settings, File profile, File targetDir,
+ Path settings, Path profile, Path targetDir,
Function<Properties, Object> customize)
throws Exception {
Properties settingsProps = new CamelCaseOrderedProperties();
RuntimeUtil.loadProperties(settingsProps, settings);
Properties profileProps = new CamelCaseOrderedProperties();
- if (profile.exists()) {
+ if (Files.exists(profile)) {
RuntimeUtil.loadProperties(profileProps, profile);
}
profileProps.putAll(settingsProps);
@@ -752,44 +751,45 @@ public abstract class ExportBaseCommand extends CamelCommand {
Properties userProps = new CamelCaseOrderedProperties();
prepareUserProperties(userProps);
- try (var fos = new FileOutputStream(new File(targetDir, "application.properties"), false)) {
- for (Map.Entry<Object, Object> entry : profileProps.entrySet()) {
- String k = entry.getKey().toString();
- String v = entry.getValue().toString();
+ Path appPropsPath = targetDir.resolve("application.properties");
+ StringBuilder content = new StringBuilder();
- boolean skip = k.startsWith("camel.jbang.") || k.startsWith("jkube.");
- if (skip) {
- continue;
- }
+ for (Map.Entry<Object, Object> entry : profileProps.entrySet()) {
+ String k = entry.getKey().toString();
+ String v = entry.getValue().toString();
- // files are now loaded in classpath
- v = v.replaceAll("file:", "classpath:");
- if ("camel.main.routesIncludePattern".equals(k)) {
- // camel.main.routesIncludePattern should remove all .java as we use move them to regular src/main/java
- // camel.main.routesIncludePattern should remove all file: classpath: as we copy
- // them to src/main/resources/camel where camel autoload from
- v = Arrays.stream(v.split(","))
- .filter(n -> !n.endsWith(".java") && !n.startsWith("file:") && !n.startsWith("classpath:"))
- .collect(Collectors.joining(","));
- }
- if (!v.isBlank()) {
- String line = applicationPropertyLine(k, v);
- if (line != null && !line.isBlank()) {
- fos.write(line.getBytes(StandardCharsets.UTF_8));
- fos.write("\n".getBytes(StandardCharsets.UTF_8));
- }
- }
+ boolean skip = k.startsWith("camel.jbang.") || k.startsWith("jkube.");
+ if (skip) {
+ continue;
}
- for (Map.Entry<Object, Object> entryUserProp : userProps.entrySet()) {
- String uK = entryUserProp.getKey().toString();
- String uV = entryUserProp.getValue().toString();
- String line = applicationPropertyLine(uK, uV);
+
+ // files are now loaded in classpath
+ v = v.replaceAll("file:", "classpath:");
+ if ("camel.main.routesIncludePattern".equals(k)) {
+ // camel.main.routesIncludePattern should remove all .java as we use move them to regular src/main/java
+ // camel.main.routesIncludePattern should remove all file: classpath: as we copy
+ // them to src/main/resources/camel where camel autoload from
+ v = Arrays.stream(v.split(","))
+ .filter(n -> !n.endsWith(".java") && !n.startsWith("file:") && !n.startsWith("classpath:"))
+ .collect(Collectors.joining(","));
+ }
+ if (!v.isBlank()) {
+ String line = applicationPropertyLine(k, v);
if (line != null && !line.isBlank()) {
- fos.write(line.getBytes(StandardCharsets.UTF_8));
- fos.write("\n".getBytes(StandardCharsets.UTF_8));
+ content.append(line).append("\n");
}
}
}
+ for (Map.Entry<Object, Object> entryUserProp : userProps.entrySet()) {
+ String uK = entryUserProp.getKey().toString();
+ String uV = entryUserProp.getValue().toString();
+ String line = applicationPropertyLine(uK, uV);
+ if (line != null && !line.isBlank()) {
+ content.append(line).append("\n");
+ }
+ }
+
+ Files.writeString(appPropsPath, content.toString(), StandardCharsets.UTF_8);
}
protected void prepareApplicationProperties(Properties properties) {
@@ -830,42 +830,60 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
protected void copyMavenWrapper() throws Exception {
- File wrapper = new File(BUILD_DIR, ".mvn/wrapper");
- wrapper.mkdirs();
+ Path wrapperPath = Paths.get(BUILD_DIR, ".mvn/wrapper");
+ Files.createDirectories(wrapperPath);
// copy files
- InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/mvnw");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(BUILD_DIR, "mvnw")));
- is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/mvnw.cmd");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(BUILD_DIR, "mvnw.cmd")));
- is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/maven-wrapper.jar");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(wrapper, "maven-wrapper.jar")));
- is = ExportBaseCommand.class.getClassLoader()
- .getResourceAsStream("maven-wrapper/maven-wrapper.properties");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(wrapper, "maven-wrapper.properties")));
+ Path mvnwPath = Paths.get(BUILD_DIR, "mvnw");
+ Path mvnwCmdPath = Paths.get(BUILD_DIR, "mvnw.cmd");
+ Path wrapperJarPath = wrapperPath.resolve("maven-wrapper.jar");
+ Path wrapperPropsPath = wrapperPath.resolve("maven-wrapper.properties");
+
+ try (InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/mvnw")) {
+ Files.copy(is, mvnwPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/mvnw.cmd")) {
+ Files.copy(is, mvnwCmdPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/maven-wrapper.jar")) {
+ Files.copy(is, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is
+ = ExportBaseCommand.class.getClassLoader().getResourceAsStream("maven-wrapper/maven-wrapper.properties")) {
+ Files.copy(is, wrapperPropsPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+
// set execute file permission on mvnw/mvnw.cmd files
- File file = new File(BUILD_DIR, "mvnw");
- file.setExecutable(true);
- file = new File(BUILD_DIR, "mvnw.cmd");
- file.setExecutable(true);
+ Files.setPosixFilePermissions(mvnwPath, PosixFilePermissions.fromString("rwxr-xr-x"));
+ Files.setPosixFilePermissions(mvnwCmdPath, PosixFilePermissions.fromString("rwxr-xr-x"));
}
protected void copyGradleWrapper() throws Exception {
- File wrapper = new File(BUILD_DIR, "gradle/wrapper");
- wrapper.mkdirs();
+ Path wrapperPath = Paths.get(BUILD_DIR, "gradle/wrapper");
+ Files.createDirectories(wrapperPath);
// copy files
- InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradlew");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(BUILD_DIR, "gradlew")));
- is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradlew.bat");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(BUILD_DIR, "gradlew.bat")));
- is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradle-wrapper.jar");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(wrapper, "gradle-wrapper.jar")));
- is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradle-wrapper.properties");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(wrapper, "gradle-wrapper.properties")));
- // set execute file permission on gradlew/gradlew.cmd files
- File file = new File(BUILD_DIR, "gradlew");
- file.setExecutable(true);
- file = new File(BUILD_DIR, "gradlew.bat");
- file.setExecutable(true);
+ Path gradlewPath = Paths.get(BUILD_DIR, "gradlew");
+ Path gradlewBatPath = Paths.get(BUILD_DIR, "gradlew.bat");
+ Path wrapperJarPath = wrapperPath.resolve("gradle-wrapper.jar");
+ Path wrapperPropsPath = wrapperPath.resolve("gradle-wrapper.properties");
+
+ try (InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradlew")) {
+ Files.copy(is, gradlewPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradlew.bat")) {
+ Files.copy(is, gradlewBatPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is
+ = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradle-wrapper.jar")) {
+ Files.copy(is, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream is
+ = ExportBaseCommand.class.getClassLoader().getResourceAsStream("gradle-wrapper/gradle-wrapper.properties")) {
+ Files.copy(is, wrapperPropsPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ // set execute file permission on gradlew/gradlew.bat files
+ Files.setPosixFilePermissions(gradlewPath, PosixFilePermissions.fromString("rwxr-xr-x"));
+ Files.setPosixFilePermissions(gradlewBatPath, PosixFilePermissions.fromString("rwxr-xr-x"));
}
protected String applicationPropertyLine(String key, String value) {
@@ -879,7 +897,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
* @param camelVersion the camel version
* @return repositories or null if none are in use
*/
- protected String getMavenRepositories(File settings, Properties prop, String camelVersion) throws Exception {
+ protected String getMavenRepositories(Path settings, Properties prop, String camelVersion) throws Exception {
Set<String> answer = new LinkedHashSet<>();
String propRepositories = prop.getProperty("camel.jbang.repositories");
@@ -913,7 +931,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
.collect(Collectors.joining(","));
}
- protected static boolean hasModeline(File settings) {
+ protected static boolean hasModeline(Path settings) {
try {
List<String> lines = RuntimeUtil.loadPropertiesLines(settings);
return lines.stream().anyMatch(l -> l.startsWith("modeline="));
@@ -923,7 +941,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
return false;
}
- protected static int httpServerPort(File settings) {
+ protected static int httpServerPort(Path settings) {
try {
List<String> lines = RuntimeUtil.loadPropertiesLines(settings);
String port = lines.stream().filter(l -> l.startsWith("camel.jbang.platform-http.port="))
@@ -935,7 +953,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
return -1;
}
- protected static String jibMavenPluginVersion(File settings, Properties prop) {
+ protected static String jibMavenPluginVersion(Path settings, Properties prop) {
String answer = null;
if (prop != null) {
answer = prop.getProperty("camel.jbang.jib-maven-plugin-version");
@@ -952,7 +970,7 @@ public abstract class ExportBaseCommand extends CamelCommand {
return answer != null ? answer : "3.4.5";
}
- protected static String jkubeMavenPluginVersion(File settings, Properties props) {
+ protected static String jkubeMavenPluginVersion(Path settings, Properties props) {
String answer = null;
if (props != null) {
answer = props.getProperty("camel.jbang.jkube-maven-plugin-version");
@@ -970,30 +988,33 @@ public abstract class ExportBaseCommand extends CamelCommand {
return answer != null ? answer : "1.18.1";
}
- private void safeCopy(String scheme, Path source, File target, boolean override) throws Exception {
+ private void safeCopy(String scheme, Path source, Path target, boolean override) throws Exception {
if ("classpath".equals(scheme)) {
- try (var ins = getClass().getClassLoader().getResourceAsStream(source.toString())) {
- IOHelper.copy(ins, new FileOutputStream(target));
+ try (var ins = getClass().getClassLoader().getResourceAsStream(source.toString());
+ var outs = Files.newOutputStream(target)) {
+ IOHelper.copy(ins, outs);
}
} else {
- safeCopy(source.toFile(), target, override);
+ safeCopy(source, target, override);
}
}
- protected void safeCopy(File source, File target, boolean override) throws Exception {
- if (!source.exists()) {
+ protected void safeCopy(Path source, Path target, boolean override) throws Exception {
+ if (!Files.exists(source)) {
return;
}
- if (source.isDirectory()) {
+ if (Files.isDirectory(source)) {
// flatten files if they are from a directory
- File[] children = source.listFiles();
- if (children != null) {
- for (File child : children) {
- if (child.isFile()) {
- safeCopy(child, new File(target, child.getName()), override);
- }
- }
+ try (var stream = Files.list(source)) {
+ stream.filter(Files::isRegularFile)
+ .forEach(child -> {
+ try {
+ safeCopy(child, target.resolve(child.getFileName()), override);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
}
return;
}
@@ -1001,8 +1022,8 @@ public abstract class ExportBaseCommand extends CamelCommand {
if (symbolicLink) {
try {
// must use absolute paths
- Path link = target.toPath().toAbsolutePath();
- Path src = source.toPath().toAbsolutePath();
+ Path link = target.toAbsolutePath();
+ Path src = source.toAbsolutePath();
if (Files.exists(link)) {
Files.delete(link);
}
@@ -1013,29 +1034,41 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
}
- if (!target.exists()) {
- Files.copy(source.toPath(), target.toPath());
+ if (!Files.exists(target)) {
+ Files.copy(source, target);
} else if (override) {
- Files.copy(source.toPath(), target.toPath(),
+ Files.copy(source, target,
StandardCopyOption.REPLACE_EXISTING);
}
}
- protected void safeCopy(InputStream source, File target) throws Exception {
+ // This method is kept for backward compatibility with derived classes
+ @Deprecated
+ protected void safeCopy(java.io.File source, java.io.File target, boolean override) throws Exception {
+ safeCopy(source.toPath(), target.toPath(), override);
+ }
+
+ protected void safeCopy(InputStream source, Path target) throws Exception {
if (source == null) {
return;
}
- File dir = target.getParentFile();
- if (!dir.exists()) {
- dir.mkdirs();
+ Path dir = target.getParent();
+ if (!Files.exists(dir)) {
+ Files.createDirectories(dir);
}
- if (!target.exists()) {
- Files.copy(source, target.toPath());
+ if (!Files.exists(target)) {
+ Files.copy(source, target);
}
}
+ // This method is kept for backward compatibility with derived classes
+ @Deprecated
+ protected void safeCopy(InputStream source, java.io.File target) throws Exception {
+ safeCopy(source, target.toPath());
+ }
+
private static String determinePackageName(String content) {
final Matcher matcher = PACKAGE_PATTERN.matcher(content);
return matcher.find() ? matcher.group(1) : null;
@@ -1093,27 +1126,26 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
private static MavenGav parseLocalJar(String dep) {
- File file = new File(dep + ".jar");
- if (!file.isFile() || !file.exists()) {
+ Path path = Paths.get(dep + ".jar");
+ if (!Files.isRegularFile(path) || !Files.exists(path)) {
return null;
}
- try {
- JarFile jf = new JarFile(file);
+ try (JarFile jf = new JarFile(path.toFile())) {
Optional<JarEntry> je = jf.stream().filter(e -> e.getName().startsWith("META-INF/maven/")
&& e.getName().endsWith("/pom.properties")).findFirst();
if (je.isPresent()) {
JarEntry e = je.get();
- InputStream is = jf.getInputStream(e);
- Properties prop = new Properties();
- prop.load(is);
- IOHelper.close(is);
- MavenGav gav = new MavenGav();
- gav.setGroupId(prop.getProperty("groupId"));
- gav.setArtifactId(prop.getProperty("artifactId"));
- gav.setVersion(prop.getProperty("version"));
- gav.setPackaging("lib");
- return gav;
+ try (InputStream is = jf.getInputStream(e)) {
+ Properties prop = new Properties();
+ prop.load(is);
+ MavenGav gav = new MavenGav();
+ gav.setGroupId(prop.getProperty("groupId"));
+ gav.setArtifactId(prop.getProperty("artifactId"));
+ gav.setVersion(prop.getProperty("version"));
+ gav.setPackaging("lib");
+ return gav;
+ }
}
} catch (Exception e) {
// ignore
@@ -1125,12 +1157,12 @@ public abstract class ExportBaseCommand extends CamelCommand {
protected void copyLocalLibDependencies(Set<String> deps) throws Exception {
for (String d : deps) {
if (d.startsWith("lib:")) {
- File libDir = new File(BUILD_DIR, "lib");
- libDir.mkdirs();
+ Path libDirPath = Paths.get(BUILD_DIR, "lib");
+ Files.createDirectories(libDirPath);
String n = d.substring(4);
- File source = new File(n);
- File target = new File(libDir, n);
- safeCopy(source, target, true);
+ Path sourcePath = Paths.get(n);
+ Path targetPath = libDirPath.resolve(n);
+ safeCopy(sourcePath, targetPath, true);
}
}
}
@@ -1138,8 +1170,8 @@ public abstract class ExportBaseCommand extends CamelCommand {
protected void copyAgentDependencies(Set<String> deps) throws Exception {
for (String d : deps) {
if (d.startsWith("agent:")) {
- File libDir = new File(BUILD_DIR, "agent");
- libDir.mkdirs();
+ Path libDirPath = Paths.get(BUILD_DIR, "agent");
+ Files.createDirectories(libDirPath);
String n = d.substring(6);
MavenGav gav = MavenGav.parseGav(n);
copyAgentLibDependencies(gav);
@@ -1165,35 +1197,47 @@ public abstract class ExportBaseCommand extends CamelCommand {
}
}
- protected void copyApplicationPropertiesFiles(File srcResourcesDir) throws Exception {
- File[] files = new File(".").listFiles(f -> {
- if (!f.isFile()) {
- return false;
- }
- String ext = FileUtil.onlyExt(f.getName());
- String name = FileUtil.onlyName(f.getName());
- if (!"properties".equals(ext)) {
- return false;
- }
- if (name.equals("application")) {
- // skip generic as its handled specially
- return false;
- }
- if (profile == null) {
- // accept all kind of configuration files
- return name.startsWith("application");
- } else {
- // only accept the configuration file that matches the profile
- return name.equals("application-" + profile);
- }
- });
- if (files != null) {
- for (File f : files) {
- safeCopy(f, new File(srcResourcesDir, f.getName()), true);
- }
+ protected void copyApplicationPropertiesFiles(Path srcResourcesDir) throws Exception {
+ try {
+ Files.list(Paths.get("."))
+ .filter(p -> Files.isRegularFile(p))
+ .filter(p -> {
+ String fileName = p.getFileName().toString();
+ String ext = FileUtil.onlyExt(fileName);
+ String name = FileUtil.onlyName(fileName);
+ if (!"properties".equals(ext)) {
+ return false;
+ }
+ if (name.equals("application")) {
+ // skip generic as its handled specially
+ return false;
+ }
+ if (profile == null) {
+ // accept all kind of configuration files
+ return name.startsWith("application");
+ } else {
+ // only accept the configuration file that matches the profile
+ return name.equals("application-" + profile);
+ }
+ })
+ .forEach(p -> {
+ try {
+ safeCopy(p, srcResourcesDir.resolve(p.getFileName()), true);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } catch (IOException e) {
+ // Ignore
}
}
+ // This method is kept for backward compatibility with derived classes
+ @Deprecated
+ protected void copyApplicationPropertiesFiles(java.io.File srcResourcesDir) throws Exception {
+ copyApplicationPropertiesFiles(srcResourcesDir.toPath());
+ }
+
private MavenDownloader getDownloader() {
if (downloader == null) {
init();
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportCamelMain.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportCamelMain.java
index 99d3c22bb76..851274b6402 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportCamelMain.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportCamelMain.java
@@ -16,9 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -27,14 +28,13 @@ import java.util.Set;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.RuntimeUtil;
import org.apache.camel.dsl.jbang.core.common.VersionHelper;
import org.apache.camel.tooling.maven.MavenGav;
import org.apache.camel.util.CamelCaseOrderedProperties;
-import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
-import org.apache.commons.io.FileUtils;
class ExportCamelMain extends Export {
@@ -59,8 +59,8 @@ class ExportCamelMain extends Export {
}
// the settings file has information what to export
- File settings = new File(CommandLineHelper.getWorkDir(), Run.RUN_SETTINGS_FILE);
- if (fresh || !files.isEmpty() || !settings.exists()) {
+ Path settings = CommandLineHelper.getWorkDir().resolve(Run.RUN_SETTINGS_FILE);
+ if (fresh || !files.isEmpty() || !Files.exists(settings)) {
// allow to automatic build
printer().println("Generating fresh run data");
int silent = runSilently(ignoreLoadingError, lazyBean, verbose);
@@ -73,61 +73,65 @@ class ExportCamelMain extends Export {
printer().println("Exporting as Camel Main project to: " + exportDir);
- File profile = new File("application.properties");
+ Path profile = Path.of("application.properties");
// use a temporary work dir
- File buildDir = new File(BUILD_DIR);
- FileUtil.removeDir(buildDir);
- buildDir.mkdirs();
+ Path buildDir = Path.of(BUILD_DIR);
+ PathUtils.deleteDirectory(buildDir);
+ Files.createDirectories(buildDir);
// gather dependencies
Set<String> deps = resolveDependencies(settings, profile);
// compute source folders
- File srcJavaDirRoot = new File(BUILD_DIR, "src/main/java");
+ Path srcJavaDirRoot = buildDir.resolve("src/main/java");
String srcPackageName = exportPackageName(ids[0], ids[1], packageName);
- File srcJavaDir;
+ Path srcJavaDir;
if (srcPackageName == null) {
srcJavaDir = srcJavaDirRoot;
} else {
- srcJavaDir = new File(srcJavaDirRoot, srcPackageName.replace('.', File.separatorChar));
+ srcJavaDir = srcJavaDirRoot.resolve(srcPackageName.replace('.', '/'));
}
- srcJavaDir.mkdirs();
- File srcResourcesDir = new File(BUILD_DIR, "src/main/resources");
- srcResourcesDir.mkdirs();
- File srcCamelResourcesDir = new File(BUILD_DIR, "src/main/resources/camel");
- File srcKameletsResourcesDir = new File(BUILD_DIR, "src/main/resources/kamelets");
+ Files.createDirectories(srcJavaDir);
+ Path srcResourcesDir = buildDir.resolve("src/main/resources");
+ Files.createDirectories(srcResourcesDir);
+ Path srcCamelResourcesDir = buildDir.resolve("src/main/resources/camel");
+ Path srcKameletsResourcesDir = buildDir.resolve("src/main/resources/kamelets");
// copy application properties files
copyApplicationPropertiesFiles(srcResourcesDir);
// copy source files
- copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir, srcResourcesDir, srcCamelResourcesDir,
+ copySourceFiles(settings, profile,
+ srcJavaDirRoot, srcJavaDir,
+ srcResourcesDir, srcCamelResourcesDir,
srcKameletsResourcesDir, srcPackageName);
// copy from settings to profile
- copySettingsAndProfile(settings, profile, srcResourcesDir, prop -> {
- if (!prop.containsKey("camel.main.basePackageScan")
- && !prop.containsKey("camel.main.base-package-scan")) {
- // use dot as root package if no package are in use
- prop.put("camel.main.basePackageScan", srcPackageName == null ? "." : srcPackageName);
- }
- if (!hasModeline(settings)) {
- prop.remove("camel.main.modeline");
- }
- // are we using http then enable embedded HTTP server (if not explicit configured already)
- int port = httpServerPort(settings);
- if (port == -1 && deps.stream().anyMatch(d -> d.contains("camel-platform-http") || d.contains("camel-rest"))) {
- port = 8080;
- }
- if (port != -1 && !prop.containsKey("camel.server.enabled")) {
- prop.put("camel.server.enabled", "true");
- if (port != 8080 && !prop.containsKey("camel.server.port")) {
- prop.put("camel.server.port", port);
- }
- if (!prop.containsKey("camel.server.health-check-enabled")) {
- prop.put("camel.server.health-check-enabled", "true");
- }
- }
- return prop;
- });
+ copySettingsAndProfile(settings, profile,
+ srcResourcesDir, prop -> {
+ if (!prop.containsKey("camel.main.basePackageScan")
+ && !prop.containsKey("camel.main.base-package-scan")) {
+ // use dot as root package if no package are in use
+ prop.put("camel.main.basePackageScan", srcPackageName == null ? "." : srcPackageName);
+ }
+ if (!hasModeline(settings)) {
+ prop.remove("camel.main.modeline");
+ }
+ // are we using http then enable embedded HTTP server (if not explicit configured already)
+ int port = httpServerPort(settings);
+ if (port == -1
+ && deps.stream().anyMatch(d -> d.contains("camel-platform-http") || d.contains("camel-rest"))) {
+ port = 8080;
+ }
+ if (port != -1 && !prop.containsKey("camel.server.enabled")) {
+ prop.put("camel.server.enabled", "true");
+ if (port != 8080 && !prop.containsKey("camel.server.port")) {
+ prop.put("camel.server.port", port);
+ }
+ if (!prop.containsKey("camel.server.health-check-enabled")) {
+ prop.put("camel.server.health-check-enabled", "true");
+ }
+ }
+ return prop;
+ });
// create main class
createMainClassSource(srcJavaDir, srcPackageName, mainClassname);
// copy local lib JARs
@@ -136,13 +140,14 @@ class ExportCamelMain extends Export {
copyAgentDependencies(deps);
deps.removeIf(d -> d.startsWith("agent:"));
if ("maven".equals(buildTool)) {
- createMavenPom(settings, profile, new File(BUILD_DIR, "pom.xml"), deps, srcPackageName);
+ createMavenPom(settings, profile,
+ buildDir.resolve("pom.xml"), deps, srcPackageName);
if (mavenWrapper) {
copyMavenWrapper();
}
}
copyDockerFiles(BUILD_DIR);
- String appJar = "target" + File.separator + ids[1] + "-" + ids[2] + ".jar";
+ String appJar = Paths.get("target", ids[1] + "-" + ids[2] + ".jar").toString();
copyReadme(BUILD_DIR, appJar);
if (cleanExportDir || !exportDir.equals(".")) {
// cleaning current dir can be a bit dangerous so only clean if explicit enabled
@@ -150,13 +155,13 @@ class ExportCamelMain extends Export {
CommandHelper.cleanExportDir(exportDir);
}
// copy to export dir and remove work dir
- FileUtils.copyDirectory(new File(BUILD_DIR), new File(exportDir));
- FileUtil.removeDir(new File(BUILD_DIR));
+ PathUtils.copyDirectory(buildDir, Path.of(exportDir));
+ PathUtils.deleteDirectory(buildDir);
return 0;
}
- private void createMavenPom(File settings, File profile, File pom, Set<String> deps, String packageName) throws Exception {
+ private void createMavenPom(Path settings, Path profile, Path pom, Set<String> deps, String packageName) throws Exception {
String[] ids = gav.split(":");
InputStream is = ExportCamelMain.class.getClassLoader().getResourceAsStream("templates/" + pomTemplateName);
@@ -241,16 +246,16 @@ class ExportCamelMain extends Export {
// include docker/kubernetes with jib/jkube
context = enrichMavenPomJib(context, settings, profile);
- IOHelper.writeText(context, new FileOutputStream(pom, false));
+ Files.writeString(pom, context);
}
- protected String enrichMavenPomJib(String context, File settings, File profile) throws Exception {
+ protected String enrichMavenPomJib(String context, Path settings, Path profile) throws Exception {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
// is kubernetes included?
Properties prop = new CamelCaseOrderedProperties();
- if (profile.exists()) {
+ if (Files.exists(profile)) {
RuntimeUtil.loadProperties(prop, profile);
}
// include additional build properties
@@ -280,7 +285,8 @@ class ExportCamelMain extends Export {
String context2 = IOHelper.loadText(is);
IOHelper.close(is);
- context2 = context2.replaceFirst("\\{\\{ \\.JibMavenPluginVersion }}", jibMavenPluginVersion(settings, prop));
+ context2 = context2.replaceFirst("\\{\\{ \\.JibMavenPluginVersion }}",
+ jibMavenPluginVersion(settings, prop));
// image from/to auth
String auth = "";
@@ -325,10 +331,10 @@ class ExportCamelMain extends Export {
}
@Override
- protected Set<String> resolveDependencies(File settings, File profile) throws Exception {
+ protected Set<String> resolveDependencies(Path settings, Path profile) throws Exception {
Set<String> answer = super.resolveDependencies(settings, profile);
- if (profile != null && profile.exists()) {
+ if (profile != null && Files.exists(profile)) {
Properties prop = new CamelCaseOrderedProperties();
RuntimeUtil.loadProperties(prop, profile);
// if metrics is defined then include camel-micrometer-prometheus for camel-main runtime
@@ -360,7 +366,7 @@ class ExportCamelMain extends Export {
return answer;
}
- private void createMainClassSource(File srcJavaDir, String packageName, String mainClassname) throws Exception {
+ private void createMainClassSource(Path srcJavaDir, String packageName, String mainClassname) throws Exception {
InputStream is = ExportCamelMain.class.getClassLoader().getResourceAsStream("templates/main.tmpl");
String context = IOHelper.loadText(is);
IOHelper.close(is);
@@ -371,13 +377,14 @@ class ExportCamelMain extends Export {
context = context.replaceFirst("\\{\\{ \\.PackageName }}", "");
}
context = context.replaceAll("\\{\\{ \\.MainClassname }}", mainClassname);
- IOHelper.writeText(context, new FileOutputStream(srcJavaDir + "/" + mainClassname + ".java", false));
+ Path outputFile = srcJavaDir.resolve(mainClassname + ".java");
+ Files.writeString(outputFile, context);
}
@Override
protected void copySourceFiles(
- File settings, File profile, File srcJavaDirRoot, File srcJavaDir, File srcResourcesDir, File srcCamelResourcesDir,
- File srcKameletsResourcesDir, String packageName)
+ Path settings, Path profile, Path srcJavaDirRoot, Path srcJavaDir, Path srcResourcesDir, Path srcCamelResourcesDir,
+ Path srcKameletsResourcesDir, String packageName)
throws Exception {
super.copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir, srcResourcesDir, srcCamelResourcesDir,
@@ -385,11 +392,11 @@ class ExportCamelMain extends Export {
// log4j configuration
InputStream is = ExportCamelMain.class.getResourceAsStream("/log4j2-main.properties");
- safeCopy(is, new File(srcResourcesDir, "log4j2.properties"));
+ safeCopy(is, srcResourcesDir.resolve("log4j2.properties"));
is = ExportCamelMain.class.getResourceAsStream("/log4j2.component.properties");
- safeCopy(is, new File(srcResourcesDir, "log4j2.component.properties"));
+ safeCopy(is, srcResourcesDir.resolve("log4j2.component.properties"));
// assembly for runner jar
is = ExportCamelMain.class.getResourceAsStream("/assembly/runner.xml");
- safeCopy(is, new File(srcResourcesDir, "assembly/runner.xml"));
+ safeCopy(is, srcResourcesDir.resolve("assembly/runner.xml"));
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportQuarkus.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportQuarkus.java
index 995276a589f..5a3c369aaf2 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportQuarkus.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportQuarkus.java
@@ -17,8 +17,9 @@
package org.apache.camel.dsl.jbang.core.commands;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -32,15 +33,14 @@ import java.util.stream.Collectors;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.RuntimeUtil;
import org.apache.camel.dsl.jbang.core.common.VersionHelper;
import org.apache.camel.tooling.maven.MavenGav;
import org.apache.camel.tooling.model.ArtifactModel;
import org.apache.camel.util.CamelCaseOrderedProperties;
-import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
-import org.apache.commons.io.FileUtils;
class ExportQuarkus extends Export {
@@ -61,11 +61,11 @@ class ExportQuarkus extends Export {
return 1;
}
- File profile = new File("application.properties");
+ Path profile = Path.of("application.properties");
// the settings file has information what to export
- File settings = new File(CommandLineHelper.getWorkDir(), Run.RUN_SETTINGS_FILE);
- if (fresh || !files.isEmpty() || !settings.exists()) {
+ Path settings = CommandLineHelper.getWorkDir().resolve(Run.RUN_SETTINGS_FILE);
+ if (fresh || !files.isEmpty() || !Files.exists(settings)) {
// allow to automatic build
printer().println("Generating fresh run data");
int silent = runSilently(ignoreLoadingError, lazyBean, verbose);
@@ -79,25 +79,26 @@ class ExportQuarkus extends Export {
printer().println("Exporting as Quarkus project to: " + exportDir);
// use a temporary work dir
- File buildDir = new File(BUILD_DIR);
- FileUtil.removeDir(buildDir);
- buildDir.mkdirs();
+ Path buildDir = Path.of(BUILD_DIR);
+ PathUtils.deleteDirectory(buildDir);
+ Files.createDirectories(buildDir);
- File srcJavaDirRoot = new File(BUILD_DIR, "src/main/java");
+ Path srcJavaDirRoot = buildDir.resolve("src/main/java");
String srcPackageName = exportPackageName(ids[0], ids[1], packageName);
- File srcJavaDir;
+ Path srcJavaDir;
if (srcPackageName == null) {
srcJavaDir = srcJavaDirRoot;
} else {
- srcJavaDir = new File(srcJavaDirRoot, srcPackageName.replace('.', File.separatorChar));
+ srcJavaDir = srcJavaDirRoot.resolve(srcPackageName.replace('.', File.separatorChar));
}
- srcJavaDir.mkdirs();
- File srcResourcesDir = new File(BUILD_DIR, "src/main/resources");
- srcResourcesDir.mkdirs();
- File srcCamelResourcesDir = new File(BUILD_DIR, "src/main/resources/camel");
- File srcKameletsResourcesDir = new File(BUILD_DIR, "src/main/resources/kamelets");
+ Files.createDirectories(srcJavaDir);
+ Path srcResourcesDir = buildDir.resolve("src/main/resources");
+ Files.createDirectories(srcResourcesDir);
+ Path srcCamelResourcesDir = buildDir.resolve("src/main/resources/camel");
+ Path srcKameletsResourcesDir = buildDir.resolve("src/main/resources/kamelets");
// copy source files
- copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir, srcResourcesDir, srcCamelResourcesDir,
+ copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir,
+ srcResourcesDir, srcCamelResourcesDir,
srcKameletsResourcesDir, srcPackageName);
// copy from settings to profile
copySettingsAndProfile(settings, profile, srcResourcesDir, prop -> {
@@ -115,14 +116,14 @@ class ExportQuarkus extends Export {
// copy local lib JARs
copyLocalLibDependencies(deps);
if ("maven".equals(buildTool)) {
- createMavenPom(settings, new File(BUILD_DIR, "pom.xml"), deps);
+ createMavenPom(settings, buildDir.resolve("pom.xml"), deps);
if (mavenWrapper) {
copyMavenWrapper();
}
} else if ("gradle".equals(buildTool)) {
- createGradleProperties(new File(BUILD_DIR, "gradle.properties"));
- createSettingsGradle(new File(BUILD_DIR, "settings.gradle"));
- createBuildGradle(settings, new File(BUILD_DIR, "build.gradle"), deps);
+ createGradleProperties(buildDir.resolve("gradle.properties"));
+ createSettingsGradle(buildDir.resolve("settings.gradle"));
+ createBuildGradle(settings, buildDir.resolve("build.gradle"), deps);
if (gradleWrapper) {
copyGradleWrapper();
}
@@ -134,8 +135,8 @@ class ExportQuarkus extends Export {
CommandHelper.cleanExportDir(exportDir);
}
// copy to export dir and remove work dir
- FileUtils.copyDirectory(new File(BUILD_DIR), new File(exportDir));
- FileUtil.removeDir(new File(BUILD_DIR));
+ PathUtils.copyDirectory(buildDir, Path.of(exportDir));
+ PathUtils.deleteDirectory(buildDir);
return 0;
}
@@ -217,7 +218,7 @@ class ExportQuarkus extends Export {
return s;
}
- private void createGradleProperties(File output) throws Exception {
+ private void createGradleProperties(Path output) throws Exception {
InputStream is = ExportQuarkus.class.getClassLoader().getResourceAsStream("templates/quarkus-gradle-properties.tmpl");
String context = IOHelper.loadText(is);
IOHelper.close(is);
@@ -226,10 +227,10 @@ class ExportQuarkus extends Export {
context = context.replaceFirst("\\{\\{ \\.QuarkusArtifactId }}", quarkusArtifactId);
context = context.replaceAll("\\{\\{ \\.QuarkusVersion }}", quarkusVersion);
- IOHelper.writeText(context, new FileOutputStream(output, false));
+ Files.writeString(output, context);
}
- private void createSettingsGradle(File output) throws Exception {
+ private void createSettingsGradle(Path output) throws Exception {
String[] ids = gav.split(":");
InputStream is = ExportQuarkus.class.getClassLoader().getResourceAsStream("templates/quarkus-settings-gradle.tmpl");
@@ -240,10 +241,10 @@ class ExportQuarkus extends Export {
context = context.replaceFirst("\\{\\{ \\.ArtifactId }}", ids[1]);
context = context.replaceFirst("\\{\\{ \\.Version }}", ids[2]);
- IOHelper.writeText(context, new FileOutputStream(output, false));
+ Files.writeString(output, context);
}
- private void createBuildGradle(File settings, File gradleBuild, Set<String> deps) throws Exception {
+ private void createBuildGradle(Path settings, Path gradleBuild, Set<String> deps) throws Exception {
String[] ids = gav.split(":");
InputStream is = ExportSpringBoot.class.getClassLoader().getResourceAsStream("templates/quarkus-build-gradle.tmpl");
@@ -251,7 +252,7 @@ class ExportQuarkus extends Export {
IOHelper.close(is);
Properties prop = new CamelCaseOrderedProperties();
- RuntimeUtil.loadProperties(prop, settings);
+ RuntimeUtil.loadProperties(prop, settings.toFile());
// quarkus controls the camel version
String repos = getMavenRepositories(settings, prop, quarkusVersion);
@@ -331,7 +332,7 @@ class ExportQuarkus extends Export {
}
context = context.replaceFirst("\\{\\{ \\.CamelDependencies }}", sb.toString());
- IOHelper.writeText(context, new FileOutputStream(gradleBuild, false));
+ Files.writeString(gradleBuild, context);
}
private void replaceQuarkusDependencies(List<MavenGav> gavs) {
@@ -381,25 +382,25 @@ class ExportQuarkus extends Export {
@Override
protected void copyDockerFiles(String buildDir) throws Exception {
- File docker = new File(buildDir, "src/main/docker");
- docker.mkdirs();
+ Path docker = Path.of(buildDir).resolve("src/main/docker");
+ Files.createDirectories(docker);
// copy files
InputStream is = ExportQuarkus.class.getClassLoader().getResourceAsStream("quarkus-docker/Dockerfile.jvm");
// Deprecated, use Dockerfile instead
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(docker, "Dockerfile.jvm")));
+ PathUtils.copyFromStream(is, docker.resolve("Dockerfile.jvm"), true);
is = ExportQuarkus.class.getClassLoader().getResourceAsStream("quarkus-docker/Dockerfile.jvm");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(docker, "Dockerfile")));
+ PathUtils.copyFromStream(is, docker.resolve("Dockerfile"), true);
// Deprecated, to be removed in the future
is = ExportQuarkus.class.getClassLoader().getResourceAsStream("quarkus-docker/Dockerfile.legacy-jar");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(docker, "Dockerfile.legacy-jar")));
+ PathUtils.copyFromStream(is, docker.resolve("Dockerfile.legacy-jar"), true);
is = ExportQuarkus.class.getClassLoader().getResourceAsStream("quarkus-docker/Dockerfile.native");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(docker, "Dockerfile.native")));
+ PathUtils.copyFromStream(is, docker.resolve("Dockerfile.native"), true);
// Deprecated, to be removed in the future
is = ExportQuarkus.class.getClassLoader().getResourceAsStream("quarkus-docker/Dockerfile.native-micro");
- IOHelper.copyAndCloseInput(is, new FileOutputStream(new File(docker, "Dockerfile.native-micro")));
+ PathUtils.copyFromStream(is, docker.resolve("Dockerfile.native-micro"), true);
}
- private void createMavenPom(File settings, File pom, Set<String> deps) throws Exception {
+ private void createMavenPom(Path settings, Path pom, Set<String> deps) throws Exception {
String[] ids = gav.split(":");
InputStream is = ExportQuarkus.class.getClassLoader().getResourceAsStream("templates/" + pomTemplateName);
@@ -494,11 +495,11 @@ class ExportQuarkus extends Export {
}
context = context.replaceFirst("\\{\\{ \\.CamelDependencies }}", sb.toString());
- IOHelper.writeText(context, new FileOutputStream(pom, false));
+ Files.writeString(pom, context);
}
@Override
- protected Set<String> resolveDependencies(File settings, File profile) throws Exception {
+ protected Set<String> resolveDependencies(Path settings, Path profile) throws Exception {
Set<String> answer = super.resolveDependencies(settings, profile);
// remove out of the box dependencies
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportSpringBoot.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportSpringBoot.java
index 5b83a73ab47..3e11da71c79 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportSpringBoot.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ExportSpringBoot.java
@@ -17,10 +17,13 @@
package org.apache.camel.dsl.jbang.core.commands;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@@ -30,15 +33,14 @@ import java.util.Set;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.RuntimeUtil;
import org.apache.camel.dsl.jbang.core.common.VersionHelper;
import org.apache.camel.tooling.maven.MavenGav;
import org.apache.camel.tooling.model.ArtifactModel;
import org.apache.camel.util.CamelCaseOrderedProperties;
-import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
-import org.apache.commons.io.FileUtils;
class ExportSpringBoot extends Export {
@@ -59,11 +61,11 @@ class ExportSpringBoot extends Export {
return 1;
}
- File profile = new File("application.properties");
+ Path profile = Path.of("application.properties");
// the settings file has information what to export
- File settings = new File(CommandLineHelper.getWorkDir(), Run.RUN_SETTINGS_FILE);
- if (fresh || !files.isEmpty() || !settings.exists()) {
+ Path settings = CommandLineHelper.getWorkDir().resolve(Run.RUN_SETTINGS_FILE);
+ if (fresh || !files.isEmpty() || !Files.exists(settings)) {
// allow to automatic build
printer().println("Generating fresh run data");
int silent = runSilently(ignoreLoadingError, lazyBean, verbose);
@@ -77,28 +79,29 @@ class ExportSpringBoot extends Export {
printer().println("Exporting as Spring Boot project to: " + exportDir);
// use a temporary work dir
- File buildDir = new File(BUILD_DIR);
- FileUtil.removeDir(buildDir);
- buildDir.mkdirs();
+ Path buildDir = Path.of(BUILD_DIR);
+ PathUtils.deleteDirectory(buildDir);
+ Files.createDirectories(buildDir);
- File srcJavaDirRoot = new File(BUILD_DIR, "src/main/java");
+ Path srcJavaDirRoot = buildDir.resolve("src/main/java");
String srcPackageName = exportPackageName(ids[0], ids[1], packageName);
- File srcJavaDir;
+ Path srcJavaDir;
if (srcPackageName == null) {
srcJavaDir = srcJavaDirRoot;
} else {
- srcJavaDir = new File(srcJavaDirRoot, srcPackageName.replace('.', File.separatorChar));
+ srcJavaDir = srcJavaDirRoot.resolve(srcPackageName.replace('.', File.separatorChar));
}
- srcJavaDir.mkdirs();
- File srcResourcesDir = new File(BUILD_DIR, "src/main/resources");
- srcResourcesDir.mkdirs();
- File srcCamelResourcesDir = new File(BUILD_DIR, "src/main/resources/camel");
- File srcKameletsResourcesDir = new File(BUILD_DIR, "src/main/resources/kamelets");
+ Files.createDirectories(srcJavaDir);
+ Path srcResourcesDir = buildDir.resolve("src/main/resources");
+ Files.createDirectories(srcResourcesDir);
+ Path srcCamelResourcesDir = buildDir.resolve("src/main/resources/camel");
+ Path srcKameletsResourcesDir = buildDir.resolve("src/main/resources/kamelets");
// copy application properties files
copyApplicationPropertiesFiles(srcResourcesDir);
// copy source files
- copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir, srcResourcesDir, srcCamelResourcesDir,
+ copySourceFiles(settings, profile, srcJavaDirRoot, srcJavaDir,
+ srcResourcesDir, srcCamelResourcesDir,
srcKameletsResourcesDir, srcPackageName);
// create main class
@@ -120,13 +123,13 @@ class ExportSpringBoot extends Export {
return prop;
});
if ("maven".equals(buildTool)) {
- createMavenPom(settings, profile, new File(BUILD_DIR, "pom.xml"), deps);
+ createMavenPom(settings, profile, buildDir.resolve("pom.xml"), deps);
if (mavenWrapper) {
copyMavenWrapper();
}
} else if ("gradle".equals(buildTool)) {
- createSettingsGradle(new File(BUILD_DIR, "settings.gradle"));
- createBuildGradle(settings, new File(BUILD_DIR, "build.gradle"), deps);
+ createSettingsGradle(buildDir.resolve("settings.gradle"));
+ createBuildGradle(settings, buildDir.resolve("build.gradle"), deps);
if (gradleWrapper) {
copyGradleWrapper();
}
@@ -140,20 +143,20 @@ class ExportSpringBoot extends Export {
CommandHelper.cleanExportDir(exportDir);
}
// copy to export dir and remove work dir
- FileUtils.copyDirectory(new File(BUILD_DIR), new File(exportDir));
- FileUtil.removeDir(new File(BUILD_DIR));
+ org.apache.commons.io.file.PathUtils.copyDirectory(buildDir, Paths.get(exportDir));
+ PathUtils.deleteDirectory(buildDir);
return 0;
}
- private void createSettingsGradle(File file) throws Exception {
+ private void createSettingsGradle(Path file) throws Exception {
String[] ids = gav.split(":");
String text = String.format("rootProject.name = '%s'", ids[1]);
- IOHelper.writeText(text, new FileOutputStream(file, false));
+ IOHelper.writeText(text, Files.newOutputStream(file));
}
- private void createMavenPom(File settings, File profile, File pom, Set<String> deps) throws Exception {
+ private void createMavenPom(Path settings, Path profile, Path pom, Set<String> deps) throws Exception {
String[] ids = gav.split(":");
Properties prop = new CamelCaseOrderedProperties();
@@ -252,10 +255,10 @@ class ExportSpringBoot extends Export {
}
context = context.replaceFirst("\\{\\{ \\.CamelDependencies }}", sb.toString());
- IOHelper.writeText(context, new FileOutputStream(pom, false));
+ IOHelper.writeText(context, Files.newOutputStream(pom));
}
- private void createBuildGradle(File settings, File gradleBuild, Set<String> deps) throws Exception {
+ private void createBuildGradle(Path settings, Path gradleBuild, Set<String> deps) throws Exception {
String[] ids = gav.split(":");
String context = readResourceTemplate("templates/spring-boot-build-gradle.tmpl");
@@ -335,11 +338,11 @@ class ExportSpringBoot extends Export {
}
context = context.replaceFirst("\\{\\{ \\.CamelDependencies }}", sb.toString());
- IOHelper.writeText(context, new FileOutputStream(gradleBuild, false));
+ IOHelper.writeText(context, Files.newOutputStream(gradleBuild));
}
@Override
- protected Set<String> resolveDependencies(File settings, File profile) throws Exception {
+ protected Set<String> resolveDependencies(Path settings, Path profile) throws Exception {
Set<String> answer = super.resolveDependencies(settings, profile);
// remove out of the box dependencies
@@ -354,16 +357,17 @@ class ExportSpringBoot extends Export {
return answer;
}
- private void createMainClassSource(File srcJavaDir, String packageName, String mainClassname) throws Exception {
+ private void createMainClassSource(Path srcJavaDir, String packageName, String mainClassname) throws Exception {
String context = readResourceTemplate("templates/spring-boot-main.tmpl");
context = context.replaceFirst("\\{\\{ \\.PackageName }}", packageName);
context = context.replaceAll("\\{\\{ \\.MainClassname }}", mainClassname);
- IOHelper.writeText(context, new FileOutputStream(srcJavaDir + "/" + mainClassname + ".java", false));
+ IOHelper.writeText(context,
+ Files.newOutputStream(srcJavaDir.resolve(mainClassname + ".java")));
}
@Override
- protected void adjustJavaSourceFileLine(String line, FileOutputStream fos) throws Exception {
+ protected void adjustJavaSourceFileLine(String line, OutputStream fos) throws Exception {
if (line.startsWith("public class")
&& (line.contains("RouteBuilder") || line.contains("EndpointRouteBuilder"))) {
fos.write("import org.springframework.stereotype.Component;\n\n"
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java
index 581b499a5a8..d12c9224ef9 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java
@@ -16,11 +16,12 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-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.nio.file.Paths;
import java.util.Stack;
import java.util.StringJoiner;
@@ -149,12 +150,12 @@ public class Init extends CamelCommand {
// ensure target dir is created after clean
CommandHelper.cleanExportDir(directory);
}
- File dir = new File(directory);
- dir.mkdirs();
+ Path dirPath = Paths.get(directory);
+ Files.createDirectories(dirPath);
}
- File target = new File(file);
- if (!target.isAbsolute()) {
- target = new File(directory, file);
+ Path targetPath = Paths.get(file);
+ if (!targetPath.isAbsolute()) {
+ targetPath = Paths.get(directory, file);
}
content = content.replaceFirst("\\{\\{ \\.Name }}", name);
if (fromKamelet != null) {
@@ -177,33 +178,33 @@ public class Init extends CamelCommand {
content = sb.toString();
}
if ("java".equals(ext)) {
- String packageDeclaration = computeJavaPackageDeclaration(target);
+ String packageDeclaration = computeJavaPackageDeclaration(targetPath);
content = content.replaceFirst("\\{\\{ \\.PackageDeclaration }}", packageDeclaration);
}
// in case of using relative paths in the file name
- File p = target.getParentFile();
- if (p != null) {
- if (".".equals(p.getName())) {
- target = new File(file);
+ Path parentPath = targetPath.getParent();
+ if (parentPath != null) {
+ if (".".equals(parentPath.getFileName().toString())) {
+ targetPath = Paths.get(file);
} else {
- p.mkdirs();
+ Files.createDirectories(parentPath);
}
}
- IOHelper.writeText(content, new FileOutputStream(target, false));
+ Files.writeString(targetPath, content);
return 0;
}
/**
* @return The package declaration lines to insert at the beginning of the file or empty string if no package found
*/
- private String computeJavaPackageDeclaration(File target) throws IOException {
+ private String computeJavaPackageDeclaration(Path targetPath) throws IOException {
String packageDeclaration = "";
- String canonicalPath = target.getParentFile().getCanonicalPath();
- String srcMainJavaPath = "src" + File.separatorChar + "main" + File.separatorChar + "java";
+ String canonicalPath = targetPath.getParent().toRealPath().toString();
+ String srcMainJavaPath = Paths.get("src", "main", "java").toString();
int index = canonicalPath.indexOf(srcMainJavaPath);
if (index != -1) {
String packagePath = canonicalPath.substring(index + srcMainJavaPath.length() + 1);
- String packageName = packagePath.replace(File.separatorChar, '.');
+ String packageName = packagePath.replace(java.io.File.separatorChar, '.');
if (!packageName.isEmpty()) {
packageDeclaration = "package " + packageName + ";\n\n";
}
@@ -212,9 +213,13 @@ public class Init extends CamelCommand {
}
private void createWorkingDirectoryIfAbsent() {
- File work = CommandLineHelper.getWorkDir();
- if (!work.exists()) {
- work.mkdirs();
+ Path work = CommandLineHelper.getWorkDir();
+ if (!Files.exists(work)) {
+ try {
+ Files.createDirectories(work);
+ } catch (IOException e) {
+ // ignore
+ }
}
}
@@ -234,12 +239,12 @@ public class Init extends CamelCommand {
if (all.length() > 0) {
// okay we downloaded something so prepare export dir
if (!directory.equals(".")) {
- File dir = new File(directory);
+ Path dirPath = Paths.get(directory);
if (cleanDirectory) {
// ensure target dir is created after clean
CommandHelper.cleanExportDir(directory);
}
- dir.mkdirs();
+ Files.createDirectories(dirPath);
}
CamelContext tiny = new DefaultCamelContext();
@@ -252,9 +257,9 @@ public class Init extends CamelCommand {
}
String loc = resource.getLocation();
String name = FileUtil.stripPath(loc);
- File target = new File(directory, name);
- try (FileOutputStream fo = new FileOutputStream(target)) {
- IOUtils.copy(resource.getInputStream(), fo);
+ Path targetPath = Paths.get(directory, name);
+ try (OutputStream os = Files.newOutputStream(targetPath)) {
+ IOUtils.copy(resource.getInputStream(), os);
}
}
}
@@ -270,12 +275,12 @@ public class Init extends CamelCommand {
if (all.length() > 0) {
// okay we downloaded something so prepare export dir
if (!directory.equals(".")) {
- File dir = new File(directory);
+ Path dirPath = Paths.get(directory);
if (cleanDirectory) {
// ensure target dir is created after clean
CommandHelper.cleanExportDir(directory);
}
- dir.mkdirs();
+ Files.createDirectories(dirPath);
}
CamelContext tiny = new DefaultCamelContext();
@@ -288,9 +293,9 @@ public class Init extends CamelCommand {
}
String loc = resource.getLocation();
String name = FileUtil.stripPath(loc);
- File target = new File(directory, name);
- try (FileOutputStream fo = new FileOutputStream(target)) {
- IOUtils.copy(resource.getInputStream(), fo);
+ Path targetPath = Paths.get(directory, name);
+ try (OutputStream os = Files.newOutputStream(targetPath)) {
+ IOUtils.copy(resource.getInputStream(), os);
}
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Run.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Run.java
index 2abdde240bc..880efd7658c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Run.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Run.java
@@ -21,10 +21,7 @@ import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
@@ -33,6 +30,8 @@ import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.function.Supplier;
import java.util.regex.Matcher;
@@ -116,7 +115,7 @@ public class Run extends CamelCommand {
boolean transformMessageRun;
boolean debugRun;
- private File logFile;
+ private Path logFile;
public long spawnPid;
private Printer quietPrinter;
@@ -422,9 +421,13 @@ public class Run extends CamelCommand {
}
}
- private Properties loadProfileProperties(File source) throws Exception {
+ private Properties loadProfileProperties(Path source) throws Exception {
Properties prop = new CamelCaseOrderedProperties();
- RuntimeUtil.loadProperties(prop, source);
+ if (Files.exists(source)) {
+ try (InputStream is = Files.newInputStream(source)) {
+ prop.load(is);
+ }
+ }
// special for routes include pattern that we need to "fix" after reading from properties
// to make this work in run command
@@ -455,14 +458,18 @@ public class Run extends CamelCommand {
// special if user type: camel run .
if (sourceDir == null && (files != null && files.size() == 1 && ".".equals(files.get(0)))) {
files.clear();
- File[] fs = new File(".").listFiles();
- if (fs != null) {
- for (File f : fs) {
- // skip hidden files
- if (f.isFile() && !f.isHidden()) {
- files.add(f.getName());
- }
- }
+ try {
+ Files.list(Paths.get("."))
+ .filter(p -> {
+ try {
+ return Files.isRegularFile(p) && !Files.isHidden(p);
+ } catch (IOException e) {
+ return false;
+ }
+ })
+ .forEach(p -> files.add(p.getFileName().toString()));
+ } catch (IOException e) {
+ // Ignore
}
}
@@ -474,10 +481,14 @@ public class Run extends CamelCommand {
}
}
- File work = CommandLineHelper.getWorkDir();
+ Path work = CommandLineHelper.getWorkDir();
removeDir(work);
- if (!work.exists() && !work.mkdirs()) {
- printer().println("WARN: Failed to create working directory: " + work.getAbsolutePath());
+ if (!Files.exists(work)) {
+ try {
+ Files.createDirectories(work);
+ } catch (IOException e) {
+ printer().println("WARN: Failed to create working directory: " + work.toAbsolutePath());
+ }
}
Properties profileProperties = !empty ? loadProfileProperties() : null;
@@ -491,16 +502,16 @@ public class Run extends CamelCommand {
// code may refer to an existing file
String name = "CodeRoute";
boolean file = false;
- File f = new File(code);
- if (f.isFile() && f.exists()) {
+ Path codePath = Paths.get(code);
+ if (Files.isRegularFile(codePath) && Files.exists(codePath)) {
// must be a java file
- boolean java = f.getName().endsWith(".java");
+ boolean java = codePath.getFileName().toString().endsWith(".java");
if (!java) {
printer().printErr("Only java source files is accepted when using --code parameter");
return 1;
}
- code = Files.readString(f.toPath());
- name = FileUtil.onlyName(f.getName());
+ code = Files.readString(codePath);
+ name = FileUtil.onlyName(codePath.getFileName().toString());
file = true;
}
// store code in temporary file
@@ -515,11 +526,12 @@ public class Run extends CamelCommand {
if (!empty && autoDetectFiles) {
if (sourceDir != null) {
// silent-run then auto-detect all initial files for source-dir
- String[] allFiles = new File(sourceDir).list();
- if (allFiles != null) {
- for (String f : allFiles) {
- files.add(sourceDir + File.separator + f);
- }
+ try {
+ Path sourceDirPath = Paths.get(sourceDir);
+ Files.list(sourceDirPath)
+ .forEach(p -> files.add(sourceDirPath.resolve(p.getFileName()).toString()));
+ } catch (IOException e) {
+ // Ignore
}
} else {
String routes
@@ -538,9 +550,12 @@ public class Run extends CamelCommand {
return 1;
} else {
// silent-run then auto-detect all files
- String[] allFiles = new File(".").list();
- if (allFiles != null) {
- files.addAll(Arrays.asList(allFiles));
+ try {
+ Files.list(Paths.get("."))
+ .map(p -> p.getFileName().toString())
+ .forEach(files::add);
+ } catch (IOException e) {
+ // Ignore
}
}
}
@@ -610,7 +625,7 @@ public class Run extends CamelCommand {
writeSetting(main, profileProperties, "camel.jbang.prompt", "true");
}
writeSetting(main, profileProperties, "camel.jbang.compileWorkDir",
- CommandLineHelper.CAMEL_JBANG_WORK_DIR + File.separator + "compile");
+ Paths.get(CommandLineHelper.CAMEL_JBANG_WORK_DIR, "compile").toString());
if (gav != null) {
writeSetting(main, profileProperties, "camel.jbang.gav", gav);
@@ -717,13 +732,13 @@ public class Run extends CamelCommand {
if (profile != null) {
// need to include profile application properties if exists
String name = "application-" + profile + ".properties";
- if (new File(name).exists() && !files.contains(name)) {
+ if (Files.exists(Paths.get(name)) && !files.contains(name)) {
files.add(name);
}
}
for (String file : files) {
- if (file.startsWith("clipboard") && !(new File(file).exists())) {
+ if (file.startsWith("clipboard") && !(Files.exists(Paths.get(file)))) {
file = loadFromClipboard(file);
} else if (skipFile(file)) {
continue;
@@ -772,8 +787,8 @@ public class Run extends CamelCommand {
}
if (file.startsWith("file:")) {
// check if file exist
- File inputFile = new File(file.substring(5));
- if (!inputFile.exists() && !inputFile.isFile()) {
+ Path inputPath = Paths.get(file.substring(5));
+ if (!Files.exists(inputPath) || !Files.isRegularFile(inputPath)) {
printer().printErr("File does not exist: " + file);
return 1;
}
@@ -817,8 +832,8 @@ public class Run extends CamelCommand {
if (sourceDir != null) {
// must be an existing directory
- File dir = new File(sourceDir);
- if (!dir.exists() && !dir.isDirectory()) {
+ Path dirPath = Paths.get(sourceDir);
+ if (!Files.exists(dirPath) || !Files.isDirectory(dirPath)) {
printer().printErr("Directory does not exist: " + sourceDir);
return 1;
}
@@ -891,7 +906,7 @@ public class Run extends CamelCommand {
for (String file : names) {
if (!file.startsWith("file:")) {
if (!file.startsWith("/")) {
- file = FileSystems.getDefault().getPath("").toAbsolutePath() + File.separator + file;
+ file = Paths.get(FileSystems.getDefault().getPath("").toAbsolutePath().toString(), file).toString();
}
file = "file://" + file;
}
@@ -983,10 +998,18 @@ public class Run extends CamelCommand {
}
// create temp run dir
- File runDir = new File(RUN_PLATFORM_DIR, Long.toString(System.currentTimeMillis()));
+ Path runDirPath = Paths.get(RUN_PLATFORM_DIR, Long.toString(System.currentTimeMillis()));
if (!this.background) {
- runDir.deleteOnExit();
+ // Mark for deletion on exit
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ try {
+ removeDir(runDirPath);
+ } catch (Exception e) {
+ // Ignore
+ }
+ }));
}
+ Files.createDirectories(runDirPath);
// export to hidden folder
ExportQuarkus eq = new ExportQuarkus(getMain());
@@ -999,7 +1022,7 @@ public class Run extends CamelCommand {
eq.quarkusArtifactId = this.quarkusArtifactId;
eq.camelVersion = this.camelVersion;
eq.kameletsVersion = this.kameletsVersion;
- eq.exportDir = runDir.toString();
+ eq.exportDir = runDirPath.toString();
eq.localKameletDir = this.localKameletDir;
eq.excludes = this.excludes;
eq.filePaths = this.filePaths;
@@ -1038,7 +1061,8 @@ public class Run extends CamelCommand {
mvnw = "/mvnw.cmd";
}
ProcessBuilder pb = new ProcessBuilder();
- pb.command(runDir + mvnw, "--quiet", "--file", runDir.getCanonicalPath() + File.separatorChar + "pom.xml", "package",
+ pb.command(runDirPath.toString() + mvnw, "--quiet", "--file",
+ runDirPath.toRealPath().resolve("pom.xml").toString(), "package",
"quarkus:" + (dev ? "dev" : "run"));
pb.inheritIO(); // run in foreground (with IO so logs are visible)
@@ -1055,10 +1079,18 @@ public class Run extends CamelCommand {
}
// create temp run dir
- File runDir = new File(RUN_PLATFORM_DIR, Long.toString(System.currentTimeMillis()));
+ Path runDirPath = Paths.get(RUN_PLATFORM_DIR, Long.toString(System.currentTimeMillis()));
if (!this.background) {
- runDir.deleteOnExit();
+ // Mark for deletion on exit
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ try {
+ removeDir(runDirPath);
+ } catch (Exception e) {
+ // Ignore
+ }
+ }));
}
+ Files.createDirectories(runDirPath);
// export to hidden folder
ExportSpringBoot eq = new ExportSpringBoot(getMain());
@@ -1071,7 +1103,7 @@ public class Run extends CamelCommand {
eq.camelVersion = this.camelVersion;
eq.camelSpringBootVersion = this.camelSpringBootVersion != null ? this.camelSpringBootVersion : this.camelVersion;
eq.kameletsVersion = this.kameletsVersion;
- eq.exportDir = runDir.toString();
+ eq.exportDir = runDirPath.toString();
eq.localKameletDir = this.localKameletDir;
eq.excludes = this.excludes;
eq.filePaths = this.filePaths;
@@ -1110,11 +1142,10 @@ public class Run extends CamelCommand {
}
// prepare spring-boot for logging to file
- InputStream is = Run.class.getClassLoader().getResourceAsStream("spring-boot-logback.xml");
- try {
- eq.safeCopy(is, new File(eq.exportDir + "/src/main/resources/logback.xml"));
- } finally {
- IOHelper.close(is);
+ try (InputStream is = Run.class.getClassLoader().getResourceAsStream("spring-boot-logback.xml")) {
+ Path logbackPath = Paths.get(eq.exportDir, "src/main/resources/logback.xml");
+ Files.createDirectories(logbackPath.getParent());
+ Files.copy(is, logbackPath, StandardCopyOption.REPLACE_EXISTING);
}
// run spring-boot via maven
@@ -1123,7 +1154,8 @@ public class Run extends CamelCommand {
if (FileUtil.isWindows()) {
mvnw = "/mvnw.cmd";
}
- pb.command(runDir + mvnw, "--quiet", "--file", runDir.getCanonicalPath() + File.separatorChar + "pom.xml",
+ pb.command(runDirPath.toString() + mvnw, "--quiet", "--file",
+ runDirPath.toRealPath().resolve("pom.xml").toString(),
"spring-boot:run");
pb.inheritIO(); // run in foreground (with IO so logs are visible)
@@ -1184,23 +1216,23 @@ public class Run extends CamelCommand {
}
// application.properties
- File profilePropertiesFile;
+ Path profilePropertiesPath;
if (sourceDir != null) {
- profilePropertiesFile = new File(sourceDir, "application.properties");
+ profilePropertiesPath = Paths.get(sourceDir).resolve("application.properties");
} else {
- profilePropertiesFile = new File("application.properties");
+ profilePropertiesPath = Paths.get("application.properties");
}
// based application-profile.properties
- answer = doLoadAndInitProfileProperties(profilePropertiesFile);
+ answer = doLoadAndInitProfileProperties(profilePropertiesPath);
if (profile != null) {
if (sourceDir != null) {
- profilePropertiesFile = new File(sourceDir, "application-" + profile + ".properties");
+ profilePropertiesPath = Paths.get(sourceDir).resolve("application-" + profile + ".properties");
} else {
- profilePropertiesFile = new File("application-" + profile + ".properties");
+ profilePropertiesPath = Paths.get("application-" + profile + ".properties");
}
// application-profile.properties should override standard application.properties
- Properties override = doLoadAndInitProfileProperties(profilePropertiesFile);
+ Properties override = doLoadAndInitProfileProperties(profilePropertiesPath);
if (override != null) {
if (answer == null) {
answer = override;
@@ -1216,10 +1248,10 @@ public class Run extends CamelCommand {
return answer;
}
- private Properties doLoadAndInitProfileProperties(File profilePropertiesFile) throws Exception {
+ private Properties doLoadAndInitProfileProperties(Path profilePropertiesPath) throws Exception {
Properties answer = null;
- if (profilePropertiesFile.exists()) {
- answer = loadProfileProperties(profilePropertiesFile);
+ if (Files.exists(profilePropertiesPath)) {
+ answer = this.loadProfileProperties((Path) profilePropertiesPath);
// logging level/color may be configured in the properties file
loggingLevel = answer.getProperty("loggingLevel", loggingLevel);
loggingColor
@@ -1365,13 +1397,18 @@ public class Run extends CamelCommand {
}
protected int runBackgroundProcess(ProcessBuilder pb, String kind) throws Exception {
- File log = null;
+ Path logPath = null;
if (backgroundWait) {
// store background output in a log file to capture any error on startup
- log = getRunBackgroundLogFile("" + new Random().nextLong());
- log.deleteOnExit();
+ logPath = getRunBackgroundLogFile("" + new Random().nextLong());
+ try {
+ Files.createFile(logPath);
+ logPath.toFile().deleteOnExit();
+ } catch (IOException e) {
+ // Ignore
+ }
pb.redirectErrorStream(true);
- pb.redirectOutput(log);
+ pb.redirectOutput(logPath.toFile());
}
Process p = pb.start();
@@ -1383,7 +1420,7 @@ public class Run extends CamelCommand {
}
int ec = 0;
- if (log != null) {
+ if (logPath != null) {
StopWatch watch = new StopWatch();
int state = 0; // state 5 is running
while (p.isAlive() && watch.taken() < 20000 && state < 5) {
@@ -1408,15 +1445,19 @@ public class Run extends CamelCommand {
if (ec != 0) {
printer().println(kind + ": " + name + " startup failure");
printer().println("");
- String text = IOHelper.loadText(new FileInputStream(log));
+ String text = Files.readString(logPath);
printer().print(text);
}
} else {
printer().println(kind + ": " + name + " (state: " + extractState(state) + ")");
}
}
- if (log != null) {
- log.delete();
+ if (logPath != null) {
+ try {
+ Files.deleteIfExists(logPath);
+ } catch (IOException e) {
+ // Ignore
+ }
}
return ec;
@@ -1516,7 +1557,7 @@ public class Run extends CamelCommand {
// cleanup and delete log file
if (logFile != null) {
- FileUtil.deleteFile(logFile);
+ Files.deleteIfExists(logFile);
}
return main.getExitCode();
@@ -1689,10 +1730,16 @@ public class Run extends CamelCommand {
if (!scriptRun) {
// remember log file
String name = RuntimeUtil.getPid() + ".log";
- final File logDir = CommandLineHelper.getCamelDir();
- logDir.mkdirs(); //make sure the parent dir exists
- logFile = new File(logDir, name);
- logFile.deleteOnExit();
+ final Path logDir = CommandLineHelper.getCamelDir();
+ Files.createDirectories(logDir); //make sure the parent dir exists
+ logFile = logDir.resolve(name);
+ try {
+ // Create an empty file that will be deleted on exit
+ Files.createFile(logFile);
+ logFile.toFile().deleteOnExit();
+ } catch (IOException e) {
+ // Ignore
+ }
}
} else {
if (exportRun) {
@@ -1706,22 +1753,21 @@ public class Run extends CamelCommand {
}
private void generateOpenApi() throws Exception {
- File file = Paths.get(openapi).toFile();
- if (!file.exists() && !file.isFile()) {
- throw new FileNotFoundException("Cannot find file: " + file);
+ Path filePath = Paths.get(openapi);
+ if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
+ throw new FileNotFoundException("Cannot find file: " + filePath);
}
- InputStream is = Run.class.getClassLoader().getResourceAsStream("templates/rest-dsl.yaml.tmpl");
- String content = IOHelper.loadText(is);
- IOHelper.close(is);
+ try (InputStream is = Run.class.getClassLoader().getResourceAsStream("templates/rest-dsl.yaml.tmpl")) {
+ String content = IOHelper.loadText(is);
+ String onlyName = filePath.toString();
+ content = content.replaceFirst("\\{\\{ \\.Spec }}", onlyName);
- String onlyName = file.getPath();
- content = content.replaceFirst("\\{\\{ \\.Spec }}", onlyName);
+ Files.writeString(Paths.get(OPENAPI_GENERATED_FILE), content);
- Files.writeString(Paths.get(OPENAPI_GENERATED_FILE), content);
-
- // we need to include the spec on the classpath
- files.add(openapi);
+ // we need to include the spec on the classpath
+ files.add(openapi);
+ }
}
private boolean knownFile(String file) throws Exception {
@@ -1811,8 +1857,8 @@ public class Run extends CamelCommand {
}
// skip dirs
- File f = new File(name);
- if (f.exists() && f.isDirectory()) {
+ Path path = Paths.get(name);
+ if (Files.exists(path) && Files.isDirectory(path)) {
return true;
}
@@ -1854,7 +1900,6 @@ public class Run extends CamelCommand {
}
private void writeSettings(String key, String value) {
- FileOutputStream fos = null;
try {
// use java.util.Properties to ensure the value is escaped correctly
Properties prop = new Properties();
@@ -1862,49 +1907,70 @@ public class Run extends CamelCommand {
StringWriter sw = new StringWriter();
prop.store(sw, null);
- File runSettings = new File(CommandLineHelper.getWorkDir(), RUN_SETTINGS_FILE);
- fos = new FileOutputStream(runSettings, true);
+ Path runSettingsPath = CommandLineHelper.getWorkDir().resolve(RUN_SETTINGS_FILE);
+ StringBuilder content = new StringBuilder();
String[] lines = sw.toString().split(System.lineSeparator());
for (String line : lines) {
// properties store timestamp as comment which we want to skip
if (!line.startsWith("#")) {
- fos.write(line.getBytes(StandardCharsets.UTF_8));
- fos.write(System.lineSeparator().getBytes(StandardCharsets.UTF_8));
+ content.append(line).append(System.lineSeparator());
}
}
+
+ // Append to the file if it exists, otherwise create it
+ if (Files.exists(runSettingsPath)) {
+ Files.write(runSettingsPath, content.toString().getBytes(StandardCharsets.UTF_8),
+ StandardOpenOption.APPEND);
+ } else {
+ Files.write(runSettingsPath, content.toString().getBytes(StandardCharsets.UTF_8));
+ }
} catch (Exception e) {
// ignore
- } finally {
- IOHelper.close(fos);
}
}
- private static void removeDir(File d) {
- String[] list = d.list();
- if (list == null) {
- list = new String[0];
- }
- for (String s : list) {
- File f = new File(d, s);
- if (f.isDirectory()) {
- removeDir(f);
- } else {
- delete(f);
+ private static void removeDir(Path directory) {
+ try {
+ if (Files.exists(directory)) {
+ Files.walk(directory)
+ .sorted(java.util.Comparator.reverseOrder())
+ .forEach(path -> {
+ try {
+ Files.deleteIfExists(path);
+ } catch (IOException e) {
+ // Fallback to deleteOnExit if we can't delete immediately
+ try {
+ path.toFile().deleteOnExit();
+ } catch (Exception ex) {
+ // Ignore
+ }
+ }
+ });
}
+ } catch (IOException e) {
+ // Ignore
}
- delete(d);
}
- private static void delete(File f) {
- if (!f.delete()) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
+ private static void delete(Path path) {
+ try {
+ if (!Files.deleteIfExists(path)) {
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ if (!Files.deleteIfExists(path)) {
+ path.toFile().deleteOnExit();
+ }
}
- if (!f.delete()) {
- f.deleteOnExit();
+ } catch (IOException e) {
+ // Fallback to deleteOnExit
+ try {
+ path.toFile().deleteOnExit();
+ } catch (Exception ex) {
+ // Ignore
}
}
}
@@ -2026,12 +2092,12 @@ public class Run extends CamelCommand {
private JsonObject loadStatus(long pid) {
try {
- File f = getStatusFile(Long.toString(pid));
- if (f != null) {
- FileInputStream fis = new FileInputStream(f);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
- return (JsonObject) Jsoner.deserialize(text);
+ Path p = getStatusFile(Long.toString(pid));
+ if (Files.exists(p)) {
+ try (InputStream is = Files.newInputStream(p)) {
+ String text = IOHelper.loadText(is);
+ return (JsonObject) Jsoner.deserialize(text);
+ }
}
} catch (Exception e) {
// ignore
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/RunHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/RunHelper.java
index 23d4aa0d0c7..ca0b2631793 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/RunHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/RunHelper.java
@@ -16,19 +16,18 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
+import java.io.Reader;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
-import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ReflectionHelper;
import org.apache.camel.util.StringHelper;
import org.apache.maven.model.Dependency;
@@ -41,13 +40,13 @@ public final class RunHelper {
}
public static String mavenArtifactId() {
- File f = new File("pom.xml");
- if (f.exists() && f.isFile()) {
+ Path pomPath = Paths.get("pom.xml");
+ if (Files.exists(pomPath) && Files.isRegularFile(pomPath)) {
// find additional dependencies form pom.xml
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
- try {
- Model model = mavenReader.read(new FileReader(f));
- model.setPomFile(f);
+ try (Reader reader = Files.newBufferedReader(pomPath)) {
+ Model model = mavenReader.read(reader);
+ model.setPomFile(pomPath.toFile()); // Still need File for Maven Model
return model.getArtifactId();
} catch (Exception e) {
@@ -60,13 +59,13 @@ public final class RunHelper {
public static List<String> scanMavenDependenciesFromPom() {
List<String> answer = new ArrayList<>();
- File f = new File("pom.xml");
- if (f.exists() && f.isFile()) {
+ Path pomPath = Paths.get("pom.xml");
+ if (Files.exists(pomPath) && Files.isRegularFile(pomPath)) {
// find additional dependencies form pom.xml
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
- try {
- Model model = mavenReader.read(new FileReader(f));
- model.setPomFile(f);
+ try (Reader reader = Files.newBufferedReader(pomPath)) {
+ Model model = mavenReader.read(reader);
+ model.setPomFile(pomPath.toFile()); // Still need File for Maven Model
for (Dependency d : model.getDependencies()) {
String g = d.getGroupId();
@@ -78,7 +77,7 @@ public final class RunHelper {
if (v != null && v.startsWith("${") && v.endsWith("}")) {
// version uses placeholder, so try to find them
v = v.substring(2, v.length() - 1);
- v = findMavenProperty(f, v);
+ v = findMavenProperty((Path) pomPath, v);
}
if (v != null) {
String gav = "mvn:" + g + ":" + d.getArtifactId() + ":" + v;
@@ -122,28 +121,27 @@ public final class RunHelper {
// scan as maven based project
Stream<Path> s = Stream.concat(walk(Path.of("src/main/java")), walk(Path.of("src/main/resources")));
- s.filter(p -> p.toFile().isFile())
- .map(p -> p.toFile().getPath())
+ s.filter(Files::isRegularFile)
+ .map(Path::toString)
.forEach(answer::add);
return answer;
}
- public static String findMavenProperty(File f, String placeholder) {
- if (f.exists() && f.isFile()) {
+ public static String findMavenProperty(Path pomPath, String placeholder) {
+ if (Files.exists(pomPath) && Files.isRegularFile(pomPath)) {
// find additional dependencies form pom.xml
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
- try {
- Model model = mavenReader.read(new FileReader(f));
- model.setPomFile(f);
+ try (Reader reader = Files.newBufferedReader(pomPath)) {
+ Model model = mavenReader.read(reader);
+ model.setPomFile(pomPath.toFile()); // Still need File for Maven Model
String p = model.getProperties().getProperty(placeholder);
if (p != null) {
return p;
} else if (model.getParent() != null) {
p = model.getParent().getRelativePath();
if (p != null) {
- String dir = FileUtil.onlyPath(f.getAbsolutePath());
- String parent = FileUtil.compactPath(dir + File.separatorChar + p);
- return findMavenProperty(new File(parent), placeholder);
+ Path parentPath = pomPath.getParent().resolve(p);
+ return findMavenProperty(parentPath, placeholder);
}
}
} catch (Exception ex) {
@@ -153,6 +151,12 @@ public final class RunHelper {
return null;
}
+ // Keep for backward compatibility
+ @Deprecated
+ public static String findMavenProperty(java.io.File f, String placeholder) {
+ return findMavenProperty(f.toPath(), placeholder);
+ }
+
public static Stream<Path> walk(Path dir) {
try {
if (Files.isDirectory(dir)) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/SBOMGenerator.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/SBOMGenerator.java
index 6697fb21146..e1206185aa9 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/SBOMGenerator.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/SBOMGenerator.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
@@ -79,7 +80,7 @@ public class SBOMGenerator extends Export {
protected Integer export() throws Exception {
Integer answer = doExport();
if (answer == 0) {
- File buildDir = new File(EXPORT_DIR);
+ Path buildDir = Paths.get(EXPORT_DIR);
String mvnProgramCall;
if (FileUtil.isWindows()) {
mvnProgramCall = "cmd /c mvn";
@@ -103,7 +104,7 @@ public class SBOMGenerator extends Export {
+ " -DoutputFormat="
+ sbomOutputFormat,
null,
- buildDir);
+ buildDir.toFile());
done = p.waitFor(60, TimeUnit.SECONDS);
if (!done) {
answer = 1;
@@ -127,10 +128,10 @@ public class SBOMGenerator extends Export {
Process p = Runtime.getRuntime()
.exec(mvnProgramCall + " org.spdx:spdx-maven-plugin:" + spdxPluginVersion
+ ":createSPDX -DspdxFileName="
- + outputDirectoryParameter + File.separator + outputName + "." + sbomOutputFormat
+ + Paths.get(outputDirectoryParameter, outputName + "." + sbomOutputFormat).toString()
+ " -DoutputFormat=" + outputFormat,
null,
- buildDir);
+ buildDir.toFile());
done = p.waitFor(60, TimeUnit.SECONDS);
if (!done) {
answer = 1;
@@ -140,15 +141,15 @@ public class SBOMGenerator extends Export {
}
}
// cleanup dir after complete
- FileUtil.removeDir(buildDir);
+ org.apache.camel.dsl.jbang.core.common.PathUtils.deleteDirectory(buildDir);
}
return answer;
}
protected Integer doExport() throws Exception {
// read runtime and gav from properties if not configured
- File profile = new File("application.properties");
- if (profile.exists()) {
+ Path profile = Paths.get("application.properties");
+ if (Files.exists(profile)) {
Properties prop = new CamelCaseOrderedProperties();
RuntimeUtil.loadProperties(prop, profile);
if (this.runtime == null && prop.containsKey("camel.jbang.runtime")) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java
index 1a38bf3abed..2076b260bde 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java
@@ -16,8 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileInputStream;
+import java.io.InputStream;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -109,7 +109,7 @@ public class TransformRoute extends CamelCommand {
if (output == null) {
// load target file and print to console
- dump = waitForDumpFile(new File(target));
+ dump = waitForDumpFile(Path.of(target));
if (dump != null) {
printer().println(dump);
}
@@ -118,18 +118,17 @@ public class TransformRoute extends CamelCommand {
return 0;
}
- protected String waitForDumpFile(File dumpFile) {
+ protected String waitForDumpFile(Path dumpFile) {
StopWatch watch = new StopWatch();
while (watch.taken() < 5000) {
try {
// give time for response to be ready
Thread.sleep(100);
- if (dumpFile.exists()) {
- FileInputStream fis = new FileInputStream(dumpFile);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
- return text;
+ if (Files.exists(dumpFile)) {
+ try (InputStream is = Files.newInputStream(dumpFile)) {
+ return IOHelper.loadText(is);
+ }
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
index 36632f43ea4..b55f2adfd84 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/ActionBaseCommand.java
@@ -16,17 +16,17 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
@@ -37,17 +37,15 @@ abstract class ActionBaseCommand extends CamelCommand {
super(main);
}
- protected static JsonObject getJsonObject(File outputFile) {
+ protected static JsonObject getJsonObject(Path outputFile) {
StopWatch watch = new StopWatch();
while (watch.taken() < 5000) {
try {
// give time for response to be ready
Thread.sleep(100);
- if (outputFile.exists()) {
- FileInputStream fis = new FileInputStream(outputFile);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ if (Files.exists(outputFile)) {
+ String text = Files.readString(outputFile);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (InterruptedException e) {
@@ -117,11 +115,9 @@ abstract class ActionBaseCommand extends CamelCommand {
JsonObject loadStatus(long pid) {
try {
- File f = getStatusFile(Long.toString(pid));
- if (f != null) {
- FileInputStream fis = new FileInputStream(f);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ Path f = getStatusFile(Long.toString(pid));
+ if (f != null && Files.exists(f)) {
+ String text = Files.readString(f);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (Exception e) {
@@ -129,4 +125,31 @@ abstract class ActionBaseCommand extends CamelCommand {
}
return null;
}
+
+ /**
+ * Prepares and writes an action to the action file.
+ *
+ * @param pid the process ID
+ * @param action the action name
+ * @param configureAction a function to configure the action JSON object
+ * @return the output file path
+ */
+ protected Path prepareAction(String pid, String action, java.util.function.Consumer<JsonObject> configureAction) {
+ // ensure output file is deleted before executing action
+ Path outputFile = getOutputFile(pid);
+ PathUtils.deleteFile(outputFile);
+
+ JsonObject root = new JsonObject();
+ root.put("action", action);
+
+ // Allow caller to configure the action
+ if (configureAction != null) {
+ configureAction.accept(root);
+ }
+
+ Path file = getActionFile(pid);
+ PathUtils.writeTextSafely(root.toJson(), file);
+
+ return outputFile;
+ }
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBeanDump.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBeanDump.java
index 417031da491..684de4fce8c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBeanDump.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBeanDump.java
@@ -16,7 +16,7 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -27,8 +27,7 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -99,8 +98,8 @@ public class CamelBeanDump extends ActionBaseCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "bean");
@@ -110,12 +109,8 @@ public class CamelBeanDump extends ActionBaseCommand {
root.put("properties", properties);
root.put("nulls", nulls);
root.put("internal", internal);
- File f = getActionFile(Long.toString(pid));
- try {
- IOHelper.writeText(root.toJson(), f);
- } catch (Exception e) {
- // ignore
- }
+ Path f = getActionFile(Long.toString(pid));
+ PathUtils.writeTextSafely(root.toJson(), f);
JsonObject jo = waitForOutputFile(outputFile);
@@ -174,7 +169,7 @@ public class CamelBeanDump extends ActionBaseCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -222,8 +217,8 @@ public class CamelBeanDump extends ActionBaseCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
- return getJsonObject(outputFile);
+ protected JsonObject waitForOutputFile(Path outputFile) {
+ return getJsonObject((Path) outputFile);
}
private static class Row {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBrowseAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBrowseAction.java
index 9366d70305e..112f29f48b5 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBrowseAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBrowseAction.java
@@ -16,7 +16,7 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -28,9 +28,8 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.json.JsonArray;
@@ -136,8 +135,8 @@ public class CamelBrowseAction extends ActionBaseCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "browse");
@@ -151,15 +150,15 @@ public class CamelBrowseAction extends ActionBaseCommand {
root.put("bodyMaxChars", bodyMaxChars);
}
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ PathUtils.writeTextSafely(root.toJson(), f);
} catch (Exception e) {
// ignore
}
List<Row> rows = new ArrayList<>();
- JsonObject jo = getJsonObject(outputFile);
+ JsonObject jo = getJsonObject((Path) outputFile);
if (jo != null) {
root = loadStatus(this.pid);
if (root != null) {
@@ -207,7 +206,7 @@ public class CamelBrowseAction extends ActionBaseCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGCAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGCAction.java
index 40fb7a43c3a..70c1c2b2c28 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGCAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelGCAction.java
@@ -16,11 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Path;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -41,8 +41,8 @@ public class CamelGCAction extends ActionBaseCommand {
for (long pid : pids) {
JsonObject root = new JsonObject();
root.put("action", "gc");
- File f = getActionFile(Long.toString(pid));
- IOHelper.writeText(root.toJson(), f);
+ Path f = getActionFile(Long.toString(pid));
+ PathUtils.writeTextSafely(root.toJson(), f);
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelLogAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelLogAction.java
index a88e4b5c47a..793bc91cb6c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelLogAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelLogAction.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
@@ -255,12 +255,12 @@ public class CamelLogAction extends ActionBaseCommand {
for (Row row : rows.values()) {
if (row.reader == null) {
- File file = logFile(row.pid);
- if (file.exists()) {
- row.reader = new LineNumberReader(new FileReader(file));
+ Path file = logFile(row.pid);
+ if (Files.exists(file)) {
+ row.reader = new LineNumberReader(Files.newBufferedReader(file));
if (tail == 0) {
// only read new lines so forward to end of reader
- long size = file.length();
+ long size = Files.size(file);
row.reader.skip(size);
}
}
@@ -429,17 +429,18 @@ public class CamelLogAction extends ActionBaseCommand {
}
}
- private static File logFile(String pid) {
+ private static Path logFile(String pid) {
String name = pid + ".log";
- return new File(CommandLineHelper.getCamelDir(), name);
+ Path parent = CommandLineHelper.getCamelDir();
+ return parent.resolve(name);
}
private void tailStartupLogFiles(Map<Long, Row> rows) throws Exception {
for (Row row : rows.values()) {
- File log = logFile(row.pid);
- if (log.exists()) {
+ Path log = logFile(row.pid);
+ if (Files.exists(log)) {
row.fifo = new ArrayDeque<>();
- row.reader = new LineNumberReader(new FileReader(log));
+ row.reader = new LineNumberReader(Files.newBufferedReader(log));
String line;
do {
line = row.reader.readLine();
@@ -458,9 +459,9 @@ public class CamelLogAction extends ActionBaseCommand {
private void tailLogFiles(Map<Long, Row> rows, int tail, Date limit) throws Exception {
for (Row row : rows.values()) {
- File log = logFile(row.pid);
- if (log.exists()) {
- row.reader = new LineNumberReader(new FileReader(log));
+ Path log = logFile(row.pid);
+ if (Files.exists(log)) {
+ row.reader = new LineNumberReader(Files.newBufferedReader(log));
String line;
if (tail <= 0) {
row.fifo = new ArrayDeque<>();
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java
index 7efcbaa9536..311f4ac8aad 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
@@ -43,10 +43,9 @@ import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.catalog.impl.TimePatternConverter;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.commands.CommandHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.PidNameAgeCompletionCandidates;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
@@ -201,14 +200,14 @@ public class CamelReceiveAction extends ActionBaseCommand {
List<Long> pids = findPids(name);
for (long pid : pids) {
if ("clear".equals(action)) {
- File f = getReceiveFile("" + pid);
- if (f.exists()) {
- IOHelper.writeText("{}", f);
+ Path f = getReceiveFile("" + pid);
+ if (Files.exists(f)) {
+ Files.writeString(f, "{}");
}
} else {
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "receive");
@@ -222,8 +221,8 @@ public class CamelReceiveAction extends ActionBaseCommand {
} else if ("stop".equals(action)) {
root.put("enabled", "false");
}
- File f = getActionFile(Long.toString(pid));
- IOHelper.writeText(root.toJson(), f);
+ Path f = getActionFile(Long.toString(pid));
+ Files.writeString(f, root.toJson());
JsonObject jo = waitForOutputFile(outputFile);
if (jo != null) {
@@ -258,7 +257,7 @@ public class CamelReceiveAction extends ActionBaseCommand {
return 0;
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
@@ -451,9 +450,9 @@ public class CamelReceiveAction extends ActionBaseCommand {
private void tailReceiveFiles(Map<Long, Pid> pids, int tail) throws Exception {
for (Pid pid : pids.values()) {
- File file = getReceiveFile(pid.pid);
- if (file.exists() && file.length() > 0) {
- pid.reader = new LineNumberReader(new FileReader(file));
+ Path file = getReceiveFile(pid.pid);
+ if (Files.exists(file) && Files.size(file) > 0) {
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
String line;
if (tail <= 0) {
pid.fifo = new ArrayDeque<>();
@@ -522,12 +521,12 @@ public class CamelReceiveAction extends ActionBaseCommand {
for (Pid pid : pids.values()) {
if (pid.reader == null) {
- File file = getReceiveFile(pid.pid);
- if (file.exists()) {
- pid.reader = new LineNumberReader(new FileReader(file));
+ Path file = getReceiveFile(pid.pid);
+ if (Files.exists(file)) {
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
if (tail == 0) {
// only read new lines so forward to end of reader
- long size = file.length();
+ long size = Files.size(file);
pid.reader.skip(size);
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
index 3a1860864b4..ff57343793b 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
@@ -16,11 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -41,8 +41,8 @@ public class CamelReloadAction extends ActionBaseCommand {
for (long pid : pids) {
JsonObject root = new JsonObject();
root.put("action", "reload");
- File f = getActionFile(Long.toString(pid));
- IOHelper.writeText(root.toJson(), f);
+ Path f = getActionFile(Long.toString(pid));
+ Files.writeString(f, root.toJson());
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelResetStatsAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelResetStatsAction.java
index ea6a86ae9fa..b879f6d052f 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelResetStatsAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelResetStatsAction.java
@@ -16,11 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -41,8 +41,8 @@ public class CamelResetStatsAction extends ActionBaseCommand {
for (long pid : pids) {
JsonObject root = new JsonObject();
root.put("action", "reset-stats");
- File f = getActionFile(Long.toString(pid));
- IOHelper.writeText(root.toJson(), f);
+ Path f = getActionFile(Long.toString(pid));
+ Files.writeString(f, root.toJson());
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteAction.java
index 850449baa0e..a4122151298 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteAction.java
@@ -16,11 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Path;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -45,9 +45,9 @@ public abstract class CamelRouteAction extends ActionBaseCommand {
JsonObject root = new JsonObject();
root.put("action", "route");
root.put("id", id);
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
onAction(root);
- IOHelper.writeText(root.toJson(), f);
+ PathUtils.writeTextSafely(root.toJson(), f);
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteDumpAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteDumpAction.java
index b204fc57406..6cfe45cd612 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteDumpAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelRouteDumpAction.java
@@ -16,16 +16,17 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
@@ -95,17 +96,17 @@ public class CamelRouteDumpAction extends ActionBaseCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "route-dump");
root.put("filter", "*");
root.put("format", format);
root.put("uriAsParameters", uriAsParameters);
- File file = getActionFile(Long.toString(pid));
+ Path file = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), file);
+ Files.writeString(file, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -165,7 +166,7 @@ public class CamelRouteDumpAction extends ActionBaseCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -207,7 +208,7 @@ public class CamelRouteDumpAction extends ActionBaseCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSendAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSendAction.java
index 4aacfebade5..a6659a21064 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSendAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSendAction.java
@@ -16,15 +16,15 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
@@ -120,8 +120,8 @@ public class CamelSendAction extends ActionBaseCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "send");
@@ -151,9 +151,10 @@ public class CamelSendAction extends ActionBaseCommand {
}
root.put("headers", arr);
}
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ String text = root.toJson();
+ Files.writeString(f, text);
} catch (Exception e) {
// ignore
}
@@ -166,12 +167,16 @@ public class CamelSendAction extends ActionBaseCommand {
JsonObject cause = jo.getMap("exception");
if (message != null || cause != null) {
if (replyFile != null) {
- File target = new File(replyFile);
+ Path target = Path.of(replyFile);
String json = jo.toJson();
if (pretty) {
json = Jsoner.prettyPrint(json, 2);
}
- IOHelper.writeText(json, target);
+ try {
+ Files.writeString(target, json);
+ } catch (IOException e) {
+ // ignore
+ }
}
if (!showExchangeProperties && message != null) {
message.remove("exchangeProperties");
@@ -201,7 +206,7 @@ public class CamelSendAction extends ActionBaseCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -285,7 +290,7 @@ public class CamelSendAction extends ActionBaseCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
StopWatch watch = new StopWatch();
long wait = timeout + 10000; // wait longer than timeout
while (watch.taken() < wait) {
@@ -293,10 +298,8 @@ public class CamelSendAction extends ActionBaseCommand {
// give time for response to be ready
Thread.sleep(20);
- if (outputFile.exists()) {
- FileInputStream fis = new FileInputStream(outputFile);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ if (Files.exists(outputFile)) {
+ String text = Files.readString(outputFile);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (InterruptedException e) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceAction.java
index 8c3bc282810..b18e390e172 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceAction.java
@@ -16,14 +16,15 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
@@ -67,19 +68,9 @@ public class CamelSourceAction extends ActionBaseCommand {
this.pid = pids.get(0);
- // ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
-
- JsonObject root = new JsonObject();
- root.put("action", "source");
- root.put("filter", "*");
- File file = getActionFile(Long.toString(pid));
- try {
- IOHelper.writeText(root.toJson(), file);
- } catch (Exception e) {
- // ignore
- }
+ Path outputFile = prepareAction(Long.toString(pid), "source", root -> {
+ root.put("filter", "*");
+ });
JsonObject jo = waitForOutputFile(outputFile);
if (jo != null) {
@@ -136,7 +127,11 @@ public class CamelSourceAction extends ActionBaseCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ try {
+ Files.deleteIfExists(outputFile);
+ } catch (IOException e) {
+ // ignore
+ }
return 0;
}
@@ -170,8 +165,8 @@ public class CamelSourceAction extends ActionBaseCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
- return getJsonObject(outputFile);
+ protected JsonObject waitForOutputFile(Path outputFile) {
+ return getJsonObject((Path) outputFile);
}
public static String extractSourceName(String loc) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceTop.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceTop.java
index 0fe5dfc3cf1..056abeba550 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceTop.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelSourceTop.java
@@ -16,14 +16,14 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
@@ -67,14 +67,14 @@ public class CamelSourceTop extends ActionWatchCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "top-processors");
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ Files.writeString(f, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -147,7 +147,7 @@ public class CamelSourceTop extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -167,7 +167,7 @@ public class CamelSourceTop extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStartupRecorderAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStartupRecorderAction.java
index a85421d9949..47253bb0f9c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStartupRecorderAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStartupRecorderAction.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -27,8 +28,7 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -67,14 +67,14 @@ public class CamelStartupRecorderAction extends ActionWatchCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "startup-recorder");
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ Files.writeString(f, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -109,7 +109,7 @@ public class CamelStartupRecorderAction extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -147,7 +147,7 @@ public class CamelStartupRecorderAction extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStubAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStubAction.java
index f194883bcde..b9b63b692c4 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStubAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStubAction.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -30,9 +31,8 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.support.PatternHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -149,8 +149,8 @@ public class CamelStubAction extends ActionWatchCommand {
}
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "stub");
@@ -158,9 +158,9 @@ public class CamelStubAction extends ActionWatchCommand {
root.put("browse", browse);
root.put("filter", "*");
root.put("limit", limit);
- File file = getActionFile(Long.toString(pid));
+ Path file = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), file);
+ Files.writeString(file, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -231,7 +231,7 @@ public class CamelStubAction extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -341,7 +341,7 @@ public class CamelStubAction extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelThreadDump.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelThreadDump.java
index a2ee0e7901d..f996bee5f82 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelThreadDump.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelThreadDump.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -27,9 +28,8 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.support.PatternHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -97,14 +97,14 @@ public class CamelThreadDump extends ActionWatchCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "thread-dump");
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ Files.writeString(f, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -159,7 +159,7 @@ public class CamelThreadDump extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -210,7 +210,7 @@ public class CamelThreadDump extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelTraceAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelTraceAction.java
index c50c2b8f9f9..97b1d51c21e 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelTraceAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelTraceAction.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -207,9 +207,9 @@ public class CamelTraceAction extends ActionBaseCommand {
List<Long> pids = findPids(name);
for (long pid : pids) {
if ("clear".equals(action)) {
- File f = getTraceFile("" + pid);
- if (f.exists()) {
- IOHelper.writeText("{}", f);
+ Path f = getTraceFile("" + pid);
+ if (Files.exists(f)) {
+ Files.writeString(f, "{}");
}
} else {
JsonObject root = new JsonObject();
@@ -219,8 +219,8 @@ public class CamelTraceAction extends ActionBaseCommand {
} else if ("stop".equals(action)) {
root.put("enabled", "false");
}
- File f = getActionFile(Long.toString(pid));
- IOHelper.writeText(root.toJson(), f);
+ Path f = getActionFile(Long.toString(pid));
+ Files.writeString(f, root.toJson());
}
}
@@ -420,10 +420,10 @@ public class CamelTraceAction extends ActionBaseCommand {
private void positionTraceLatest(Map<Long, Pid> pids) throws Exception {
for (Pid pid : pids.values()) {
- File file = getTraceFile(pid.pid);
+ Path file = getTraceFile(pid.pid);
long position = -1;
- if (file.exists()) {
- pid.reader = new LineNumberReader(new FileReader(file));
+ if (Files.exists(file)) {
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
String line;
long counter = 0;
do {
@@ -443,7 +443,7 @@ public class CamelTraceAction extends ActionBaseCommand {
if (position != -1) {
IOHelper.close(pid.reader);
// re-create reader and forward to position
- pid.reader = new LineNumberReader(new FileReader(file));
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
while (--position > 0) {
pid.reader.readLine();
}
@@ -453,9 +453,9 @@ public class CamelTraceAction extends ActionBaseCommand {
private void tailTraceFiles(Map<Long, Pid> pids, int tail) throws Exception {
for (Pid pid : pids.values()) {
- File file = getTraceFile(pid.pid);
- if (file.exists()) {
- pid.reader = new LineNumberReader(new FileReader(file));
+ Path file = getTraceFile(pid.pid);
+ if (Files.exists(file)) {
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
String line;
if (tail <= 0) {
pid.fifo = new ArrayDeque<>();
@@ -524,12 +524,12 @@ public class CamelTraceAction extends ActionBaseCommand {
for (Pid pid : pids.values()) {
if (pid.reader == null) {
- File file = getTraceFile(pid.pid);
- if (file.exists()) {
- pid.reader = new LineNumberReader(new FileReader(file));
+ Path file = getTraceFile(pid.pid);
+ if (Files.exists(file)) {
+ pid.reader = new LineNumberReader(Files.newBufferedReader(file));
if (tail == 0) {
// only read new lines so forward to end of reader
- long size = file.length();
+ long size = Files.size(file);
pid.reader.skip(size);
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/LoggerAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/LoggerAction.java
index 8918740af8c..21b03bc596c 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/LoggerAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/LoggerAction.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -30,7 +31,6 @@ import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.LoggingLevelCompletionCandidates;
import org.apache.camel.dsl.jbang.core.common.PidNameAgeCompletionCandidates;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonObject;
import picocli.CommandLine;
@@ -75,11 +75,11 @@ public class LoggerAction extends ActionBaseCommand {
for (long pid : pids) {
JsonObject root = new JsonObject();
root.put("action", "logger");
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
root.put("command", "set-logging-level");
root.put("logger-name", logger);
root.put("logging-level", loggingLevel);
- IOHelper.writeText(root.toJson(), f);
+ Files.writeString(f, root.toJson());
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/RouteControllerAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/RouteControllerAction.java
index 831404e9af9..c6a78058895 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/RouteControllerAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/RouteControllerAction.java
@@ -16,7 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -28,8 +29,7 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonArray;
@@ -99,15 +99,15 @@ public class RouteControllerAction extends ActionWatchCommand {
this.pid = pids.get(0);
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "route-controller");
root.put("stacktrace", trace ? "true" : "false");
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ Files.writeString(f, root.toJson());
} catch (Exception e) {
// ignore
}
@@ -191,7 +191,7 @@ public class RouteControllerAction extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -249,7 +249,7 @@ public class RouteControllerAction extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
return getJsonObject(outputFile);
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java
index 39e59b11030..32f81f55eb0 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java
@@ -16,8 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.action;
-import java.io.File;
-import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@@ -25,9 +25,8 @@ import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.commands.Run;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.VersionHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
@@ -146,15 +145,15 @@ public class TransformMessageAction extends ActionWatchCommand {
if (source != null && source.startsWith("file:")) {
String s = source.substring(5);
s = StringHelper.beforeLast(s, ":", s); // remove line number
- File f = new File(s);
- if (!f.exists()) {
+ Path f = Path.of(s);
+ if (!Files.exists(f)) {
printer().printErr("Source file does not exist: " + f);
return -1;
}
}
if (template != null && template.startsWith("file:")) {
- File f = new File(template.substring(5));
- if (!f.exists()) {
+ Path f = Path.of(template.substring(5));
+ if (!Files.exists(f)) {
printer().printErr("Template file does not exist: " + f);
return -1;
}
@@ -177,12 +176,13 @@ public class TransformMessageAction extends ActionWatchCommand {
} finally {
if (pid > 0) {
// cleanup output file
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
// stop running camel as we are done
- File pidFile = new File(CommandLineHelper.getCamelDir(), Long.toString(pid));
- if (pidFile.exists()) {
- FileUtil.deleteFile(pidFile);
+ Path parent = CommandLineHelper.getCamelDir();
+ Path pidFile = parent.resolve(Long.toString(pid));
+ if (Files.exists(pidFile)) {
+ PathUtils.deleteFile(pidFile);
}
}
}
@@ -193,8 +193,8 @@ public class TransformMessageAction extends ActionWatchCommand {
@Override
protected Integer doWatchCall() throws Exception {
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(pid));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(pid));
+ PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "transform");
@@ -242,9 +242,9 @@ public class TransformMessageAction extends ActionWatchCommand {
}
root.put("options", arr);
}
- File f = getActionFile(Long.toString(pid));
+ Path f = getActionFile(Long.toString(pid));
try {
- IOHelper.writeText(root.toJson(), f);
+ PathUtils.writeTextSafely(root.toJson(), f);
} catch (Exception e) {
// ignore
}
@@ -257,12 +257,12 @@ public class TransformMessageAction extends ActionWatchCommand {
JsonObject cause = jo.getMap("exception");
if (message != null || cause != null) {
if (output != null) {
- File target = new File(output);
+ Path target = Path.of(output);
String json = jo.toJson();
if (pretty) {
json = Jsoner.prettyPrint(json, 2);
}
- IOHelper.writeText(json, target);
+ Files.writeString(target, json);
}
if (!showExchangeProperties && message != null) {
message.remove("exchangeProperties");
@@ -291,7 +291,7 @@ public class TransformMessageAction extends ActionWatchCommand {
}
// delete output file after use
- FileUtil.deleteFile(outputFile);
+ PathUtils.deleteFile(outputFile);
return 0;
}
@@ -344,17 +344,15 @@ public class TransformMessageAction extends ActionWatchCommand {
}
}
- protected JsonObject waitForOutputFile(File outputFile) {
+ protected JsonObject waitForOutputFile(Path outputFile) {
StopWatch watch = new StopWatch();
while (watch.taken() < timeout) {
try {
// give time for response to be ready
Thread.sleep(20);
- if (outputFile.exists()) {
- FileInputStream fis = new FileInputStream(outputFile);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ if (Files.exists(outputFile)) {
+ String text = Files.readString(outputFile);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (InterruptedException e) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraGet.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraGet.java
index bf93843c226..3b2c0136a94 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraGet.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraGet.java
@@ -16,9 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.infra;
-import java.io.File;
+import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
+import java.util.stream.Collectors;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
@@ -39,11 +41,20 @@ public class InfraGet extends InfraBaseCommand {
public Integer doCall() throws Exception {
String serviceToGet = serviceName.get(0);
boolean found = false;
- for (File jsonFile : CommandLineHelper.getCamelDir().listFiles(
- (dir, name) -> name.startsWith("infra-" + serviceToGet + "-") && name.endsWith(".json"))) {
- printer().println(Files.readString(jsonFile.toPath()));
- found = true;
- break;
+ try {
+ List<Path> jsonFiles = Files.list(CommandLineHelper.getCamelDir())
+ .filter(p -> {
+ String name = p.getFileName().toString();
+ return name.startsWith("infra-" + serviceToGet + "-") && name.endsWith(".json");
+ })
+ .collect(java.util.stream.Collectors.toList());
+
+ if (!jsonFiles.isEmpty()) {
+ printer().println(Files.readString(jsonFiles.get(0)));
+ found = true;
+ }
+ } catch (IOException e) {
+ // ignore
}
if (!found) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java
index c0a2d52c696..97a7e6a6a9f 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java
@@ -18,12 +18,14 @@ package org.apache.camel.dsl.jbang.core.commands.infra;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.stream.Collectors;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
@@ -52,12 +54,20 @@ public class InfraLog extends InfraBaseCommand {
List<Future<?>> futures = new ArrayList<>();
if (serviceName == null || serviceName.isEmpty()) {
// Log everything
- for (File logFile : CommandLineHelper.getCamelDir().listFiles(
- (dir, name) -> name.startsWith("infra-") && name.endsWith(".log"))) {
-
- String alias = logFile.getName().split("-")[1];
-
- createTailer(logFile, alias, futures);
+ try {
+ List<Path> logFiles = Files.list(CommandLineHelper.getCamelDir())
+ .filter(p -> {
+ String name = p.getFileName().toString();
+ return name.startsWith("infra-") && name.endsWith(".log");
+ })
+ .collect(java.util.stream.Collectors.toList());
+
+ for (Path logFile : logFiles) {
+ String alias = logFile.getFileName().toString().split("-")[1];
+ createTailer(logFile.toFile(), alias, futures);
+ }
+ } catch (IOException e) {
+ // ignore
}
if (futures.isEmpty()) {
@@ -68,10 +78,18 @@ public class InfraLog extends InfraBaseCommand {
} else {
String alias = serviceName.get(0);
- File logFile = Arrays.stream(CommandLineHelper.getCamelDir().listFiles(
- (dir, name) -> name.startsWith("infra-" + alias + "-") && name.endsWith(".log")))
- .findFirst()
- .orElse(null);
+ Path logFile = null;
+ try {
+ logFile = Files.list(CommandLineHelper.getCamelDir())
+ .filter(p -> {
+ String name = p.getFileName().toString();
+ return name.startsWith("infra-" + alias + "-") && name.endsWith(".log");
+ })
+ .findFirst()
+ .orElse(null);
+ } catch (IOException e) {
+ // ignore
+ }
if (logFile == null) {
printer().println("Log not found for service " + alias);
@@ -79,7 +97,7 @@ public class InfraLog extends InfraBaseCommand {
return -1;
}
- createTailer(logFile, alias, futures);
+ createTailer(logFile.toFile(), alias, futures);
}
for (Future<?> future : futures) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraPs.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraPs.java
index 973d3e08599..6b30df016d9 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraPs.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraPs.java
@@ -16,9 +16,13 @@
*/
package org.apache.camel.dsl.jbang.core.commands.infra;
-import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
@@ -36,10 +40,17 @@ public class InfraPs extends InfraBaseCommand {
public Integer doCall() throws Exception {
// retrieve running services to filter output
Set<String> runningAliases = new HashSet<>();
- for (File pidFile : CommandLineHelper.getCamelDir().listFiles(
- (dir, name) -> name.startsWith("infra-"))) {
- String runningServiceName = pidFile.getName().split("-")[1];
- runningAliases.add(runningServiceName);
+ try {
+ List<Path> pidFiles = Files.list(CommandLineHelper.getCamelDir())
+ .filter(p -> p.getFileName().toString().startsWith("infra-"))
+ .collect(java.util.stream.Collectors.toList());
+
+ for (Path pidFile : pidFiles) {
+ String runningServiceName = pidFile.getFileName().toString().split("-")[1];
+ runningAliases.add(runningServiceName);
+ }
+ } catch (IOException e) {
+ // ignore
}
return listServices(rows -> {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
index 8b80fb4370d..ee22b4f6a2b 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
@@ -16,7 +16,6 @@
*/
package org.apache.camel.dsl.jbang.core.commands.infra;
-import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
@@ -153,17 +152,17 @@ public class InfraRun extends InfraBaseCommand {
printer().println(jsonProperties);
String name = getLogFileName(testService, RuntimeUtil.getPid());
- File logFile = createFile(name);
+ Path logFile = createFile(name);
String jsonName = getJsonFileName(testService, RuntimeUtil.getPid());
- File jsonFile = createFile(jsonName);
- Files.write(jsonFile.toPath(), jsonProperties.getBytes());
+ Path jsonFile = createFile(jsonName);
+ Files.write(jsonFile, jsonProperties.getBytes());
if (Arrays.stream(actualService.getClass().getInterfaces()).filter(
c -> c.getName().contains("ContainerService")).count()
> 0) {
Object containerLogConsumer = cl.loadClass("org.apache.camel.test.infra.common.CamelLogConsumer")
- .getConstructor(Path.class, boolean.class).newInstance(logFile.toPath(), logToStdout);
+ .getConstructor(Path.class, boolean.class).newInstance(logFile, logToStdout);
actualService.getClass()
.getMethod("followLog", cl.loadClass("org.testcontainers.containers.output.BaseConsumer"))
@@ -182,10 +181,9 @@ public class InfraRun extends InfraBaseCommand {
sc.close();
}
- private static File createFile(String name) throws IOException {
- File logFile = new File(CommandLineHelper.getCamelDir(), name);
- logFile.createNewFile();
- logFile.deleteOnExit();
+ private static Path createFile(String name) throws IOException {
+ Path logFile = CommandLineHelper.getCamelDir().resolve(name);
+ Files.createFile(logFile);
return logFile;
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
index 001b212d40e..174a7833b7f 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
@@ -16,12 +16,14 @@
*/
package org.apache.camel.dsl.jbang.core.commands.infra;
-import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
+import java.util.stream.Collectors;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
-import org.apache.camel.util.FileUtil;
import picocli.CommandLine;
@CommandLine.Command(name = "stop",
@@ -41,15 +43,21 @@ public class InfraStop extends InfraBaseCommand {
boolean serviceStopped = false;
String pid = null;
- for (File pidFile : CommandLineHelper.getCamelDir().listFiles(
- (dir, name) -> name.startsWith("infra-" + serviceToStop + "-"))) {
+ try {
+ List<Path> pidFiles = Files.list(CommandLineHelper.getCamelDir())
+ .filter(p -> p.getFileName().toString().startsWith("infra-" + serviceToStop + "-"))
+ .collect(java.util.stream.Collectors.toList());
- String name = pidFile.getName();
- pid = name.substring(name.lastIndexOf("-") + 1, name.lastIndexOf('.'));
+ for (Path pidFile : pidFiles) {
+ String name = pidFile.getFileName().toString();
+ pid = name.substring(name.lastIndexOf("-") + 1, name.lastIndexOf('.'));
- FileUtil.deleteFile(pidFile);
-
- serviceStopped = true;
+ Files.deleteIfExists(pidFile);
+ serviceStopped = true;
+ break;
+ }
+ } catch (IOException e) {
+ // ignore
}
if (!serviceStopped) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListKafka.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListKafka.java
index edd2ff1f272..7171ff326d7 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListKafka.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListKafka.java
@@ -16,8 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.process;
-import java.io.File;
-import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -28,10 +28,9 @@ import com.github.freva.asciitable.Column;
import com.github.freva.asciitable.HorizontalAlign;
import com.github.freva.asciitable.OverflowBehaviour;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.dsl.jbang.core.common.PidNameAgeCompletionCandidates;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
-import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
@@ -102,14 +101,14 @@ public class ListKafka extends ProcessWatchCommand {
if (committed) {
// we ask for committed so need to do an action on-demand to get data
// ensure output file is deleted before executing action
- File outputFile = getOutputFile(Long.toString(ph.pid()));
- FileUtil.deleteFile(outputFile);
+ Path outputFile = getOutputFile(Long.toString(ph.pid()));
+ PathUtils.deleteFile(outputFile);
JsonObject root2 = new JsonObject();
root2.put("action", "kafka");
- File file = getActionFile(Long.toString(ph.pid()));
+ Path file = getActionFile(Long.toString(ph.pid()));
try {
- IOHelper.writeText(root2.toJson(), file);
+ PathUtils.writeTextSafely(root2.toJson(), file);
} catch (Exception e) {
// ignore
}
@@ -296,7 +295,7 @@ public class ListKafka extends ProcessWatchCommand {
}
}
- private JsonObject waitForOutputFile(File outputFile) {
+ private JsonObject waitForOutputFile(Path outputFile) {
JsonObject answer = null;
StopWatch watch = new StopWatch();
@@ -305,10 +304,8 @@ public class ListKafka extends ProcessWatchCommand {
// give time for response to be ready
Thread.sleep(100);
- if (outputFile.exists()) {
- FileInputStream fis = new FileInputStream(outputFile);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ if (Files.exists(outputFile)) {
+ String text = Files.readString(outputFile);
answer = (JsonObject) Jsoner.deserialize(text);
}
} catch (Exception e) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ProcessBaseCommand.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ProcessBaseCommand.java
index 1274c448d33..845d5c25d46 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ProcessBaseCommand.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ProcessBaseCommand.java
@@ -16,8 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands.process;
-import java.io.File;
-import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -26,7 +26,6 @@ import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.util.FileUtil;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.json.JsonObject;
import org.apache.camel.util.json.Jsoner;
@@ -95,11 +94,9 @@ abstract class ProcessBaseCommand extends CamelCommand {
JsonObject loadStatus(long pid) {
try {
- File f = getStatusFile(Long.toString(pid));
- if (f != null && f.exists()) {
- FileInputStream fis = new FileInputStream(f);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ Path f = getStatusFile(Long.toString(pid));
+ if (f != null && Files.exists(f)) {
+ String text = Files.readString(f);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (Exception e) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/StopProcess.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/StopProcess.java
index 1d0b9256f53..6a5b66bdaa9 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/StopProcess.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/StopProcess.java
@@ -16,12 +16,13 @@
*/
package org.apache.camel.dsl.jbang.core.commands.process;
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
-import org.apache.camel.util.FileUtil;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import picocli.CommandLine;
import picocli.CommandLine.Command;
@@ -46,10 +47,10 @@ public class StopProcess extends ProcessBaseCommand {
// stop by deleting the pid file
for (Long pid : pids) {
- File pidFile = new File(CommandLineHelper.getCamelDir(), Long.toString(pid));
- if (pidFile.exists()) {
+ Path pidFile = CommandLineHelper.getCamelDir().resolve(Long.toString(pid));
+ if (Files.exists(pidFile)) {
printer().println("Shutting down Camel integration (PID: " + pid + ")");
- FileUtil.deleteFile(pidFile);
+ PathUtils.deleteFile(pidFile);
}
}
for (Long pid : pids) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/CamelUpdate.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/CamelUpdate.java
index 2469a55e2fd..591275beb6a 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/CamelUpdate.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/CamelUpdate.java
@@ -16,7 +16,6 @@
*/
package org.apache.camel.dsl.jbang.core.commands.update;
-import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystem;
@@ -56,7 +55,7 @@ public final class CamelUpdate implements Update {
= downloader.downloadArtifact("org.apache.camel.upgrade", getArtifactCoordinates(), updateMixin.version);
try {
- recipes = getRecipesInJar(mavenArtifact.getFile());
+ recipes = getRecipesInJar(mavenArtifact.getFile().toPath());
} catch (IOException ex) {
throw new CamelUpdateException(ex);
}
@@ -76,11 +75,10 @@ public final class CamelUpdate implements Update {
return activeRecipes;
}
- private List<Recipe> getRecipesInJar(File jar) throws IOException {
+ private List<Recipe> getRecipesInJar(Path jar) throws IOException {
List<Recipe> recipes = new ArrayList<>();
- Path jarPath = jar.toPath();
- try (FileSystem fileSystem = FileSystems.newFileSystem(jarPath, (ClassLoader) null)) {
+ try (FileSystem fileSystem = FileSystems.newFileSystem(jar, (ClassLoader) null)) {
Path recipePath = fileSystem.getPath("META-INF", "rewrite");
if (Files.exists(recipePath)) {
try (Stream<Path> walk = Files.walk(recipePath)) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
index 129bfc2f71d..31736eaa4d0 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandLineHelper.java
@@ -16,17 +16,17 @@
*/
package org.apache.camel.dsl.jbang.core.common;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.Properties;
import java.util.function.Consumer;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.OrderedProperties;
import picocli.CommandLine;
@@ -35,7 +35,7 @@ import picocli.CommandLine;
*/
public final class CommandLineHelper {
- private static volatile String homeDir = System.getProperty("user.home");
+ private static volatile Path homeDir = Paths.get(System.getProperty("user.home"));
public static final String USER_CONFIG = ".camel-jbang-user.properties";
public static final String LOCAL_USER_CONFIG = "camel-jbang-user.properties";
public static final String CAMEL_DIR = ".camel";
@@ -46,11 +46,11 @@ public final class CommandLineHelper {
}
public static void augmentWithUserConfiguration(CommandLine commandLine) {
- File file = getUserConfigurationFile();
- if (file.isFile() && file.exists()) {
+ Path file = getUserConfigurationFile();
+ if (Files.isRegularFile(file) && Files.exists(file)) {
Properties properties = new Properties();
- try {
- properties.load(new FileReader(file));
+ try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
+ properties.load(reader);
} catch (IOException e) {
commandLine.setDefaultValueProvider(new CamelUserConfigDefaultValueProvider(file));
}
@@ -59,10 +59,10 @@ public final class CommandLineHelper {
}
}
- private static File getUserConfigurationFile() {
- File file;
- if (Files.exists(Path.of(LOCAL_USER_CONFIG))) {
- file = new File(LOCAL_USER_CONFIG);
+ private static Path getUserConfigurationFile() {
+ Path file;
+ if (Files.exists(Paths.get(LOCAL_USER_CONFIG))) {
+ file = Paths.get(LOCAL_USER_CONFIG);
} else {
file = getUserPropertyFile(false);
}
@@ -70,9 +70,9 @@ public final class CommandLineHelper {
}
public static void createPropertyFile(boolean local) throws IOException {
- File file = getUserPropertyFile(local);
- if (!file.exists()) {
- file.createNewFile();
+ Path file = getUserPropertyFile(local);
+ if (!Files.exists(file)) {
+ Files.createFile(file);
}
}
@@ -81,32 +81,28 @@ public final class CommandLineHelper {
}
public static void loadProperties(Consumer<Properties> consumer, boolean local) {
- File file = getUserPropertyFile(local);
- if (file.isFile() && file.exists()) {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(file);
+ Path file = getUserPropertyFile(local);
+ if (Files.isRegularFile(file) && Files.exists(file)) {
+ try (InputStream is = Files.newInputStream(file)) {
Properties prop = new OrderedProperties();
- prop.load(fis);
+ prop.load(is);
consumer.accept(prop);
} catch (Exception e) {
throw new RuntimeException("Cannot load user configuration: " + file);
- } finally {
- IOHelper.close(fis);
}
}
}
public static void storeProperties(Properties properties, Printer printer, boolean local) {
- File file = getUserPropertyFile(local);
- if (file.isFile() && file.exists()) {
- try (FileOutputStream fos = new FileOutputStream(file)) {
- properties.store(fos, null);
+ Path file = getUserPropertyFile(local);
+ if (Files.isRegularFile(file) && Files.exists(file)) {
+ try (OutputStream os = Files.newOutputStream(file)) {
+ properties.store(os, null);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} else {
- printer.println(file.getName() + " does not exist");
+ printer.println(file.getFileName() + " does not exist");
}
}
@@ -116,11 +112,11 @@ public final class CommandLineHelper {
* @param local
* @return
*/
- private static File getUserPropertyFile(boolean local) {
+ private static Path getUserPropertyFile(boolean local) {
if (local) {
- return new File(LOCAL_USER_CONFIG);
+ return Paths.get(LOCAL_USER_CONFIG);
} else {
- return new File(homeDir, USER_CONFIG);
+ return homeDir.resolve(USER_CONFIG);
}
}
@@ -129,7 +125,7 @@ public final class CommandLineHelper {
*
* @return the user home directory.
*/
- public static String getHomeDir() {
+ public static Path getHomeDir() {
return homeDir;
}
@@ -140,7 +136,7 @@ public final class CommandLineHelper {
* @param homeDir the home directory.
*/
public static void useHomeDir(String homeDir) {
- CommandLineHelper.homeDir = homeDir;
+ CommandLineHelper.homeDir = Paths.get(homeDir);
}
/**
@@ -148,8 +144,8 @@ public final class CommandLineHelper {
*
* @return file pointing to the camel directory.
*/
- public static File getCamelDir() {
- return new File(homeDir, CAMEL_DIR);
+ public static Path getCamelDir() {
+ return homeDir.resolve(CAMEL_DIR);
}
/**
@@ -157,14 +153,14 @@ public final class CommandLineHelper {
*
* @return file pointing to the working directory.
*/
- public static File getWorkDir() {
- return new File(CAMEL_JBANG_WORK_DIR);
+ public static Path getWorkDir() {
+ return Paths.get(CAMEL_JBANG_WORK_DIR);
}
private static class CamelUserConfigDefaultValueProvider extends CommandLine.PropertiesDefaultProvider {
- public CamelUserConfigDefaultValueProvider(File file) {
- super(file);
+ public CamelUserConfigDefaultValueProvider(Path file) {
+ super(file.toFile());
}
public CamelUserConfigDefaultValueProvider(Properties properties) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PathUtils.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PathUtils.java
new file mode 100644
index 00000000000..59780c8218c
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PathUtils.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.common;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.stream.Stream;
+
+/**
+ * Utility methods for working with Path and File objects.
+ */
+public final class PathUtils {
+
+ private PathUtils() {
+ // Utility class
+ }
+
+ /**
+ * Delete a file if it exists.
+ *
+ * @param path the path to delete
+ * @return true if the file was deleted, false otherwise
+ */
+ public static boolean deleteFile(Path path) {
+ try {
+ return Files.deleteIfExists(path);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Safely write text to a file, ignoring any exceptions.
+ *
+ * @param text the text to write
+ * @param path the path to write to
+ * @return true if the write was successful, false otherwise
+ */
+ public static boolean writeTextSafely(String text, Path path) {
+ try {
+ Files.writeString(path, text);
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Copy content from an InputStream to a Path.
+ *
+ * @param input the input stream to copy from
+ * @param target the target path to copy to
+ * @param closeInput whether to close the input stream after copying
+ * @throws IOException if an I/O error occurs
+ */
+ public static void copyFromStream(InputStream input, Path target, boolean closeInput) throws IOException {
+ try {
+ // Ensure parent directories exist
+ Path parent = target.getParent();
+ if (parent != null && !Files.exists(parent)) {
+ Files.createDirectories(parent);
+ }
+
+ // Copy the stream to the target path
+ Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
+ } finally {
+ if (closeInput && input != null) {
+ input.close();
+ }
+ }
+ }
+
+ /**
+ * Delete a directory and all its contents.
+ *
+ * @param directory the directory to delete
+ * @return true if the directory was deleted, false otherwise
+ */
+ public static boolean deleteDirectory(Path directory) {
+ if (directory == null || !Files.exists(directory)) {
+ return false;
+ }
+
+ try {
+ Files.walk(directory)
+ .sorted(java.util.Comparator.reverseOrder())
+ .forEach(path -> {
+ try {
+ Files.deleteIfExists(path);
+ } catch (IOException e) {
+ // Ignore
+ }
+ });
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Copy a directory and all its contents to another directory.
+ *
+ * @param sourceDir the source directory
+ * @param targetDir the target directory
+ * @throws IOException if an I/O error occurs
+ */
+ public static void copyDirectory(Path sourceDir, Path targetDir) throws IOException {
+ if (!Files.exists(sourceDir) || !Files.isDirectory(sourceDir)) {
+ return;
+ }
+
+ // Create target directory if it doesn't exist
+ if (!Files.exists(targetDir)) {
+ Files.createDirectories(targetDir);
+ }
+
+ // Copy all files and subdirectories
+ try (Stream<Path> stream = Files.walk(sourceDir)) {
+ stream.forEach(source -> {
+ try {
+ Path target = targetDir.resolve(sourceDir.relativize(source));
+ if (Files.isDirectory(source)) {
+ if (!Files.exists(target)) {
+ Files.createDirectories(target);
+ }
+ } else {
+ Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+ }
+
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
index fe9e504aa15..7ef9b8cada3 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java
@@ -16,11 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.common;
-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.StandardOpenOption;
import java.util.Optional;
import java.util.Properties;
@@ -174,12 +173,10 @@ public final class PluginHelper {
private static JsonObject getPluginConfig() {
try {
- File f = new File(CommandLineHelper.getHomeDir(), PLUGIN_CONFIG);
- if (f.exists()) {
- try (FileInputStream fis = new FileInputStream(f)) {
- String text = IOHelper.loadText(fis);
- return (JsonObject) Jsoner.deserialize(text);
- }
+ Path f = CommandLineHelper.getHomeDir().resolve(PLUGIN_CONFIG);
+ if (Files.exists(f)) {
+ String text = Files.readString(f);
+ return (JsonObject) Jsoner.deserialize(text);
}
} catch (Exception e) {
// ignore
@@ -189,10 +186,10 @@ public final class PluginHelper {
}
public static JsonObject createPluginConfig() {
- File f = new File(CommandLineHelper.getHomeDir(), PLUGIN_CONFIG);
+ Path f = CommandLineHelper.getHomeDir().resolve(PLUGIN_CONFIG);
JsonObject config = Jsoner.deserialize("{ \"plugins\": {} }", new JsonObject());
try {
- Files.writeString(f.toPath(), config.toJson(),
+ Files.writeString(f, config.toJson(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
@@ -204,9 +201,9 @@ public final class PluginHelper {
}
public static void savePluginConfig(JsonObject plugins) {
- File f = new File(CommandLineHelper.getHomeDir(), PLUGIN_CONFIG);
+ Path f = CommandLineHelper.getHomeDir().resolve(PLUGIN_CONFIG);
try {
- Files.writeString(f.toPath(), plugins.toJson(),
+ Files.writeString(f, plugins.toJson(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeUtil.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeUtil.java
index 5fc9357f757..cd9c21856ba 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeUtil.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeUtil.java
@@ -17,7 +17,6 @@
package org.apache.camel.dsl.jbang.core.common;
import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
@@ -140,21 +139,25 @@ public final class RuntimeUtil {
}
}
- public static void loadProperties(Properties properties, File file) throws IOException {
- if (file.exists()) {
- try (final FileInputStream fileInputStream = new FileInputStream(file)) {
- properties.load(fileInputStream);
+ public static void loadProperties(Properties properties, Path path) throws IOException {
+ if (Files.exists(path)) {
+ try (final var inputStream = Files.newInputStream(path)) {
+ properties.load(inputStream);
}
}
}
- public static List<String> loadPropertiesLines(File file) throws IOException {
- if (!file.exists()) {
+ public static void loadProperties(Properties properties, File file) throws IOException {
+ loadProperties(properties, file.toPath());
+ }
+
+ public static List<String> loadPropertiesLines(Path path) throws IOException {
+ if (!Files.exists(path)) {
return new ArrayList<>();
}
List<String> lines = new ArrayList<>();
- for (String line : Files.readAllLines(file.toPath())) {
+ for (String line : Files.readAllLines(path)) {
// need to use java.util.Properties to read raw value and un-escape
Properties prop = new OrderedProperties();
prop.load(new StringReader(line));
@@ -169,6 +172,10 @@ public final class RuntimeUtil {
return lines;
}
+ public static List<String> loadPropertiesLines(File file) throws IOException {
+ return loadPropertiesLines(file.toPath());
+ }
+
public static List<String> getCommaSeparatedPropertyAsList(Properties props, String key, List<String> defaultValue) {
var value = props.getProperty(key);
return Optional.ofNullable(value)
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/SourceHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/SourceHelper.java
index 819fed24be1..f4a0657f25a 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/SourceHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/SourceHelper.java
@@ -17,9 +17,10 @@
package org.apache.camel.dsl.jbang.core.common;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -131,18 +132,18 @@ public class SourceHelper {
}
case UNKNOWN -> {
if (isAcceptedSourceFile(fileExtension)) {
- File sourceFile = new File(source);
- if (!sourceFile.exists()) {
+ Path sourcePath = Paths.get(source);
+ if (!Files.exists(sourcePath)) {
throw new FileNotFoundException("Source file '%s' does not exist".formatted(source));
}
- if (!sourceFile.isDirectory()) {
- try (FileInputStream fis = new FileInputStream(sourceFile)) {
+ if (!Files.isDirectory(sourcePath)) {
+ try (var is = Files.newInputStream(sourcePath)) {
resolved.add(
new Source(
sourceScheme,
fileName,
- IOHelper.loadText(fis),
+ IOHelper.loadText(is),
fileExtension, compression));
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/VersionHelper.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/VersionHelper.java
index 19c0e0086d2..692336fd3fe 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/VersionHelper.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/VersionHelper.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.dsl.jbang.core.common;
-import java.io.File;
-import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
-import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
public final class VersionHelper {
@@ -35,13 +35,11 @@ public final class VersionHelper {
if (homeDir == null || homeDir.isBlank()) {
// fallback to .jbang cache that has a list of latest version
path = ".jbang/cache/";
- homeDir = CommandLineHelper.getHomeDir();
+ homeDir = CommandLineHelper.getHomeDir().toString();
}
- File file = new File(homeDir, path + "version.txt");
- if (file.exists() && file.isFile()) {
- FileInputStream fis = new FileInputStream(file);
- String text = IOHelper.loadText(fis);
- IOHelper.close(fis);
+ Path file = Paths.get(homeDir).resolve(path + "version.txt");
+ if (Files.exists(file) && Files.isRegularFile(file)) {
+ String text = Files.readString(file);
text = text.trim();
return text;
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportMainApplicationProperties.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportMainApplicationProperties.java
index 4a44484d77b..42f77aaff17 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportMainApplicationProperties.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportMainApplicationProperties.java
@@ -68,7 +68,7 @@ class ExportMainApplicationProperties {
public void shouldExportUserPropertyOverride(RuntimeType rt) throws Exception {
// prepare as we need application.properties that contains configuration to be overridden
Files.copy(
- new File("src/test/resources/sample-application.properties").toPath(),
+ Paths.get("src/test/resources/sample-application.properties"),
profile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportTest.java
index 9638633a61d..78c46377232 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ExportTest.java
@@ -29,7 +29,6 @@ import java.util.Properties;
import java.util.stream.Stream;
import org.apache.camel.dsl.jbang.core.common.RuntimeType;
-import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
@@ -55,7 +54,7 @@ class ExportTest {
@AfterEach
public void end() throws IOException {
// force removing, since deleteOnExit is not removing.
- FileUtil.removeDir(workingDir);
+ org.apache.camel.util.FileUtil.removeDir(workingDir);
}
private static Stream<Arguments> runtimeProvider() {
@@ -327,7 +326,7 @@ class ExportTest {
}
private Model readMavenModel() throws Exception {
- File f = workingDir.toPath().resolve("pom.xml").toFile();
+ File f = new File(workingDir, "pom.xml");
Assertions.assertTrue(f.isFile(), "Not a pom.xml file: " + f);
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
Model model = mavenReader.read(new FileReader(f));
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/InitTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/InitTest.java
index 184d3a1c09f..aed11b75f11 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/InitTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/InitTest.java
@@ -16,14 +16,13 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
-import org.apache.camel.util.FileUtil;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -34,17 +33,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class InitTest {
- private File workingDir;
+ private Path workingDir;
@BeforeEach
public void beforeEach() throws IOException {
Path base = Paths.get("target");
- workingDir = Files.createTempDirectory(base, "camel-init").toFile();
+ workingDir = Files.createTempDirectory(base, "camel-init");
}
@AfterEach
- public void afterEach() {
- FileUtil.removeDir(workingDir);
+ public void afterEach() throws IOException {
+ PathUtils.deleteDirectory(workingDir);
}
@Test
@@ -55,9 +54,9 @@ class InitTest {
int exit = initCommand.doCall();
assertEquals(0, exit);
- File f = new File("my.camel.yaml");
- assertTrue(f.exists(), "Yaml file not created: " + f);
- f.delete();
+ Path f = Paths.get("my.camel.yaml");
+ assertTrue(Files.exists(f), "Yaml file not created: " + f);
+ Files.delete(f);
}
@Test
@@ -68,14 +67,14 @@ class InitTest {
int exit = initCommand.doCall();
assertEquals(0, exit);
- File f = new File(workingDir, "my.camel.yaml");
- assertTrue(f.exists(), "Yaml file not created: " + f);
+ Path f = workingDir.resolve("my.camel.yaml");
+ assertTrue(Files.exists(f), "Yaml file not created: " + f);
}
@Test
void initYamlInDirectoryWithExistingFiles() throws Exception {
- Path existingFileInTargetDirectory = Files.createFile(new File(workingDir, "anotherfile.txt").toPath());
- assertTrue(existingFileInTargetDirectory.toFile().exists(), "Cannot create file to setup context");
+ Path existingFileInTargetDirectory = Files.createFile(workingDir.resolve("anotherfile.txt"));
+ assertTrue(Files.exists(existingFileInTargetDirectory), "Cannot create file to setup context");
Init initCommand = new Init(new CamelJBangMain());
CommandLine.populateCommand(initCommand, "my.camel.yaml", "--dir=" + workingDir);
@@ -83,16 +82,16 @@ class InitTest {
int exit = initCommand.doCall();
assertEquals(0, exit);
- File f = new File(workingDir, "my.camel.yaml");
- assertTrue(f.exists(), "Yaml file not created: " + f);
+ Path f = workingDir.resolve("my.camel.yaml");
+ assertTrue(Files.exists(f), "Yaml file not created: " + f);
- assertTrue(existingFileInTargetDirectory.toFile().exists(), "The file in the target folder has been deleted");
+ assertTrue(Files.exists(existingFileInTargetDirectory), "The file in the target folder has been deleted");
}
@Test
void initJavaWithPackageName() throws Exception {
Path packageFolderInsideMavenProject
- = Files.createDirectories(new File(workingDir, "src/main/java/com/acme/demo").toPath());
+ = Files.createDirectories(workingDir.resolve("src/main/java/com/acme/demo"));
Init initCommand = new Init(new CamelJBangMain());
CommandLine.populateCommand(initCommand, "MyRoute.java", "--dir=" + packageFolderInsideMavenProject);
@@ -100,13 +99,13 @@ class InitTest {
int exit = initCommand.doCall();
assertEquals(0, exit);
- File f = new File(packageFolderInsideMavenProject.toFile(), "MyRoute.java");
- assertTrue(f.exists(), "Java file not created: " + f);
- List<String> lines = Files.readAllLines(f.toPath());
+ Path f = packageFolderInsideMavenProject.resolve("MyRoute.java");
+ assertTrue(Files.exists(f), "Java file not created: " + f);
+ List<String> lines = Files.readAllLines(f);
assertEquals("package com.acme.demo;", lines.get(0));
assertEquals("", lines.get(1));
assertEquals("import org.apache.camel.builder.RouteBuilder;", lines.get(2));
- f.delete();
+ Files.delete(f);
}
@Test
@@ -117,10 +116,10 @@ class InitTest {
int exit = initCommand.doCall();
assertEquals(0, exit);
- File f = new File("MyRoute.java");
- assertTrue(f.exists(), "Java file not created: " + f);
- List<String> lines = Files.readAllLines(f.toPath());
+ Path f = Paths.get("MyRoute.java");
+ assertTrue(Files.exists(f), "Java file not created: " + f);
+ List<String> lines = Files.readAllLines(f);
assertEquals("import org.apache.camel.builder.RouteBuilder;", lines.get(0));
- f.delete();
+ Files.delete(f);
}
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/TransformTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/TransformTest.java
index e13048f3862..fbe2ab81005 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/TransformTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/TransformTest.java
@@ -16,15 +16,13 @@
*/
package org.apache.camel.dsl.jbang.core.commands;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
-import org.apache.camel.util.FileUtil;
+import org.apache.camel.dsl.jbang.core.common.PathUtils;
import org.apache.camel.util.IOHelper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@@ -34,32 +32,31 @@ import picocli.CommandLine;
class TransformTest {
- private File workingDir;
+ private Path workingDir;
@BeforeEach
public void setup() throws IOException {
Path base = Paths.get("target");
- workingDir = Files.createTempDirectory(base, "camel-transform").toFile();
+ workingDir = Files.createTempDirectory(base, "camel-transform");
}
@AfterEach
public void end() throws IOException {
// force removing, since deleteOnExit is not removing.
- FileUtil.removeDir(workingDir);
+ PathUtils.deleteDirectory(workingDir);
}
@Test
public void shouldTransformToYaml() throws Exception {
- String name = workingDir + "/transform.yaml";
- File out = new File(name);
+ Path outPath = workingDir.resolve("transform.yaml");
- String[] args = new String[] { "--output=" + out.getPath() };
+ String[] args = new String[] { "--output=" + outPath.toString() };
TransformRoute command = createCommand(new String[] { "src/test/resources/transform.xml" }, args);
int exit = command.doCall();
Assertions.assertEquals(0, exit);
- Assertions.assertTrue(out.exists());
- String data = IOHelper.loadText(new FileInputStream(out));
+ Assertions.assertTrue(Files.exists(outPath));
+ String data = Files.readString(outPath);
String expected
= IOHelper.stripLineComments(Paths.get("src/test/resources/transform-out.yaml"), "#", true);
Assertions.assertEquals(expected, data);
@@ -67,16 +64,15 @@ class TransformTest {
@Test
public void shouldTransformBlueprintToYaml() throws Exception {
- String name = workingDir + "/blueprint.yaml";
- File out = new File(name);
+ Path outPath = workingDir.resolve("blueprint.yaml");
- String[] args = new String[] { "--output=" + out.getPath() };
+ String[] args = new String[] { "--output=" + outPath.toString() };
TransformRoute command = createCommand(new String[] { "src/test/resources/blueprint.xml" }, args);
int exit = command.doCall();
Assertions.assertEquals(0, exit);
- Assertions.assertTrue(out.exists());
- String data = IOHelper.loadText(new FileInputStream(out));
+ Assertions.assertTrue(Files.exists(outPath));
+ String data = Files.readString(outPath);
String expected
= IOHelper.stripLineComments(Paths.get("src/test/resources/blueprint-out.yaml"), "#", true);
Assertions.assertEquals(expected, data);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
index 1ff2cba6658..83cb4e425b9 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
@@ -21,6 +21,8 @@ import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
@@ -262,7 +264,7 @@ public class KubernetesExport extends Export {
var applicationProfileProperties = new String[0];
if (this.profile != null) {
// override from profile specific configuration
- applicationProfileProperties = extractPropertiesTraits(new File("application-" + profile + ".properties"));
+ applicationProfileProperties = extractPropertiesTraits(Paths.get("application-" + profile + ".properties"));
}
Traits traitsSpec = getTraitSpec(applicationProfileProperties, applicationProperties);
@@ -334,8 +336,8 @@ public class KubernetesExport extends Export {
addDependencies("org.apache.camel:camel-health", "org.apache.camel:camel-platform-http-main");
}
- File settings = new File(CommandLineHelper.getWorkDir(), Run.RUN_SETTINGS_FILE);
- var jkubeVersion = jkubeMavenPluginVersion(settings, mapBuildProperties());
+ Path settingsPath = CommandLineHelper.getWorkDir().resolve(Run.RUN_SETTINGS_FILE);
+ var jkubeVersion = jkubeMavenPluginVersion(settingsPath, mapBuildProperties());
buildProperties.add("jkube.version=%s".formatted(jkubeVersion));
setContainerHealthPaths();
@@ -358,17 +360,17 @@ public class KubernetesExport extends Export {
var ymlFragment = KubernetesHelper.dumpYaml(map);
var kind = map.get("kind").toString().toLowerCase();
safeCopy(new ByteArrayInputStream(ymlFragment.getBytes(StandardCharsets.UTF_8)),
- new File(exportDir + "/src/main/jkube/%s.yml".formatted(kind)));
+ Paths.get(exportDir, "src/main/jkube", kind + ".yml"));
}
context.doWithConfigurationResources((fileName, content) -> {
try {
- File target = new File(exportDir + SRC_MAIN_RESOURCES + fileName);
- if (target.exists()) {
- Files.writeString(target.toPath(), "%n%s".formatted(content), StandardOpenOption.APPEND);
+ Path targetPath = Paths.get(exportDir, "src/main/resources", fileName);
+ if (Files.exists(targetPath)) {
+ Files.writeString(targetPath, "%n%s".formatted(content), StandardOpenOption.APPEND);
} else {
- safeCopy(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), target);
+ safeCopy(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), targetPath);
}
} catch (Exception e) {
printer().printf("Failed to create configuration resource %s - %s%n",
@@ -516,16 +518,20 @@ public class KubernetesExport extends Export {
return imageRegistry;
}
- protected String[] extractPropertiesTraits(File file) throws Exception {
- if (file.exists()) {
+ protected String[] extractPropertiesTraits(Path path) throws Exception {
+ if (Files.exists(path)) {
Properties prop = new CamelCaseOrderedProperties();
- RuntimeUtil.loadProperties(prop, file);
+ RuntimeUtil.loadProperties(prop, path);
return TraitHelper.extractTraitsFromProperties(prop);
} else {
return null;
}
}
+ protected String[] extractPropertiesTraits(File file) throws Exception {
+ return extractPropertiesTraits(file.toPath());
+ }
+
protected String getProjectName() {
if (name != null) {
return KubernetesHelper.sanitize(name);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesHelper.java b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesHelper.java
index 5c89bb77435..9a8f9b160f4 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesHelper.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesHelper.java
@@ -19,6 +19,8 @@ package org.apache.camel.dsl.jbang.core.commands.kubernetes;
import java.io.File;
import java.io.FileNotFoundException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
@@ -269,6 +271,23 @@ public final class KubernetesHelper {
.formatted(extension, workingDir.toPath().toString()));
}
+ public static Path resolveKubernetesManifestPath(String clusterType, Path workingDir) throws FileNotFoundException {
+ return resolveKubernetesManifestPath(clusterType, workingDir, "yml");
+ }
+
+ public static Path resolveKubernetesManifestPath(String clusterType, Path workingDir, String extension)
+ throws FileNotFoundException {
+
+ var manifestPath = getKubernetesManifestPath(clusterType, workingDir, extension);
+ if (Files.exists(manifestPath)) {
+ return manifestPath;
+ }
+
+ throw new FileNotFoundException(
+ "Unable to resolve Kubernetes manifest file type `%s` in folder: %s"
+ .formatted(extension, workingDir.toString()));
+ }
+
public static String getPodPhase(Pod pod) {
return Optional.ofNullable(pod).map(p -> p.getStatus().getPhase()).orElse("Unknown");
}
@@ -290,4 +309,18 @@ public final class KubernetesHelper {
}
return new File(workingDir, "%s.%s".formatted(manifestFile, extension));
}
+
+ public static Path getKubernetesManifestPath(String clusterType, Path workingDir) {
+ return getKubernetesManifestPath(clusterType, workingDir, "yml");
+ }
+
+ public static Path getKubernetesManifestPath(String clusterType, Path workingDir, String extension) {
+ String manifestFile;
+ if (ClusterType.KIND.isEqualTo(clusterType) || ClusterType.MINIKUBE.isEqualTo(clusterType)) {
+ manifestFile = "kubernetes";
+ } else {
+ manifestFile = Optional.ofNullable(clusterType).map(String::toLowerCase).orElse("kubernetes");
+ }
+ return workingDir.resolve("%s.%s".formatted(manifestFile, extension));
+ }
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesRun.java b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesRun.java
index 418750fc82f..429053d89f2 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesRun.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesRun.java
@@ -17,10 +17,12 @@
package org.apache.camel.dsl.jbang.core.commands.kubernetes;
-import java.io.File;
import java.io.FileFilter;
-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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -315,18 +317,21 @@ public class KubernetesRun extends KubernetesBaseCommand {
return exit;
}
- File manifest;
+ Path manifestPath;
switch (output) {
case "yaml" -> {
if (ksvcEnabled) {
// trick the clusterType to be able to read from the jkube source directory
- manifest = KubernetesHelper.resolveKubernetesManifest("service", workingDir + "/src/main/jkube");
+ manifestPath = KubernetesHelper.resolveKubernetesManifestPath("service",
+ Paths.get(workingDir, "src/main/jkube"));
} else {
- manifest = KubernetesHelper.resolveKubernetesManifest(clusterType, workingDir + "/target/kubernetes");
+ manifestPath = KubernetesHelper.resolveKubernetesManifestPath(clusterType,
+ Paths.get(workingDir, "target/kubernetes"));
}
}
case "json" ->
- manifest = KubernetesHelper.resolveKubernetesManifest(clusterType, workingDir + "/target/kubernetes",
+ manifestPath = KubernetesHelper.resolveKubernetesManifestPath(clusterType,
+ Paths.get(workingDir, "target/kubernetes"),
"json");
default -> {
printer().printErr("Unsupported output format '%s' (supported: yaml, json)".formatted(output));
@@ -334,8 +339,8 @@ public class KubernetesRun extends KubernetesBaseCommand {
}
}
- try (FileInputStream fis = new FileInputStream(manifest)) {
- super.printer().println(IOHelper.loadText(fis));
+ try (InputStream is = Files.newInputStream(manifestPath)) {
+ super.printer().println(IOHelper.loadText(is));
}
return 0;
diff --git a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/RouteTrait.java b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/RouteTrait.java
index b5169e888bd..47def435890 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/RouteTrait.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/RouteTrait.java
@@ -16,10 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.kubernetes.traits;
-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.util.Optional;
import io.fabric8.kubernetes.api.model.IntOrString;
@@ -123,14 +124,14 @@ public class RouteTrait extends BaseTrait {
private String getContent(String value) {
if (value.startsWith("file:")) {
String filePath = StringHelper.after(value, ":");
- final File file = new File(filePath);
- if (!file.exists()) {
+ final Path path = Paths.get(filePath);
+ if (!Files.exists(path)) {
throw new RuntimeException(filePath + " does not exist");
}
- if (file.isDirectory()) {
+ if (Files.isDirectory(path)) {
throw new RuntimeException(filePath + " is not a file");
}
- try (InputStream is = new FileInputStream(file)) {
+ try (InputStream is = Files.newInputStream(path)) {
return IOHelper.loadText(is);
} catch (IOException e) {
throw new RuntimeException(e);