Search in sources :

Example 6 with Descriptor

use of org.apache.felix.service.command.Descriptor in project felix by apache.

the class Basic method start.

@Descriptor("start bundles")
public void start(@Descriptor("start bundle transiently") @Parameter(names = { "-t", "--transient" }, presentValue = "true", absentValue = "false") boolean trans, @Descriptor("use declared activation policy") @Parameter(names = { "-p", "--policy" }, presentValue = "true", absentValue = "false") boolean policy, @Descriptor("target bundle identifiers or URLs") String[] ss) {
    int options = 0;
    // Check for "transient" switch.
    if (trans) {
        options |= Bundle.START_TRANSIENT;
    }
    // Check for "start policy" switch.
    if (policy) {
        options |= Bundle.START_ACTIVATION_POLICY;
    }
    // There should be at least one bundle id.
    if ((ss != null) && (ss.length >= 1)) {
        for (String s : ss) {
            String id = s.trim();
            try {
                Bundle bundle = null;
                // The id may be a number or a URL, so check.
                if (Character.isDigit(id.charAt(0))) {
                    long l = Long.parseLong(id);
                    bundle = m_bc.getBundle(l);
                } else {
                    bundle = m_bc.installBundle(id);
                }
                if (bundle != null) {
                    bundle.start(options);
                } else {
                    System.err.println("Bundle ID " + id + " is invalid.");
                }
            } catch (NumberFormatException ex) {
                System.err.println("Unable to parse id '" + id + "'.");
            } catch (BundleException ex) {
                if (ex.getNestedException() != null) {
                    ex.printStackTrace();
                    System.err.println(ex.getNestedException().toString());
                } else {
                    System.err.println(ex.toString());
                }
            } catch (Exception ex) {
                System.err.println(ex.toString());
            }
        }
    } else {
        System.err.println("Incorrect number of arguments");
    }
}
Also used : Bundle(org.osgi.framework.Bundle) BundleException(org.osgi.framework.BundleException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Descriptor(org.apache.felix.service.command.Descriptor)

Example 7 with Descriptor

use of org.apache.felix.service.command.Descriptor in project felix by apache.

the class Files method ls.

@Descriptor("get specified path contents")
public File[] ls(@Descriptor("automatically supplied shell session") CommandSession session, @Descriptor("path with optionally wildcarded file name") String pattern) throws IOException {
    pattern = ((pattern == null) || (pattern.length() == 0)) ? "." : pattern;
    pattern = ((pattern.charAt(0) != File.separatorChar) && (pattern.charAt(0) != '.')) ? "./" + pattern : pattern;
    int idx = pattern.lastIndexOf(File.separatorChar);
    String parent = (idx < 0) ? "." : pattern.substring(0, idx + 1);
    String target = (idx < 0) ? pattern : pattern.substring(idx + 1);
    File actualParent = ((parent.charAt(0) == File.separatorChar) ? new File(parent) : new File(cd(session), parent)).getCanonicalFile();
    idx = target.indexOf(File.separatorChar, idx);
    boolean isWildcarded = (target.indexOf('*', idx) >= 0);
    File[] files;
    if (isWildcarded) {
        if (!actualParent.exists()) {
            throw new IOException("File does not exist");
        }
        final List<String> pieces = parseSubstring(target);
        files = actualParent.listFiles(new FileFilter() {

            public boolean accept(File pathname) {
                return compareSubstring(pieces, pathname.getName());
            }
        });
    } else {
        File actualTarget = new File(actualParent, target).getCanonicalFile();
        if (!actualTarget.exists()) {
            throw new IOException("File does not exist");
        }
        if (actualTarget.isDirectory()) {
            files = actualTarget.listFiles();
        } else {
            files = new File[] { actualTarget };
        }
    }
    return files;
}
Also used : IOException(java.io.IOException) FileFilter(java.io.FileFilter) File(java.io.File) Descriptor(org.apache.felix.service.command.Descriptor)

Example 8 with Descriptor

use of org.apache.felix.service.command.Descriptor in project felix by apache.

the class Shell method source.

@Descriptor("Evaluates contents of file")
public Object source(CommandSession session, String script) throws Exception {
    URI uri = session.currentDir().toUri().resolve(script);
    session.put("0", uri);
    try {
        return session.execute(readScript(uri));
    } finally {
        // API doesn't support remove
        session.put("0", null);
    }
}
Also used : URI(java.net.URI) Descriptor(org.apache.felix.service.command.Descriptor)

Example 9 with Descriptor

use of org.apache.felix.service.command.Descriptor in project felix by apache.

the class Shell method help.

@Descriptor("displays information about a specific command")
public void help(CommandSession session, @Descriptor("target command") String name) {
    Map<String, List<Method>> commands = getReflectionCommands(session);
    List<Method> methods = null;
    // If the specified command doesn't have a scope, then
    // search for matching methods by ignoring the scope.
    int scopeIdx = name.indexOf(':');
    if (scopeIdx < 0) {
        for (Entry<String, List<Method>> entry : commands.entrySet()) {
            String k = entry.getKey().substring(entry.getKey().indexOf(':') + 1);
            if (name.equals(k)) {
                name = entry.getKey();
                methods = entry.getValue();
                break;
            }
        }
    } else // Otherwise directly look up matching methods.
    {
        methods = commands.get(name);
    }
    if ((methods != null) && (methods.size() > 0)) {
        for (Method m : methods) {
            Descriptor d = m.getAnnotation(Descriptor.class);
            if (d == null) {
                System.out.println("\n" + m.getName());
            } else {
                System.out.println("\n" + m.getName() + " - " + d.value());
            }
            System.out.println("   scope: " + name.substring(0, name.indexOf(':')));
            // Get flags and options.
            Class<?>[] paramTypes = m.getParameterTypes();
            Map<String, Parameter> flags = new TreeMap<>();
            Map<String, String> flagDescs = new TreeMap<>();
            Map<String, Parameter> options = new TreeMap<>();
            Map<String, String> optionDescs = new TreeMap<>();
            List<String> params = new ArrayList<>();
            Annotation[][] anns = m.getParameterAnnotations();
            for (int paramIdx = 0; paramIdx < anns.length; paramIdx++) {
                Class<?> paramType = m.getParameterTypes()[paramIdx];
                if (paramType == CommandSession.class) {
                    /* Do not bother the user with a CommandSession. */
                    continue;
                }
                Parameter p = findAnnotation(anns[paramIdx], Parameter.class);
                d = findAnnotation(anns[paramIdx], Descriptor.class);
                if (p != null) {
                    if (p.presentValue().equals(Parameter.UNSPECIFIED)) {
                        options.put(p.names()[0], p);
                        if (d != null) {
                            optionDescs.put(p.names()[0], d.value());
                        }
                    } else {
                        flags.put(p.names()[0], p);
                        if (d != null) {
                            flagDescs.put(p.names()[0], d.value());
                        }
                    }
                } else if (d != null) {
                    params.add(paramTypes[paramIdx].getSimpleName());
                    params.add(d.value());
                } else {
                    params.add(paramTypes[paramIdx].getSimpleName());
                    params.add("");
                }
            }
            // Print flags and options.
            if (flags.size() > 0) {
                System.out.println("   flags:");
                for (Entry<String, Parameter> entry : flags.entrySet()) {
                    // Print all aliases.
                    String[] names = entry.getValue().names();
                    System.out.print("      " + names[0]);
                    for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++) {
                        System.out.print(", " + names[aliasIdx]);
                    }
                    System.out.println("   " + flagDescs.get(entry.getKey()));
                }
            }
            if (options.size() > 0) {
                System.out.println("   options:");
                for (Entry<String, Parameter> entry : options.entrySet()) {
                    // Print all aliases.
                    String[] names = entry.getValue().names();
                    System.out.print("      " + names[0]);
                    for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++) {
                        System.out.print(", " + names[aliasIdx]);
                    }
                    System.out.println("   " + optionDescs.get(entry.getKey()) + ((entry.getValue().absentValue() == null) ? "" : " [optional]"));
                }
            }
            if (params.size() > 0) {
                System.out.println("   parameters:");
                for (Iterator<String> it = params.iterator(); it.hasNext(); ) {
                    System.out.println("      " + it.next() + "   " + it.next());
                }
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) TreeMap(java.util.TreeMap) Descriptor(org.apache.felix.service.command.Descriptor) Parameter(org.apache.felix.service.command.Parameter) List(java.util.List) ArrayList(java.util.ArrayList) Descriptor(org.apache.felix.service.command.Descriptor)

Example 10 with Descriptor

use of org.apache.felix.service.command.Descriptor in project felix by apache.

the class DMCommand method dm.

/**
 * Dependency Manager "dm" command. We use gogo annotations, in order to automate documentation,
 * and also to automatically manage optional flags/options and parameters ordering.
 *
 * @param session the gogo command session, used to get some variables declared in the shell
 *        This parameter is automatically passed by the gogo runtime.
 * @param nodeps false means that dependencies are not displayed
 * @param compact true means informations are displayed in a compact format. This parameter can also be
 *        set using the "dependencymanager.compact" gogo shell variable.
 * @param notavail only unregistered components / unavailable dependencies are displayed
 * @param stats true means some statistics are displayed
 * @param services an osgi filter used to filter on some given osgi service properties.  This parameter can also be
 *        set using the "dependencymanager.services" gogo shell variable.
 * @param components a regular expression to match either component implementation class names.  This parameter can also be
 *        set using the "dependencymanager.components" gogo shell variable.
 * @param componentIds only components matching one of the specified components ids are displayed
 * @param bundleIds a list of bundle ids or symbolic names, used to filter on some given bundles
 */
@Descriptor("List dependency manager components")
public void dm(CommandSession session, @Descriptor("Hides component dependencies") @Parameter(names = { "nodeps", "nd" }, presentValue = "true", absentValue = "false") boolean nodeps, @Descriptor("Displays components using a compact form") @Parameter(names = { "compact", "cp" }, presentValue = "true", absentValue = "") String compact, @Descriptor("Only displays unavailable components") @Parameter(names = { "notavail", "na" }, presentValue = "true", absentValue = "false") boolean notavail, @Descriptor("Detects where are the root failures") @Parameter(names = { "wtf" }, presentValue = "true", absentValue = "false") boolean wtf, @Descriptor("Displays components statistics") @Parameter(names = { "stats", "stat", "st" }, presentValue = "true", absentValue = "false") boolean stats, @Descriptor("<OSGi filter used to filter some service properties>") @Parameter(names = { "services", "s" }, absentValue = "") String services, @Descriptor("<Regex(s) used to filter on component implementation class names (comma separated), can be negated using \"!\" prefix>") @Parameter(names = { "components", "c" }, absentValue = "") String components, @Descriptor("<List of component identifiers to display (comma separated)>") @Parameter(names = { "componentIds", "cid", "ci" }, absentValue = "") String componentIds, @Descriptor("<List of bundle ids or bundle symbolic names to display (comma separated)>") @Parameter(names = { "bundleIds", "bid", "bi", "b" }, absentValue = "") String bundleIds, @Descriptor("<Max number of top components to display (0=all)> This command displays components callbacks (init/start) times>") @Parameter(names = { "top" }, absentValue = "-1") int top) throws Throwable {
    boolean comp = Boolean.parseBoolean(getParam(session, ENV_COMPACT, compact));
    services = getParam(session, ENV_SERVICES, services);
    String[] componentsRegex = getParams(session, ENV_COMPONENTS, components);
    // list of bundle ids or bundle symbolic names
    ArrayList<String> bids = new ArrayList<String>();
    // list of component ids
    ArrayList<Long> cids = new ArrayList<Long>();
    // Parse and check componentIds option
    StringTokenizer tok = new StringTokenizer(componentIds, ", ");
    while (tok.hasMoreTokens()) {
        try {
            cids.add(Long.parseLong(tok.nextToken()));
        } catch (NumberFormatException e) {
            System.out.println("Invalid value for componentIds option");
            return;
        }
    }
    // Parse services filter
    Filter servicesFilter = null;
    try {
        if (services != null) {
            servicesFilter = m_context.createFilter(services);
        }
    } catch (InvalidSyntaxException e) {
        System.out.println("Invalid services OSGi filter: " + services);
        e.printStackTrace(System.err);
        return;
    }
    // Parse and check bundleIds option
    tok = new StringTokenizer(bundleIds, ", ");
    while (tok.hasMoreTokens()) {
        bids.add(tok.nextToken());
    }
    if (top != -1) {
        showTopComponents(top);
        return;
    }
    if (wtf) {
        wtf();
        return;
    }
    DependencyGraph graph = null;
    if (notavail) {
        graph = DependencyGraph.getGraph(ComponentState.UNREGISTERED, DependencyState.ALL_UNAVAILABLE);
    } else {
        graph = DependencyGraph.getGraph(ComponentState.ALL, DependencyState.ALL);
    }
    List<ComponentDeclaration> allComponents = graph.getAllComponents();
    Collections.sort(allComponents, COMPONENT_DECLARATION_COMPARATOR);
    long numberOfComponents = 0;
    long numberOfDependencies = 0;
    long lastBundleId = -1;
    for (ComponentDeclaration cd : allComponents) {
        Bundle bundle = cd.getBundleContext().getBundle();
        if (!matchBundle(bundle, bids)) {
            continue;
        }
        Component component = (Component) cd;
        String name = cd.getName();
        if (!mayDisplay(component, servicesFilter, componentsRegex, cids)) {
            continue;
        }
        numberOfComponents++;
        long bundleId = bundle.getBundleId();
        if (lastBundleId != bundleId) {
            lastBundleId = bundleId;
            if (comp) {
                System.out.println("[" + bundleId + "] " + compactName(bundle.getSymbolicName()));
            } else {
                System.out.println("[" + bundleId + "] " + bundle.getSymbolicName());
            }
        }
        if (comp) {
            System.out.print(" [" + cd.getId() + "] " + compactName(name) + " " + compactState(ComponentDeclaration.STATE_NAMES[cd.getState()]));
        } else {
            System.out.println(" [" + cd.getId() + "] " + name + " " + ComponentDeclaration.STATE_NAMES[cd.getState()]);
        }
        if (!nodeps) {
            List<ComponentDependencyDeclaration> dependencies = graph.getDependecies(cd);
            if (!dependencies.isEmpty()) {
                numberOfDependencies += dependencies.size();
                if (comp) {
                    System.out.print('(');
                }
                for (int j = 0; j < dependencies.size(); j++) {
                    ComponentDependencyDeclaration dep = dependencies.get(j);
                    String depName = dep.getName();
                    String depType = dep.getType();
                    int depState = dep.getState();
                    if (comp) {
                        if (j > 0) {
                            System.out.print(' ');
                        }
                        System.out.print(compactName(depName) + " " + compactState(depType) + " " + compactState(ComponentDependencyDeclaration.STATE_NAMES[depState]));
                    } else {
                        System.out.println("    " + depName + " " + depType + " " + ComponentDependencyDeclaration.STATE_NAMES[depState]);
                    }
                }
                if (comp) {
                    System.out.print(')');
                }
            }
        }
        if (comp) {
            System.out.println();
        }
    }
    if (stats) {
        System.out.println("Statistics:");
        System.out.println(" - Dependency managers: " + DependencyManager.getDependencyManagers().size());
        System.out.println(" - Components: " + numberOfComponents);
        if (!nodeps) {
            System.out.println(" - Dependencies: " + numberOfDependencies);
        }
    }
}
Also used : ComponentDeclaration(org.apache.felix.dm.ComponentDeclaration) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) ComponentDependencyDeclaration(org.apache.felix.dm.ComponentDependencyDeclaration) DependencyGraph(org.apache.felix.dm.diagnostics.DependencyGraph) StringTokenizer(java.util.StringTokenizer) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Component(org.apache.felix.dm.Component) Descriptor(org.apache.felix.service.command.Descriptor)

Aggregations

Descriptor (org.apache.felix.service.command.Descriptor)31 ArrayList (java.util.ArrayList)13 ServiceReference (org.osgi.framework.ServiceReference)8 IOException (java.io.IOException)6 Bundle (org.osgi.framework.Bundle)6 StartLevel (org.osgi.service.startlevel.StartLevel)5 URL (java.net.URL)4 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)4 PrintStream (java.io.PrintStream)3 Method (java.lang.reflect.Method)3 MalformedURLException (java.net.MalformedURLException)3 List (java.util.List)3 TreeMap (java.util.TreeMap)3 HandlerFactory (org.apache.felix.ipojo.HandlerFactory)3 TypeDeclaration (org.apache.felix.ipojo.extender.TypeDeclaration)3 BundleException (org.osgi.framework.BundleException)3 File (java.io.File)2 InputStream (java.io.InputStream)2 URI (java.net.URI)2 Factory (org.apache.felix.ipojo.Factory)2