blob: 7f3e9a3e256873e0eb036f1b173bb924e117da0b [file] [log] [blame]
Richard S. Hallaf656a02009-06-11 16:07:20 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Guillaume Nodetb4e055d2009-06-22 15:21:30 +000019// DWB1: osgi:each too verbose (formats reults to System.out)
20// DWB2: ClassNotFoundException should be caught in convert() method
Richard S. Hallaf656a02009-06-11 16:07:20 +000021package aQute.shell.osgi;
22
23import java.io.*;
24import java.util.*;
25import java.util.regex.*;
26
27import org.osgi.framework.*;
28import org.osgi.service.command.*;
29
30public class OSGiCommands implements Converter {
31 Bundle bundle;
32 String COLUMN = "%40s %s\n";
33
34 protected OSGiCommands(Bundle bundle) {
35 this.bundle = bundle;
36 }
37
38// Bundle[] getBundles() {
39// return getContext().getBundles();
40// }
41
42 public BundleContext getContext() {
43 if ( bundle.getState() != Bundle.ACTIVE )
44 throw new IllegalStateException("Framework is not started yet");
45 return bundle.getBundleContext();
46 }
47
48 CharSequence print(Bundle bundle) {
49 String version = (String) bundle.getHeaders().get("Bundle-Version");
50 if ( version == null )
51 version = "0.0.0";
52 return String.format("%06d %s %s-%s", bundle.getBundleId(),
53 getState(bundle), bundle.getSymbolicName(), version);
54 }
55
56 CharSequence print(ServiceReference ref) {
57 StringBuilder sb = new StringBuilder();
58 Formatter f = new Formatter(sb);
59
60 String spid = "";
61 Object pid = ref.getProperty("service.pid");
62 if (pid != null) {
63 spid = pid.toString();
64 }
65
66 f.format("%06d %3s %-40s %s", ref.getProperty("service.id"), ref
67 .getBundle().getBundleId(), getShortNames((String[]) ref
68 .getProperty("objectclass")), spid);
69 return sb;
70 }
71
72 CharSequence getShortNames(String[] list) {
73 StringBuilder sb = new StringBuilder();
74 String del = "";
75 for (String s : list) {
76 sb.append(del + getShortName(s));
77 del = " | ";
78 }
79 return sb;
80 }
81
82 CharSequence getShortName(String name) {
83 int n = name.lastIndexOf('.');
84 if (n < 0)
85 n = 0;
86 else
87 n++;
88 return name.subSequence(n, name.length());
89 }
90
91 private String getState(Bundle bundle) {
92 switch (bundle.getState()) {
93 case Bundle.ACTIVE:
94 return "ACT";
95
96 case Bundle.INSTALLED:
97 return "INS";
98
99 case Bundle.RESOLVED:
100 return "RES";
101
102 case Bundle.STARTING:
103 return "STA";
104
105 case Bundle.STOPPING:
106 return "STO";
107
108 case Bundle.UNINSTALLED:
109 return "UNI ";
110 }
111 return null;
112 }
113
114 public void grep(String match) throws IOException {
115 Pattern p = Pattern.compile(match);
116 BufferedReader rdr = new BufferedReader(
117 new InputStreamReader(System.in));
118 String s = rdr.readLine();
119 while (s != null) {
120 if (p.matcher(s).find()) {
121 System.out.println(s);
122 }
123 s = rdr.readLine();
124 }
125 }
126
127 public String tac() throws IOException {
128 StringWriter sw = new StringWriter();
129 BufferedReader rdr = new BufferedReader(
130 new InputStreamReader(System.in));
131 String s = rdr.readLine();
132 while (s != null) {
133 sw.write(s);
134 s = rdr.readLine();
135 }
136 return sw.toString();
137 }
138
139 public CharSequence echo(CommandSession session, Object args[]) {
140 StringBuilder sb = new StringBuilder();
141 String del = "";
142 for (Object arg : args) {
143 sb.append(del);
144 if (arg != null) {
145 sb.append(arg);
146 del = " ";
147 }
148 }
149 return sb;
150 }
151
152 public void each(CommandSession session, Collection<Object> list, Function closure) throws Exception {
153 List<Object> args = new ArrayList<Object>();
154 args.add(null);
155 for (Object x : list) {
156 args.set(0, x);
Guillaume Nodetb4e055d2009-06-22 15:21:30 +0000157 //Object result = closure.execute(session, args);
158 // System.out.println(session.format(result,Converter.INSPECT));
159 // derek: this is way too noisy
160 closure.execute(session, args);
Richard S. Hallaf656a02009-06-11 16:07:20 +0000161 }
162 }
163
164 public Bundle bundle(Bundle i) {
165 return i;
166 }
167
168 public String[] ls(CommandSession session, File f) throws Exception{
169 File cwd = (File) session.get("_cwd");
170 if (cwd == null)
171 cwd = new File("").getAbsoluteFile();
172
173 if ( f == null )
174 f = cwd;
175 else if (!f.isAbsolute())
176 f = new File(cwd, f.getPath());
177
178 if ( f.isDirectory() )
179 return f.list();
180
181 if ( f.isFile() ) {
182 cat(session,f);
183 }
184
185 return null;
186 }
187
188 public Object cat(CommandSession session, File f ) throws Exception {
189 File cwd = (File) session.get("_cwd");
190 if (cwd == null)
191 cwd = new File("").getAbsoluteFile();
192
193 if ( !f.isAbsolute() )
194 f = new File(cwd,f.getPath());
195
196 ByteArrayOutputStream bout = new ByteArrayOutputStream();
197 FileInputStream in = new FileInputStream(f);
198 byte [] buffer = new byte[ (int) (f.length() % 100000) ];
199 int size = in.read(buffer);
200 while ( size > 0 ) {
201 bout.write(buffer,0,size);
202 size = in.read(buffer);
203 }
204 return new String(bout.toByteArray());
205 }
206 public Object convert(Class<?> desiredType, Object in) throws Exception {
207 if (desiredType == Bundle.class)
208 return convertBundle(in);
209 else if (desiredType == ServiceReference.class)
210 return convertServiceReference(in);
Guillaume Nodetb4e055d2009-06-22 15:21:30 +0000211 else if (desiredType == Class.class) {
212 // derek.baum@paremus.com - added try/catch
213 try {
214 return Class.forName(in.toString());
215 } catch (ClassNotFoundException e) {
216 return null;
217 }
218 }
Richard S. Hallaf656a02009-06-11 16:07:20 +0000219 else if (desiredType.isAssignableFrom(String.class) && in instanceof InputStream)
220 return read(((InputStream) in));
221
222 return null;
223 }
224
225 private Object convertServiceReference(Object in)
226 throws InvalidSyntaxException {
227 String s = in.toString();
228 if (s.startsWith("(") && s.endsWith(")")) {
229 ServiceReference refs[] = getContext().getServiceReferences(null, String
230 .format("(|(service.id=%s)(service.pid=%s))", in, in));
231 if (refs != null && refs.length > 0)
232 return refs[0];
233 }
234
235 ServiceReference refs[] = getContext().getServiceReferences(null, String
236 .format("(|(service.id=%s)(service.pid=%s))", in, in));
237 if (refs != null && refs.length > 0)
238 return refs[0];
239 return null;
240 }
241
242 private Object convertBundle(Object in) {
243 String s = in.toString();
244 try {
245 long id = Long.parseLong(s);
246 return getContext().getBundle(id);
247 } catch (NumberFormatException nfe) {
248 // Ignore
249 }
250
251 Bundle bundles[] = getContext().getBundles();
252 for (Bundle b : bundles) {
253 if (b.getLocation().equals(s))
254 return b;
255
256 if (b.getSymbolicName().equals(s))
257 return b;
258 }
259
260 return null;
261 }
262
263 public CharSequence format(Object target, int level, Converter converter ) throws IOException {
264 if ( level == INSPECT && target instanceof InputStream ) {
265 return read(((InputStream)target));
266 }
267 if (level == LINE && target instanceof Bundle)
268 return print((Bundle) target);
269 if (level == LINE && target instanceof ServiceReference)
270 return print((ServiceReference) target);
271 if (level == PART && target instanceof Bundle)
272 return ((Bundle) target).getSymbolicName();
273 if (level == PART && target instanceof ServiceReference)
274 return getShortNames((String[]) ((ServiceReference) target)
275 .getProperty("objectclass"));
276 return null;
277 }
278
279 public CharSequence read(InputStream in) throws IOException {
280 int c;
281 StringBuffer sb = new StringBuffer();
282 while ( (c=in.read())> 0 ) {
283 if ( c >=32 && c <= 0x7F || c=='\n' || c=='\r') {
284 sb.append( (char) c);
285 } else {
286 String s = Integer.toHexString(c).toUpperCase();
287 sb.append("\\");
288 if ( s.length() < 1)
289 sb.append(0);
290 sb.append(s);
291 }
292 }
293 return sb;
294 }
295
296 public void start(Bundle b) throws BundleException {
297 b.start();
298 }
299
300 public void stop(Bundle b) throws BundleException {
301 b.stop();
302 }
303
304 public Object service(String clazz, String filter) throws InvalidSyntaxException {
305 ServiceReference ref[] = getContext().getServiceReferences(clazz,filter);
306 if (ref == null )
307 return null;
308
309 return getContext().getService(ref[0]);
310 }
311
312}