blob: eb66635890a6c1be8ebe476ad7d207b1f78b1cfc [file] [log] [blame]
Stuart McCulloch39cc9ac2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochbb014372012-06-07 21:57:32 +00002
3import java.io.*;
4
5import aQute.libg.command.*;
6
7public class CommandResource extends WriteResource {
Stuart McCulloch2286f232012-06-15 13:27:53 +00008 final long lastModified;
9 final Builder domain;
10 final String command;
11
Stuart McCullochbb014372012-06-07 21:57:32 +000012 public CommandResource(String command, Builder domain, long lastModified) {
13 this.lastModified = lastModified;
14 this.domain = domain;
15 this.command = command;
16 }
17
18 @Override
19 public void write(OutputStream out) throws IOException, Exception {
20 StringBuilder errors = new StringBuilder();
21 StringBuilder stdout = new StringBuilder();
22 try {
23 domain.trace("executing command %s", command);
Stuart McCulloch2286f232012-06-15 13:27:53 +000024 Command cmd = new Command("sh");
Stuart McCullochbb014372012-06-07 21:57:32 +000025 cmd.inherit();
26 String oldpath = cmd.var("PATH");
Stuart McCulloch2286f232012-06-15 13:27:53 +000027
Stuart McCullochbb014372012-06-07 21:57:32 +000028 String path = domain.getProperty("-PATH");
29 if (path != null) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000030 path = path.replaceAll("\\s*,\\s*", File.pathSeparator);
Stuart McCullochbb014372012-06-07 21:57:32 +000031 path = path.replaceAll("\\$\\{@\\}", oldpath);
32 cmd.var("PATH", path);
33 domain.trace("PATH: %s", path);
34 }
Stuart McCullochd4826102012-06-26 16:34:24 +000035 OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
Stuart McCulloch2286f232012-06-15 13:27:53 +000036 int result = cmd.execute(command, stdout, errors);
Stuart McCullochbb014372012-06-07 21:57:32 +000037 osw.append(stdout);
38 osw.flush();
Stuart McCulloch2286f232012-06-15 13:27:53 +000039 if (result != 0) {
Stuart McCullochbb014372012-06-07 21:57:32 +000040 domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
41 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000042 }
43 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000044 domain.error("executing command failed %s %s", command, e.getMessage());
45 }
46 }
47
48 @Override
49 public long lastModified() {
50 return lastModified;
51 }
52
53}