java - ServiceMix 找不到 OSGI 数据源

标签 java osgi openjpa blueprint-osgi apache-servicemix

我一直在研究 ServiceMix 5.4.0 和 OSGi,并且遇到了 OpenJPA 的一个相当奇怪的行为。

我有一个这样定义的数据源:

<blueprint
        xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:5432/test"/>
        <property name="username" value="test"/>
        <property name="password" value="test"/>
    </bean>

    <service interface="javax.sql.DataSource" ref="dataSource">
      <service-properties>
        <entry key="osgi.jndi.service.name" value="jdbc/test"/>
      </service-properties>
    </service>
</blueprint>

使用 jndi:names 命令,我可以验证数据源是否可见:

karaf@root> jndi:names
JNDI Name            Class Name                                                  
osgi:service/jndi    org.apache.karaf.jndi.internal.JndiServiceImpl              
osgi:service/jdbc/test org.apache.commons.dbcp.BasicDataSource                     
karaf@root> 

我的 persistence.xml:

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="test" transaction-type="JTA">               
        <jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/test)</jta-data-source>

        <class>com.example.persistence.security.User</class>

        <exclude-unlisted-classes>true</exclude-unlisted-classes>

        <properties>
            <property name="openjpa.jdbc.DBDictionary" value="postgres"/>                       
            <property name="openjpa.Log" value="slf4j"/>
        </properties>
    </persistence-unit>
</persistence>

然后我通过蓝图将持久化单元注入(inject)到 DAO 类中:

<?xml version="1.0" encoding="UTF-8"?>

<blueprint  default-activation="eager" 
            xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
            xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
            xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">

    <bean id="securityDAO" class="com.example.security.dao.SecurityDAOImpl" init-method="init">
        <tx:transaction method="*" value="Required" />
        <jpa:context property="entityManager" unitname="test" />
    </bean>

    <service ref="securityDAO" interface="com.example.security.dao.SecurityDAO">
    </service>


</blueprint>

持久化单元注入(inject)成功,我在DAO的init-method中验证:

public void init() {
    if (em==null) {
        log.error("Entity manager not found. Check JPA configuration.");
        throw new RuntimeException("No EntityManager found");
    }

    log.info("Started SecurityDAO");
}

在我所有的辛勤工作之后,当我从另一个 bean 调用我的 DAO 方法时,ServiceMix 奖励我以下神秘异常:

....
public void setSecurityDAO (SecurityDAO dao) {
    this.dao = dao;
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String userName = req.getParameter("userName");
    String password = req.getParameter("password");

    // Invocation of injected DAO results in exception
    User u = dao.authenticateUser(userName, password);          

结果如下:

Caused by: java.lang.RuntimeException: The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/test) required by bundle persistence/0.0.1.SNAPSHOT could not be found.
    at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:87)
    at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)
    at org.apache.openjpa.lib.jdbc.DelegatingDataSource.getConnection(DelegatingDataSource.java:116)
    at org.apache.openjpa.lib.jdbc.DecoratingDataSource.getConnection(DecoratingDataSource.java:93)
    at org.apache.openjpa.jdbc.schema.DataSourceFactory.installDBDictionary(DataSourceFactory.java:233)
    ... 54 more
Caused by: javax.naming.NoInitialContextException: Unable to find the InitialContextFactory org.eclipse.jetty.jndi.InitialContextFactory.
    at org.apache.aries.jndi.ContextHelper.getInitialContext(ContextHelper.java:148)
    at org.apache.aries.jndi.OSGiInitialContextFactoryBuilder.getInitialContext(OSGiInitialContextFactoryBuilder.java:49)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
    at javax.naming.InitialContext.init(InitialContext.java:244)
    at javax.naming.InitialContext.<init>(InitialContext.java:216)
    at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:64)
    ... 58 more

不知何故,OSGi 导出的数据源没有找到进入持久性包的方式。奇怪的是,当我将以下代码添加到 init-method 中以查看是否可以执行测试查询时,OpenJPA 不仅没有在 init 方法中抛出异常,现在触发异常的 DAO 的调用也适用:

public void init() {
    if (em==null) {
        log.error("Entity manager not found. Check JPA configuration.");
        throw new RuntimeException("No EntityManager found");
    }

    try {
        Query q = em.createNativeQuery("SELECT 1=1");           
        q.getFirstResult();         
    } catch (Exception ex) {
        log.error("Unable to execute test query against database", ex);
        throw new RuntimeException(ex);
    }

    log.info("Started SecurityDAO");
}

因此,总结一下:如果我从与我的 DAO 不同的包中调用方法,OpenJPA 会抛出一个异常,指示它找不到 InitialNamingContext,并且不会在日志中显示它已启动的任何指示。如果我在外部组件调用它之前在我的 DAO 中执行查询,OpenJPA 能够以某种方式找到 InitialNamingContext,OpenJPA 出现在日志中,随后来自 DAO 包外部的调用开始工作。

