KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > osgi > framework > internal > core > FrameworkCommandProvider


1 /*******************************************************************************
2  * Copyright (c) 2003, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11
12 package org.eclipse.osgi.framework.internal.core;
13
14 import java.io.*;
15 import java.lang.reflect.Field JavaDoc;
16 import java.lang.reflect.Method JavaDoc;
17 import java.net.URL JavaDoc;
18 import java.security.ProtectionDomain JavaDoc;
19 import java.util.*;
20
21 import org.eclipse.osgi.framework.console.CommandInterpreter;
22 import org.eclipse.osgi.framework.console.CommandProvider;
23 import org.eclipse.osgi.framework.launcher.Launcher;
24 import org.eclipse.osgi.internal.profile.Profile;
25 import org.eclipse.osgi.service.resolver.*;
26 import org.eclipse.osgi.util.NLS;
27 import org.osgi.framework.*;
28 import org.osgi.service.condpermadmin.ConditionalPermissionAdmin;
29 import org.osgi.service.condpermadmin.ConditionalPermissionInfo;
30 import org.osgi.service.packageadmin.PackageAdmin;
31 import org.osgi.service.packageadmin.RequiredBundle;
32 import org.osgi.service.permissionadmin.PermissionAdmin;
33
34 /**
35  * This class provides methods to execute commands from the command line. It registers
36  * itself as a CommandProvider so it can be invoked by a CommandInterpreter. The
37  * FrameworkCommandProvider registers itself with the highest ranking (Integer.MAXVALUE) so it will always be
38  * called first. Other CommandProviders should register with lower rankings.
39  *
40  * The commands provided by this class are:
41  ---Controlling the OSGi framework---
42  close - shutdown and exit
43  exit - exit immediately (System.exit)
44  gc - perform a garbage collection
45  init - uninstall all bundles
46  launch - start the Service Management Framework
47  setprop <key>=<value> - set the OSGI property
48  shutdown - shutdown the Service Management Framework
49  ---Controlliing Bundles---
50  install <url> {s[tart]} - install and optionally start bundle from the given URL
51  refresh (<id>|<location>) - refresh the packages of the specified bundles
52  start (<id>|<location>) - start the specified bundle(s)
53  stop (<id>|<location>) - stop the specified bundle(s)
54  uninstall (<id>|<location>) - uninstall the specified bundle(s)
55  update (<id>|<location>|<*>) - update the specified bundle(s)
56  ---Displaying Status---
57  bundle (<id>|<location>) - display details for the specified bundle(s)
58  bundles - display details for all installed bundles
59  headers (<id>|<location>) - print bundle headers
60  packages {<pkgname>|<id>|<location>} - display imported/exported package details
61  props - display System properties
62  services {filter} - display registered service details
63  ss - display installed bundles (short status)
64  status - display installed bundles and registered services
65  threads - display threads and thread groups
66  ---Log Commands---
67  log {(<id>|<location>)} - display log entries
68  ---Extras---
69  exec <command> - execute a command in a separate process and wait
70  fork <command> - execute a command in a separate process
71  getprop <name> - Displays the system properties with the given name, or all of them.
72  ---Controlling StartLevel---
73  sl {(<id>|<location>)} - display the start level for the specified bundle, or for the framework if no bundle specified
74  setfwsl <start level> - set the framework start level
75  setbsl <start level> (<id>|<location>) - set the start level for the bundle(s)
76  setibsl <start level> - set the initial bundle start level
77  
78  *
79  * There is a method for each command which is named '_'+method. The methods are
80  * invoked by a CommandInterpreter's execute method.
81  */

