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 execute(ExecContext context, Commandline cl) {
49 try {
50 logger.info("[{}]", cl);
51 StreamConsumer stdout = getStreamConsumer(context.getStandardOutConsumer(), logger, LoggerLevel.INFO);
52 StreamConsumer stderr = getStreamConsumer(context.getStandardErrConsumer(), logger, LoggerLevel.WARN);
53 return CommandLineUtils.executeCommandLine(cl, context.getInput(), stdout, stderr, context.getTimeoutInSeconds());
54 } catch (CommandLineException e) {
55 throw new IllegalStateException(e);
56 }
57 }
58
59 protected StreamConsumer getStreamConsumer(StreamConsumer provided, Logger logger, LoggerLevel level) {
60 if (provided != null) {
61 return provided;
62 } else {
63 return new LoggingStreamConsumer(logger, level);
64 }
65 }
66
67 protected Commandline getCommandLine(ExecContext context) {
68 Commandline cl = new Commandline();
69 cl.setExecutable(context.getExecutable());
70 if (context.getArgs() != null) {
71 cl.addArguments(CollectionUtils.toStringArray(context.getArgs()));
72 }
73 if (context.getWorkingDirectory() != null) {
74 cl.setWorkingDirectory(context.getWorkingDirectory());
75 }
76 return cl;
77 }
78
79 }