blob: 0e7394530d7475f57a0df91cdea86a5925998eb1 [file] [log] [blame]
Stuart McCulloch42151ee2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochf3173222012-06-07 21:57:32 +00002
3import java.io.*;
4
5import aQute.libg.command.*;
6
7public class CommandResource extends WriteResource {
Stuart McCulloch4482c702012-06-15 13:27:53 +00008 final long lastModified;
9 final Builder domain;
10 final String command;
Stuart McCulloch2a0afd62012-09-06 18:28:06 +000011 final File wd;
Stuart McCulloch4482c702012-06-15 13:27:53 +000012
Stuart McCulloch2a0afd62012-09-06 18:28:06 +000013 public CommandResource(String command, Builder domain, long lastModified, File wd) {
Stuart McCullochf3173222012-06-07 21:57:32 +000014 this.lastModified = lastModified;
15 this.domain = domain;
16 this.command = command;
Stuart McCulloch2a0afd62012-09-06 18:28:06 +000017 this.wd = wd;
Stuart McCullochf3173222012-06-07 21:57:32 +000018 }
19
20 @Override
21 public void write(OutputStream out) throws IOException, Exception {
22 StringBuilder errors = new StringBuilder();
23 StringBuilder stdout = new StringBuilder();
24 try {
25 domain.trace("executing command %s", command);
Stuart McCulloch4482c702012-06-15 13:27:53 +000026 Command cmd = new Command("sh");
Stuart McCulloch2a0afd62012-09-06 18:28:06 +000027 cmd.setCwd(wd);
Stuart McCullochf3173222012-06-07 21:57:32 +000028 cmd.inherit();
29 String oldpath = cmd.var("PATH");
Stuart McCulloch4482c702012-06-15 13:27:53 +000030
Stuart McCullochf3173222012-06-07 21:57:32 +000031 String path = domain.getProperty("-PATH");
32 if (path != null) {
Stuart McCulloch4482c702012-06-15 13:27:53 +000033 path = path.replaceAll("\\s*,\\s*", File.pathSeparator);
Stuart McCullochf3173222012-06-07 21:57:32 +000034 path = path.replaceAll("\\$\\{@\\}", oldpath);
35 cmd.var("PATH", path);
36 domain.trace("PATH: %s", path);
37 }
Stuart McCulloch669423b2012-06-26 16:34:24 +000038 OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
Stuart McCulloch4482c702012-06-15 13:27:53 +000039 int result = cmd.execute(command, stdout, errors);
Stuart McCullochf3173222012-06-07 21:57:32 +000040 osw.append(stdout);
41 osw.flush();
Stuart McCulloch4482c702012-06-15 13:27:53 +000042 if (result != 0) {
Stuart McCullochf3173222012-06-07 21:57:32 +000043 domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
44 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000045 }
46 catch (Exception e) {
Stuart McCullochf3173222012-06-07 21:57:32 +000047 domain.error("executing command failed %s %s", command, e.getMessage());
48 }
49 }
50
51 @Override
52 public long lastModified() {
53 return lastModified;
54 }
55
56}