82 public class FrameworkCommandProvider implements CommandProvider, SynchronousBundleListener {
83
84     /** An instance of the OSGi framework */
85     private OSGi osgi;
86     /** The system bundle context */
87     private org.osgi.framework.BundleContext context;
88     /** The start level implementation */
89     private StartLevelManager slImpl;
90     private ConditionalPermissionAdmin condPermAdmin;
91     private PermissionAdmin permAdmin;
92
93     /** Strings used to format other strings */
94     private String JavaDoc tab = "\t"; //$NON-NLS-1$
95
private String JavaDoc newline = "\r\n"; //$NON-NLS-1$
96

97     /** this list contains the bundles known to be lazily awaiting activation */
98     private final List lazyActivation = new ArrayList();
99
100     /**
101      * Constructor.
102      *
103      * initialize must be called after creating this object.
104      *
105      * @param osgi The current instance of OSGi
106      */

107     public FrameworkCommandProvider(OSGi osgi) {
108         this.osgi = osgi;
109         context = osgi.getBundleContext();
110         slImpl = osgi.framework.startLevelManager;
111         condPermAdmin = osgi.framework.condPermAdmin;
112         permAdmin = osgi.framework.permissionAdmin;
113     }
114     
115     /**
116      * Intialize this CommandProvider.
117      *
118      * Registers this object as a CommandProvider with the highest ranking possible.
119      * Adds this object as a SynchronousBundleListener.
120      *
121      * @return this
122      */

123     public FrameworkCommandProvider intialize() {
124         Dictionary props = new Hashtable();
125         props.put(Constants.SERVICE_RANKING, new Integer JavaDoc(Integer.MAX_VALUE));
126         context.registerService(CommandProvider.class.getName(), this, props);
127         
128         context.addBundleListener(this);
129         return this;
130     }
131
132     /**
133      Answer a string (may be as many lines as you like) with help
134      texts that explain the command. This getHelp() method uses the
135      ConsoleMsg class to obtain the correct NLS data to display to the user.
136      
137      @return The help string
138      */

139     public String JavaDoc getHelp() {
140         StringBuffer JavaDoc help = new StringBuffer JavaDoc(1024);
141         help.append(newline);
142         help.append(ConsoleMsg.CONSOLE_HELP_VALID_COMMANDS_HEADER);
143         help.append(newline);
144         addHeader(ConsoleMsg.CONSOLE_HELP_CONTROLLING_FRAMEWORK_HEADER, help);
145         addCommand("launch", ConsoleMsg.CONSOLE_HELP_LAUNCH_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
146
addCommand("shutdown", ConsoleMsg.CONSOLE_HELP_SHUTDOWN_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
147
addCommand("close", ConsoleMsg.CONSOLE_HELP_CLOSE_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
148
addCommand("exit", ConsoleMsg.CONSOLE_HELP_EXIT_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
149
addCommand("init", ConsoleMsg.CONSOLE_HELP_INIT_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
150
addCommand("setprop", ConsoleMsg.CONSOLE_HELP_KEYVALUE_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_SETPROP_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
151
addHeader(ConsoleMsg.CONSOLE_HELP_CONTROLLING_BUNDLES_HEADER, help);
152         addCommand("install", ConsoleMsg.CONSOLE_HELP_INSTALL_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
153
addCommand("uninstall", ConsoleMsg.CONSOLE_HELP_UNINSTALL_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
154
addCommand("start", ConsoleMsg.CONSOLE_HELP_START_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
155
addCommand("stop", ConsoleMsg.CONSOLE_HELP_STOP_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
156
addCommand("refresh", ConsoleMsg.CONSOLE_HELP_REFRESH_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
157
addCommand("update", ConsoleMsg.CONSOLE_HELP_UPDATE_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
158
addHeader(ConsoleMsg.CONSOLE_HELP_DISPLAYING_STATUS_HEADER, help);
159         addCommand("status", ConsoleMsg.CONSOLE_HELP_STATE_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_STATUS_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
160
addCommand("ss", ConsoleMsg.CONSOLE_HELP_STATE_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_SS_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
161
addCommand("services", ConsoleMsg.CONSOLE_HELP_FILTER_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_SERVICES_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
162
addCommand("packages", ConsoleMsg.CONSOLE_HELP_PACKAGES_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_PACKAGES_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
163
addCommand("bundles", ConsoleMsg.CONSOLE_HELP_STATE_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_BUNDLES_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
164
addCommand("bundle", ConsoleMsg.CONSOLE_HELP_IDLOCATION_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_BUNDLE_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
165
addCommand("headers", ConsoleMsg.CONSOLE_HELP_IDLOCATION_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_HEADERS_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
166
addCommand("log", ConsoleMsg.CONSOLE_HELP_IDLOCATION_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_LOG_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
167
addHeader(ConsoleMsg.CONSOLE_HELP_EXTRAS_HEADER, help);
168         addCommand("exec", ConsoleMsg.CONSOLE_HELP_COMMAND_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_EXEC_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
169
addCommand("fork", ConsoleMsg.CONSOLE_HELP_COMMAND_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_FORK_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
170
addCommand("gc", ConsoleMsg.CONSOLE_HELP_GC_COMMAND_DESCRIPTION, help); //$NON-NLS-1$
171
addCommand("getprop ", ConsoleMsg.CONSOLE_HELP_GETPROP_ARGUMENT_DESCRIPTION, ConsoleMsg.CONSOLE_HELP_GETPROP_COMMAND_DESCRIPTION, help);//$NON-NLS-1$
172
addHeader(ConsoleMsg.STARTLEVEL_HELP_HEADING, help);
173         addCommand("sl", ConsoleMsg.CONSOLE_HELP_OPTIONAL_IDLOCATION_ARGUMENT_DESCRIPTION, ConsoleMsg.STARTLEVEL_HELP_SL, help); //$NON-NLS-1$
174
addCommand("setfwsl", ConsoleMsg.STARTLEVEL_ARGUMENT_DESCRIPTION, ConsoleMsg.STARTLEVEL_HELP_SETFWSL, help); //$NON-NLS-1$
175
addCommand("setbsl", ConsoleMsg.STARTLEVEL_IDLOCATION_ARGUMENT_DESCRIPTION, ConsoleMsg.STARTLEVEL_HELP_SETBSL, help); //$NON-NLS-1$
176
addCommand("setibsl", ConsoleMsg.STARTLEVEL_ARGUMENT_DESCRIPTION, ConsoleMsg.STARTLEVEL_HELP_SETIBSL, help); //$NON-NLS-1$
177
addHeader(ConsoleMsg.CONSOLE_HELP_PROFILE_HEADING, help);
178         addCommand("profilelog", ConsoleMsg.CONSOLE_HELP_PROFILELOG_DESCRIPTION, help); //$NON-NLS-1$
179
return help.toString();
180     }
181
182     /** Private helper method for getHelp. Formats the help headers. */
183     private void addHeader(String JavaDoc header, StringBuffer JavaDoc help) {
184         help.append("---"); //$NON-NLS-1$
185
help.append(header);
186         help.append("---"); //$NON-NLS-1$
187
help.append(newline);
188     }
189
190     /** Private helper method for getHelp. Formats the command descriptions. */
191     private void addCommand(String JavaDoc command, String JavaDoc description, StringBuffer JavaDoc help) {
192         help.append(tab);
193         help.append(command);
194         help.append(" - "); //$NON-NLS-1$
195
help.append(description);
196         help.append(newline);
197     }
198
199     /** Private helper method for getHelp. Formats the command descriptions with command arguements. */
200     private void addCommand(String JavaDoc command, String JavaDoc parameters, String JavaDoc description, StringBuffer JavaDoc help) {
201         help.append(tab);
202         help.append(command);
203         help.append(" "); //$NON-NLS-1$
204
help.append(parameters);
205         help.append(" - "); //$NON-NLS-1$
206
help.append(description);
207         help.append(newline);
208     }
209
210     /**
211      * Handle the exit command. Exit immediately (System.exit)
212      *
213      * @param intp A CommandInterpreter object containing the command and it's arguments.
214      */

215     public void _exit(CommandInterpreter intp) throws Exception JavaDoc {
216         intp.println();
217         System.exit(0);
218     }
219
220     /**
221      * Handle the launch command. Start the OSGi framework.
222      *
223      * @param intp A CommandInterpreter object containing the command and it's arguments.
224      */

225     public void _launch(CommandInterpreter intp) throws Exception JavaDoc {
226         osgi.launch();
227     }
228
229     /**
230      * Handle the shutdown command. Shutdown the OSGi framework.
231      *
232      * @param intp A CommandInterpreter object containing the command and it's arguments.
233      */

234     public void _shutdown(CommandInterpreter intp) throws Exception JavaDoc {
235         osgi.shutdown();
236     }
237
238     /**
239      * Handle the start command's abbreviation. Invoke _start()
240      *
241      * @param intp A CommandInterpreter object containing the command and it's arguments.
242      */

243     public void _sta(CommandInterpreter intp) throws Exception JavaDoc {
244         _start(intp);
245     }
246
247     /**
248      * Handle the start command. Start the specified bundle(s).
249      *
250      * @param intp A CommandInterpreter object containing the command and it's arguments.
251      */

252     public void _start(CommandInterpreter intp) throws Exception JavaDoc {
253         String JavaDoc nextArg = intp.nextArgument();
254         if (nextArg == null) {
255             intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
256         }
257         while (nextArg != null) {
258             AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
259             if (bundle != null) {
260                 bundle.start();
261             }
262             nextArg = intp.nextArgument();
263         }
264     }
265
266     /**
267      * Handle the stop command's abbreviation. Invoke _stop()
268      *
269      * @param intp A CommandInterpreter object containing the command and it's arguments.
270      */

271     public void _sto(CommandInterpreter intp) throws Exception JavaDoc {
272         _stop(intp);
273     }
274
275     /**
276      * Handle the stop command. Stop the specified bundle(s).
277      *
278      * @param intp A CommandInterpreter object containing the command and it's arguments.
279      */

280     public void _stop(CommandInterpreter intp) throws Exception JavaDoc {
281         String JavaDoc nextArg = intp.nextArgument();
282         if (nextArg == null) {
283             intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
284         }
285         while (nextArg != null) {
286             AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
287             if (bundle != null) {
288                 bundle.stop();
289             }
290             nextArg = intp.nextArgument();
291         }
292     }
293
294     /**
295      * Handle the install command's abbreviation. Invoke _install()
296      *
297      * @param intp A CommandInterpreter object containing the command and it's arguments.
298      */

299     public void _i(CommandInterpreter intp) throws Exception JavaDoc {
300         _install(intp);
301     }
302
303     /**
304      * Handle the install command. Install and optionally start bundle from the given URL\r\n"
305      *
306      * @param intp A CommandInterpreter object containing the command and it's arguments.
307      */

308     public void _install(CommandInterpreter intp) throws Exception JavaDoc {
309         String JavaDoc url = intp.nextArgument();
310         if (url == null) {
311             intp.println(ConsoleMsg.CONSOLE_NOTHING_TO_INSTALL_ERROR);
312         } else {
313             AbstractBundle bundle = (AbstractBundle) context.installBundle(url);
314             intp.print(ConsoleMsg.CONSOLE_BUNDLE_ID_MESSAGE);
315             intp.println(new Long JavaDoc(bundle.getBundleId()));
316
317             String JavaDoc nextArg = intp.nextArgument();
318             if (nextArg != null) {
319                 String JavaDoc start = nextArg.toLowerCase();
320
321                 if (Launcher.matchCommand("start", start, 1)) { //$NON-NLS-1$
322
bundle.start();
323                 }
324             }
325         }
326
327     }
328
329     /**
330      * Handle the update command's abbreviation. Invoke _update()
331      *
332      * @param intp A CommandInterpreter object containing the command and it's arguments.
333      */

334     public void _up(CommandInterpreter intp) throws Exception JavaDoc {
335         _update(intp);
336     }
337
338     /**
339      * Handle the update command. Update the specified bundle(s).
340      *
341      * @param intp A CommandInterpreter object containing the command and it's arguments.
342      */

343     public void _update(CommandInterpreter intp) throws Exception JavaDoc {
344         String JavaDoc token = intp.nextArgument();
345         if (token == null) {
346             intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
347         }
348         while (token != null) {
349
350             if ("*".equals(token)) { //$NON-NLS-1$
351
AbstractBundle[] bundles = (AbstractBundle[]) context.getBundles();
352
353                 int size = bundles.length;
354
355                 if (size > 0) {
356                     for (int i = 0; i < size; i++) {
357                         AbstractBundle bundle = bundles[i];
358
359                         if (bundle.getBundleId() != 0) {
360                             try {
361                                 bundle.update();
362                             } catch (BundleException e) {
363                                 intp.printStackTrace(e);
364                             }
365                         }
366                     }
367                 } else {
368                     intp.println(ConsoleMsg.CONSOLE_NO_INSTALLED_BUNDLES_ERROR);
369                 }
370             } else {
371                 AbstractBundle bundle = getBundleFromToken(intp, token, true);
372                 if (bundle != null) {
373                     String JavaDoc source = intp.nextArgument();
374                     try {
375                         if (source != null) {
376                             bundle.update(new URL JavaDoc(source).openStream());
377                         } else {
378                             bundle.update();
379                         }
380                     } catch (BundleException e) {
381                         intp.printStackTrace(e);
382                     }
383                 }
384             }
385             token = intp.nextArgument();
386         }
387     }
388
389     /**
390      * Handle the uninstall command's abbreviation. Invoke _uninstall()
391      *
392      * @param intp A CommandInterpreter object containing the command and it's arguments.
393      */

394     public void _un(CommandInterpreter intp) throws Exception JavaDoc {
395         _uninstall(intp);
396     }
397
398     /**
399      * Handle the uninstall command. Uninstall the specified bundle(s).
400      *
401      * @param intp A CommandInterpreter object containing the command and it's arguments.
402      */

403     public void _uninstall(CommandInterpreter intp) throws Exception JavaDoc {
404         String JavaDoc nextArg = intp.nextArgument();
405         if (nextArg == null) {
406             intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
407         }
408         while (nextArg != null) {
409             AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
410             if (bundle != null) {
411                 bundle.uninstall();
412             }
413             nextArg = intp.nextArgument();
414         }
415     }
416
417     /**
418      * Handle the status command's abbreviation. Invoke _status()
419      *
420      * @param intp A CommandInterpreter object containing the command and it's arguments.
421      */

422     public void _s(CommandInterpreter intp) throws Exception JavaDoc {
423         _status(intp);
424     }
425
426     private Object JavaDoc[] processOption(CommandInterpreter intp) {
427         String JavaDoc option = intp.nextArgument();
428         String JavaDoc filteredName = null;
429         int stateFilter = -1;
430         if (option != null && option.equals("-s")) {
431             String JavaDoc searchedState = intp.nextArgument();
432             StringTokenizer tokens = new StringTokenizer(searchedState, ",");
433             while (tokens.hasMoreElements()) {
434                 String JavaDoc desiredState = (String JavaDoc) tokens.nextElement();
435                 Field JavaDoc match = null;
436                 try {
437                     match = Bundle.class.getField(desiredState.toUpperCase());
438                     if (stateFilter == -1)
439                         stateFilter = 0;
440                     stateFilter |= match.getInt(match);
441                 } catch (NoSuchFieldException JavaDoc e) {
442                     intp.println(ConsoleMsg.CONSOLE_INVALID_INPUT + ": " + desiredState);
443                     return null;
444                 } catch (IllegalAccessException JavaDoc e) {
445                     intp.println(ConsoleMsg.CONSOLE_INVALID_INPUT + ": " + desiredState);
446                     return null;
447                 }
448             }
449         } else {
450             filteredName = option;
451         }
452         String JavaDoc tmp = intp.nextArgument();
453         if (tmp != null)
454             filteredName = tmp;
455         return new Object JavaDoc[] {filteredName, new Integer JavaDoc(stateFilter)};
456     }
457
458     /**
459      * Handle the status command. Display installed bundles and registered services.
460      *
461      * @param intp A CommandInterpreter object containing the command and it's arguments.
462      */

463     public void _status(CommandInterpreter intp) throws Exception JavaDoc {
464         if (osgi.isActive()) {
465             intp.println(ConsoleMsg.CONSOLE_FRAMEWORK_IS_LAUNCHED_MESSAGE);
466         } else {
467             intp.println(ConsoleMsg.CONSOLE_FRAMEWORK_IS_SHUTDOWN_MESSAGE);
468         }
469         intp.println();
470
471         Object JavaDoc[] options = processOption(intp);
472         if (options == null)
473             return;
474
475         AbstractBundle[] bundles = (AbstractBundle[]) context.getBundles();
476         int size = bundles.length;
477
478         if (size == 0) {
479             intp.println(ConsoleMsg.CONSOLE_NO_INSTALLED_BUNDLES_ERROR);
480             return;
481         }
482         intp.print(ConsoleMsg.CONSOLE_ID);
483         intp.print(tab);
484         intp.println(ConsoleMsg.CONSOLE_BUNDLE_LOCATION_MESSAGE);
485         intp.println(ConsoleMsg.CONSOLE_STATE_BUNDLE_FILE_NAME_HEADER);
486         for (int i = 0; i < size; i++) {
487             AbstractBundle bundle = bundles[i];
488             if (!match(bundle, (String JavaDoc) options[0], ((Integer JavaDoc) options[1]).intValue()))
489                 continue;
490             intp.print(new Long JavaDoc(bundle.getBundleId()));
491             intp.print(tab);
492             intp.println(bundle.getLocation());
493             intp.print(" "); //$NON-NLS-1$
494
intp.print(getStateName(bundle));
495             intp.println(bundle.bundledata);
496         }
497
498         ServiceReference[] services = context.getServiceReferences(null, null);
499         if (services != null) {
500             intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE);
501             size = services.length;
502             for (int i = 0; i < size; i++) {
503                 intp.println(services[i]);
504             }
505         }
506     }
507
508     /**
509      * Handle the services command's abbreviation. Invoke _services()
510      *
511      * @param intp A CommandInterpreter object containing the command and it's arguments.
512      */

513     public void _se(CommandInterpreter intp) throws Exception JavaDoc {
514         _services(intp);
515     }
516
517     /**
518      * Handle the services command. Display registered service details.
519      *
520      * @param intp A CommandInterpreter object containing the command and it's arguments.
521      */

522     public void _services(CommandInterpreter intp) throws Exception JavaDoc {
523         String JavaDoc filter = null;
524
525         String JavaDoc nextArg = intp.nextArgument();
526         if (nextArg != null) {
527             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
528             while (nextArg != null) {
529                 buf.append(' ');
530                 buf.append(nextArg);
531                 nextArg = intp.nextArgument();
532             }
533             filter = buf.toString();
534         }
535
536         ServiceReference[] services = context.getServiceReferences(null, filter);
537         if (services != null) {
538             int size = services.length;
539             if (size > 0) {
540                 for (int j = 0; j < size; j++) {
541                     ServiceReference service = services[j];
542                     intp.println(service);
543                     intp.print(" "); //$NON-NLS-1$
544
intp.print(ConsoleMsg.CONSOLE_REGISTERED_BY_BUNDLE_MESSAGE);
545                     intp.print(" "); //$NON-NLS-1$
546
intp.println(service.getBundle());
547                     AbstractBundle[] users = (AbstractBundle[]) service.getUsingBundles();
548                     if (users != null) {
549                         intp.print(" "); //$NON-NLS-1$
550
intp.println(ConsoleMsg.CONSOLE_BUNDLES_USING_SERVICE_MESSAGE);
551                         for (int k = 0; k < users.length; k++) {
552                             intp.print(" "); //$NON-NLS-1$
553
intp.println(users[k]);
554                         }
555                     } else {
556                         intp.print(" "); //$NON-NLS-1$
557
intp.println(ConsoleMsg.CONSOLE_NO_BUNDLES_USING_SERVICE_MESSAGE);
558                     }
559                 }
560                 return;
561             }
562         }
563         intp.println(ConsoleMsg.CONSOLE_NO_REGISTERED_SERVICES_MESSAGE);
564     }
565
566     /**
567      * Handle the packages command's abbreviation. Invoke _packages()
568      *
569      * @param intp A CommandInterpreter object containing the command and it's arguments.
570      */

571     public void _p(CommandInterpreter intp) throws Exception JavaDoc {
572         _packages(intp);
573     }
574
575     /**
576      * Handle the packages command. Display imported/exported package details.
577      *
578      * @param intp A CommandInterpreter object containing the command and it's arguments.
579      */

580     public void _packages(CommandInterpreter intp) throws Exception JavaDoc {
581         org.osgi.framework.Bundle bundle = null;
582
583         String JavaDoc token = intp.nextArgument();
584         if (token != null) {
585             bundle = getBundleFromToken(intp, token, false);
586         }
587
588         org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$
589
if (packageAdminRef != null) {
590             org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef);
591             if (packageAdmin != null) {
592                 try {
593                     org.osgi.service.packageadmin.ExportedPackage[] packages = null;
594
595                     if (token != null)
596                         packages = packageAdmin.getExportedPackages(token);
597                     if (packages == null)
598                         packages = packageAdmin.getExportedPackages(bundle);
599
600                     if (packages == null) {
601                         intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_MESSAGE);
602                     } else {
603                         for (int i = 0; i < packages.length; i++) {
604                             org.osgi.service.packageadmin.ExportedPackage pkg = packages[i];
605                             intp.print(pkg);
606
607                             boolean removalPending = pkg.isRemovalPending();
608                             if (removalPending) {
609                                 intp.print("("); //$NON-NLS-1$
610
intp.print(ConsoleMsg.CONSOLE_REMOVAL_PENDING_MESSAGE);
611                                 intp.println(")"); //$NON-NLS-1$
612
}
613
614                             org.osgi.framework.Bundle exporter = pkg.getExportingBundle();
615                             if (exporter != null) {
616                                 intp.print("<"); //$NON-NLS-1$
617
intp.print(exporter);
618                                 intp.println(">"); //$NON-NLS-1$
619

620                                 org.osgi.framework.Bundle[] importers = pkg.getImportingBundles();
621                                 for (int j = 0; j < importers.length; j++) {
622                                     intp.print(" "); //$NON-NLS-1$
623
intp.print(importers[j]);
624                                     intp.print(" "); //$NON-NLS-1$
625
intp.println(ConsoleMsg.CONSOLE_IMPORTS_MESSAGE);
626                                 }
627                             } else {
628                                 intp.print("<"); //$NON-NLS-1$
629
intp.print(ConsoleMsg.CONSOLE_STALE_MESSAGE);
630                                 intp.println(">"); //$NON-NLS-1$
631
}
632
633                         }
634                     }
635                 } finally {
636                     context.ungetService(packageAdminRef);
637                 }
638             }
639         } else {
640             intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_NO_PACKAGE_ADMIN_MESSAGE);
641         }
642     }
643
644     /**
645      * Handle the bundles command. Display details for all installed bundles.
646      *
647      * @param intp A CommandInterpreter object containing the command and it's arguments.
648      */

649     public void _bundles(CommandInterpreter intp) throws Exception JavaDoc {
650         Object JavaDoc[] options = processOption(intp);
651         if (options == null)
652             return;
653
654         AbstractBundle[] bundles = (AbstractBundle[]) context.getBundles();
655         int size = bundles.length;
656
657         if (size == 0) {
658             intp.println(ConsoleMsg.CONSOLE_NO_INSTALLED_BUNDLES_ERROR);
659             return;
660         }
661
662         for (int i = 0; i < size; i++) {
663             AbstractBundle bundle = bundles[i];
664             if (!match(bundle, (String JavaDoc) options[0], ((Integer JavaDoc) options[1]).intValue()))
665                 continue;
666             long id = bundle.getBundleId();
667             intp.println(bundle);
668             intp.print(" "); //$NON-NLS-1$
669
intp.print(NLS.bind(ConsoleMsg.CONSOLE_ID_MESSAGE, String.valueOf(id)));
670             intp.print(", "); //$NON-NLS-1$
671
intp.print(NLS.bind(ConsoleMsg.CONSOLE_STATUS_MESSAGE, getStateName(bundle)));
672             if (id != 0) {
673                 File dataRoot = osgi.framework.getDataFile(bundle, ""); //$NON-NLS-1$
674

675                 String JavaDoc root = (dataRoot == null) ? null : dataRoot.getAbsolutePath();
676
677                 intp.print(NLS.bind(ConsoleMsg.CONSOLE_DATA_ROOT_MESSAGE, root));
678             } else {
679                 intp.println();
680             }
681
682             ServiceReference[] services = bundle.getRegisteredServices();
683             if (services != null) {
684                 intp.print(" "); //$NON-NLS-1$
685
intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE);
686                 for (int j = 0; j < services.length; j++) {
687                     intp.print(" "); //$NON-NLS-1$
688
intp.println(services[j]);
689                 }
690             } else {
691                 intp.print(" "); //$NON-NLS-1$
692
intp.println(ConsoleMsg.CONSOLE_NO_REGISTERED_SERVICES_MESSAGE);
693             }
694
695             services = bundle.getServicesInUse();
696             if (services != null) {
697                 intp.print(" "); //$NON-NLS-1$
698
intp.println(ConsoleMsg.CONSOLE_SERVICES_IN_USE_MESSAGE);
699                 for (int j = 0; j < services.length; j++) {
700                     intp.print(" "); //$NON-NLS-1$
701
intp.println(services[j]);
702                 }
703             } else {
704                 intp.print(" "); //$NON-NLS-1$
705
intp.println(ConsoleMsg.CONSOLE_NO_SERVICES_IN_USE_MESSAGE);
706             }
707         }
708     }
709
710     /**
711      * Handle the bundle command's abbreviation. Invoke _bundle()
712      *
713      * @param intp A CommandInterpreter object containing the command and it's arguments.
714      */

715     public void _b(CommandInterpreter intp) throws Exception JavaDoc {
716         _bundle(intp);
717     }
718
719     /**
720      * Handle the bundle command. Display details for the specified bundle(s).
721      *
722      * @param intp A CommandInterpreter object containing the command and it's arguments.
723      */

724     public void _bundle(CommandInterpreter intp) throws Exception JavaDoc {
725         String JavaDoc nextArg = intp.nextArgument();
726         if (nextArg == null) {
727             intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
728         }
729         while (nextArg != null) {
730             AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
731             if (bundle != null) {
732                 long id = bundle.getBundleId();
733                 intp.println(bundle);
734                 intp.print(" "); //$NON-NLS-1$
735
intp.print(NLS.bind(ConsoleMsg.CONSOLE_ID_MESSAGE, String.valueOf(id)));
736                 intp.print(", "); //$NON-NLS-1$
737
intp.print(NLS.bind(ConsoleMsg.CONSOLE_STATUS_MESSAGE, getStateName(bundle)));
738                 if (id != 0) {
739                     File dataRoot = osgi.framework.getDataFile(bundle, ""); //$NON-NLS-1$
740

741                     String JavaDoc root = (dataRoot == null) ? null : dataRoot.getAbsolutePath();
742
743                     intp.print(NLS.bind(ConsoleMsg.CONSOLE_DATA_ROOT_MESSAGE, root));
744                     intp.println();
745                 } else {
746                     intp.println();
747                 }
748
749                 ServiceReference[] services = bundle.getRegisteredServices();
750                 if (services != null) {
751                     intp.print(" "); //$NON-NLS-1$
752
intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE);
753                     for (int j = 0; j < services.length; j++) {
754                         intp.print(" "); //$NON-NLS-1$
755
intp.println(services[j]);
756                     }
757                 } else {
758                     intp.print(" "); //$NON-NLS-1$
759
intp.println(ConsoleMsg.CONSOLE_NO_REGISTERED_SERVICES_MESSAGE);
760                 }
761
762                 services = bundle.getServicesInUse();
763                 if (services != null) {
764                     intp.print(" "); //$NON-NLS-1$
765
intp.println(ConsoleMsg.CONSOLE_SERVICES_IN_USE_MESSAGE);
766                     for (int j = 0; j < services.length; j++) {
767                         intp.print(" "); //$NON-NLS-1$
768
intp.println(services[j]);
769                     }
770                 } else {
771                     intp.print(" "); //$NON-NLS-1$
772
intp.println(ConsoleMsg.CONSOLE_NO_SERVICES_IN_USE_MESSAGE);
773                 }
774
775                 org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$
776
if (packageAdminRef != null) {
777                     BundleDescription desc = bundle.getBundleDescription();
778                     if (desc != null) {
779                         boolean title = true;
780                         try {
781                             ExportPackageDescription[] exports = desc.getExportPackages();
782                             if (exports == null || exports.length == 0) {
783                                 intp.print(" "); //$NON-NLS-1$
784
intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_MESSAGE);
785                             } else {
786                                 title = true;
787
788                                 for (int i = 0; i < exports.length; i++) {
789                                     if (title) {
790                                         intp.print(" "); //$NON-NLS-1$
791
intp.println(ConsoleMsg.CONSOLE_EXPORTED_PACKAGES_MESSAGE);
792                                         title = false;
793                                     }
794                                     intp.print(" "); //$NON-NLS-1$
795
intp.print(exports[i].getName());
796                                     intp.print("; version=\""); //$NON-NLS-1$
797
intp.print(exports[i].getVersion());
798                                     intp.print("\""); //$NON-NLS-1$
799
if (desc.isRemovalPending()) {
800                                         intp.println(ConsoleMsg.CONSOLE_EXPORTED_REMOVAL_PENDING_MESSAGE);
801                                     } else {
802                                         intp.println(ConsoleMsg.CONSOLE_EXPORTED_MESSAGE);
803                                     }
804                                 }
805
806                                 if (title) {
807                                     intp.print(" "); //$NON-NLS-1$
808
intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_MESSAGE);
809                                 }
810                             }
811                             title = true;
812                             if (desc != null) {
813                                 ExportPackageDescription[] imports = desc.getContainingState().getStateHelper().getVisiblePackages(desc, StateHelper.VISIBLE_INCLUDE_EE_PACKAGES);
814                                 title = printImportedPackages(imports, intp, title);
815                             }
816
817                             if (title) {
818                                 intp.print(" "); //$NON-NLS-1$
819
intp.println(ConsoleMsg.CONSOLE_NO_IMPORTED_PACKAGES_MESSAGE);
820                             }
821
822                             PackageAdmin packageAdmin = (PackageAdmin) context.getService(packageAdminRef);
823                             if (packageAdmin != null) {
824                                 intp.print(" "); //$NON-NLS-1$
825
if ((packageAdmin.getBundleType(bundle) & PackageAdminImpl.BUNDLE_TYPE_FRAGMENT) > 0) {
826                                     org.osgi.framework.Bundle[] hosts = packageAdmin.getHosts(bundle);
827                                     if (hosts != null) {
828                                         intp.println(ConsoleMsg.CONSOLE_HOST_MESSAGE);
829                                         for (int i = 0; i < hosts.length; i++) {
830                                             intp.print(" "); //$NON-NLS-1$
831
intp.println(hosts[i]);
832                                         }
833                                     } else {
834                                         intp.println(ConsoleMsg.CONSOLE_NO_HOST_MESSAGE);
835                                     }
836                                 } else {
837                                     org.osgi.framework.Bundle[] fragments = packageAdmin.getFragments(bundle);
838                                     if (fragments != null) {
839                                         intp.println(ConsoleMsg.CONSOLE_FRAGMENT_MESSAGE);
840                                         for (int i = 0; i < fragments.length; i++) {
841                                             intp.print(" "); //$NON-NLS-1$
842
intp.println(fragments[i]);
843                                         }
844                                     } else {
845                                         intp.println(ConsoleMsg.CONSOLE_NO_FRAGMENT_MESSAGE);
846                                     }
847                                 }
848
849                                 RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(null);
850                                 RequiredBundle requiredBundle = null;
851                                 if (requiredBundles != null) {
852                                     for (int i = 0; i < requiredBundles.length; i++) {
853                                         if (requiredBundles[i].getBundle() == bundle) {
854                                             requiredBundle = requiredBundles[i];
855                                             break;
856                                         }
857                                     }
858                                 }
859
860                                 if (requiredBundle == null) {
861                                     intp.print(" "); //$NON-NLS-1$
862
intp.println(ConsoleMsg.CONSOLE_NO_NAMED_CLASS_SPACES_MESSAGE);
863                                 } else {
864                                     intp.print(" "); //$NON-NLS-1$
865
intp.println(ConsoleMsg.CONSOLE_NAMED_CLASS_SPACE_MESSAGE);
866                                     intp.print(" "); //$NON-NLS-1$
867
intp.print(requiredBundle);
868                                     if (requiredBundle.isRemovalPending()) {
869                                         intp.println(ConsoleMsg.CONSOLE_REMOVAL_PENDING_MESSAGE);
870                                     } else {
871                                         intp.println(ConsoleMsg.CONSOLE_PROVIDED_MESSAGE);
872                                     }
873                                 }
874                                 title = true;
875                                 for (int i = 0; i < requiredBundles.length; i++) {
876                                     if (requiredBundles[i] == requiredBundle)
877                                         continue;
878
879                                     org.osgi.framework.Bundle[] depBundles = requiredBundles[i].getRequiringBundles();
880                                     if (depBundles == null)
881                                         continue;
882
883                                     for (int j = 0; j < depBundles.length; j++) {
884                                         if (depBundles[j] == bundle) {
885                                             if (title) {
886                                                 intp.print(" "); //$NON-NLS-1$
887
intp.println(ConsoleMsg.CONSOLE_REQUIRED_BUNDLES_MESSAGE);
888                                                 title = false;
889                                             }
890                                             intp.print(" "); //$NON-NLS-1$
891
intp.print(requiredBundles[i]);
892
893                                             org.osgi.framework.Bundle provider = requiredBundles[i].getBundle();
894                                             intp.print("<"); //$NON-NLS-1$
895
intp.print(provider);
896                                             intp.println(">"); //$NON-NLS-1$
897
}
898                                     }
899                                 }
900                                 if (title) {
901                                     intp.print(" "); //$NON-NLS-1$
902
intp.println(ConsoleMsg.CONSOLE_NO_REQUIRED_BUNDLES_MESSAGE);
903                                 }
904
905                             }
906                         } finally {
907                             context.ungetService(packageAdminRef);
908                         }
909                     }
910                 } else {
911                     intp.print(" "); //$NON-NLS-1$
912
intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_NO_PACKAGE_ADMIN_MESSAGE);
913                 }
914
915                 SecurityManager JavaDoc sm = System.getSecurityManager();
916                 if (sm != null) {
917                     ProtectionDomain JavaDoc domain = bundle.getProtectionDomain();
918
919                     intp.println(domain);
920                 }
921             }
922             nextArg = intp.nextArgument();
923         }
924     }
925
926     private boolean printImportedPackages(ExportPackageDescription[] importedPkgs, CommandInterpreter intp, boolean title) {
927         for (int i = 0; i < importedPkgs.length; i++) {
928             if (title) {
929                 intp.print(" "); //$NON-NLS-1$
930
intp.println(ConsoleMsg.CONSOLE_IMPORTED_PACKAGES_MESSAGE);
931                 title = false;
932             }
933             intp.print(" "); //$NON-NLS-1$
934
intp.print(importedPkgs[i].getName());
935             intp.print("; version=\""); //$NON-NLS-1$
936
intp.print(importedPkgs[i].getVersion());
937             intp.print("\""); //$NON-NLS-1$
938
Bundle exporter = context.getBundle(importedPkgs[i].getSupplier().getBundleId());
939             if (exporter != null) {
940                 intp.print("<"); //$NON-NLS-1$
941
intp.print(exporter);
942                 intp.println(">"); //$NON-NLS-1$
943
} else {
944                 intp.print("<"); //$NON-NLS-1$
945
intp.print(ConsoleMsg.CONSOLE_STALE_MESSAGE);
946                 intp.println(">"); //$NON-NLS-1$
947
}
948         }
949         return title;
950     }
951
952     /**
953      * Handle the log command's abbreviation. Invoke _log()
954      *
955      * @param intp A CommandInterpreter object containing the command and it's arguments.
956      */

957     public void _l(CommandInterpreter intp) throws Exception JavaDoc {
958         _log(intp);
959     }
960
961     /**
962      * Handle the log command. Display log entries.
963      *
964      * @param intp A CommandInterpreter object containing the command and it's arguments.
965      */

966     public void _log(CommandInterpreter intp) throws Exception JavaDoc {
967         long logid = -1;
968         String JavaDoc token = intp.nextArgument();
969         if (token != null) {
970             AbstractBundle bundle = getBundleFromToken(intp, token, false);
971
972             if (bundle == null) {
973                 try {
974                     logid = Long.parseLong(token);
975                 } catch (NumberFormatException JavaDoc e) {
976                     return;
977                 }
978             } else {
979                 logid = bundle.getBundleId();
980             }
981         }
982
983         org.osgi.framework.ServiceReference logreaderRef = context.getServiceReference("org.osgi.service.log.LogReaderService"); //$NON-NLS-1$
984
if (logreaderRef != null) {
985             Object JavaDoc logreader = context.getService(logreaderRef);
986             if (logreader != null) {
987                 try {
988                     Enumeration logs = (Enumeration) (logreader.getClass().getMethod("getLog", null).invoke(logreader, null)); //$NON-NLS-1$
989
ArrayList entriesList = new ArrayList();
990                     while (logs.hasMoreElements())
991                         entriesList.add(0, logs.nextElement());
992                     Object JavaDoc[] entries = entriesList.toArray();
993                     if (entries.length == 0)
994                         return;
995                     Class JavaDoc clazz = entries[0].getClass();
996                     Method JavaDoc getBundle = clazz.getMethod("getBundle", null); //$NON-NLS-1$
997
Method JavaDoc getLevel = clazz.getMethod("getLevel", null); //$NON-NLS-1$
998
Method JavaDoc getMessage = clazz.getMethod("getMessage", null); //$NON-NLS-1$
999
Method JavaDoc getServiceReference = clazz.getMethod("getServiceReference", null); //$NON-NLS-1$
1000
Method JavaDoc getException = clazz.getMethod("getException", null); //$NON-NLS-1$
1001

1002                    for (int i = 0; i < entries.length; i++) {
1003                        Object JavaDoc logentry = entries[i];
1004                        AbstractBundle bundle = (AbstractBundle) getBundle.invoke(logentry, null);
1005
1006                        if ((logid == -1) || ((bundle != null) && (logid == bundle.getBundleId()))) {
1007                            Integer JavaDoc level = (Integer JavaDoc) getLevel.invoke(logentry, null);
1008                            switch (level.intValue()) {
1009                                case 4 :
1010                                    intp.print(">"); //$NON-NLS-1$
1011
intp.print(ConsoleMsg.CONSOLE_DEBUG_MESSAGE);
1012                                    intp.print(" "); //$NON-NLS-1$
1013
break;
1014                                case 3 :
1015                                    intp.print(">"); //$NON-NLS-1$
1016
intp.print(ConsoleMsg.CONSOLE_INFO_MESSAGE);
1017                                    intp.print(" "); //$NON-NLS-1$
1018
break;
1019                                case 2 :
1020                                    intp.print(">"); //$NON-NLS-1$
1021
intp.print(ConsoleMsg.CONSOLE_WARNING_MESSAGE);
1022                                    intp.print(" "); //$NON-NLS-1$
1023
break;
1024                                case 1 :
1025                                    intp.print(">"); //$NON-NLS-1$
1026
intp.print(ConsoleMsg.CONSOLE_ERROR_MESSAGE);
1027                                    intp.print(" "); //$NON-NLS-1$
1028
break;
1029                                default :
1030                                    intp.print(">"); //$NON-NLS-1$
1031
intp.print(level);
1032                                    intp.print(" "); //$NON-NLS-1$
1033
break;
1034                            }
1035
1036                            if (bundle != null) {
1037                                intp.print("["); //$NON-NLS-1$
1038
intp.print(new Long JavaDoc(bundle.getBundleId()));
1039                                intp.print("] "); //$NON-NLS-1$
1040
}
1041
1042                            intp.print(getMessage.invoke(logentry, null));
1043                            intp.print(" "); //$NON-NLS-1$
1044

1045                            ServiceReferenceImpl svcref = (ServiceReferenceImpl) getServiceReference.invoke(logentry, null);
1046                            if (svcref != null) {
1047                                intp.print("{"); //$NON-NLS-1$
1048
intp.print(Constants.SERVICE_ID);
1049                                intp.print("="); //$NON-NLS-1$
1050
intp.print(svcref.getProperty(Constants.SERVICE_ID).toString());
1051                                intp.println("}"); //$NON-NLS-1$
1052
} else {
1053                                if (bundle != null) {
1054                                    intp.println(bundle.getLocation());
1055                                } else {
1056                                    intp.println();
1057                                }
1058                            }
1059
1060                            Throwable JavaDoc t = (Throwable JavaDoc) getException.invoke(logentry, null);
1061                            if (t != null) {
1062                                intp.printStackTrace(t);
1063                            }
1064                        }
1065                    }
1066                } finally {
1067                    context.ungetService(logreaderRef);
1068                }
1069                return;
1070            }
1071        }
1072
1073        intp.println(ConsoleMsg.CONSOLE_LOGSERVICE_NOT_REGISTERED_MESSAGE);
1074    }
1075
1076    /**
1077     * Handle the gc command. Perform a garbage collection.
1078     *
1079     * @param intp A CommandInterpreter object containing the command and it's arguments.
1080     */

1081    public void _gc(CommandInterpreter intp) throws Exception JavaDoc {
1082        long before = Runtime.getRuntime().freeMemory();
1083
1084        /* Let the finilizer finish its work and remove objects from its queue */
1085        System.gc(); /* asyncronous garbage collector might already run */
1086        System.gc(); /* to make sure it does a full gc call it twice */
1087        System.runFinalization();
1088        try {
1089            Thread.sleep(100);
1090        } catch (InterruptedException JavaDoc e) {
1091            // do nothing
1092
}
1093
1094        long after = Runtime.getRuntime().freeMemory();
1095        intp.print(ConsoleMsg.CONSOLE_TOTAL_MEMORY_MESSAGE);
1096        intp.println(String.valueOf(Runtime.getRuntime().totalMemory()));
1097        intp.print(ConsoleMsg.CONSOLE_FREE_MEMORY_BEFORE_GARBAGE_COLLECTION_MESSAGE);
1098        intp.println(String.valueOf(before));
1099        intp.print(ConsoleMsg.CONSOLE_FREE_MEMORY_AFTER_GARBAGE_COLLECTION_MESSAGE);
1100        intp.println(String.valueOf(after));
1101        intp.print(ConsoleMsg.CONSOLE_MEMORY_GAINED_WITH_GARBAGE_COLLECTION_MESSAGE);
1102        intp.println(String.valueOf(after - before));
1103    }
1104
1105    /**
1106     * Handle the init command. Uninstall all bundles.
1107     *
1108     * @param intp A CommandInterpreter object containing the command and it's arguments.
1109     */

1110    public void _init(CommandInterpreter intp) throws Exception JavaDoc {
1111        if (osgi.isActive()) {
1112            intp.print(newline);
1113            intp.println(ConsoleMsg.CONSOLE_FRAMEWORK_LAUNCHED_PLEASE_SHUTDOWN_MESSAGE);
1114            return;
1115        }
1116
1117        AbstractBundle[] bundles = (AbstractBundle[]) context.getBundles();
1118
1119        int size = bundles.length;
1120
1121        if (size > 0) {
1122            for (int i = 0; i < size; i++) {
1123                AbstractBundle bundle = bundles[i];
1124
1125                if (bundle.getBundleId() != 0) {
1126                    try {
1127                        bundle.uninstall();
1128                    } catch (BundleException e) {
1129                        intp.printStackTrace(e);
1130                    }
1131                }
1132            }
1133        } else {
1134            intp.println(ConsoleMsg.CONSOLE_NO_INSTALLED_BUNDLES_ERROR);
1135        }
1136        if (permAdmin != null) {
1137            // clear the permissions from permission admin
1138
permAdmin.setDefaultPermissions(null);
1139            String JavaDoc[] permLocations = permAdmin.getLocations();
1140            if (permLocations != null)
1141                for (int i = 0; i < permLocations.length; i++)
1142                    permAdmin.setPermissions(permLocations[i], null);
1143        }
1144        // clear the permissions from conditional permission admin
1145
if (condPermAdmin != null)
1146            for (Enumeration infos = condPermAdmin.getConditionalPermissionInfos(); infos.hasMoreElements();)
1147                ((ConditionalPermissionInfo) infos.nextElement()).delete();
1148    }
1149
1150    /**
1151     * Handle the close command. Shutdown and exit.
1152     *
1153     * @param intp A CommandInterpreter object containing the command and it's arguments.
1154     */

1155    public void _close(CommandInterpreter intp) throws Exception JavaDoc {
1156        intp.println();
1157        osgi.close();
1158        System.exit(0);
1159    }
1160
1161    /**
1162     * Handle the refresh command's abbreviation. Invoke _refresh()
1163     *
1164     * @param intp A CommandInterpreter object containing the command and it's arguments.
1165     */

1166    public void _r(CommandInterpreter intp) throws Exception JavaDoc {
1167        _refresh(intp);
1168    }
1169
1170    /**
1171     * Handle the refresh command. Refresh the packages of the specified bundles.
1172     *
1173     * @param intp A CommandInterpreter object containing the command and it's arguments.
1174     */

1175    public void _refresh(CommandInterpreter intp) throws Exception JavaDoc {
1176        org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$
1177
if (packageAdminRef != null) {
1178            org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef);
1179            if (packageAdmin != null) {
1180                try {
1181                    AbstractBundle[] refresh = null;
1182
1183                    String JavaDoc token = intp.nextArgument();
1184                    if (token != null) {
1185                        Vector bundles = new Vector();
1186
1187                        while (token != null) {
1188                            AbstractBundle bundle = getBundleFromToken(intp, token, true);
1189
1190                            if (bundle != null) {
1191                                bundles.addElement(bundle);
1192                            }
1193                            token = intp.nextArgument();
1194                        }
1195
1196                        int size = bundles.size();
1197
1198                        if (size == 0) {
1199                            intp.println(ConsoleMsg.CONSOLE_INVALID_BUNDLE_SPECIFICATION_ERROR);
1200                            return;
1201                        }
1202
1203                        refresh = new AbstractBundle[size];
1204                        bundles.copyInto(refresh);
1205                    }
1206
1207                    packageAdmin.refreshPackages(refresh);
1208                } finally {
1209                    context.ungetService(packageAdminRef);
1210                }
1211            }
1212        } else {
1213            intp.println(ConsoleMsg.CONSOLE_CAN_NOT_REFRESH_NO_PACKAGE_ADMIN_ERROR);
1214        }
1215    }
1216
1217    /**
1218     * Executes the given system command in a separate system process
1219     * and waits for it to finish.
1220     *
1221     * @param intp A CommandInterpreter object containing the command and it's arguments.
1222     */

1223    public void _exec(CommandInterpreter intp) throws Exception JavaDoc {
1224        String JavaDoc command = intp.nextArgument();
1225        if (command == null) {
1226            intp.println(ConsoleMsg.CONSOLE_NO_COMMAND_SPECIFIED_ERROR);
1227            return;
1228        }
1229
1230        Process JavaDoc p = Runtime.getRuntime().exec(command);
1231
1232        intp.println(NLS.bind(ConsoleMsg.CONSOLE_STARTED_IN_MESSAGE, command, String.valueOf(p)));
1233        int result = p.waitFor();
1234        intp.println(NLS.bind(ConsoleMsg.CONSOLE_EXECUTED_RESULT_CODE_MESSAGE, command, String.valueOf(result)));
1235    }
1236
1237    /**
1238     * Executes the given system command in a separate system process. It does
1239     * not wait for a result.
1240     *
1241     * @param intp A CommandInterpreter object containing the command and it's arguments.
1242     */

1243    public void _fork(CommandInterpreter intp) throws Exception JavaDoc {
1244        String JavaDoc command = intp.nextArgument();
1245        if (command == null) {
1246            intp.println(ConsoleMsg.CONSOLE_NO_COMMAND_SPECIFIED_ERROR);
1247            return;
1248        }
1249
1250        Process JavaDoc p = Runtime.getRuntime().exec(command);
1251        intp.println(NLS.bind(ConsoleMsg.CONSOLE_STARTED_IN_MESSAGE, command, String.valueOf(p)));
1252    }
1253
1254    /**
1255     * Handle the headers command's abbreviation. Invoke _headers()
1256     *
1257     * @param intp A CommandInterpreter object containing the command and it's arguments.
1258     */

1259    public void _h(CommandInterpreter intp) throws Exception JavaDoc {
1260        _headers(intp);
1261    }
1262
1263    /**
1264     * Handle the headers command. Display headers for the specified bundle(s).
1265     *
1266     * @param intp A CommandInterpreter object containing the command and it's arguments.
1267     */

1268    public void _headers(CommandInterpreter intp) throws Exception JavaDoc {
1269
1270        String JavaDoc nextArg = intp.nextArgument();
1271        if (nextArg == null) {
1272            intp.println(ConsoleMsg.CONSOLE_NO_BUNDLE_SPECIFIED_ERROR);
1273        }
1274        while (nextArg != null) {
1275            AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
1276            if (bundle != null) {
1277                intp.printDictionary(bundle.getHeaders(), ConsoleMsg.CONSOLE_BUNDLE_HEADERS_TITLE);
1278            }
1279            nextArg = intp.nextArgument();
1280        }
1281    }
1282
1283    /**
1284     * Handles the props command's abbreviation. Invokes _props()
1285     *
1286     * @param intp A CommandInterpreter object containing the command and it's arguments.
1287     */

1288    public void _pr(CommandInterpreter intp) throws Exception JavaDoc {
1289        _props(intp);
1290    }
1291
1292    /**
1293     * Handles the _props command. Prints the system properties sorted.
1294     *
1295     * @param intp A CommandInterpreter object containing the command and it's arguments.
1296     */

1297    public void _props(CommandInterpreter intp) throws Exception JavaDoc {
1298        intp.printDictionary(FrameworkProperties.getProperties(), ConsoleMsg.CONSOLE_SYSTEM_PROPERTIES_TITLE);
1299    }
1300
1301    /**
1302     * Handles the setprop command's abbreviation. Invokes _setprop()
1303     *
1304     * @param intp A CommandInterpreter object containing the command and it's arguments.
1305     */

1306    public void _setp(CommandInterpreter intp) throws Exception JavaDoc {
1307        _setprop(intp);
1308    }
1309
1310    /**
1311     * Handles the setprop command. Sets the CDS property in the given argument.
1312     *
1313     * @param intp A CommandInterpreter object containing the command and it's arguments.
1314     */

1315    public void _setprop(CommandInterpreter intp) throws Exception JavaDoc {
1316        String JavaDoc argument = intp.nextArgument();
1317        if (argument == null) {
1318            intp.println(ConsoleMsg.CONSOLE_NO_PARAMETERS_SPECIFIED_TITLE);
1319            _props(intp);
1320        } else {
1321            InputStream in = new ByteArrayInputStream(argument.getBytes());
1322            try {
1323                Properties sysprops = FrameworkProperties.getProperties();
1324                Properties newprops = new Properties();
1325                newprops.load(in);
1326                intp.println(ConsoleMsg.CONSOLE_SETTING_PROPERTIES_TITLE);
1327                Enumeration keys = newprops.propertyNames();
1328                while (keys.hasMoreElements()) {
1329                    String JavaDoc key = (String JavaDoc) keys.nextElement();
1330                    String JavaDoc value = (String JavaDoc) newprops.get(key);
1331                    sysprops.put(key, value);
1332                    intp.println(tab + key + " = " + value); //$NON-NLS-1$
1333
}
1334            } catch (IOException e) {
1335                // ignore
1336
} finally {
1337                try {
1338                    in.close();
1339                } catch (IOException e) {
1340                    // ignore
1341
}
1342            }
1343        }
1344    }
1345
1346    /**
1347     * Prints the short version of the status.
1348     * For the long version use "status".
1349     *
1350     * @param intp A CommandInterpreter object containing the command and it's arguments.
1351     */

1352    public void _ss(CommandInterpreter intp) throws Exception JavaDoc {
1353        if (osgi.isActive()) {
1354            intp.println();
1355            intp.println(ConsoleMsg.CONSOLE_FRAMEWORK_IS_LAUNCHED_MESSAGE);
1356        } else {
1357            intp.println();
1358            intp.println(ConsoleMsg.CONSOLE_FRAMEWORK_IS_SHUTDOWN_MESSAGE);
1359        }
1360
1361        Object JavaDoc[] options = processOption(intp);
1362        if (options == null)
1363            return;
1364
1365        AbstractBundle[] bundles = (AbstractBundle[]) context.getBundles();
1366        if (bundles.length == 0) {
1367            intp.println(ConsoleMsg.CONSOLE_NO_INSTALLED_BUNDLES_ERROR);
1368        } else {
1369            intp.print(newline);
1370            intp.print(ConsoleMsg.CONSOLE_ID);
1371            intp.print(tab);
1372            intp.println(ConsoleMsg.CONSOLE_STATE_BUNDLE_TITLE);
1373            for (int i = 0; i < bundles.length; i++) {
1374                AbstractBundle b = bundles[i];
1375                if (!match(b, (String JavaDoc) options[0], ((Integer JavaDoc) options[1]).intValue()))
1376                    continue;
1377                String JavaDoc label = b.getSymbolicName();
1378                if (label == null || label.length() == 0)
1379                    label = b.toString();
1380                else
1381                    label = label + "_" + b.getVersion(); //$NON-NLS-1$
1382
intp.println(b.getBundleId() + "\t" + getStateName(b) + label); //$NON-NLS-1$
1383
if (b.isFragment()) {
1384                    BundleLoaderProxy[] hosts = b.getHosts();
1385                    if (hosts != null)
1386                        for (int j = 0; j < hosts.length; j++)
1387                            intp.println("\t Master=" + hosts[j].getBundleHost().getBundleId()); //$NON-NLS-1$
1388
} else {
1389                    org.osgi.framework.Bundle fragments[] = b.getFragments();
1390                    if (fragments != null) {
1391                        intp.print("\t Fragments="); //$NON-NLS-1$
1392
for (int f = 0; f < fragments.length; f++) {
1393                            AbstractBundle fragment = (AbstractBundle) fragments[f];
1394                            intp.print((f > 0 ? ", " : "") + fragment.getBundleId()); //$NON-NLS-1$ //$NON-NLS-2$
1395
}
1396                        intp.println();
1397                    }
1398                }
1399            }
1400        }
1401    }
1402
1403    private boolean match(Bundle toFilter, String JavaDoc searchedName, int searchedState) {
1404        if ((toFilter.getState() & searchedState) == 0) {
1405            return false;
1406        }
1407        if (searchedName != null && toFilter.getSymbolicName() != null && toFilter.getSymbolicName().indexOf(searchedName) == -1) {
1408            return false;
1409        }
1410        return true;
1411    }
1412
1413    /**
1414     * Handles the threads command abbreviation. Invokes _threads().
1415     *
1416     * @param intp A CommandInterpreter object containing the command and it's arguments.
1417     */

1418    public void _t(CommandInterpreter intp) throws Exception JavaDoc {
1419        _threads(intp);
1420    }
1421
1422    /**
1423     * Prints the information about the currently running threads
1424     * in the embedded system.
1425     *
1426     * @param intp A CommandInterpreter object containing the command
1427     * and it's arguments.
1428     */

1429    public void _threads(CommandInterpreter intp) throws Exception JavaDoc {
1430
1431        ThreadGroup JavaDoc[] threadGroups = getThreadGroups();
1432        Util.sort(threadGroups);
1433
1434        ThreadGroup JavaDoc tg = getTopThreadGroup();
1435        Thread JavaDoc[] threads = new Thread JavaDoc[tg.activeCount()];
1436        int count = tg.enumerate(threads, true);
1437        Util.sort(threads);
1438
1439        StringBuffer JavaDoc sb = new StringBuffer JavaDoc(120);
1440        intp.println();
1441        intp.println(ConsoleMsg.CONSOLE_THREADGROUP_TITLE);
1442        for (int i = 0; i < threadGroups.length; i++) {
1443            tg = threadGroups[i];
1444            int all = tg.activeCount(); //tg.allThreadsCount();
1445
int local = tg.enumerate(new Thread JavaDoc[all], false); //tg.threadsCount();
1446
ThreadGroup JavaDoc p = tg.getParent();
1447            String JavaDoc parent = (p == null) ? "-none-" : p.getName(); //$NON-NLS-1$
1448
sb.setLength(0);
1449            sb.append(Util.toString(simpleClassName(tg), 18)).append(" ").append(Util.toString(tg.getName(), 21)).append(" ").append(Util.toString(parent, 16)).append(Util.toString(new Integer JavaDoc(tg.getMaxPriority()), 3)).append(Util.toString(new Integer JavaDoc(local), 4)).append("/").append(Util.toString(String.valueOf(all), 6)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1450
intp.println(sb.toString());
1451        }
1452        intp.print(newline);
1453        intp.println(ConsoleMsg.CONSOLE_THREADTYPE_TITLE);
1454        for (int j = 0; j < count; j++) {
1455            Thread JavaDoc t = threads[j];
1456            if (t != null) {
1457                sb.setLength(0);
1458                sb.append(Util.toString(simpleClassName(t), 18)).append(" ").append(Util.toString(t.getName(), 21)).append(" ").append(Util.toString(t.getThreadGroup().getName(), 16)).append(Util.toString(new Integer JavaDoc(t.getPriority()), 3)); //$NON-NLS-1$ //$NON-NLS-2$
1459
if (t.isDaemon())
1460                    sb.append(" [daemon]"); //$NON-NLS-1$
1461
intp.println(sb.toString());
1462            }
1463        }
1464    }
1465
1466    /**
1467     * Handles the sl (startlevel) command.
1468     *
1469     * @param intp A CommandInterpreter object containing the command and it's arguments.
1470     */

1471    public void _sl(CommandInterpreter intp) throws Exception JavaDoc {
1472        if (isStartLevelSvcPresent(intp)) {
1473            org.osgi.framework.Bundle bundle = null;
1474            String JavaDoc token = intp.nextArgument();
1475            int value = 0;
1476            if (token != null) {
1477                bundle = getBundleFromToken(intp, token, true);
1478                if (bundle == null) {
1479                    return;
1480                }
1481            }
1482            if (bundle == null) { // must want framework startlevel
1483
value = slImpl.getStartLevel();
1484                intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_FRAMEWORK_ACTIVE_STARTLEVEL, String.valueOf(value)));
1485            } else { // must want bundle startlevel
1486
value = slImpl.getBundleStartLevel(bundle);
1487                intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_BUNDLE_STARTLEVEL, new Long JavaDoc(bundle.getBundleId()), new Integer JavaDoc(value)));
1488            }
1489        }
1490    }
1491
1492    /**
1493     * Handles the setfwsl (set framework startlevel) command.
1494     *
1495     * @param intp A CommandInterpreter object containing the command and it's arguments.
1496     */

1497    public void _setfwsl(CommandInterpreter intp) throws Exception JavaDoc {
1498        if (isStartLevelSvcPresent(intp)) {
1499            int value = 0;
1500            String JavaDoc token = intp.nextArgument();
1501            if (token == null) {
1502                intp.println(ConsoleMsg.STARTLEVEL_NO_STARTLEVEL_GIVEN);
1503                value = slImpl.getStartLevel();
1504                intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_FRAMEWORK_ACTIVE_STARTLEVEL, String.valueOf(value)));
1505            } else {
1506                value = this.getStartLevelFromToken(intp, token);
1507                if (value > 0) {
1508                    try {
1509                        slImpl.setStartLevel(value);
1510                        intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_FRAMEWORK_ACTIVE_STARTLEVEL, String.valueOf(value)));
1511                    } catch (IllegalArgumentException JavaDoc e) {
1512                        intp.println(e.getMessage());
1513                    }
1514                }
1515            }
1516        }
1517    }
1518
1519    /**
1520     * Handles the setbsl (set bundle startlevel) command.
1521     *
1522     * @param intp A CommandInterpreter object containing the command and it's arguments.
1523     */

1524    public void _setbsl(CommandInterpreter intp) throws Exception JavaDoc {
1525        if (isStartLevelSvcPresent(intp)) {
1526            String JavaDoc token;
1527            AbstractBundle bundle = null;
1528            token = intp.nextArgument();
1529            if (token == null) {
1530                intp.println(ConsoleMsg.STARTLEVEL_NO_STARTLEVEL_OR_BUNDLE_GIVEN);
1531                return;
1532            }
1533
1534            int newSL = this.getStartLevelFromToken(intp, token);
1535
1536            token = intp.nextArgument();
1537            if (token == null) {
1538                intp.println(ConsoleMsg.STARTLEVEL_NO_STARTLEVEL_OR_BUNDLE_GIVEN);
1539                return;
1540            }
1541            while (token != null) {
1542                bundle = getBundleFromToken(intp, token, true);
1543                if (bundle != null) {
1544                    try {
1545                        slImpl.setBundleStartLevel(bundle, newSL);
1546                        intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_BUNDLE_STARTLEVEL, new Long JavaDoc(bundle.getBundleId()), new Integer JavaDoc(newSL)));
1547                    } catch (IllegalArgumentException JavaDoc e) {
1548                        intp.println(e.getMessage());
1549                    }
1550                }
1551                token = intp.nextArgument();
1552            }
1553        }
1554    }
1555
1556    /**
1557     * Handles the setibsl (set initial bundle startlevel) command.
1558     *
1559     * @param intp A CommandInterpreter object containing the command and it's arguments.
1560     */

1561    public void _setibsl(CommandInterpreter intp) throws Exception JavaDoc {
1562        if (isStartLevelSvcPresent(intp)) {
1563            int value = 0;
1564            String JavaDoc token = intp.nextArgument();
1565            if (token == null) {
1566                intp.println(ConsoleMsg.STARTLEVEL_NO_STARTLEVEL_GIVEN);
1567                value = slImpl.getInitialBundleStartLevel();
1568                intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_INITIAL_BUNDLE_STARTLEVEL, String.valueOf(value)));
1569            } else {
1570                value = this.getStartLevelFromToken(intp, token);
1571                if (value > 0) {
1572                    try {
1573                        slImpl.setInitialBundleStartLevel(value);
1574                        intp.println(NLS.bind(ConsoleMsg.STARTLEVEL_INITIAL_BUNDLE_STARTLEVEL, String.valueOf(value)));
1575                    } catch (IllegalArgumentException JavaDoc e) {
1576                        intp.println(e.getMessage());
1577                    }
1578                }
1579            }
1580        }
1581    }
1582
1583    public void _requiredBundles(CommandInterpreter intp) {
1584        _classSpaces(intp);
1585    }
1586
1587    public void _classSpaces(CommandInterpreter intp) {
1588
1589        String JavaDoc token = intp.nextArgument();
1590
1591        org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$
1592
if (packageAdminRef != null) {
1593            org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef);
1594            if (packageAdmin != null) {
1595                try {
1596                    org.osgi.service.packageadmin.RequiredBundle[] symBundles = null;
1597
1598                    symBundles = packageAdmin.getRequiredBundles(token);
1599
1600                    if (symBundles == null) {
1601                        intp.println(ConsoleMsg.CONSOLE_NO_NAMED_CLASS_SPACES_MESSAGE);
1602                    } else {
1603                        for (int i = 0; i < symBundles.length; i++) {
1604                            org.osgi.service.packageadmin.RequiredBundle symBundle = symBundles[i];
1605                            intp.print(symBundle);
1606
1607                            boolean removalPending = symBundle.isRemovalPending();
1608                            if (removalPending) {
1609                                intp.print("("); //$NON-NLS-1$
1610
intp.print(ConsoleMsg.CONSOLE_REMOVAL_PENDING_MESSAGE);
1611                                intp.println(")"); //$NON-NLS-1$
1612
}
1613
1614                            org.osgi.framework.Bundle provider = symBundle.getBundle();
1615                            if (provider != null) {
1616                                intp.print("<"); //$NON-NLS-1$
1617
intp.print(provider);
1618                                intp.println(">"); //$NON-NLS-1$
1619

1620                                org.osgi.framework.Bundle[] requiring = symBundle.getRequiringBundles();
1621                                if (requiring != null)
1622                                    for (int j = 0; j < requiring.length; j++) {
1623                                        intp.print(" "); //$NON-NLS-1$
1624
intp.print(requiring[j]);
1625                                        intp.print(" "); //$NON-NLS-1$
1626
intp.println(ConsoleMsg.CONSOLE_REQUIRES_MESSAGE);
1627                                    }
1628                            } else {
1629                                intp.print("<"); //$NON-NLS-1$
1630
intp.print(ConsoleMsg.CONSOLE_STALE_MESSAGE);
1631                                intp.println(">"); //$NON-NLS-1$
1632
}
1633
1634                        }
1635                    }
1636                } finally {
1637                    context.ungetService(packageAdminRef);
1638                }
1639            }
1640        } else {
1641            intp.println(ConsoleMsg.CONSOLE_NO_EXPORTED_PACKAGES_NO_PACKAGE_ADMIN_MESSAGE);
1642        }
1643    }
1644
1645    /**
1646     * Handles the profilelog command.
1647     *
1648     * @param intp A CommandInterpreter object containing the command and it's arguments.
1649     */

1650    public void _profilelog(CommandInterpreter intp) throws Exception JavaDoc {
1651        intp.println(Profile.getProfileLog());
1652    }
1653
1654    public void _getPackages(CommandInterpreter intp) {
1655
1656        String JavaDoc nextArg = intp.nextArgument();
1657        if (nextArg == null)
1658            return;
1659        AbstractBundle bundle = getBundleFromToken(intp, nextArg, true);
1660        ServiceReference ref = context.getServiceReference("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$
1661
if (ref == null)
1662            return;
1663        PlatformAdmin platformAdmin = (PlatformAdmin) context.getService(ref);
1664        try {
1665            ExportPackageDescription[] exports = platformAdmin.getStateHelper().getVisiblePackages(bundle.getBundleDescription(), StateHelper.VISIBLE_INCLUDE_EE_PACKAGES);
1666            for (int i = 0; i < exports.length; i++) {
1667                intp.println(exports[i] + ": " + platformAdmin.getStateHelper().getAccessCode(bundle.getBundleDescription(), exports[i])); //$NON-NLS-1$
1668
}
1669        } finally {
1670            context.ungetService(ref);
1671        }
1672    }
1673
1674    /**
1675     * Checks for the presence of the StartLevel Service. Outputs a message if it is not present.
1676     * @param intp The CommandInterpreter object to be used to write to the console
1677     * @return true or false if service is present or not
1678     */

1679    protected boolean isStartLevelSvcPresent(CommandInterpreter intp) {
1680        boolean retval = false;
1681        org.osgi.framework.ServiceReference slSvcRef = context.getServiceReference("org.osgi.service.startlevel.StartLevel"); //$NON-NLS-1$
1682
if (slSvcRef != null) {
1683            org.osgi.service.startlevel.StartLevel slSvc = (org.osgi.service.startlevel.StartLevel) context.getService(slSvcRef);
1684            if (slSvc != null) {
1685                retval = true;
1686            }
1687        } else {
1688            intp.println(ConsoleMsg.CONSOLE_CAN_NOT_USE_STARTLEVEL_NO_STARTLEVEL_SVC_ERROR);
1689        }
1690        return retval;
1691    }
1692
1693    /**
1694     * Given a number or a token representing a bundle symbolic name or bundle location,
1695     * retrieve the Bundle object with that id. The bundle symbolic name token is parsed as
1696     * symbolicname[@version]
1697     *
1698     * @param intp The CommandInterpreter
1699     * @param token A string containing a potential bundle it
1700     * @param error A boolean indicating whether or not to output a message
1701     * @return The requested Bundle object
1702     */

1703    protected AbstractBundle getBundleFromToken(CommandInterpreter intp, String JavaDoc token, boolean error) {
1704        AbstractBundle bundle = null;
1705        try {
1706            long id = Long.parseLong(token);
1707            bundle = (AbstractBundle) context.getBundle(id);
1708        } catch (NumberFormatException JavaDoc nfe) {
1709
1710            // if not found, assume token is either symbolic name@version, or location
1711
String JavaDoc symbolicName = token;
1712            Version version = null;
1713
1714            // check for @ -- this may separate either the version string, or be part of the
1715
// location
1716
int ix = token.indexOf("@"); //$NON-NLS-1$
1717
if (ix != -1) {
1718                if ((ix + 1) != token.length()) {
1719                    try {
1720                        // if the version parses, then use the token prior to @ as a symbolic name
1721
version = Version.parseVersion(token.substring(ix + 1, token.length()));
1722                        symbolicName = token.substring(0, ix);
1723                    } catch (IllegalArgumentException JavaDoc e) {
1724                        // version doesn't parse, assume token is symbolic name without version, or location
1725
}
1726                }
1727            }
1728
1729            Bundle[] bundles = context.getBundles();
1730            for (int i = 0, n = bundles.length; i < n; i++) {
1731                AbstractBundle b = (AbstractBundle) bundles[i];
1732                // if symbolicName matches, then matches if there is no version specific on command, or the version matches
1733
// if there is no version specified on command, pick first matching bundle
1734
if ((symbolicName.equals(b.getSymbolicName()) && (version == null || version.equals(b.getVersion()))) || token.equals(b.getLocation())) {
1735                    bundle = b;
1736                    break;
1737                }
1738            }
1739        }
1740
1741        if ((bundle == null) && error) {
1742            intp.println(NLS.bind(ConsoleMsg.CONSOLE_CANNOT_FIND_BUNDLE_ERROR, token));
1743        }
1744
1745        return (bundle);
1746    }
1747
1748    /**
1749     * Given a string containing a startlevel value, validate it and convert it to an int
1750     *
1751     * @param intp A CommandInterpreter object used for printing out error messages
1752     * @param value A string containing a potential startlevel
1753     * @return The start level or an int <0 if it was invalid
1754     */

1755    protected int getStartLevelFromToken(CommandInterpreter intp, String JavaDoc value) {
1756        int retval = -1;
1757        try {
1758            retval = Integer.parseInt(value);
1759            if (Integer.parseInt(value) <= 0) {
1760                intp.println(ConsoleMsg.STARTLEVEL_POSITIVE_INTEGER);
1761            }
1762        } catch (NumberFormatException JavaDoc nfe) {
1763            intp.println(ConsoleMsg.STARTLEVEL_POSITIVE_INTEGER);
1764        }
1765        return retval;
1766    }
1767
1768    /**
1769     * Given a state value, return the string describing that state.
1770     *
1771     * @param state An int containing a state value
1772     * @return A String describing the state
1773     */

1774    protected String JavaDoc getStateName(Bundle bundle) {
1775        int state = bundle.getState();
1776        switch (state) {
1777            case Bundle.UNINSTALLED :
1778                return "UNINSTALLED "; //$NON-NLS-1$
1779

1780            case Bundle.INSTALLED :
1781                return "INSTALLED "; //$NON-NLS-1$
1782

1783            case Bundle.RESOLVED :
1784                return "RESOLVED "; //$NON-NLS-1$
1785

1786            case Bundle.STARTING :
1787                synchronized (lazyActivation) {
1788                    if (lazyActivation.contains(bundle)) {
1789                        return "<<LAZY>> "; //$NON-NLS-1$
1790
}
1791                    return "STARTING "; //$NON-NLS-1$
1792
}
1793
1794            case Bundle.STOPPING :
1795                return "STOPPING "; //$NON-NLS-1$
1796

1797            case Bundle.ACTIVE :
1798                return "ACTIVE "; //$NON-NLS-1$
1799

1800            default :
1801                return Integer.toHexString(state);
1802        }
1803    }
1804
1805    /**
1806     * Answers all thread groups in the system.
1807     *
1808     * @return An array of all thread groups.
1809     */

1810    protected ThreadGroup JavaDoc[] getThreadGroups() {
1811        ThreadGroup JavaDoc tg = getTopThreadGroup();
1812        ThreadGroup JavaDoc[] groups = new ThreadGroup JavaDoc[tg.activeGroupCount()];
1813        int count = tg.enumerate(groups, true);
1814        if (count == groups.length) {
1815            return groups;
1816        }
1817        // get rid of null entries
1818
ThreadGroup JavaDoc[] ngroups = new ThreadGroup JavaDoc[count];
1819        System.arraycopy(groups, 0, ngroups, 0, count);
1820        return ngroups;
1821    }
1822
1823    /**
1824     * Answers the top level group of the current thread.
1825     * <p>
1826     * It is the 'system' or 'main' thread group under
1827     * which all 'user' thread groups are allocated.
1828     *
1829     * @return The parent of all user thread groups.
1830     */

1831    protected ThreadGroup JavaDoc getTopThreadGroup() {
1832        ThreadGroup JavaDoc topGroup = Thread.currentThread().getThreadGroup();
1833        if (topGroup != null) {
1834            while (topGroup.getParent() != null) {
1835                topGroup = topGroup.getParent();
1836            }
1837        }
1838        return topGroup;
1839    }
1840
1841    /**
1842     * Returns the simple class name of an object.
1843     *
1844     * @param o The object for which a class name is requested
1845     * @return The simple class name.
1846     */

1847    public String JavaDoc simpleClassName(Object JavaDoc o) {
1848        java.util.StringTokenizer JavaDoc t = new java.util.StringTokenizer JavaDoc(o.getClass().getName(), "."); //$NON-NLS-1$
1849
int ct = t.countTokens();
1850        for (int i = 1; i < ct; i++) {
1851            t.nextToken();
1852        }
1853        return t.nextToken();
1854    }
1855
1856    public void _getprop(CommandInterpreter ci) throws Exception JavaDoc {
1857        Properties allProperties = FrameworkProperties.getProperties();
1858        String JavaDoc filter = ci.nextArgument();
1859        Enumeration propertyNames = allProperties.keys();
1860        while (propertyNames.hasMoreElements()) {
1861            String JavaDoc prop = (String JavaDoc) propertyNames.nextElement();
1862            if (filter == null || prop.startsWith(filter)) {
1863                ci.println(prop + '=' + allProperties.getProperty(prop));
1864            }
1865        }
1866    }
1867
1868    /**
1869     * This is used to track lazily activated bundles.
1870     */

1871    public void bundleChanged(BundleEvent event) {
1872        int type = event.getType();
1873        Bundle bundle = event.getBundle();
1874        synchronized (lazyActivation) {
1875            switch (type) {
1876                case BundleEvent.LAZY_ACTIVATION:
1877                    if (!lazyActivation.contains(bundle)) {
1878                        lazyActivation.add(bundle);
1879                    }
1880                    break;
1881            
1882                default:
1883                    lazyActivation.remove(bundle);
1884                    break;
1885            }
1886        }
1887        
1888    }
1889}
1890
Popular Tags