Cargo Maven Tomcat NoInitialContextException当我已经有了Context

时间:2016-07-17 08:40:56

标签: maven tomcat java-ee integration-testing cargo-maven2-plugin

我正在使用cargo maven插件将我的.war部署到Tomcat 8实例进行集成测试。 该应用程序是基于平针织的REST Web界面。 我的问题出现在底层数据库连接池中。 在集成测试中,有一个NoInitialContextException导致NullPointerexception。

我构建了2个池(1个用于应用程序,1个用于oacc):

public class DBCPool {

   static final Logger LOGGER = LogManager.getRootLogger();
   static DataSource dbs = null;
   static DataSource oaccDS = null;

   private DBCPool() {};

public static boolean startup() {
      if (dbs != null && oaccDS != null) {
         LOGGER.trace("DBCPool startup when pool != null");
         return true;
      } else {
         try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Context ctxt = new InitialContext();
            LOGGER.debug("Initial context is: " + ctxt.getNameInNamespace());
            if (dbs == null) {
               LOGGER.trace("GTM DBCPool startup");
               dbs = (DataSource) ctxt.lookup("java:comp/env/jdbc/gtmdb");
               LOGGER.trace("Set dbs as " + dbs.toString());
            }
            if (oaccDS == null) {
               LOGGER.trace("OACC DBCPool startup");
               oaccDS = (DataSource) ctxt.lookup("java:comp/env/jdbc/oaccdb");
            }
            return true;
         } catch (Exception e) {
            LOGGER.catching(e);
            return false;
         }
      }
   }

   public static Connection getConnection() throws SQLException {
      if (dbs == null) {
         LOGGER.debug("Had to start DBCPool in getConnection.");
      }
      return dbs.getConnection();
   }

我现在添加了一些日志记录,以便了解错误,稍后将删除该错误。

在contextInitialized上调用startup(),因此在应用程序运行时设置DBCPool。

作为整合测试,我写道:

 @Test
   public void getConnectionShouldReturnConnection() throws SQLException {
      DBCPool.startup();
      assertEquals(true, DBCPool.getConnection() != null);
   }

DBCPool.startup()对于测试来说是不必要的,但在这里有帮助,因为它将基础异常带入了cli中的日志。

然后我使用cargo maven插件将其部署到tomcat 8实例并且可以进行集成测试。 这是pom.xml片段:

<profile>
            <id>run-its</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>failsafe-it</id>
                                <phase>integration-test</phase>
                                <goals>
                                    <goal>integration-test</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>failsafe-verify</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.codehaus.cargo</groupId>
                        <artifactId>cargo-maven2-plugin</artifactId>
                        <version>1.5.0</version>
                        <configuration>
                            <container>
                                <containerId>tomcat8x</containerId>
                            </container>
                            <configuration>
                                <home>${project.build.directory}/catalina-base</home>
                            </configuration>
                        </configuration>
                        <executions>
                            <execution>
                                <id>start-server</id>
                                <phase>pre-integration-test</phase>
                                <goals>
                                    <goal>start</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>stop-server</id>
                                <phase>post-integration-test</phase>
                                <goals>
                                    <goal>stop</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

启动tomcat并部署应用程序。 然后甚至设置了DBCPool,并且在记录数据源的toString()时我没有得到NullPointerException。这是启动日志,log4j部分被删除,因为它太长了。

