Package Spring Boot application with Unittests JDBC connections - spring-boot

I'm trying to package a Spring Boot application where there are some unittests. After looking around for the last few days to find an answer I thought maybe I'd get the (probably obvious) answer here.
The command that runs is mvn package
The errors I get are:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections
2017-06-10 12:10:12.156 INFO 9822 --- [main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-06-10 12:10:12.158 WARN 9822 --- [main] o.h.j.i.EntityManagerFactoryRegistry : HHH000436: Entity manager factory name (default) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
2017-06-10 12:10:12.158 INFO 9822 --- [main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-06-10 12:10:12.197 INFO 9822 --- [main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-06-10 12:10:12.223 INFO 9822 --- [main] o.s.ws.soap.saaj.SaajSoapMessageFactory : Creating SAAJ 1.3 MessageFactory with SOAP 1.1 Protocol
2017-06-10 12:10:12.359 INFO 9822 --- [main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
...
Tests in error:
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
SessionServiceTest.setUp:36 » CannotCreateTransaction Could not open JPA Entit...
IBANGeneratorTest.generateIban:50 » DataAccessResourceFailure Unable to acquir...
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 53.643 s
[INFO] Finished at: 2017-06-10T12:10:18+02:00
[INFO] Final Memory: 20M/335M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project bank: There are test failures.
[ERROR]
[ERROR] Please refer to /home/johan/Devel/internetbankieren/bank/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
I would say I have a pretty straightforward setup.
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/bank?useSSL=false
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=bank
spring.datasource.password=************
spring.datasource.max-active=5
OR
spring.datasource.tomcat.max-active
spring.datasource.pool-size=20
OR
spring.datasource.tomcat.pool=20
spring.jpa.database_platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false
spring.datasource.testWhileIdle=true
spring.datasource.timeBetweenEvictionRunsMillis=3600000
spring.datasource.validationQuery=SELECT 1
server.port=8082
Appconfig
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
#Configuration
#ComponentScan({"com.flojo.internetbankieren"})
#PropertySource("classpath:application.properties")
#EnableConfigurationProperties(BankProperties.class)
public class AppConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Unittest
import com.flojo.internetbankieren.config.AppConfig;
import com.flojo.internetbankieren.domain.BankAccount;
import com.flojo.internetbankieren.domain.Customer;
import com.flojo.internetbankieren.domain.Session;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class BankAccountServiceTest {
private BankAccountService bankAccountService;
private SessionService sessionService;
private CustomerService customerService;
private String ip = "123.123.132.123";
#Before
public void setUp() throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
this.customerService = (CustomerService) context.getBean("customerService");
this.sessionService = (SessionService) context.getBean("sessionService");
this.bankAccountService = (BankAccountService) context.getBean("bankAccountService");
}
#Test
public void createAccount() throws Exception {
Customer customer = this.customerService.register("Johan", "Helmond", "1234");
Session session = this.sessionService.startSession(ip, "johanhelmond", "1234");
BankAccount account = this.bankAccountService.createAccount(session);
assertNotNull(account);
assertEquals(1, this.bankAccountService.getCount());
}
}
MySql max_connections
mysql> show variables like "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 151 |
+-----------------+-------+
1 row in set (0,01 sec)
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>com.flojo.internetbankieren</groupId>
<artifactId>bank</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.3.RELEASE</version>
</plugin>
<!-- SOAP Client -->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.13.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaLanguage>WSDL</schemaLanguage>
<generatePackage>com.flojo.internetbankieren.wsdl</generatePackage>
<!--<schemas>-->
<!--<schema>-->
<!--<!– TODO Set the correct URL to the central bank –>-->
<!--<url>http://www.webservicex.com/stockquote.asmx?WSDL</url>-->
<!--</schema>-->
<!--</schemas>-->
</configuration>
</plugin>
<!-- Soap server -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
</plugins>
</build>
</project>
I really hope someone can help me out here.

Related

mvn test command not running tests in a Spring Boot project

This is my pom file
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.ricardo</groupId>
<artifactId>cdh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cdh</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<azure.version>2.2.0</azure.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.1.44</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-core</artifactId>
<version>1.1.44</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.6</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-security-keyvault-secrets</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventhubs</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-spring-boot-bom</artifactId>
<version>${azure.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activatedProperties>local</activatedProperties>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
</profiles>
</project>
When I run mvn test this is the output and none of the test run. However every test work as expected using the IDE Intellij.
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) # cdh ---
[INFO] Deleting /Users/ricardochampa/mypath/target
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 140 source files to /Users/mypath/cdh-back/target/classes
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Some input files use unchecked or unsafe operations.
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Recompile with -Xlint:unchecked for details.
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/mypath/cdh-back/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # cdh ---
[INFO]
[INFO] -------------------------< com.ricardo:cdh >--------------------------
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # cdh ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.484 s
[INFO] Finished at: 2020-09-30T22:18:05+02:00
[INFO] ------------------------------------------------------------------------
UPDATE
I've just try with the following pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
And I tried this as well.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>customWildcardPattern</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
And this...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
And this...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
</plugins>
</build>
None of them works :(
The project structure.
An example of test class: ProductsServiceTest
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class ProductsServiceTest {
#Mock ProductsRepository productsRepository;
#Mock ResourceService resourceService;
#Autowired #InjectMocks ProductsService service;
private ProductsEntity productsEntity = new ProductsEntity();
private final String stubSearchText = "search this text with results";
private final String stubSearchTextNoResults = "search this text without results";
private final String notFoundStubID = "ID NOT EXISTS";
private final String stubID = "id";
private final String stubName = "name";
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
productsEntity.setId(stubID);
productsEntity.setName(stubName);
when(productsRepository.findById(stubID)).thenReturn(Optional.of(productsEntity));
when(productsRepository.findById(notFoundStubID)).thenReturn(Optional.empty());
doNothing().when(resourceService).changeResourceStatus(any(String.class), any(String.class));
List<ProductsEntity> productsEntityList = new ArrayList<>();
productsEntityList.add(productsEntity);
when(productsRepository.searchProducts(stubSearchText)).thenReturn(productsEntityList);
}
#Test
public void whenGetProduct() throws CdhException {
ProductsDto productsDto = service.getProduct(stubID);
assertEquals(productsDto.getId(), stubID);
assertEquals(productsDto.getName(), stubName);
}
#Test
public void whenGetProductNotExist() {
assertThatThrownBy(() -> service.getProduct(notFoundStubID)).isInstanceOf(CdhException.class);
}
#Test
public void whenCreateProduct() {
ProductsDto dto = new ProductsDto();
dto.setId("fake id");
dto.setIdResource("fake id resource");
service.createProduct(dto);
verify(service.productsRepository).save(any(ProductsEntity.class));
}
#Test
public void whenDeleteProduct() throws CdhException {
service.deleteProduct(stubID);
verify(service.productsRepository).save(any(ProductsEntity.class));
}
}
I finally fix it.
My problems was JUnit4, according to docs https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html I should add the plugin like this.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>3.0.0-M5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
1. First potential root cause : Test class naming
Make sure that your test class name matchs one of those default Maven Surefire plugin patterns:
Test*.java
*Test.java
*Tests.java
*TestCase.java
If you need to customize it, you need to add :
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<includes>
<include>TO_BE_REPLACED_BY_YOUR_CUSTOM_WILDCARD_PATTERN</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
###UPDATE####:
2. Second potential root cause that may lead to not executing test is the exclusion part in your spring-boot-starter-test
Replace:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
by:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
maven surefire plugin is missing in your pom.xml.
Be sure to annotate your test methods with #Test:
import org.junit.jupiter.api.Test; // <-- or whatever you are using..
public class SomeTest {
...
#Test // <----
public void testSomething() {
...
}
...
}
The key here is to understand the test engines that Spring uses.
In my case, I coded API tests with #RunWith(SpringRunner.class), which is under JUnit4, which runs with junit-vintage-engine.
But the unit tests are coded with JUnit Jupiter, which is under JUnit5, which runs with junit-jupiter-engine.
The default engine of SpringBoot is the junit-jupiter-engine. So we have to tell to Spring that we also want to use junit-vintage-engine.
We can simply add the dependency in our pom.xml:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
Or, if we want to use maven-surefire, we can add the dependency inside the plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.7.0</version>
</dependency>
</dependencies>
</plugin>

BeanDefinitionStoreException: Failed to parse configuration class ... because it does not exist

atlas-package runs without errors. But I got errors with Quick Reload.
Error is:
JiraRendererPlugin.class] cannot be opened because it does not exist
I imported this interface in java code. No errors while compilation still.
I changed dependency for jira-core in pom.xml. From "provided" to "runtime" => I got out of memory error while compilation. Added memory to maven - doesn't help.
Errors
[INFO] [talledLocalContainer] 2020-06-02 20:17:15,258 QuickReload - Plugin Installer INFO [c.a.plugin.loaders.ScanningPluginLoader] Removed plugin 'com.vladmak.ringcentral.jira-cmp-plgin'
[INFO] [talledLocalContainer] 2020-06-02 20:17:15,314 QuickReload - Plugin Installer INFO [c.a.plugin.util.WaitUntil] Plugins that have yet to be enabled: (1): [com.vladmak.ringcentral.jira-cmp-plgin], 300 seconds remaining
[INFO] [talledLocalContainer] 2020-06-02 20:17:15,337 ThreadPoolAsyncTaskExecutor::Thread 52 ERROR [c.a.p.osgi.factory.OsgiPlugin] Unable to start the plugin container for plugin 'com.vladmak.ringcentral.jira-cmp-plgin'
[INFO] [talledLocalContainer] org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.vladmak.ringcentral.jiracmp.CMRRenderer]; nested exception is java.io.FileNotFoundException: class path resource [com/atlassian/jira/issue/fields/renderer/JiraRendererPlugin.class] cannot be opened because it does not exist
[INFO] [talledLocalContainer] at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:182)
[INFO] [talledLocalContainer] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
[INFO] [talledLocalContainer] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:261)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.invokeBeanFactoryPostProcessors(AbstractDelegatedExecutionApplicationContext.java:444)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.invokeBeanFactoryPostProcessors(AbstractDelegatedExecutionApplicationContext.java:414)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.invokeBeanFactoryPostProcessors(AbstractDelegatedExecutionApplicationContext.java:362)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext$3.run(AbstractDelegatedExecutionApplicationContext.java:254)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.startRefresh(AbstractDelegatedExecutionApplicationContext.java:220)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor.stageOne(DependencyWaiterApplicationContextExecutor.java:224)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor.refresh(DependencyWaiterApplicationContextExecutor.java:177)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.refresh(AbstractDelegatedExecutionApplicationContext.java:157)
[INFO] [talledLocalContainer] at org.eclipse.gemini.blueprint.extender.internal.activator.LifecycleManager$1.run(LifecycleManager.java:207)
[INFO] [talledLocalContainer] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[INFO] [talledLocalContainer] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[INFO] [talledLocalContainer] at java.lang.Thread.run(Thread.java:748)
[INFO] [talledLocalContainer] Caused by: java.io.FileNotFoundException: class path resource [com/atlassian/jira/issue/fields/renderer/JiraRendererPlugin.class] cannot be opened because it does not exist
[INFO] [talledLocalContainer] at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
[INFO] [talledLocalContainer] at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
Class
package com.vladmak.ringcentral.jiracmp;
import com.atlassian.jira.issue.fields.renderer.wiki.AtlassianWikiRenderer;
import com.atlassian.event.api.EventPublisher;
//import com.atlassian.jira.issue.fields.renderer.IssueRenderContext;
//import com.atlassian.jira.plugin.renderer.JiraRendererModuleDescriptor;
import com.atlassian.jira.util.velocity.VelocityRequestContextFactory;
import com.atlassian.jira.config.properties.ApplicationProperties;
import com.atlassian.jira.config.FeatureManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.atlassian.plugin.spring.scanner.annotation.imports.JiraImport;
import com.atlassian.jira.issue.fields.renderer.JiraRendererPlugin;
//import com.atlassian.plugin.spring.scanner.annotation.export.ExportAsService;
//import com.atlassian.jira.issue.fields.renderer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Component
public class CMRRenderer extends AtlassianWikiRenderer implements InitializingBean, DisposableBean {
private static final Logger log = LoggerFactory.getLogger(CMRRenderer.class);
public static final String TYPE = "cmr-renderer";
#JiraImport
private final EventPublisher eventPublisher;
#Autowired
public CMRRenderer(#JiraImport EventPublisher eventPublisher_f,
ApplicationProperties applicationProperties,
VelocityRequestContextFactory velocityRequestContextFactory,
FeatureManager featureManager) {
super(eventPublisher_f, applicationProperties, velocityRequestContextFactory, featureManager);
this.eventPublisher = eventPublisher_f;
}
/**
* Called when the plugin has been enabled.
*
* #throws Exception
*/
#Override
public void afterPropertiesSet() throws Exception {
log.info("[CMP] Enabling plugin");
eventPublisher.register(this);
}
/**
* Called when the plugin is being disabled or removed.
*
* #throws Exception
*/
#Override
public void destroy() throws Exception {
log.info("[CMP] Disabling plugin");
eventPublisher.unregister(this);
}
public String getRendererType() {
return TYPE;
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vladmak.ringcentral</groupId>
<artifactId>jira-cmp-plgin</artifactId>
<version>1.0-SNAPSHOT</version>
<organization>
<name>VLADmak</name>
<url>https://www.linkedin.com/in/vladmak/</url>
</organization>
<name>JIRA CMP Plugin</name>
<description>Add panel with CMRs details</description>
<packaging>atlassian-plugin</packaging>
<dependencies>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-api</artifactId>
<version>${jira.version}</version>
<scope>provided</scope>
</dependency>
<!-- Add dependency on jira-core if you want access to JIRA implementation classes as well as the sanctioned API. -->
<!-- This is not normally recommended, but may be required eg when migrating a plugin originally developed against JIRA 4.x -->
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-core</artifactId>
<version>${jira.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.atlassian.plugin</groupId>
<artifactId>atlassian-spring-scanner-annotation</artifactId>
<version>${atlassian.spring.scanner.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.atlassian.plugin</groupId>
<artifactId>atlassian-spring-scanner-runtime</artifactId>
<version>${atlassian.spring.scanner.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>provided</scope>
</dependency>
<!-- WIRED TEST RUNNER DEPENDENCIES -->
<dependency>
<groupId>com.atlassian.plugins</groupId>
<artifactId>atlassian-plugins-osgi-testrunner</artifactId>
<version>${plugin.testrunner.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2-atlassian-1</version>
</dependency>
<!-- Uncomment to use TestKit in your project. Details at https://bitbucket.org/atlassian/jira-testkit -->
<!-- You can read more about TestKit at https://developer.atlassian.com/display/JIRADEV/Plugin+Tutorial+-+Smarter+integration+testing+with+TestKit -->
<!--
<dependency>
<groupId>com.atlassian.jira.tests</groupId>
<artifactId>jira-testkit-client</artifactId>
<version>${testkit.version}</version>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.atlassian.renderer</groupId>
<artifactId>atlassian-renderer</artifactId>
<version>8.0.9</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.atlassian.maven.plugins</groupId>
<artifactId>jira-maven-plugin</artifactId>
<version>${amps.version}</version>
<extensions>true</extensions>
<configuration>
<productVersion>${jira.version}</productVersion>
<productDataVersion>${jira.version}</productDataVersion>
<!-- Uncomment to install TestKit backdoor in JIRA. -->
<!--
<pluginArtifacts>
<pluginArtifact>
<groupId>com.atlassian.jira.tests</groupId>
<artifactId>jira-testkit-plugin</artifactId>
<version>${testkit.version}</version>
</pluginArtifact>
</pluginArtifacts>
-->
<enableQuickReload>true</enableQuickReload>
<!-- See here for an explanation of default instructions: -->
<!-- https://developer.atlassian.com/docs/advanced-topics/configuration-of-instructions-in-atlassian-plugins -->
<instructions>
<Atlassian-Plugin-Key>${atlassian.plugin.key}</Atlassian-Plugin-Key>
<!-- Add package to export here -->
<Export-Package>com.example.plugins.tutorial.api,</Export-Package>
<!-- Add package import here -->
<Import-Package>org.springframework.osgi.*;resolution:="optional", org.eclipse.gemini.blueprint.*;resolution:="optional", *</Import-Package>
<!-- Ensure plugin is spring powered -->
<Spring-Context>*</Spring-Context>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>com.atlassian.plugin</groupId>
<artifactId>atlassian-spring-scanner-maven-plugin</artifactId>
<version>${atlassian.spring.scanner.version}</version>
<executions>
<execution>
<goals>
<goal>atlassian-spring-scanner</goal>
</goals>
<phase>process-classes</phase>
</execution>
</executions>
<configuration>
<scannedDependencies>
<dependency>
<groupId>com.atlassian.plugin</groupId>
<artifactId>atlassian-spring-scanner-external-jar</artifactId>
</dependency>
</scannedDependencies>
<verbose>false</verbose>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jira.version>7.13.0</jira.version>
<amps.version>8.0.2</amps.version>
<plugin.testrunner.version>2.0.1</plugin.testrunner.version>
<atlassian.spring.scanner.version>1.2.13</atlassian.spring.scanner.version>
<!-- This property ensures consistency between the key in atlassian-plugin.xml and the OSGi bundle's key. -->
<atlassian.plugin.key>${project.groupId}.${project.artifactId}</atlassian.plugin.key>
<!-- TestKit version 6.x for JIRA 6.x -->
<testkit.version>6.3.11</testkit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
This class JiraRendererPlugin is part of
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-api</artifactId>
<version>${jira.version}</version>
<scope>provided</scope>
</dependency>
You are using the correct scope and everything else seems legit.
I suggest to erase your local copy jira-api, v7.13.0
C:\Applications\Atlassian\atlassian-plugin-sdk-8.0.16\repository\com\atlassian\jira\jira-api\7.13.0
After erasing, re run atlas-run or atlas-debug
I am not sure if this would fix it. Just a wild guess.

JavaFx 12 Spring, Maven No plugin found for prefix

I have a problem trying to debug a project with javafx and spring
my 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>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>javafx</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>javafx</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>12</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my main:
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
context = SpringApplication.run(JavafxApplication.class);
FXMLLoader loader = new FXMLLoader(JavafxApplication.class.getResource("/Home.fxml"));
loader.setControllerFactory(context::getBean);
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.show();
}
I have these errors when trying to compile with maven:
[INFO] Scanning for projects... [WARNING] The POM for
org.eclipse.m2e:lifecycle-mapping:jar:1.0.0 is missing, no dependency
information available [WARNING] Failed to retrieve plugin descriptor
for org.eclipse.m2e:lifecycle-mapping:1.0.0: Plugin
org.eclipse.m2e:lifecycle-mapping:1.0.0 or one of its dependencies
could not be resolved: Failure to find
org.eclipse.m2e:lifecycle-mapping:jar:1.0.0 in
https://repo.maven.apache.org/maven2 was cached in the local
repository, resolution will not be reattempted until the update
interval of central has elapsed or updates are forced [INFO]
Downloading from :
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
[INFO] Downloading from :
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
[INFO] Downloaded from :
https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
(14 kB at 9.1 kB/s) [INFO] Downloaded from :
https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
(20 kB at 12 kB/s) [INFO]
------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO]
------------------------------------------------------------------------ [INFO] Total time: 2.867 s [INFO] Finished at:
2019-08-08T01:13:18-03:00 [INFO]
------------------------------------------------------------------------ [ERROR] No plugin found for prefix 'javafx' in the current project and
in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo]
available from the repositories [local
(C:\Users\Gabriel.m2\repository), central
(https://repo.maven.apache.org/maven2)] -> [Help 1] [ERROR] [ERROR]
To see the full stack trace of the errors, re-run Maven with the -e
switch. [ERROR] Re-run Maven using the -X switch to enable full debug
logging. [ERROR] [ERROR] For more information about the errors and
possible solutions, please read the following articles: [ERROR] [Help
1]
http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException
I went to run configurations and make this:
The pom you have posted is missing the javafx-maven-plugin. As documented here: https://openjfx.io/openjfx-docs/#IDE-Eclipse (Maven section), you need to include it in order to deal with the JavaFX dependencies (including them in the module-path, adding the required modules), while keeping the rest of dependencies in the classpath (if your project is non-modular).
And if you want to run the goal javafx:run, as posted in the picture, you do need the plugin that defines this goal.
This works for me (JavaFX + Spring):
POM
<?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>org.openjfx</groupId>
<artifactId>hellofx</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>12</release>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.3</version>
<configuration>
<mainClass>org.openjfx.MainApp</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Main class
package org.openjfx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
#SpringBootApplication
public class MainApp extends Application {
private ConfigurableApplicationContext springContext;
private FXMLLoader fxmlLoader;
#Override
public void init() throws Exception {
springContext = SpringApplication.run(MainApp.class);
fxmlLoader = new FXMLLoader();
fxmlLoader.setControllerFactory(springContext::getBean);
}
#Override
public void start(Stage stage) throws Exception {
fxmlLoader.setLocation(getClass().getResource("scene.fxml"));
Parent root = fxmlLoader.load();
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
stage.setTitle("JavaFX and Maven");
stage.setScene(scene);
stage.show();
}
#Override
public void stop() {
springContext.stop();
}
public static void main(String[] args) {
launch(args);
}
}
FXMLController
package org.openjfx;
import org.springframework.stereotype.Controller;
#Controller
public class FXMLController {
public void initialize() {
// TODO
}
}
Now you can run from the console:
mvn clean javafx:run
or add a goal to Run configurations -> Maven Build: clean javafx:run.
You should see your JavaFX app working, and also the Spring output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2019-08-08 18:29:44.025 INFO 8648 --- [JavaFX-Launcher] o.s.boot.SpringApplication : Starting application on mac.local with PID 8648 (started by user in /path/to/Maven/hellofx)
2019-08-08 18:29:44.028 INFO 8648 --- [JavaFX-Launcher] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default
2019-08-08 18:29:44.524 INFO 8648 --- [JavaFX-Launcher] o.s.boot.SpringApplication : Started application in 0.787 seconds (JVM running for 1.577)

How to make a standalone JPA (with OpenJPA implementation) Maven project start with exec maven plugin?

I have a very simple JPA project. This is my directory layout..
/src
/main
/java
/biz
/tugay
/jpaExamples
App.java
/model
Person.java
/resources
/META-INF
persistence.xml
So it is pretty standard maven directory layout. This is my 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">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.tugay</groupId>
<artifactId>jpa-examples</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>jpa-examples</name>
<url>http://www.tugay.biz</url>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-persistence</artifactId>
<version>2.4.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
</dependencies>
<build>
<finalName>bare-maven-project</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>biz.tugay.jpaExamples.App</mainClass>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
and persistence.xml
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="jpaExamples" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>biz.tugay.jpaExamples.model.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/sampleh2db;TRACE_LEVEL_FILE=0"/>
<property name="javax.persistence.jdbc.user" value="test"/>
<property name="javax.persistence.jdbc.password" value="test"/>
<property name="openjpa.Log" value="DefaultLevel=ERROR, Tool=ERROR"/>
</properties>
</persistence-unit>
Finally, App.java
package biz.tugay.jpaExamples;
import biz.tugay.jpaExamples.model.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.sql.*;
public class App {
private static final String PERSISTENCE_UNIT_NAME = "jpaExamples";
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
public static void main(String[] args) throws ClassNotFoundException, SQLException {
final EntityManager entityManager = ENTITY_MANAGER_FACTORY.createEntityManager();
final Person person = entityManager.find(Person.class, 1L);
System.out.println(person);
entityManager.close();
ENTITY_MANAGER_FACTORY.close();
}
}
When I execute App.java from IntelliJ, all is fine. I will see the output:
Person{id=1, firstname='Koray', lastname='Tugay', address='Yıldız Cd. 43 / 30', city='İstanbul'}
This is what IntelliJ generates, when running main in App.java
"C:\Program Files\Java\jdk1.8.0_121\bin\java" -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_121\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\rt.jar;C:\Users\Koray Tugay\Desktop\jpa-examples\target\classes;C:\Users\Koray Tugay\.m2\repository\org\eclipse\persistence\javax.persistence\2.1.1\javax.persistence-2.1.1.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\openjpa\openjpa\2.4.2\openjpa-2.4.2.jar;C:\Users\Koray Tugay\.m2\repository\commons-lang\commons-lang\2.6\commons-lang-2.6.jar;C:\Users\Koray Tugay\.m2\repository\commons-collections\commons-collections\3.2.2\commons-collections-3.2.2.jar;C:\Users\Koray Tugay\.m2\repository\net\sourceforge\serp\serp\1.15.1\serp-1.15.1.jar;C:\Users\Koray Tugay\.m2\repository\junit\junit\3.8.1\junit-3.8.1.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\geronimo\specs\geronimo-jms_1.1_spec\1.1.1\geronimo-jms_1.1_spec-1.1.1.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\geronimo\specs\geronimo-jta_1.1_spec\1.1.1\geronimo-jta_1.1_spec-1.1.1.jar;C:\Users\Koray Tugay\.m2\repository\commons-pool\commons-pool\1.6\commons-pool-1.6.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\xbean\xbean-asm5-shaded\3.17\xbean-asm5-shaded-3.17.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\geronimo\specs\geronimo-jpa_2.0_spec\1.1\geronimo-jpa_2.0_spec-1.1.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\openjpa\openjpa-persistence\2.4.2\openjpa-persistence-2.4.2.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\openjpa\openjpa-kernel\2.4.2\openjpa-kernel-2.4.2.jar;C:\Users\Koray Tugay\.m2\repository\org\apache\openjpa\openjpa-lib\2.4.2\openjpa-lib-2.4.2.jar;C:\Users\Koray Tugay\.m2\repository\com\h2database\h2\1.4.192\h2-1.4.192.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain biz.tugay.jpaExamples.App
so I am pretty sure everything related to my persistence.xml configuration and dependencies are fine..
When I try mvn exec:java (after mvn clean install) I get:
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:745)
Caused by: <openjpa-2.4.2-r422266:1777108 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "
biz.tugay.jpaExamples.model.Person".
at org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:115)
at org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:311)
at org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:235)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:211)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:154)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at biz.tugay.jpaExamples.App.main(App.java:16)
... 6 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.240 s
[INFO] Finished at: 2017-05-24T22:32:46+03:00
[INFO] Final Memory: 11M/139M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project jpa-examples: An exception occured while executing the Java class. null: InvocationTargetException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "
[ERROR] biz.tugay.jpaExamples.model.Person".
How do I fix this? I think somehow OpenJPA is unable to find persistence.xml, but I can verify that it is found under target/classes.
Adding this to pom.xml worked:
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<includes>**/model/*.class</includes>
<excludes>**/model/XML*.class</excludes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<!-- set the version to be the same as the level in your runtime -->
<version>2.4.2</version>
</dependency>
</dependencies>
</plugin>

