Issue
I'm creating web application using spring boot, in this web application i need to run a command line using Runtime.getRuntime(), but the problem is that: this command is executed after the web app and this is not what i want to do, the question is :
"how can i make sure that the Runtime.getRuntime() instruction start when it's called in spring boot application (not at the end of it)"
the controller:
@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(@RequestParam(value = "input", required = false) String in,
@RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException, ExecutionException {
// the methode LinearizePDF contain the command line
linearizeService.LinearizePDf(in, out);
logger.warn("call the method linearizeService.LinearizePDf ");
FileSystemResource result = new FileSystemResource(out);
return ResponseEntity
.ok()
.contentLength(result.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(result.getInputStream())));
}
the linearizeService ( contain the method LinearizePDf(in, out)):
@Async
public void LinearizePDf(String Input , String Output) throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
// the command line
String command = "qpdf --linearize " + Input + " " + Output;
Process pr = rt.exec(command );
logger.warn("run the command");
pr.destroy();
}
Please, If there's any suggestion, do not hesitate.
Thank You !
Solution
Simply put – annotating a method of a bean with @Async will make it execute in a separate thread i.e. the caller will not wait for the completion of the called method.
Remove the @Async
from LinearizePDf
In addition, to wait for the completion of the external process you should use waitFor
and not destroy
, e.g. pr.waitFor()
Answered By - igorepst
Answer Checked By - Terry (JavaFixing Volunteer)