78 lines
2.1 KiB
Java
78 lines
2.1 KiB
Java
package ru.oa2.lti.infrastructure.runner;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.Paths;
|
|
import java.util.UUID;
|
|
|
|
@Slf4j
|
|
@Component
|
|
public class RunnerImpl implements Runner {
|
|
|
|
private final String TEMP_DIR = "./temp/";
|
|
|
|
@Override
|
|
public boolean run(UUID userId, String script) {
|
|
try {
|
|
return runScript(userId, script);
|
|
} catch (Exception ex) {
|
|
log.error(ex.getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
//TODO добавить вывод результата/интерпретации
|
|
@Override
|
|
public boolean check(UUID userId, String script) {
|
|
try {
|
|
return runScript(userId, script);
|
|
} catch (Exception ex) {
|
|
log.error(ex.getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private boolean runScript(UUID userId, String script) throws Exception {
|
|
|
|
var processBuilder = new ProcessBuilder();
|
|
processBuilder.command("bash", saveFile(userId, script));
|
|
|
|
var process = processBuilder.start();
|
|
|
|
BufferedReader reader = new BufferedReader(
|
|
new InputStreamReader(process.getInputStream())
|
|
);
|
|
|
|
StringBuilder output = new StringBuilder();
|
|
String line;
|
|
while ((line = reader.readLine()) != null) {
|
|
output.append(line).append("\n");
|
|
}
|
|
log.info(output.toString());
|
|
|
|
int exitCode = process.waitFor();
|
|
return exitCode == 0;
|
|
}
|
|
|
|
private String saveFile(UUID userId, String script) throws IOException {
|
|
Path path = Paths.get(TEMP_DIR + userId.toString());
|
|
|
|
if (!Files.exists(path)) {
|
|
Files.createDirectories(path);
|
|
}
|
|
var tm = System.currentTimeMillis();
|
|
var scriptPath = Files.write(
|
|
Paths.get(TEMP_DIR + userId + "/" + tm),
|
|
script.getBytes(StandardCharsets.UTF_8));
|
|
|
|
return scriptPath.toString();
|
|
}
|
|
}
|