Другой способ перенаправления стандартного вывода вызова метода в Spring Boot - PullRequest
0 голосов
/ 17 мая 2019

Я занимаюсь разработкой приложения Spring Boot, которое нацелено на получение кода от пользователей, его компиляцию, выполнение и, наконец, отображение пользователям их вывода кода.Для этого я создал Компонент, отвечающий за выполнение кода и сохранение вывода в текстовом файле (через PrintStream), который выглядит так:

@Component
public class SimpleExecutor implements Executor {
    @Autowired
    private FileStorageService fileStorageService;

    public Path runClass(Class helloClass, String outputPath) throws Exception {
        helloClass.getConstructor().newInstance();
        Method method = helloClass.getMethod("main", String[].class);
        try {
            PrintStream fileStream = new PrintStream(outputPath);
            System.setOut(fileStream);
            String[] params = null;
            method.invoke(null, (Object) params);
            return Paths.get(outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.setOut(null);
        }
        return null;
    }
}

Выше runClass метод вызывается другим @Async метод (поэтому он работает в другом потоке, чем в приложении).Проблема в том, что замена System.out на мой fileStream означает также и сохранение отладочной информации Spring (что, конечно, не предназначено).Например, вместо простого «Hello world» я иногда получаю:

2019-05-17 01:43:58.371 DEBUG 9720 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:43:58.372 DEBUG 9720 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:43:58.374 DEBUG 9720 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:43:58.375 DEBUG 9720 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:43:58.376 DEBUG 9720 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-05-17 01:43:59.163 DEBUG 9720 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:43:59.165 DEBUG 9720 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:43:59.167 DEBUG 9720 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:43:59.167 DEBUG 9720 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:43:59.168 DEBUG 9720 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-05-17 01:44:00.101 DEBUG 9720 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:44:00.101 DEBUG 9720 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:44:00.103 DEBUG 9720 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:44:00.103 DEBUG 9720 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:44:00.104 DEBUG 9720 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
Hello world

Есть ли другой способ перенаправить стандартный вывод вызова method.invoke?Это тот, который печатает материал, который я хотел бы сохранить.

1 Ответ

0 голосов
/ 17 мая 2019

Пожалуйста, попробуйте вот так.

public Path runClass(Class helloClass, String outputPath) throws Exception {

........ other code

FileOutputStream f = new FileOutputStream("mySeparateLog.txt");
System.setOut(new PrintStream(f));

....... other code

}
...