ScriptCaller.java
package com.sintia.ffl.admin.optique.catalogue.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
@Service
@Slf4j
public class ScriptCaller {
private static final int RESULT_KO = 1;
@Value("${glasses.purge.scriptDirectory}")
private String directory;
@Value("${local.resources.directory}")
private String localResourcesDirectory;
// Valeur possible sous Windows : C:/Program Files/Git
@Value("${shell.path.prefix:}")
private String shellPathPrefix;
public int runScript(String scriptFileName) {
// Use to run the code in local env, where we use Windows instead of Unix
ProcessBuilder pb = new ProcessBuilder(this.shellPathPrefix + "/bin/bash", "-c", scriptFileName);
pb.directory(Paths.get(localResourcesDirectory).resolve(directory).toFile());
Process process;
try {
process = pb.start();
}
catch (IOException e) {
log.error("Error launching the script {}", scriptFileName, e);
return RESULT_KO;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
}
catch (IOException e) {
log.error("Error reading the result of the script {}", scriptFileName, e);
}
try {
int result = process.waitFor();
log.info("The script {} ended with code {} and the following output\n{}", scriptFileName, result, stringBuilder);
return result;
}
catch (InterruptedException e) { // NOSONAR
log.error("Error running the script {}", scriptFileName, e);
return RESULT_KO;
}
}
}