[INFO] --- cargo-maven2-plugin:1.5.0:start (start-server) @ gtm ---
[INFO] [2.ContainerStartMojo] Resolved container artifact org.codehaus.cargo:cargo-core-container-tomcat:jar:1.5.0 for container tomcat8x
[INFO] You did not specify a container home nor any installer. CARGO will automatically download your container's binaries from [http://repo1.maven.org/maven2/org/apache/tomcat/tomcat/8.0.35/tomcat-8.0.35.zip].
[INFO] [talledLocalContainer] Tomcat 8.x starting...
[INFO] [stalledLocalDeployer] Deploying [C:\Users\timki\git\gtm-code\gtm\target\gtm.war] to [C:\Users\timki\git\gtm-code\gtm\target/catalina-base/webapps]...
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:35 AM org.apache.catalina.startup.VersionLoggerListener log
[...]
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:35 AM org.apache.catalina.startup.HostConfig deployWAR
[INFO] [talledLocalContainer] INFORMATION: Deploying web application archive C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\gtm.war
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = oaccdb Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "50" for "maxActive" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = oaccdb Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "5000" for "maxWait" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = gtmLog Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "30" for "maxActive" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = gtmLog Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "5000" for "maxWait" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = gtmdb Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "50" for "maxActive" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
[WARNING] [talledLocalContainer] WARNUNG: Name = gtmdb Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "5000" for "maxWait" property, which is being ignored.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:36 AM org.apache.jasper.servlet.TldScanner scanJars
[INFO] [talledLocalContainer] INFORMATION: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,164 localhost-startStop-1 DEBUG Initializing configuration XmlConfiguration[location=C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\gtm\WEB-INF\classes\log4j2.xml]
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,171 localhost-startStop-1 DEBUG Installed script engines
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,440 localhost-startStop-1 DEBUG Oracle Nashorn Version: 1.8.0_73, Language: ECMAScript, Threading: Not Thread Safe, Compile: true, Names: {nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript}
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,441 localhost-startStop-1 DEBUG PluginManager 'Core' found 99 plugins
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,441 localhost-startStop-1 DEBUG PluginManager 'Level' found 0 plugins
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,445 localhost-startStop-1 DEBUG No scheduled items
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,445 localhost-startStop-1 DEBUG PluginManager 'Lookup' found 13 plugins
[INFO] [talledLocalContainer] 2016-07-17 10:07:37,447 localhost-startStop-1 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
[...]
[INFO] [talledLocalContainer] 10:07:37.558 [localhost-startStop-1] INFO   - GTM servlet context initialized
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] DEBUG  - Initial context is: java:
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - GTM DBCPool startup
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - Set dbs as org.apache.tomcat.dbcp.dbcp2.BasicDataSource@79270e48
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - OACC DBCPool startup
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:37 AM com.sun.jersey.api.core.PackagesResourceConfig init
[INFO] [talledLocalContainer] INFORMATION: Scanning for root resource and provider classes in the packages:
[INFO] [talledLocalContainer]   de.osg.gtm.web
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:37 AM com.sun.jersey.api.core.ScanningResourceConfig logClasses
[INFO] [talledLocalContainer] INFORMATION: Root resource classes found:
[INFO] [talledLocalContainer]   class de.osg.gtm.web.FrontendService
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:37 AM com.sun.jersey.api.core.ScanningResourceConfig init
[INFO] [talledLocalContainer] INFORMATION: No provider classes found.
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:37 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
[INFO] [talledLocalContainer] INFORMATION: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.HostConfig deployWAR
[INFO] [talledLocalContainer] INFORMATION: Deployment of web application archive C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\gtm.war has finished in 2,448 ms
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.HostConfig deployDirectory
[INFO] [talledLocalContainer] INFORMATION: Deploying web application directory C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\host-manager
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.HostConfig deployDirectory
[INFO] [talledLocalContainer] INFORMATION: Deployment of web application directory C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\host-manager has finished in 31 ms
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.HostConfig deployDirectory
[INFO] [talledLocalContainer] INFORMATION: Deploying web application directory C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\manager
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.HostConfig deployDirectory
[INFO] [talledLocalContainer] INFORMATION: Deployment of web application directory C:\Users\timki\git\gtm-code\gtm\target\catalina-base\webapps\manager has finished in 24 ms
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.coyote.AbstractProtocol start
[INFO] [talledLocalContainer] INFORMATION: Starting ProtocolHandler ["http-nio-8080"]
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.coyote.AbstractProtocol start
[INFO] [talledLocalContainer] INFORMATION: Starting ProtocolHandler ["ajp-nio-8009"]
[INFO] [talledLocalContainer] Jul 17, 2016 10:07:38 AM org.apache.catalina.startup.Catalina start
[INFO] [talledLocalContainer] INFORMATION: Server startup in 2821 ms
[INFO] [talledLocalContainer] Tomcat 8.x started on port [8080]
[INFO] 
[INFO] --- maven-failsafe-plugin:2.19.1:integration-test (failsafe-it) @ gtm ---
[INFO] Failsafe report directory: C:\Users\timki\git\gtm-code\gtm\target\failsafe-reports

