Stuart McCulloch | 39cc9ac | 2012-07-16 13:43:38 +0000 | [diff] [blame^] | 1 | package aQute.bnd.osgi; |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 2 | |
| 3 | import java.io.*; |
| 4 | |
| 5 | import aQute.libg.command.*; |
| 6 | |
| 7 | public class CommandResource extends WriteResource { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 8 | final long lastModified; |
| 9 | final Builder domain; |
| 10 | final String command; |
| 11 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 12 | 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 24 | Command cmd = new Command("sh"); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 25 | cmd.inherit(); |
| 26 | String oldpath = cmd.var("PATH"); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 27 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 28 | String path = domain.getProperty("-PATH"); |
| 29 | if (path != null) { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 30 | path = path.replaceAll("\\s*,\\s*", File.pathSeparator); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 31 | path = path.replaceAll("\\$\\{@\\}", oldpath); |
| 32 | cmd.var("PATH", path); |
| 33 | domain.trace("PATH: %s", path); |
| 34 | } |
Stuart McCulloch | d482610 | 2012-06-26 16:34:24 +0000 | [diff] [blame] | 35 | OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8"); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 36 | int result = cmd.execute(command, stdout, errors); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 37 | osw.append(stdout); |
| 38 | osw.flush(); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 39 | if (result != 0) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 40 | domain.error("executing command failed %s %s", command, stdout + "\n" + errors); |
| 41 | } |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 42 | } |
| 43 | catch (Exception e) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 44 | 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 | } |