`
snoopy7713
  • 浏览: 1152777 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

与OSGi容器交互

阅读更多

1. Bundles

    获取Bundle信息接口:BundleContext,方法:

    getBundles();获取当前容器中所有的Bundle

    getBundle(long bundleId);获取指定Id的Bundle

    getBundle();获取的当前Bundle

    例如:

    BundleContext bundleContext = (...)
    Bundle[] bundles = bundleContext.getBundles();
    long bundleIdentifier = 12;
    Bundle bundle = bundleContext.getBundle(
         bundleIdentifier
    );
    Bundle currentBundle = bundleContext.getBundle();

 

    Accessing general and configuration information about a bundle:

    Bundle bundle = (...)
    Long bundleId = bundle.getBundleId();
    String location = bundle.getLocation();
    String symbolicName = bundle.getSymbolicName();

    Dictionary<String,String> headers = bundleContext.getBundle().getHeaders();
    String bundleName = headers.get(Constants.BUNDLE_NAME);
    String bundleVersion = headers.get(Constants.BUNDLE_VERSION);

 

    getResource()和findEntries()方法:

    Bundle bundle = (...);
    URL specificConfigurationFile = bundle.getResource("META-INF/spring/osgi-context.xml");
    Enumeration configurationFiles = bundle.findEntries("META-INF/spring", "*.xml", false);

2. Lifecycle Management

    States in a bundle’s lifecycle:

    Installed: Bundle is installed within the OSGi container.
    Uninstalled: Bundle is uninstalled from the OSGi container.
    Resolved: Bundle is installed and all dependencies are resolved.
    Starting: Bundle is starting, moving from the resolved to the active state.
    Active: Bundle is available to do work within the OSGi container.
    Stopping: Bundle is stopping, moving from the active to the resolved state.

    例如:

    BundleContext bundleContext = (...);
    String absoluteBundlePath = (...);
    Bundle bundle = bundleContext.installBundle(absoluteBundlePath);
    int state = bundle.getState();

 

    bundle.start();
    int state = bundle.getState();

3. Properties

    Access global properties which are defined by the OSGi Container via the BundleContext’s  

    getProperty method。

    Several property keys are standardized in the OSGi specification and are present in the Constants 

    interface—these constants can be used as parameters of the getProperty method:

    ■ Constants.FRAMEWORK_VERSION and Constants.FRAMEWORK_VENDOR—The version
       and name of the OSGi container used
    ■ Constants.FRAMEWORK_LANGUAGE—The language used by the container to implement   

       components
    ■ Constants.FRAMEWORK_OS_NAME and Constants.FRAMEWORK_OS_VERSION—The name and

       version of the operating system that’s running the container
    ■ Constants.FRAMEWORK_PROCESSOR—The name of the processor corresponding to the host

       computer

    例如:

    String containerName = bundleContext.getProperty(Constants.FRAMEWORK_VENDOR);

    其中:如果在OSGi容器中搜索不到指定的属性,将搜索JVM的系统属性。

4. Event Support

    OSGi’s event support at the bundle level allows code to be notified of every update to the state

    of a component during its lifetime. It provides two ways to handle these events:
    ■ An asynchronous method using the BundleListener interface
    ■ A synchronous method using the SynchronousBundleLister interface

    其中:The SynchronousBundleListener interface extends BundleListener without adding anything  

    more.

    Handling a bundle event in an asynchronous listener:

    public class SimpleBundleListener implements BundleListener {
           public void bundleChanged(BundleEvent event) {
                   int type = event.getType();
                   String symbolicName = event.getBundle().getSymbolicName();
                   if (type==BundleEvent.STARTED) {
                        System.out.println("Bundle "+symbolicName+" started...");
                   } else if (type==BundleEvent.STOPPED)

                        System.out.println("Bundle "+symbolicName+" stopped...");
                   }
           }
     }

     注册该监听器:使用BundleContext的addBundleListener方法。

5.  Persistent Storage Area

     Interacting with the persistent storage area of a component:

     BundleContext bundleContext = (...)
     File directory = bundleContext.getDataFile("/data");
           if (!directory.exists()) {
                 directory.mkdir();
           }
           File file = bundleContext.getDataFile("/data/test.txt");
           FileWriter writer = null;
           try {
                 writer = new FileWriter(file, true);
                 writer.write("my content");
           } catch(IOException ex) {
           (...)
           } finally {
                 closeWriter(writer);
           }

6. BundleActivator

    Registering and unregistering services with a BundleActivator:

    public class SimpleActivator implements BundleActivator {
       (...)
        public void start(BundleContext context) {
            registerServices(context);
        }
        public void stop(BundleContext context) {
            unregisterServices(context);
        }
    }

    其中该Activator 需要在MAINFEST.MF文件中通过Bundle-Activator Header定义。

7. Service support in OSGi

    The OSGi services feature is based on the service registry, which provides nameand property

    -based lookup, registration, and management of all service instances registered in the container.

    It also can be used to notify components when changes occur, to prevent errors from occurring.

7.1 Providing Service

    使用BundleContext的registerService()方法,该方法返回ServiceRegistration,该方法有 一下参数:

    (1) clazz or clazzes: 一个或几个名字用来注册和 识别服务。 在OSGi中,这些名称对应的是 服务类的名称,

    或者,如果是基于接口的编程,则是 实现的接口的名称 。 类型检查时将使用这些名字 。 具有相同名称的多哥服

    务可共存于OSGi服务注册表 。

    (2) service:The implementation of the service itself, or an instance of the ServiceFactory interface.

    (3) properties: A set of properties to associate with the service. These properties must be of
    type String. The value can be null if there are no properties. And the OSGi container automatically

    inserts two additional properties that are related to the service identifier (service.id) and the

    classes used for the registration (objectClass).

    Simple implementation of the HelloWorldService interface:

    public class SimpleServiceActivator implements BundleActivator {
          private ServiceRegistration serviceRegistration;
          public void start(BundleContext bundleContext) throws Exception {
               String serviceName = "com.manning.sdmia.osgi.services.providing.service.SimpleService";
               SimpleServiceImpl service = new SimpleServiceImpl();
               Properties properties = new Properties();
               properties.setProperty("creationDate",(new Date()).toString());
               this.serviceRegistration= bundleContext.registerService(serviceName, service,    

                      serviceProperties);
           }
           public void stop(BundleContext bundleContext) throws Exception {
               if (this.serviceRegistration!=null) {
                    this.serviceRegistration.unregister();
               }
           }
    }

    Simple implementation of the ServiceFactory interface:

    public class SimpleServiceFactory implements ServiceFactory {
          public Object getService(
                Bundle bundle, ServiceRegistration registration) {
                    String bundleSymbolicName = bundle.getSymbolicName();
                    if (bundleSymbolicName.startsWith("com.manning")) {
                          return new SimpleForManningServiceImpl();
                    } else {
                         return new SimpleServiceImpl();
                    }
          }
          public void ungetService(Bundle bundle,
                ServiceRegistration registration, Object service) {
          }
   }

   Note that implementations of this interface are used by the container and therefore must be  

   thread-safe. The instance returned by the getService method is cached by the framework until 

   the bundle releases the service.

7.2 Using Service

   (1) Basic Approach

   1. Get a ServiceReference instance for the service, based on the service name from the BundleContext instance.

   2. Get the service instance itself, based on the BundleContext instance and the previously obtained ServiceReference instance.

   Consuming an OSGi service:

   String serviceName = SimpleService.class.getName();
   ServiceReference serviceReference = null;
   try {
          serviceReference = bundleContext.getServiceReference(serviceName);
          if (serviceReference!=null) {
              SimpleService service= (SimpleService)bundleContext.getService(serviceReference);
              service.test();
          }
    } catch(Exception ex) {
    (...)
    } finally {
        if (serviceReference!=null) {
            bundleContext.ungetService(serviceReference);
        }
    }

    其中:ServiceReference instances can also be obtained by using bundle instances, which provide

    the following methods:
    ■ getRegisteredServices—Returns the list of services registered by the bundle
    ■ getServicesInUse—Returns the list of the bundle services used by other bundles

    (2) Service Tracker

    需现在MANIFEST.MF中Import-Package:org.osgi.util.tracker,Using the ServiceTracker:

    String serviceName = SimpleService.class.getName();
    ServiceTracker serviceTracker = null;

    try {
         serviceTracker = new ServiceTracker(
         bundleContext, serviceName, null);
         serviceTracker.open();
         SimpleService service = (SimpleService) serviceTracker.getService();
         service.test();
    } catch(Exception ex) {
    (...)
    } finally {
        if (serviceTracker!=null) {
            serviceTracker.close();
        }
    }

7.3 Service Event Support

    使用ServiceLinstner接口,A ServiceListener implementation handling service events:

    public class SimpleServiceListener implements ServiceListener {
           private String getServiceName(ServiceEvent event) {
               String[] objectClass = (String[])event.getServiceReference().getProperty("objectClass");
               return objectClass[0];
           }
           public void serviceChanged(ServiceEvent event) {
               int type = event.getType();
               String serviceName = getServiceName(event);
               String symbolicName = event.getServiceReference().getBundle().getSymbolicName();
               if (type==ServiceEvent.REGISTERED) {
                   System.out.println("Service " + serviceName + " registred by the bundle "

                   + symbolicName + "...");
               } else if (type==ServiceEvent.UNREGISTERING) {
                   System.out.println("Service " + serviceName + " being unregistered by the bundle "
                   + symbolicName + "...");
                   } else if (type==ServiceEvent.MODIFIED) {
                   System.out.println("Service " + serviceName + " modified by the bundle "

                   + symbolicName + "...");
               }
          }
    }

    注册该监听器:

    BundleContext context = (...)
    SimpleServiceListener listener = new SimpleServiceListener();
    Context.adServiceListener(listener);

分享到:
评论

相关推荐

    osgi在web容器中部署的例子

    6. 测试和调试:启动Tomcat,通过Web应用或直接与OSGi容器交互,测试bundle的功能是否正常。 总结来说,OSGi在Web容器中的部署提供了一种灵活的方式,使得我们可以独立地管理和更新应用的各个部分,同时利用Web容器...

    tomcat嵌入OSGI容器

    标题中的“tomcat嵌入OSGI容器”是指在Apache Tomcat服务器中集成OSGI(Open Service Gateway Initiative)框架,使得Tomcat能够支持模块化的应用程序部署和管理。OSGI是一种Java平台上的服务导向架构,它允许动态地...

    RAP 整合 Spring (基于 Spring-osgi )

    3. **RAP 和 OSGi**:理解 RAP 如何与 OSGi 容器交互,以及如何配置 RAP 应用来利用 OSGi 的服务发现和动态性。这涉及到 RAP 的服务器端和客户端组件如何在 OSGi 环境下工作。 4. **集成步骤**:整合 RAP 和 Spring...

    osgi 在web容器中部署

    OSGi基于服务导向架构,其中每个模块(称为bundle)都有自己的类加载器,并通过声明依赖关系来管理与其他模块的交互。这使得在运行时可以动态地安装、启动、停止和更新模块,而不会影响到其他模块。 Tomcat是基于...

    spring-dm-osgi整合jar包

    1. **配置OSGi容器**:设置OSGi容器(如Equinox或Felix),并确保其正确运行。 2. **创建OSGi服务**:定义服务接口和实现,并将它们打包为OSGi bundle。 3. **配置Spring DM**:在bundle中包含Spring DM配置文件,...

    osgi 插件开发

    OSGi容器(例如Knopflerfish、Equinox和Apache Felix等)的出现极大地简化了复杂应用的开发过程。 #### OSGi的核心特性 1. **动态性**:OSGi允许开发者在不停止整个系统的情况下安装、卸载、启动和停止单个模块。 ...

    Tomcat-Osgi

    2. **Tomcat与OSGi的集成**:Tomcat-Osgi的目的是使Tomcat成为一个OSGi容器,使得Web应用程序可以被分解为独立的OSGi bundles。每个bundle都是一个自包含的单元,包含代码、资源和元数据,可以独立部署、更新和卸载...

    spring-osgi-1.2.1.rar

    - 提供的示例程序可能包含了如何创建和配置Spring OSGi bundle,以及如何在OSGi容器中运行和交互的示例代码。 - 通过学习这些示例,开发者可以快速掌握Spring OSGi的基本用法和最佳实践。 8. **Spring OSGi的应用...

    osgi,林昊写的osgi实战和进阶

    3. **远程服务**:如何利用OSGI实现远程服务调用,使服务能在不同OSGI容器间通信。 4. **开发工具与环境**:推荐的开发工具和IDE插件,以及如何设置和优化开发环境。 5. **性能优化**:针对OSGI环境的性能调优技巧...

    OSGI进阶插件开发

    1. **启动OSGi容器**:例如Equinox或Felix,它们是OSGi规范的实现,提供运行时环境。 2. **部署bundle**:将bundle文件放入容器的bundle目录,或者通过API动态安装。 3. **管理bundle状态**:通过控制台或API启动、...

    基于 OSGI 的 RCP 测试 1 Equinox

    "基于 OSGi 的 RCP 测试" 标签明确了这个项目的核心内容是测试 OSGi 与 RCP 结合的工作方式,主要关注点在于如何在 OSGi 环境下构建和测试客户端应用程序。 **文件名解析:** "osgi_component_test" 这个文件名...

    OSGi Web示例工程

    1. **OSGi容器**:这是运行OSGi应用的基础,它负责管理模块(也称为bundle),提供依赖注入,并处理模块间的生命周期。 2. **Bundle**:OSGi中的基本单位,类似Java的JAR文件,但包含元数据以描述其依赖和其他元...

    OSGI + Webservice 例子

    6. **部署与生命周期管理**:学习如何在OSGI容器(如Equinox或Felix)中部署这些模块,以及如何管理和控制模块的生命周期,包括启动、停止、更新和依赖解析。 7. **测试与调试**:了解如何对OSGI环境中的Web服务...

    OSGI

    而工具的使用则可以加速这一过程,例如使用Equinox或Felix作为OSGI容器,使用Bnd或Bndtools进行bundle的构建和管理。 总的来说,OSGI是一种强大的技术,尤其适合大型企业级应用或需要高度模块化和动态性的场景。...

    osgi-tutorial.zip

    4. **启动和管理服务**: 在OSGi容器中,我们可以启动和停止bundle,这会影响到其中的服务生命周期。当bundle激活时,Blueprint会自动解析配置并创建相应的Spring上下文。 5. **服务发现和消费**: 由于OSGi的动态性...

    osgi 资料 总结 实践

    Spring DM允许在OSGi容器中管理Spring应用的bean和服务。 - **与Hibernate的集成**:在OSGi环境中使用Hibernate,需要处理类加载和依赖的问题。可以通过使用特定的OSGi友好的Hibernate版本或适配器,如Hibernate ...

    spring-osgi-1.2.1-with-dependencies

    而Spring OSGi则是Spring框架与OSGi(Open Service Gateway Initiative)规范的结合,它为Spring应用提供了在OSGi容器中运行的能力。本文将围绕“spring-osgi-1.2.1-with-dependencies”这一完整包展开,详细解析其...

    eclipse下构建spring与OSGI项目

    这可能涉及到模拟OSGi服务的交互,确保bean的依赖得到正确解决,并能在OSGi环境中正常工作。 总结,通过以上步骤,我们可以在Eclipse环境下构建一个结合了Spring和OSGi的项目,利用Spring的强大功能和OSGi的模块化...

Global site tag (gtag.js) - Google Analytics