显然,我在这里遗漏了一些基本的东西。非常感谢任何有关问题或我做错了什么的帮助或深思熟虑的解释。

编辑:

昨晚我没有注意到,但是当我在测试查询中添加时,日志中出现了以下几行。当我注释掉该查询时,它们不存在:

... | Runtime | 220 - org.apache.openjpa - 2.3.0 | Starting OpenJPA 2.3.0
... | JDBC    | 220 - org.apache.openjpa - 2.3.0 | Using dictionary class "org.apache.openjpa.jdbc.sql.PostgresDictionary".
... | JDBC    | 220 - org.apache.openjpa - 2.3.0 | Connected to PostgreSQL version 9.9 using JDBC driver PostgreSQL Native Driver version PostgreSQL 9.3 JDBC4.1 (build 1102).

编辑 2:

在普通的 Vanilla Karaf 3.0.3 上试过,得到了同样的错误。作为解决方法,我在执行上述测试查询的包中创建了一个单独的 bean。显然,只要 bundle 中的单个 bean 在 bundle 外的 bean 尝试调用之前调用 OpenJPA,OpenJPA 就会正确初始化。

由于在 OpenJPA/ServiceMix 文档中我看不到这一点,所以我只能假设我在配置的其他地方做错了什么。

编辑 3:

Per John Forth,这里是 MANIFEST.MF

Manifest-Version: 1.0
Bnd-LastModified: 1430533396366
Build-Jdk: 1.8.0_45
Built-By: somedude
Bundle-Blueprint: OSGI-INF/blueprint/blueprint.xml
Bundle-Description: Database access layer for Peer Review product
Bundle-ManifestVersion: 2
Bundle-Name: Example :: Persistence
Bundle-SymbolicName: persistence-jpa
Bundle-Version: 0.0.1.SNAPSHOT
Created-By: Apache Maven Bundle Plugin
Export-Package: com.example.persistence.security;version="0.0.1.SNAPSHOT",co
 m.example.security.dao;version="0.0.1.SNAPSHOT";uses:="com.example.persistence.
 security,javax.persistence"
Export-Service: com.example.security.dao.SecurityDAO
Import-Package: javax.persistence;version="[1.1,2)",org.osgi.service.blu
 eprint;version="[1.0.0,2.0.0)",org.slf4j;version="[1.7,2)"
Meta-Persistence: META-INF/persistence.xml
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.7))"
Tool: Bnd-2.3.0.201405100607

并且,由于它可能与 JPA 包的 pom.xml 相关:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>example</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>persistence-jpa</artifactId>
    <packaging>bundle</packaging>

    <name>Example :: Persistence</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jpa_2.0_spec</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.5.3</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Version>${project.version}</Bundle-Version>                     
                        <Import-Package>*</Import-Package>
                        <Export-Package>com.example.persistence*,com.example.security.*;version=${project.version}</Export-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

最佳答案

如果您使用的是 OSGI,则类可见性在 MANIFEST.MF 文件中定义。

因此持久性包只能看到和加载在其 MANIFEST.MF 中导入的类。

扩展现有包的正确方法是定义附加到现有包的片段。通过这种方式,您可以提供类(例如 DAO)和文件(例如 persistence.xml)并使片段主机可见。

然后 MANIFEST.MF 看起来像

Bundle-ManifestVersion: 2
Bundle-Name: foo.bar.openjpa-fragment
Bundle-SymbolicName: foo.bar.openjpa-fragment;singleton:=true
Bundle-Version: 0.0.1.SNAPSHOT
Bundle-Vendor: foo bar
Fragment-Host: org.apache.openjpa-bundle
Bundle-ClassPath: .

请注意,这只是一个示例。

OSGI 意味着提供适当的可见性。

您可以将多个片段添加到现有的包中,例如将配置保存在单独的包中,这样可以更轻松地切换配置。

关于java - ServiceMix 找不到 OSGI 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838372/

相关文章:

java - 如何在绘制到 Canvas 之前为位图设置坐标

java - 在 Spring Boot 中增加 HTTP Post maxPostSize

java - 如何区分不同jar版本的类加载器?

java - 自动更新 OpenJPA 表

garbage-collection - 如何将详细的垃圾收集输出重定向到文件?

java - spring hibernate .. H2 数据库 - 找不到模式

java - OSGI kafka 客户端包由于缺少约束导致框架异常

jpa - 未注入(inject) OSGI 服务 JPA PersistenceContext

java - 外键作为 OpenJPA 中复合主键和 ManyToOne 关系的一部分