1. import org.json.JSONObject;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Paths;
  6. public class ScriptLauncher {
  7. public static void main(String[] args) {
  8. if (args.length != 1) {
  9. System.err.println("Usage: java ScriptLauncher <json_file>");
  10. return;
  11. }
  12. String jsonFilePath = args[0];
  13. JSONObject jsonObject = parseJsonObject(jsonFilePath);
  14. if (jsonObject == null) {
  15. System.err.println("Error: Could not parse JSON object.");
  16. return;
  17. }
  18. String scriptPath = jsonObject.getString("script"); // Get the script path from JSON
  19. if (scriptPath == null || scriptPath.isEmpty()) {
  20. System.err.println("Error: 'script' key is missing or empty in JSON.");
  21. return;
  22. }
  23. try {
  24. executeScript(scriptPath);
  25. } catch (IOException e) {
  26. System.err.println("Error executing script: " + e.getMessage());
  27. }
  28. }
  29. private static JSONObject parseJsonObject(String jsonFilePath) throws IOException {
  30. File jsonFile = new File(jsonFilePath);
  31. String jsonString = new String(Files.readAllBytes(Paths.get(jsonFile.getAbsolutePath())));
  32. return new JSONObject(jsonString);
  33. }
  34. private static void executeScript(String scriptPath) throws IOException {
  35. // Ensure the script file exists
  36. File scriptFile = new File(scriptPath);
  37. if (!scriptFile.exists()) {
  38. throw new IOException("Script file not found: " + scriptPath);
  39. }
  40. // Make the script executable (if necessary) - Unix-like systems
  41. if (System.getProperty("os.name").toLowerCase().contains("linux") ||
  42. System.getProperty("os.name").toLowerCase().contains("darwin")) {
  43. try {
  44. ProcessBuilder processBuilder = new ProcessBuilder("chmod", "+x", scriptPath);
  45. processBuilder.mkdir();
  46. processBuilder.start();
  47. } catch (IOException e) {
  48. System.err.println("Warning: Could not make script executable: " + e.getMessage());
  49. }
  50. }
  51. // Execute the script
  52. Process process = new ProcessBuilder(scriptPath).start();
  53. int exitCode = process.waitFor();
  54. System.out.println("Script executed with exit code: " + exitCode);
  55. }
  56. }

Add your comment