⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frameworkcommandgroup.java

📁 OSGI这是一个中间件,与UPNP齐名,是用于移植到嵌入式平台之上
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/* * Copyright (c) 2003, KNOPFLERFISH project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright *   notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above *   copyright notice, this list of conditions and the following *   disclaimer in the documentation and/or other materials *   provided with the distribution. * * - Neither the name of the KNOPFLERFISH project nor the names of its *   contributors may be used to endorse or promote products derived *   from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */package org.knopflerfish.bundle.frameworkcommands;import java.io.File;import java.io.FileNotFoundException;import java.io.InputStream;import java.io.PrintWriter;import java.io.Reader;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import java.security.AccessController;import java.security.PrivilegedAction;import java.util.Dictionary;import java.util.Enumeration;import java.util.StringTokenizer;import java.util.Vector;import org.knopflerfish.service.console.CommandGroupAdapter;import org.knopflerfish.service.console.Session;import org.knopflerfish.service.console.Util;import org.osgi.framework.Bundle;import org.osgi.framework.BundleContext;import org.osgi.framework.BundleException;import org.osgi.framework.ServiceReference;import org.osgi.service.packageadmin.ExportedPackage;import org.osgi.service.packageadmin.PackageAdmin;import org.osgi.service.permissionadmin.PermissionAdmin;import org.osgi.service.permissionadmin.PermissionInfo;import org.osgi.service.startlevel.StartLevel;// ******************** FrameworkCommandGroup ********************/** * * Interface for commands to be handled by the console. * * *  * @author Gatespace AB * * @version $Revision: 1.1.1.1 $ */public class FrameworkCommandGroup extends CommandGroupAdapter {    BundleContext bc;    private PackageAdmin packageAdmin = null;    private PermissionAdmin permissionAdmin = null;    private StartLevel startLevel = null;    /**     * * The default directories for bundle jar files. *     * <p> * The system property <code>org.knopflerfish.gosg.jars</code> holds     * a * semicolon separated path of URLs that is used to complete the *     * location when it is given as a partial URL. *     * </p>     */    private String[] bundleDirs = null;    FrameworkCommandGroup(BundleContext bc) {        super("framework", "Framework commands");        this.bc = bc;        // all of these services are framework singleton internal services        // thus, we take a shortcut and skip the service tracking        ServiceReference sr = bc.getServiceReference(PackageAdmin.class                .getName());        if (sr != null) {            packageAdmin = (PackageAdmin) bc.getService(sr);        }        sr = bc.getServiceReference(PermissionAdmin.class.getName());        if (sr != null) {            permissionAdmin = (PermissionAdmin) bc.getService(sr);        }        sr = bc.getServiceReference(StartLevel.class.getName());        if (sr != null) {            startLevel = (StartLevel) bc.getService(sr);        }        setupJars();    }    void setupJars() {        String jars = System.getProperty("org.knopflerfish.gosg.jars",                "file:./");        StringTokenizer st = new StringTokenizer(jars, ";");        bundleDirs = new String[st.countTokens()];        for (int i = 0; i < bundleDirs.length; i++) {            String path = st.nextToken();            try {                bundleDirs[i] = new URL(path).toString();            } catch (Exception e) {                bundleDirs[i] = path;            }        }    }    /**     * Completes a partial bundle location using the bundles dir path. * The     * result is the first combination of a directory URL (as * returned by     * <code>getBundleDirs()</code>) and the specified * location that     * results in a valid URL with accessible data.     */    public String completeLocation(String location) {        int ic = location.indexOf(":");        if (ic < 2 || ic > location.indexOf("/")) {            // URL wihtout protocol complete it.            String[] paths = bundleDirs;            for (int i = 0; i < paths.length; i++) {                try {                    URL url = new URL(new URL(paths[i]), location);                    if ("file".equals(url.getProtocol())) {                        File f = new File(url.getFile());                        if (!f.exists() || !f.canRead()) {                            continue; // Noope; try next.                        }                    } else if ("http".equals(url.getProtocol())) {                        HttpURLConnection uc = (HttpURLConnection) url                                .openConnection();                        uc.connect();                        int rc = uc.getResponseCode();                        uc.disconnect();                        if (rc != HttpURLConnection.HTTP_OK) {                            continue; // Noope; try next.                        }                    } else {                        // Generic case; Check if we can read data from this URL                        InputStream is = null;                        try {                            is = url.openStream();                        } finally {                            if (is != null)                                is.close();                        }                    }                    location = url.toString();                    break; // Found.                } catch (Exception _e) {                }            }        }        return location;    }    //    // Addpermission command    //    public final static String USAGE_ADDPERMISSION = "-b #bundle# | -d | -l #location# <type> <name> <actions>";    public final static String[] HELP_ADDPERMISSION = new String[] {            "Add permissions to bundle",            "-d            Add default permissions",            "-b #bundle#   Add permission for bundle name or id",            "-l #location# Add permission for location",            "<type>        Permission type", "<name>        Permission name",            "<actions>     Permission actions" };    public int cmdAddpermission(Dictionary opts, Reader in, PrintWriter out,            Session session) {        if (permissionAdmin == null) {            out.println("Permission Admin service is not available");            return 1;        }        String loc = null;        PermissionInfo[] pi;        String selection = (String) opts.get("-b");        if (selection != null) {            Bundle[] b = bc.getBundles();            Util.selectBundles(b, new String[] { selection });            for (int i = 0; i < b.length; i++) {                if (b[i] != null) {                    if (loc == null) {                        loc = b[i].getLocation();                    } else {                        out.println("ERROR! Multiple bundles selected");                        return 1;                    }                }            }            if (loc == null) {                out.println("ERROR! No matching bundle");                return 1;            }            pi = permissionAdmin.getPermissions(loc);        } else if (opts.get("-d") != null) {            pi = permissionAdmin.getDefaultPermissions();        } else {            loc = (String) opts.get("-l");            pi = permissionAdmin.getPermissions(loc);        }        String perm = "(" + opts.get("type") + " \"" + opts.get("name")                + "\" \"" + opts.get("actions") + "\")";        PermissionInfo pia;        try {            pia = new PermissionInfo(perm);        } catch (IllegalArgumentException e) {            out.println("ERROR! " + e.getMessage());            out.println("PermissionInfo string = " + perm);            return 1;        }        if (pi != null) {            PermissionInfo[] npi = new PermissionInfo[pi.length + 1];            System.arraycopy(pi, 0, npi, 0, pi.length);            pi = npi;        } else {            pi = new PermissionInfo[1];        }        pi[pi.length - 1] = pia;        if (loc != null) {            permissionAdmin.setPermissions(loc, pi);        } else {            permissionAdmin.setDefaultPermissions(pi);        }        return 0;    }    //    // Bundles command    //    public final static String USAGE_BUNDLES = "[-1] [-i] [-l] [-s] [<bundle>] ...";    public final static String[] HELP_BUNDLES = new String[] { "List bundles",            "-1       One column output", "-i       Sort on bundle id",            "-s       Sort on bundle start level", "-l       Verbose output",            "<bundle> Name or id of bundle" };    public int cmdBundles(Dictionary opts, Reader in, PrintWriter out,            Session session) {        Bundle[] b = getBundles((String[]) opts.get("bundle"),                opts.get("-i") != null, opts.get("-s") != null);        boolean needNl = false;        // .println("12 5/active CM Commands 2 1/active CM Service");        if (opts.get("-l") != null) {            out.println("   id  level/state location");        } else {            out.println("   id  level/state name");        }        out.println("   --------------------");        for (int i = 0; i < b.length; i++) {            String level = null;            try {                level = "" + startLevel.getBundleStartLevel(b[i]);                if (level.length() < 2) {                    level = " " + level;                }            } catch (Exception e) {                // no start level set.            }            if (b[i] == null) {                break;            }            if (opts.get("-l") != null) {                out.println(Util.showId(b[i]) + showState(b[i])                        + b[i].getLocation());            } else {                if ((i & 1) == 0 && opts.get("-1") == null) {                    String s = Util.showId(b[i]) + showState(b[i])                            + Util.shortName(b[i]);                    out.print(s);                    int l = 40 - s.length();                    if (l > 0) {                        String blank = "                                    ";                        out.print(blank.substring(blank.length() - l));                    }                    needNl = true;                } else {                    out.println(Util.showId(b[i]) + showState(b[i])                            + Util.shortName(b[i]));                    needNl = false;                }            }        }        if (needNl) {            out.println("");        }        return 0;    }    //    // Call command    //    public final static String USAGE_CALL = "<interface> <method> [<args>] ...";    public final static String[] HELP_CALL = new String[] {            "Call a method with zero or more java.lang.String",            "arguments in a registered service.",            "<interface> Service interface",            "<method>    Method in service to call",            "<args>      Arguments to method. If arguments",            "            are on the form \"value::type\", the value",            "            will be attempted to created as the",            "            specified type", };    public int cmdCall(Dictionary opts, Reader in, PrintWriter out,            Session session) {        int res = 1;        final String si = (String) opts.get("interface");        final ServiceReference sr = (ServiceReference) AccessController                .doPrivileged(new PrivilegedAction() {                    public Object run() {                        return bc.getServiceReference(si);                    }                });        if (sr == null) {            out.println("No such service reference class: " + si);            return 1;        }        Object s = AccessController.doPrivileged(new PrivilegedAction() {            public Object run() {                return bc.getService(sr);            }        });        if (s == null) {            out.println("No such service: " + si);            return 1;        }        String method = (String) opts.get("method");        Class[] parameterTypes = null;        Object[] methodArgs = null;        String[] args = (String[]) opts.get("args");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -