FrameworkUtil.getBundle всегда возвращает мне NULL
Я пытаюсь установить пакет с помощью OSGi Framework. Ниже мой код, который пытается получить bundleContext
,
В приведенном ниже коде, каждый раз, когда эта строка FrameworkUtil.getBundle
возвращает меня null
,
Ниже код моего приложения
public App() {
String basePath = "C:\\Tool\\LocalStorage";
final BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
// install various bundles-
final Bundle bundle = bundleContext.installBundle(localFilenameOfBundles);
bundle.start();
}
Когда я отладил код, я обнаружил, что в getBundle method
FrameworkUtil класса
public static Bundle getBundle(final Class< ? > classFromBundle) {
// We use doPriv since the caller may not have permission
// to call getClassLoader.
Object cl = AccessController
.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return classFromBundle.getClassLoader();
}
});
if (cl instanceof BundleReference) {
return ((BundleReference) cl).getBundle();
}
return null;
}
cl is not an instance of BundleReference
и именно поэтому он всегда возвращает мне NULL. И когда я проверил на cl
Я нашел что-то вроде этого
sun.misc.Launcher$AppClassLoader@69956995
а какой я считаю не экземпляр BundleReference? Мне нужно это org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader
Ниже мой файл pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.host.Stream</groupId>
<artifactId>Stream-parent</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../Build/superpom</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.host.personallization.eye</groupId>
<artifactId>eye</artifactId>
<packaging>jar</packaging>
<name>eye</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration> <!-- Configuration of the archiver -->
<archive> <!-- Manifest specific configuration -->
<manifest> <!-- Classpath is added to the manifest of the created jar file. -->
<addClasspath>true</addClasspath> <!-- Configures the classpath prefix. This configuration option is used to
specify that all needed libraries are found under lib/ directory. -->
<classpathPrefix>lib/</classpathPrefix> <!-- Specifies the main class of the application -->
<mainClass>com.host.Stream.eye.eyeApp</mainClass>
</manifest>
</archive>
<includes>
<include>**/*.xml</include>
<include>**/*.class</include>
</includes>
<finalName>${project.artifactId}</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>unpack</id>
<phase>prepare-package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.host.raptor</groupId>
<artifactId>ConfigWeb</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>buildsrc/StreamConf</outputDirectory>
<includes>**</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>target/config/StreamConf</outputDirectory>
<resources>
<resource>
<directory>buildsrc/StreamConf</directory>
<includes>
<include>**</include>
</includes>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>maven-replacer-plugin</artifactId>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<file>target/config/StreamConf/eyewiring.xml</file>
<regex>false</regex>
<replacements>
<replacement>
<token>dynamic_build_label_place_holder</token>
<value>${project.artifactId}-${project.version}-${buildNumber}</value>
</replacement>
</replacements>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<id>assembly</id>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
<finalName>${project.artifactId}-${project.version}-${buildNumber}</finalName>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.host.Stream</groupId>
<artifactId>Streamframework</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.host.external</groupId>
<artifactId>ucirrus-db</artifactId>
<version>0.7.3</version>
</dependency>
<dependency>
<groupId>com.host.Stream</groupId>
<artifactId>Streamcore</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.osgi</groupId>
<artifactId>spring-osgi-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.osgi</groupId>
<artifactId>spring-osgi-extender</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.osgi</groupId>
<artifactId>spring-osgi-io</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
</project>
Есть ли что-то, чего я здесь не хватает? Я предполагаю, что проблема, с которой я сталкиваюсь, связана с загрузкой класса OSGi. Потому что я думаю, что каждый комплект имеет свой собственный загрузчик классов, DefaultClassLoader. Но в моем случае этот загрузчик классов отличается, я не уверен, как это исправить?
1 ответ
Ваш класс не был загружен загрузчиком классов OSGi. На самом деле это было загружено AppClassLoader
, который является загрузчиком классов по умолчанию в JVM, который загружает классы в основной путь к классам приложения - то есть в jar и каталоги, перечисленные с -classpath
переменная командной строки.
Вы действительно создали пакет OSGi? Вы запустили OSGi Framework и установили в него свой пакет? Потому что, похоже, вы просто используете Java.
Я обнаружил, что есть еще один не столь очевидный случай, в котором FrameworkUtil.getBundle будет возвращать ноль. Если указанный класс является дополнительным классом, экспортируемым самим пакетом системы фреймворка (bundle(0)), эти классы будут возвращать нулевой результат. Причина в точности та же, что объяснил Нейл Бартлетт; эти классы не разрешаются напрямую из загрузчика классов OSGI. Пакеты, которые импортируют классы, поставляемые из системного пакета, работают превосходно; просто FrameworkUtil не даст вам знать, что эти классы происходят из системного пакета.
Причина, по которой вы можете это сделать, заключается в том, что вы хотите получить ресурс из пакета, из которого поступил класс.