1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util.service;
17
18 import java.util.List;
19
20 import org.codehaus.plexus.util.cli.CommandLineException;
21 import org.codehaus.plexus.util.cli.CommandLineUtils;
22 import org.codehaus.plexus.util.cli.Commandline;
23 import org.codehaus.plexus.util.cli.StreamConsumer;
24 import org.kuali.common.util.CollectionUtils;
25 import org.kuali.common.util.LoggerLevel;
26 import org.kuali.common.util.LoggingStreamConsumer;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public class DefaultExecService implements ExecService {
31
32 private static final Logger logger = LoggerFactory.getLogger(DefaultExecService.class);
33
34 @Override
35 public int execute(ExecContext context) {
36 Commandline cl = getCommandLine(context);
37 return execute(context, cl);
38 }
39
40 @Override
41 public int execute(String executable, List<String> args) {
42 DefaultExecContext context = new DefaultExecContext();
43 context.setExecutable(executable);
44 context.setArgs(args);
45 return execute(context);
46 }
47
48 protected int executeAndValidate(String executable, List<String> args) {
49 int exitValue = execute(executable, args);
50 validateExitValue(exitValue);
51 return exitValue;
52 }
53
54 protected int executeAndValidate(ExecContext context) {
55 int exitValue = execute(context);
56 validateExitValue(exitValue);
57 return exitValue;
58 }
59
60 protected int execute(ExecContext context, Commandline cl) {
61 try {
62 logger.debug("[{}]", cl);
63 StreamConsumer stdout = getStreamConsumer(context.getStandardOutConsumer(), logger, LoggerLevel.INFO);
64 StreamConsumer stderr = getStreamConsumer(context.getStandardErrConsumer(), logger, LoggerLevel.WARN);
65 return CommandLineUtils.executeCommandLine(cl, context.getInput(), stdout, stderr, context.getTimeoutInSeconds());
66 } catch (CommandLineException e) {
67 throw new IllegalStateException(e);
68 }
69 }
70
71 protected StreamConsumer getStreamConsumer(StreamConsumer provided, Logger logger, LoggerLevel level) {
72 if (provided != null) {
73 return provided;
74 } else {
75 return new LoggingStreamConsumer(logger, level);
76 }
77 }
78
79 protected void validateExitValue(int exitValue) {
80 if (exitValue != 0) {
81 throw new IllegalStateException("Non-zero exit value - " + exitValue);
82 }
83 }
84
85 protected Commandline getCommandLine(ExecContext context) {
86 Commandline cl = new Commandline();
87 cl.setExecutable(context.getExecutable());
88 if (context.isAddSystemEnvironment()) {
89 try {
90 cl.addSystemEnvironment();
91 } catch (Exception e) {
92 throw new IllegalStateException(e);
93 }
94 }
95 if (context.getArgs() != null) {
96 cl.addArguments(CollectionUtils.toStringArray(context.getArgs()));
97 }
98 if (context.getWorkingDirectory() != null) {
99 cl.setWorkingDirectory(context.getWorkingDirectory());
100 }
101 return cl;
102 }
103
104 }