blob: eefc1e2347b78511d6d1a208fe259e87a2ca73a7 [file] [log] [blame]
Stuart McCullochf3173222012-06-07 21:57:32 +00001/*
2 * Copyright (c) OSGi Alliance (2012). All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Stuart McCullochf3173222012-06-07 21:57:32 +000017package aQute.lib.osgi;
18
19import java.io.*;
20
21import aQute.libg.command.*;
22
23public class CommandResource extends WriteResource {
Stuart McCulloch4482c702012-06-15 13:27:53 +000024 final long lastModified;
25 final Builder domain;
26 final String command;
27
Stuart McCullochf3173222012-06-07 21:57:32 +000028 public CommandResource(String command, Builder domain, long lastModified) {
29 this.lastModified = lastModified;
30 this.domain = domain;
31 this.command = command;
32 }
33
34 @Override
35 public void write(OutputStream out) throws IOException, Exception {
36 StringBuilder errors = new StringBuilder();
37 StringBuilder stdout = new StringBuilder();
38 try {
39 domain.trace("executing command %s", command);
Stuart McCulloch4482c702012-06-15 13:27:53 +000040 Command cmd = new Command("sh");
Stuart McCullochf3173222012-06-07 21:57:32 +000041 cmd.inherit();
42 String oldpath = cmd.var("PATH");
Stuart McCulloch4482c702012-06-15 13:27:53 +000043
Stuart McCullochf3173222012-06-07 21:57:32 +000044 String path = domain.getProperty("-PATH");
45 if (path != null) {
Stuart McCulloch4482c702012-06-15 13:27:53 +000046 path = path.replaceAll("\\s*,\\s*", File.pathSeparator);
Stuart McCullochf3173222012-06-07 21:57:32 +000047 path = path.replaceAll("\\$\\{@\\}", oldpath);
48 cmd.var("PATH", path);
49 domain.trace("PATH: %s", path);
50 }
Stuart McCulloch669423b2012-06-26 16:34:24 +000051 OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
Stuart McCulloch4482c702012-06-15 13:27:53 +000052 int result = cmd.execute(command, stdout, errors);
Stuart McCullochf3173222012-06-07 21:57:32 +000053 osw.append(stdout);
54 osw.flush();
Stuart McCulloch4482c702012-06-15 13:27:53 +000055 if (result != 0) {
Stuart McCullochf3173222012-06-07 21:57:32 +000056 domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
57 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000058 }
59 catch (Exception e) {
Stuart McCullochf3173222012-06-07 21:57:32 +000060 domain.error("executing command failed %s %s", command, e.getMessage());
61 }
62 }
63
64 @Override
65 public long lastModified() {
66 return lastModified;
67 }
68
69}