Cargo Maven Tomcat NoInitialContextException Когда я уже получил контекст

Я использую плагин Cargo Maven для развертывания моего.war на экземпляр Tomcat 8 для тестирования интеграции. Приложение представляет собой веб-интерфейс REST на основе джерси. Моя проблема появляется в базовом пуле соединений с базой данных. В интеграционном тесте существует исключение NoInitialContextException, ведущее к исключению NullPointerexception.

Я строю 2 пула (один для приложения и один для 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();
   }

Сейчас есть некоторые записи, которые я добавил, чтобы понять ошибку, которая будет удалена позже.

Функция startup() вызывается для contextInitialized, поэтому 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 настроен, и я не получаю NullPointerException при регистрации toString() источника данных. Это журнал запуска, часть 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

Я получил исходныйКонтекст и даже источник данных из поиска. Но тогда, в тестировании:

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 (источник данных, экземпляр DBCPool) снова становится нулевым, и initialContext не может быть получен.

Я думаю, что я сделал что-то не так в настройке отказоустойчивого, чтобы он не проверял развернутое приложение и, следовательно, не получал контекст. Но я не нахожу свою ошибку, независимо от того, сколько примеров и учебных пособий я изучаю. У меня была та же ошибка с плагином maven tomcat, и я надеялся решить ее с плагином Cargo Maven, но нет.

Заранее благодарю за любую помощь. RMG

1 ответ

Задумывались ли вы о жизненном цикле maven и когда плагин cargo-maven2 начинает работать? Возможно, приложение будет развернуто после интеграционных тестов.

Если жизненный цикл будет выглядеть так:

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

Ваш it-suite будет работать без необходимого контейнера кота. И терпеть неудачу по уважительным причинам.

Может быть, вы разделили свой профиль run-its в:

  1. развернуть приложение с грузом (исключить его)
  2. запустить его (исключить развертывание)

Такой подход обеспечит бесперебойную работу контейнера Tomcat.

Другие вопросы по тегам