Failed when generating report into time stamp folder

Before talking about the issue, I want to explain something first.
I have a basic project with 4 files:
The project contains:
1.testbase01.java: contains information to preparing for initial parameter of testing like: get driver before testing...
2.test01.java: contains some tests and this class extends from testbase01.java
3.test01.xml: contains parameter for test file test01.java
4.pom.xml: contains where to store test report, which xml suite is called for testing, which listener is using...
The flow is:
I use 'mvn test' to run project
Test is run but the report is failed.
It cannot generate report to specified folder as I configured in pom.xml (timestamp).
I found that if I change the report folder to a fixed name (my report for example), it works.
Can you help me to fix this issue?
I dont know where to fix it.
Thank you
The issue is:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
...
... TestNG 6.8.2beta_20130330_0839 by Cédric Beust (cedric#beust.com)
...
LOCAL URL IS http://192.168.10.26:8000/enigma/candidate/index#candidates
NAME= Hoang
[TestNG] Reporter org.uncommons.reportng.JUnitXMLReporter#584534b2 failed
org.uncommons.reportng.ReportNGException: Failed generating JUnit XML report.
at org.uncommons.reportng.JUnitXMLReporter.generateReport(JUnitXMLReporter.java:83)
at org.testng.TestNG.generateReports(TestNG.java:1115)
at org.testng.TestNG.run(TestNG.java:1074)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:217)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:92)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
**Caused by: java.io.FileNotFoundException: D:\WORK\Workspace\bmp\test.reports\20131003-1346\xml\testsample.test01_results.xml (The system cannot find the path specified)**
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileWriter.<init>(FileWriter.java:90)
at org.uncommons.reportng.AbstractReporter.generateFile(AbstractReporter.java:99)
at org.uncommons.reportng.JUnitXMLReporter.generateReport(JUnitXMLReporter.java:77)
... 8 more
[TestNG] Reporter org.uncommons.reportng.HTMLReporter#41ce5a9 failed
org.uncommons.reportng.ReportNGException: Failed generating HTML report.
This is my first test
This is my second test
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 20.441 sec - in TestSuite
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:117)
at org.testng.TestNG.generateReports(TestNG.java:1115)
at org.testng.TestNG.run(TestNG.java:1074)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:217)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:84)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:92)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: java.io.FileNotFoundException: D:\WORK\Workspace\bmp\test.reports\20131003-1346\html\index.html (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileWriter.<init>(FileWriter.java:90)
at org.uncommons.reportng.AbstractReporter.generateFile(AbstractReporter.java:99)
at org.uncommons.reportng.HTMLReporter.createFrameset(HTMLReporter.java:129)
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:104)
... 8 more
1.testbase01.java:
package common;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
public class testbase01{
#Parameters({"localurl"})
#BeforeSuite(alwaysRun = true)
public void beforeSuite(ITestContext context, String localurl){
// get all UI controls
System.out.println("LOCAL URL IS "+localurl);
try
{
//init web driver
WebDriver driver = new FirefoxDriver();
driver.get(localurl);
// add driver into context. This is used for ScreenshotHTMLReporter
context.setAttribute("driver", driver);
}
catch (Exception ex)
{
Assert.assertTrue(false,ex.getMessage());
}
}
}
2.test01.java:
package testsample;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import common.TestBase;
import common.testbase01;
public class test01 extends testbase01 {
#Parameters({"user"})
#Test
public void getUser(String user)
{
System.out.println("NAME= " + user);
}
#Test
public void test01_no01()
{
System.out.println("This is my first test");
}
#Test
public void test01_no02()
{
System.out.println("This is my second test");
}
}
3.test01.xml:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="test01" verbose="3" parallel="false">
<parameter name="localurl" value="http://192.168.10.26:8000/enigma/candidate/index#candidates"/>
<test name="test01">
<parameter name="user" value="Hoang"/>
<classes>
<class name="testsample.test01"/>
</classes>
</test>
</suite>
4.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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BasicMavenProj</groupId>
<artifactId>bmp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyyMMdd-HHmm</maven.build.timestamp.format>
<test.suite.dir>test.suites</test.suite.dir>
<test.report.dir>test.reports</test.report.dir>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.uncommons</groupId>
<artifactId>reportng</artifactId>
<version>1.1.2</version>
<exclusions>
<exclusion>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${test.suite.dir}/test01.xml</suiteXmlFile>
</suiteXmlFiles>
<reportsDirectory>${test.report.dir}/${timestamp}</reportsDirectory>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
<property>
<name>listener</name>
<value>org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>
<!-- <value>com.validant.enigma3.reports.ScreenshotHTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>-->
</property>
</properties>
<systemPropertyVariables>
<test.screenshot.dir>${test.report.dir}/${timestamp}</test.screenshot.dir>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
Did you try using ReportNG with default settings like described in this tutorial?I see some differences in your settings, so make that work for default settings and then you add your own configuration so you will what exactly caused your error.
One note - convention for naming Java classes is Camel Case with first letter in capital.

Resources