import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScriptLauncher {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java ScriptLauncher <json_file>");
return;
}
String jsonFilePath = args[0];
JSONObject jsonObject = parseJsonObject(jsonFilePath);
if (jsonObject == null) {
System.err.println("Error: Could not parse JSON object.");
return;
}
String scriptPath = jsonObject.getString("script"); // Get the script path from JSON
if (scriptPath == null || scriptPath.isEmpty()) {
System.err.println("Error: 'script' key is missing or empty in JSON.");
return;
}
try {
executeScript(scriptPath);
} catch (IOException e) {
System.err.println("Error executing script: " + e.getMessage());
}
}
private static JSONObject parseJsonObject(String jsonFilePath) throws IOException {
File jsonFile = new File(jsonFilePath);
String jsonString = new String(Files.readAllBytes(Paths.get(jsonFile.getAbsolutePath())));
return new JSONObject(jsonString);
}
private static void executeScript(String scriptPath) throws IOException {
// Ensure the script file exists
File scriptFile = new File(scriptPath);
if (!scriptFile.exists()) {
throw new IOException("Script file not found: " + scriptPath);
}
// Make the script executable (if necessary) - Unix-like systems
if (System.getProperty("os.name").toLowerCase().contains("linux") ||
System.getProperty("os.name").toLowerCase().contains("darwin")) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("chmod", "+x", scriptPath);
processBuilder.mkdir();
processBuilder.start();
} catch (IOException e) {
System.err.println("Warning: Could not make script executable: " + e.getMessage());
}
}
// Execute the script
Process process = new ProcessBuilder(scriptPath).start();
int exitCode = process.waitFor();
System.out.println("Script executed with exit code: " + exitCode);
}
}
Add your comment