概要：  
JavaEEでプロジェクトを開発中、解決できないエラーが発生しました。  
Jbatchが意図しないタイミングで動作し、DBアクセスエラーを起こします。

環境：

  * Windows 8.1
  * netbeans 8.0.2
  * JDK 1.8.0_25
  * JAVAEE 7.0
  * Glassfish 4.1
  * PostgreSQL 9.2.7

構成：（最小構成を構築してエラー再現を確認）

  * src/main/java/local/arquilliansample/jbatch/jobBatchlet.java
  * src/main/java/local/arquilliansample/SampleBean.java
  * src/main/java/resources/META-INF/batch-jobs/jobBatchlet.xml
  * src/test/java/local/arquilliansample/SampleBeanTest.java

詳細：  
作成した単体テストプログラムを実行すると、テストプログラム終了後に  
Jbatchが起動し、DBへアクセスを試みますが下記エラーにて接続できません。  
（テスト自体は完了後なので単体テストはグリーンで終了する）

```

    情報: RAR7094: __xa_jdbc_ra shutdown successful.
    2 24, 2015 9:19:01 午前 com.ibm.jbatch.container.services.impl.JDBCPersistenceManagerImpl logException
    重大: FAILED GETTING DATABASE CONNECTION; Exception stack trace: java.sql.SQLException: Error in allocating a connection. Cause: This Managed Connection is not valid as the physical connection is not usable
            at com.sun.gjc.spi.base.AbstractDataSource.getConnection(AbstractDataSource.java:121)
            at com.ibm.jbatch.container.services.impl.JDBCPersistenceManagerImpl.getConnectionToDefaultSchema(JDBCPersistenceManagerImpl.java:340)
            at com.ibm.jbatch.container.services.impl.JDBCPersistenceManagerImpl.isDerby(JDBCPersistenceManagerImpl.java:171)
            at com.ibm.jbatch.container.services.impl.JDBCPersistenceManagerImpl.init(JDBCPersistenceManagerImpl.java:132)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.getService(ServicesManagerImpl.java:358)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.access$300(ServicesManagerImpl.java:341)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getService(ServicesManagerImpl.java:261)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getPersistenceManagerService(ServicesManagerImpl.java:292)
            at com.ibm.jbatch.container.impl.BatchKernelImpl.<init>(BatchKernelImpl.java:86)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader._loadService(ServicesManagerImpl.java:404)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader._loadServiceHelper(ServicesManagerImpl.java:377)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.getService(ServicesManagerImpl.java:357)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.access$300(ServicesManagerImpl.java:341)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getService(ServicesManagerImpl.java:261)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getBatchKernelService(ServicesManagerImpl.java:307)
            at com.ibm.jbatch.container.api.impl.JobOperatorImpl.<init>(JobOperatorImpl.java:72)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
            at java.lang.Class.newInstance(Class.java:438)
            at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
            at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
            at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
            at javax.batch.runtime.BatchRuntime$1.run(BatchRuntime.java:52)
            at javax.batch.runtime.BatchRuntime$1.run(BatchRuntime.java:47)
            at java.security.AccessController.doPrivileged(Native Method)
            at javax.batch.runtime.BatchRuntime.getJobOperator(BatchRuntime.java:47)
            at org.glassfish.batch.spi.impl.BatchRuntimeHelper.event(BatchRuntimeHelper.java:218)
            at org.glassfish.kernel.event.EventsImpl$1.run(EventsImpl.java:123)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:745)
    Caused by: javax.resource.spi.ResourceAllocationException: Error in allocating a connection. Cause: This Managed Connection is not valid as the physical connection is not usable
            at com.sun.enterprise.connectors.ConnectionManagerImpl.internalGetConnection(ConnectionManagerImpl.java:319)
            at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:196)
            at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:171)
            at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:166)
            at com.sun.gjc.spi.base.AbstractDataSource.getConnection(AbstractDataSource.java:114)
            ... 38 more
    Caused by: com.sun.appserv.connectors.internal.api.PoolingException: This Managed Connection is not valid as the physical connection is not usable
            at com.sun.enterprise.resource.allocator.ConnectorAllocator.fillInResourceObjects(ConnectorAllocator.java:194)
            at com.sun.enterprise.resource.pool.ConnectionPool.getResource(ConnectionPool.java:488)
            at com.sun.enterprise.resource.pool.PoolManagerImpl.getResourceFromPool(PoolManagerImpl.java:245)
            at com.sun.enterprise.resource.pool.PoolManagerImpl.getResource(PoolManagerImpl.java:170)
            at com.sun.enterprise.connectors.ConnectionManagerImpl.getResource(ConnectionManagerImpl.java:354)
            at com.sun.enterprise.connectors.ConnectionManagerImpl.internalGetConnection(ConnectionManagerImpl.java:307)
            ... 42 more
    Caused by: javax.resource.ResourceException: This Managed Connection is not valid as the physical connection is not usable
            at com.sun.gjc.spi.ManagedConnectionImpl.checkIfValid(ManagedConnectionImpl.java:756)
            at com.sun.gjc.spi.ManagedConnectionImpl.getConnection(ManagedConnectionImpl.java:443)
            at com.sun.enterprise.resource.allocator.ConnectorAllocator.fillInResourceObjects(ConnectorAllocator.java:189)
            ... 47 more
    
    2 24, 2015 9:19:01 午前 com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader _loadServiceHelper
    重大: Could not instantiate service: com.ibm.jbatch.container.impl.BatchKernelImpl due to exception:java.lang.reflect.InvocationTargetException
    2 24, 2015 9:19:01 午前 org.glassfish.kernel.event.EventsImpl$1 run
    警告: Exception while dispatching an event
    java.util.ServiceConfigurationError: javax.batch.operations.JobOperator: Provider com.ibm.jbatch.container.api.impl.JobOperatorImpl could not be instantiated
            at java.util.ServiceLoader.fail(ServiceLoader.java:232)
            at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
            at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
            at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
            at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
            at javax.batch.runtime.BatchRuntime$1.run(BatchRuntime.java:52)
            at javax.batch.runtime.BatchRuntime$1.run(BatchRuntime.java:47)
            at java.security.AccessController.doPrivileged(Native Method)
            at javax.batch.runtime.BatchRuntime.getJobOperator(BatchRuntime.java:47)
            at org.glassfish.batch.spi.impl.BatchRuntimeHelper.event(BatchRuntimeHelper.java:218)
            at org.glassfish.kernel.event.EventsImpl$1.run(EventsImpl.java:123)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.RuntimeException: Could not instantiate service com.ibm.jbatch.container.impl.BatchKernelImpl due to exception: java.lang.reflect.InvocationTargetException
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader._loadServiceHelper(ServicesManagerImpl.java:385)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.getService(ServicesManagerImpl.java:357)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl$ServiceLoader.access$300(ServicesManagerImpl.java:341)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getService(ServicesManagerImpl.java:261)
            at com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl.getBatchKernelService(ServicesManagerImpl.java:307)
            at com.ibm.jbatch.container.api.impl.JobOperatorImpl.<init>(JobOperatorImpl.java:72)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
            at java.lang.Class.newInstance(Class.java:438)
            at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
            ... 13 more
    
```

