blob: 0fa43fecd255e1ddae5d8e830442ed6efb0337a5 [file] [log] [blame]
Stuart McCullochbb014372012-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 McCullochbb014372012-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 McCulloch2286f232012-06-15 13:27:53 +000024 final long lastModified;
25 final Builder domain;
26 final String command;
27
Stuart McCullochbb014372012-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 McCulloch2286f232012-06-15 13:27:53 +000040 Command cmd = new Command("sh");
Stuart McCullochbb014372012-06-07 21:57:32 +000041 cmd.inherit();
42 String oldpath = cmd.var("PATH");
Stuart McCulloch2286f232012-06-15 13:27:53 +000043
Stuart McCullochbb014372012-06-07 21:57:32 +000044 String path = domain.getProperty("-PATH");
45 if (path != null) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000046 path = path.replaceAll("\\s*,\\s*", File.pathSeparator);
Stuart McCullochbb014372012-06-07 21:57:32 +000047 path = path.replaceAll("\\$\\{@\\}", oldpath);
48 cmd.var("PATH", path);
49 domain.trace("PATH: %s", path);
50 }
51 OutputStreamWriter osw = new OutputStreamWriter(out);
Stuart McCulloch2286f232012-06-15 13:27:53 +000052 int result = cmd.execute(command, stdout, errors);
Stuart McCullochbb014372012-06-07 21:57:32 +000053 osw.append(stdout);
54 osw.flush();
Stuart McCulloch2286f232012-06-15 13:27:53 +000055 if (result != 0) {
Stuart McCullochbb014372012-06-07 21:57:32 +000056 domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
57 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000058 }
59 catch (Exception e) {
Stuart McCullochbb014372012-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}