-------------------------------------------------------
 T E S T S

中可以看出
[INFO] [talledLocalContainer] 10:07:37.558 [localhost-startStop-1] INFO   - GTM servlet context initialized
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] DEBUG  - Initial context is: java:
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - GTM DBCPool startup
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - Set dbs as org.apache.tomcat.dbcp.dbcp2.BasicDataSource@79270e48
[INFO] [talledLocalContainer] 10:07:37.565 [localhost-startStop-1] TRACE  - OACC DBCPool startup

我从查找中获得了initialContext甚至数据源。 但是,在测试中:

10:07:39.631 [main] ERROR  - Catching
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662) ~[?:1.8.0_73]
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313) ~[?:1.8.0_73]
    at javax.naming.InitialContext.getNameInNamespace(InitialContext.java:563) ~[?:1.8.0_73]
    at de.osg.gtm.management.DBCPool.startup(DBCPool.java:34) [classes/:?]
    at de.osg.gtm.management.DBCPoolIT.getConnectionShouldReturnConnection(DBCPoolIT.java:13) [test-classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_73]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_73]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_73]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_73]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) [junit-4.8.2.jar:?]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) [junit-4.8.2.jar:?]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) [junit-4.8.2.jar:?]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) [junit-4.8.2.jar:?]
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) [junit-4.8.2.jar:?]
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) [junit-4.8.2.jar:?]
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) [junit-4.8.2.jar:?]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236) [junit-4.8.2.jar:?]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) [surefire-junit4-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) [surefire-junit4-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) [surefire-junit4-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) [surefire-junit4-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) [surefire-booter-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) [surefire-booter-2.19.1.jar:2.19.1]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) [surefire-booter-2.19.1.jar:2.19.1]
10:07:39.637 [main] DEBUG  - Had to start DBCPool in getConnection.
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.684 sec <<< FAILURE! - in de.osg.gtm.management.DBCPoolIT
getConnectionShouldReturnConnection(de.osg.gtm.management.DBCPoolIT)  Time elapsed: 0.656 sec  <<< ERROR!
java.lang.NullPointerException
    at de.osg.gtm.management.DBCPoolIT.getConnectionShouldReturnConnection(DBCPoolIT.java:14)

就是这样。我设置了DBCPool,但是在测试dbs(databasesource,DBCPool实例)时再次为null并且无法检索initialContext。

我想我在配置故障安全方面做错了,因此它不会测试已部署的应用程序,因此不会获得上下文。但无论我研究了多少例子和教程,我都找不到我的错误。 我和maven tomcat插件有同样的错误,并希望用货物maven插件解决它,但没有。

提前感谢您的帮助。 RMG

1 个答案:

答案 0 :(得分:0)

您是否考虑过maven生命周期以及cargo-maven2-plugin何时开始工作?也许应用程序将在集成测试后部署。

如果生命周期如下:

Maven: clean > test > it-test > install > deploy

您的it-suite将在没有必要的tomcat容器的情况下运行。并且有充分的理由失败。

也许您将个人资料run-its拆分为:

  1. 使用货物部署应用程序(不包括其中)
  2. 运行其(排除部署)
  3. 这种方法可以确保正在运行的tomcat容器。