設定ファイル等は以下になります。  
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>
    
        <groupId>local</groupId>
        <artifactId>ArquillianSample</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <name>ArquillianSample</name>
    
        <properties>
            <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
    
        <dependencyManagement>
            <dependencies>
                <!-- open arquillian -->
                <dependency>
                    <groupId>org.jboss.arquillian</groupId>
                    <artifactId>arquillian-bom</artifactId>
                    <version>1.1.5.Final</version>
                    <scope>import</scope>
                    <type>pom</type>
                </dependency>
                <!-- close -->
            </dependencies>
        </dependencyManagement>
    
    
        <dependencies>
            <!-- open arquillian -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.junit</groupId>
                <artifactId>arquillian-junit-container</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.container</groupId>
                <artifactId>arquillian-glassfish-embedded-3.1</artifactId>
                <version>1.0.0.CR4</version>
            </dependency>
            <dependency>
                <groupId>org.glassfish.main.extras</groupId>
                <artifactId>glassfish-embedded-all</artifactId>
                <version>4.1</version>
            </dependency>
            <!-- close -->
    
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
        <build>
    
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                        <compilerArguments>
                            <endorseddirs>${endorsed.dir}</endorseddirs>
                        </compilerArguments>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.6</version>
                    <executions>
                        <execution>
                            <phase>validate</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${endorsed.dir}</outputDirectory>
                                <silent>true</silent>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>javax</groupId>
                                        <artifactId>javaee-endorsed-api</artifactId>
                                        <version>7.0</version>
                                        <type>jar</type>
                                    </artifactItem>
                                </artifactItems>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
