1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.maven.plugins.jenkins.helper;
17
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import org.apache.commons.io.IOUtils;
22 import org.apache.commons.lang.StringUtils;
23 import org.kuali.maven.plugins.jenkins.context.ProcessContext;
24 import org.kuali.maven.plugins.jenkins.context.ProcessException;
25 import org.kuali.maven.plugins.jenkins.context.ProcessResult;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29
30
31
32
33
34
35 public class ProcessHelper {
36 private static final Logger logger = LoggerFactory.getLogger(ProcessHelper.class);
37
38 public ProcessResult execute(String executable) {
39 return execute(executable, (String[]) null);
40 }
41
42 public ProcessResult execute(String executable, String... args) {
43 return execute(executable, args, null);
44 }
45
46 public ProcessResult execute(String executable, String[] args, String input) {
47 ProcessContext context = new ProcessContext();
48 context.setExecutable(executable);
49 context.setArgs(args);
50 context.setInput(input);
51 return execute(context);
52 }
53
54 public ProcessResult execute(ProcessContext context) {
55 try {
56 String[] command = getProcessBuilderCommand(context.getExecutable(), context.getArgs());
57 ProcessBuilder builder = new ProcessBuilder(command);
58 builder.redirectErrorStream(true);
59 long start = System.currentTimeMillis();
60 logger.debug("Starting process");
61 Process process = builder.start();
62 logger.debug("Process started");
63 if (!StringUtils.isBlank(context.getInput())) {
64 logger.debug("Writing input=" + context.getInput());
65 IOUtils.write(context.getInput(), process.getOutputStream());
66 logger.debug("Done writing input");
67 process.getOutputStream().close();
68 }
69 logger.debug("Reading output");
70 String output = IOUtils.toString(process.getInputStream());
71 logger.debug("Done reading output=" + output);
72 List<String> outputLines = Helper.getLines(output);
73 int exitValue = process.waitFor();
74 long stop = System.currentTimeMillis();
75 long elapsed = stop - start;
76 ProcessResult result = new ProcessResult();
77 result.setContext(context);
78 result.setExitValue(exitValue);
79 result.setOutput(output);
80 result.setOutputLines(outputLines);
81 result.setStart(start);
82 result.setStop(stop);
83 result.setElapsed(elapsed);
84 return result;
85 } catch (Exception e) {
86 throw new ProcessException(e);
87 }
88 }
89
90 protected String[] getProcessBuilderCommand(String executable, String... args) {
91 List<String> command = new ArrayList<String>();
92 command.add(executable);
93 Helper.addToList(command, args);
94 return Helper.toArray(command);
95 }
96 }