```

jobBatchlet.java

```

    package local.arquilliansample.jbatch;
    
    import javax.batch.api.Batchlet;
    
    public class JobBatchlet implements Batchlet {
    
        @Override
        public String process() throws Exception {
            System.out.println("[Batchlet] process");
            return null;
        }
    
        @Override
        public void stop() throws Exception {
            System.out.println("[Batchlet] stop");
        }
    }
    
```

SampleBean.java

```

    package local.arquilliansample;
    
    import javax.ejb.Stateless;
    
    @Stateless
    public class SampleBean {
    
        public void writeMessage(String message) {
            System.out.println(message);
        }
    
    }
    
```

jobBatchlet.xml

```

    <?xml version="1.0" encoding="UTF-8"?>
    <job id="jobBatchlet" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
        <step id="step1">
            <batchlet ref="arquilliansample.jbatch.JobBatchlet" />
        </step>
    </job>
    
```

SampleBeanTest.java

```

    package local.arquilliansample;
    
    import javax.inject.Inject;
    import static org.junit.Assert.assertTrue;
    import org.jboss.arquillian.container.test.api.Deployment;
    import org.jboss.arquillian.junit.Arquillian;
    import org.jboss.shrinkwrap.api.ShrinkWrap;
    import org.jboss.shrinkwrap.api.spec.WebArchive;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    @RunWith(Arquillian.class)
    public class SampleBeanTest {
    
        @Deployment
        public static WebArchive createDeployment() {
            WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war")
                    .addClass(SampleBean.class)
                    .addClass(SampleBeanTest.class);
            System.out.println(archive.toString(true));
            return archive;
        }
    
        @Inject
        private SampleBean bean;
    
        @Test
        public void testWriteMessage() {
            bean.writeMessage("hello world");
    
            assertTrue(true);
        }
    
    }
    
```

またエラーが出るのは確実ではなく、3回中２回位の頻度です。

どなたか解決方法をご存じでしたらご教授頂きたいと思います。  
何卒宜しくお願い致します。

追記：  
コードブロックが派手に崩れていて申し訳ありません・・・  
このマークダウン形式をまだよくわかっていないため後ほど修正します。
CC BY-SA 3.0
2015-02-24T00:41:32.647
6987
2015-07-24T18:34:19.917
2015-02-24T01:04:14.943
5793
8508
question
java8
glassfishの単体テストをArquillianで実行した際、Jbatchが終了後に動作しDBアクセスエラーを起こす
GlassFish の Embedded コンテナを利用して Java SE 環境での実行になるかと  
思いますので、下記の URL をご参考にされてみては如何でしょうか。

<http://yoshio3.com/2014/02/18/jbatchjsr-352-on-java-se-%E7%92%B0%E5%A2%83/>

特に、2 番目の設定を行われてみては如何でしょうか？  
バッチ・コンテナは各種情報を DB(デフォルトでは Java DB)に保存しますので、  
DB に接続できない、もしくは DB が停止している状況ですと、正しく動作しないかと想定します。

  2. Batch コンテナを実行するための設定

次に Batch コンテナを稼働させるためのプロパティの設定を行います。  
META-INF ディレクトリ配下に services ディレクトリを作成して  
それぞれ下記のファイルを作成してください。

src/META-INF/services/batch-config.properties

JDBC_DRIVER=org.apache.derby.jdbc.EmbeddedDriver  
JDBC_URL=jdbc:derby://localhost:1527/batchdb;create=true

src/META-INF/services/batch-services.properties  
J2SE_MODE=true

以上で基本的には Java SE 環境上で動作させるために必要な設定は完了です。

上記の設定を行った際、  
asadmin start-database 等で JavaDB を事前に常時起動しておく必要はあります。GlassFish から Java DB
を起動する場合、GlassFish の停止時に Java DB も停止するのでタイミング的に OK/NG の可能性はあるかと思います。

また、EJB を @Inject でインジェクトしていますが、EJB は @EJB でインジェクトして頂ければと思います。
CC BY-SA 3.0
2015-02-24T15:43:14.633
7044
2015-02-24T15:50:18.317
2015-02-24T15:50:18.317
8533
8533
6987
answer