How to run cucumber + springboot application using Gradle in Eclipse - java

I have a demo springboot application and trying to run the cucumber test cases using gradle .. In maven Its working fine but unable to run using gradle.
Can you please help me with the way to execute the gradle file either from eclipse or from command line
Below is mt build.gradle file
testImplementation 'io.cucumber:cucumber-junit:5.3.0'
testImplementation 'io.cucumber:cucumber-core:5.3.0'
testImplementation 'io.cucumber:cucumber-spring:5.3.0'
testImplementation 'io.cucumber:cucumber-java:5.3.0'
testImplementation 'javax.xml.bind:jaxb-api:2.2.8'
testImplementation 'org.mockito:mockito-core:1.9.5'
testImplementation 'junit:junit:4.12'
testImplementation('org.springframework.boot:spring-boot-starter-test'){
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation ('org.springframework.boot:spring-boot-starter-actuator'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-log4j2'
}
test{
testLogging.showStandardStreams = true
}
sourceSets {
main.java.srcDir "src/main/java"
main.resources.srcDir "src/main/resources"
test.java.srcDir "src/test/java/com/b**/f**/w**/tests"
test.resources.srcDir "src/test/resources"
}
configurations {
cucumberRuntime {
extendsFrom testImplementation
}
}
task cucumber() {
dependsOn assemble, compileTestJava , testClasses
doLast {
javaexec {
main = "cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', '--glue', 'com.b**.f**.w**.tests', 'src/test/resources']
}
}
}
}
And below is the error when i execute in command line using "Gradle cucumber"
> Task :cucumber FAILED
Feb 27, 2020 9:53:29 AM cucumber.api.cli.Main run
WARNING: You are using deprecated Main class. Please use io.cucumber.core.cli.Main
Feb 27, 2020 9:53:29 AM io.cucumber.core.cli.Main run
WARNING: By default Cucumber is running in --non-strict mode.
This default will change to --strict and --non-strict will be removed.
You can use --strict to suppress this warning
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/alekhya.machiraju/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-slf4j-impl/2.12.1/14973e22497adaf0196d481fb99c5dc2a0b58d41/log4j-slf4j-impl-2.12.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/alekhya.machiraju/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-log4j12/1.7.30/c21f55139d8141d2231214fb1feaf50a1edca95e/slf4j-log4j12-1.7.30.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/alekhya.machiraju/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.2.3/7c4f3c474fb2c041d8028740440937705ebb473a/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Feb 27, 2020 9:53:30 AM io.cucumber.core.runtime.Runtime run
SEVERE: Exception while executing pickle
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at io.cucumber.core.runtime.Runtime.run(Runtime.java:108)
at io.cucumber.core.cli.Main.run(Main.java:75)
at cucumber.api.cli.Main.run(Main.java:28)
at cucumber.api.cli.Main.main(Main.java:15)
Caused by: java.lang.NullPointerException
at io.cucumber.spring.SpringFactory.stop(SpringFactory.java:171)
at io.cucumber.core.runner.Runner.disposeBackendWorlds(Runner.java:173)
at io.cucumber.core.runner.Runner.runPickle(Runner.java:69)
at io.cucumber.core.runtime.Runtime.lambda$run$2(Runtime.java:100)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at io.cucumber.core.runtime.Runtime$SameThreadExecutorService.execute(Runtime.java:243)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at io.cucumber.core.runtime.Runtime.lambda$run$3(Runtime.java:100)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.SliceOps$1$1.accept(SliceOps.java:204)
at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1359)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at io.cucumber.core.runtime.Runtime.run(Runtime.java:101)
... 3 more
Feb 27, 2020 9:53:30 AM io.cucumber.core.runtime.Runtime run
SEVERE: Exception while executing pickle
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at io.cucumber.core.runtime.Runtime.run(Runtime.java:108)
at io.cucumber.core.cli.Main.run(Main.java:75)
at cucumber.api.cli.Main.run(Main.java:28)
at cucumber.api.cli.Main.main(Main.java:15)
Caused by: java.lang.NullPointerException
at io.cucumber.spring.SpringFactory.stop(SpringFactory.java:171)
at io.cucumber.core.runner.Runner.disposeBackendWorlds(Runner.java:173)
at io.cucumber.core.runner.Runner.runPickle(Runner.java:69)
at io.cucumber.core.runtime.Runtime.lambda$run$2(Runtime.java:100)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at io.cucumber.core.runtime.Runtime$SameThreadExecutorService.execute(Runtime.java:243)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at io.cucumber.core.runtime.Runtime.lambda$run$3(Runtime.java:100)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.SliceOps$1$1.accept(SliceOps.java:204)
at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1359)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at io.cucumber.core.runtime.Runtime.run(Runtime.java:101)
... 3 more
Exception in thread "main" io.cucumber.core.exception.CompositeCucumberException: There were 2 exceptions:
java.lang.NullPointerException(null)
java.lang.NullPointerException(null)
at io.cucumber.core.runtime.Runtime.run(Runtime.java:120)
at io.cucumber.core.cli.Main.run(Main.java:75)
at cucumber.api.cli.Main.run(Main.java:28)
at cucumber.api.cli.Main.main(Main.java:15)
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\alekhya.machiraju\eclipse-workspace\bProjet name\build.gradle' line: 133
* What went wrong:
Execution failed for task ':cucumber'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_241\bin\java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2.1/userguide/command_line_interface.html#sec:command_line_warnings
My Folder stricuture is as below
src/test/java
---- com.b**.f**.w**.tests
----------------Cucumberrunnertest.java
----------------Stepdefinition.java
src/test/reaources
----------------cucumber.feature

I had a similar problem as you, but Gradle wouldn't run my Junit 5 + Cucumber tests. It seams like Cucumber doesn't have any Junit 5 support, so I had to revert back to Junit 4 (also known as Junit 5 vintage).
My trick was to enable legacy Junit-support in my build.gradle.
test {
// Use old (Junit 4) runner since Cucumber doesn't support Junit 5 *sigh*
useJUnit()
// useJUnitPlatform()
}
The reset of my code/setup:
build.gradle
plugins {
id 'org.springframework.boot' version '2.2.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'se.snorbu.cucumber'
version = '0.0.1-SNAPSHOT'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// Spring
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
// Cucumber
testCompile 'io.cucumber:cucumber-java:6.6.0'
testCompile 'io.cucumber:cucumber-junit:6.6.0'
testCompile 'io.cucumber:cucumber-spring:6.6.0'
testCompile 'io.cucumber:cucumber-junit-platform-engine:6.6.0'
// Misc
testCompileOnly 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'
// Junit5
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
// Use old (Junit 4) runner since Cucumber doesn't support Junit 5 *sigh*
useJUnit()
}
The Cucumber-runner/-context
package com.example.webapp;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.spring.CucumberContextConfiguration;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
#CucumberContextConfiguration
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "junit:build/cucumber-junit.xml", "html:build/cucumber.html"},
features = "classpath:/"
)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
#AutoConfigureMockMvc
public class ContextConfiguration {
}
My stepdef
package com.example.webapp.steps;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.junit.platform.engine.Cucumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import se.snorbu.cucumber.webapp.PizzaClient;
import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#Slf4j
#Cucumber
public class OrderPizzaSteps {
#Autowired
private MockMvc mockMvc;
private ResultActions mvcResult;
#Given("A pizza")
public void givenAPizza() {
// Do setup
}
#When("I order a pizza")
public void whenOrderAPizza() throws Exception {
// Do something
mvcResult = mockMvc.perform(
post("/order")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"pizza\": \"pepperoni\"}")
);
}
#Then("I should receive an order-id")
public void thenShouldReceiveOrderid() throws Exception {
// Do assertion
mvcResult
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("id", is("A12")));
}
}

Related

Spring boot Data JPA task :test Failed

I'm starting to use Data JPA from Spring to interact with Postgres Database, but when I try to build the project, the building phase raise an exception in the applicationTest.
This is my build.gradle:
plugins {
id 'org.springframework.boot' version '2.5.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'eu.universome.radio'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
//implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
If I comment the dependencies:
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' the build will be successful.
This is my empty applicationTest:
package eu.universome.radio.RadioUVMServer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class RadioUvmServerApplicationTests {
#Test
void contextLoads() {
}
}
Here there is the Console Error:
Gradle Distribution: Gradle wrapper from target build
Gradle Version: 7.1.1
Java Home: /usr/lib/jvm/java-11-openjdk-amd64
JVM Arguments: None
Program Arguments: None
Build Scans Enabled: false
Offline Mode Enabled: false
Gradle Tasks: build
> Task :compileJava
> Task :processResources UP-TO-DATE
> Task :classes
> Task :bootJarMainClassName
> Task :bootJar
> Task :jar UP-TO-DATE
> Task :assemble
> Task :compileTestJava
> Task :processTestResources UP-TO-DATE
> Task :testClasses
> Task :test FAILED
RadioUvmServerApplicationTests > contextLoads() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
Caused by: java.lang.IllegalStateException at Assert.java:97
1 test completed, 1 failed
Here you can find the report:
[1]: https://www.universome.eu/wp-content/uploads/RadioUVM/progetto-radio-unime/reports/tests/test/classes/eu.universome.radio.RadioUVMServer.RadioUvmServerApplicationTests.html
Not sure if you have the dependency added.
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.23'
You can check if the driver is on classpath:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
// recheck dependencies
}
Solved adding the line
runtimeOnly 'org.postgresql:postgresql'
on build.gradle file in section dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
//implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: org.apache.catalina.LifecycleException

I encountered this error when I tried to deployed war in tomcat with spring boot 2.1.2.My tomcat version is 8.5.14 and java is 1.8.0_121.I think i had done everything right and its working perfectly in my machine but its not working when i deploy it on server with below error.
08-May-2019 05:54:33.459 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.14
08-May-2019 05:54:33.462 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /opt/apache-tomcat/webappsloop/LoopServer.war
08-May-2019 05:54:33.665 WARNING [localhost-startStop-1] org.apache.tomcat.util.descriptor.web.WebXml.setVersion Unknown version string [4.0]. Default version will be used.
08-May-2019 05:54:38.037 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars 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.
08-May-2019 05:54:38.041 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/opt/apache-tomcat/webappsloop/LoopServer/WEB-INF/lib/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/opt/apache-tomcat/webappsloop/LoopServer/WEB-INF/lib/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
08-May-2019 05:54:38.231 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Loop].StandardHost[localhost].StandardContext[/LoopServer]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Cannot instantiate interface org.springframework.boot.SpringApplicationRunListener : org.springframework.boot.context.event.EventPublishingRunListener
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:450)
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:429)
at org.springframework.boot.SpringApplication.getRunListeners(SpringApplication.java:415)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:301)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 10 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.event.EventPublishingRunListener]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object;
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184)
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:446)
... 19 more
Caused by: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object;
at org.springframework.context.event.AbstractApplicationEventMulticaster.addApplicationListener(AbstractApplicationEventMulticaster.java:109)
at org.springframework.boot.context.event.EventPublishingRunListener.<init>(EventPublishingRunListener.java:58)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
... 20 more
08-May-2019 05:54:38.232 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /opt/apache-tomcat/webappsloop/LoopServer.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Loop].StandardHost[localhost].StandardContext[/LoopServer]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:756)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
08-May-2019 05:54:38.232 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/apache-tomcat/webappsloop/LoopServer.war has finished in 4,770 ms
Below is my build.gradle config
group 'com.lss.loopserver'
version '1.0-SNAPSHOT'
buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
war {
baseName = 'LoopServer'
version = '0.0.1'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
maven { url "http://repo.spring.io/libs-snapshot" }
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile 'org.springframework.boot:spring-boot-starter-aop'
compile('org.springframework.boot:spring-boot-starter-web')
compile('javax.inject:javax.inject:1')
compile ('mysql:mysql-connector-java:6.0.6')
compile ('com.google.code.gson:gson:2.8.1')
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3'
compile 'org.apache.commons:commons-io:1.3.2'
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Greenwich.RC2"
}
}
bootRun {
sourceResources sourceSets.main
}
The Application class with main function as below.
#SpringBootApplication
public class Main extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
NoSuchMethodError error, the most likely is the problem of the introduction of the jar package, or the jar package conflict.
You can look at the tree structure of the jar package through maven and see the dependencies after the jar package. If it is true that the jar package is missing, import the jar package, for example, Caused by: java.lang.NoSuchMethodError: org.springframework.aop.xxxxx.xxxxx. I will first look for the jar package that the project depends on. There is no such jar package exists, and then there is no such class, the method.
If not, you can add dependencies via the pom (maven configuration file) file. If this class exists, it is likely that the jar package conflicts.
For a jar package conflict, let's take a very simple example. If you reference the A.jar package and the B.jar package, both A and B depend on the C.jar package. However, A depends on the 1.1 version of the C.jar package, and B depends on the 2.1 version of the jar package. If your project is stored in version 1.1 at this time, it is very likely that an error will be reported.
Seems there is a dependency exclusion you should do ,
For Gradle (but not sure):
dependencies {
implementation('org.springframework.boot:spring-boot-starter-security:version) {
exclude group: 'org.springframework', module: 'spring-aop'
}
}
Maven way :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId></artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
</exclusions>
</dependency>
Refer the dependency sections of spring boot repos , seems to be transitive dependency issue https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop/2.1.2.RELEASE
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security/2.1.2.RELEASE
Also for the Tomcat part
dependencies {
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
providedRuntime group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: "2.1.2.RELEASE"
}

Spring Boot and Logging

I have Spring Boot application with slf4j logging.
Gradle:
buildscript {
ext {
springBootVersion = '2.0.0.BUILD-SNAPSHOT'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
dependencies {
compile fileTree(dir: 'lib', include: '*.jar')
compile group: 'com.google.guava', name: 'guava', version: '17.0'
// Spring
compile 'org.springframework.boot:spring-boot-starter-web:1.5.1.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '1.5.1.RELEASE'
// Spring Security
compile 'org.springframework.boot:spring-boot-starter-security'
// Template engine
compile 'org.springframework.boot:spring-boot-starter-thymeleaf:1.5.1.RELEASE'
compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity3:2.1.2.RELEASE'
compile group: 'org.thymeleaf', name: 'thymeleaf-spring5', version: '3.0.3.M1'
// DB and ORM
compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.5.1.RELEASE'
compile 'org.apache.derby:derby:10.13.1.1'
// Form validation
compile 'org.hibernate:hibernate-validator:5.2.2.Final'
compile 'javax.el:el-api:2.2'
// SNMP
compile 'org.snmp4j:snmp4j:1.10.1'
compile 'org.snmp4j:snmp4j-agent:1.2'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Class:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
.....
#SpringBootApplication
public class MyApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(MyApplication.class);
public static void main(String[] args) {
SpringApplication.run(new Class<?>[] {MyApplication.class}, args);
.....
It worked before. Now I have exception where I create Logger. I didn't change anything, only tried to build project again. Maybe Spring Boot version was changed, I don't know.
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at by.virkom.MyApplication.<clinit>(MyApplication.java:18)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I tried to exclude spring-boot-starter-logging and connect
spring-boot-starter-log4j but it not worked for me. Then ClassNotFoundException with Log4j. How can I fix it?
P.S.: When I commented creating logger, I have another exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
at by.virkom.MyApplication.main(MyApplication.java:22)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
add this to your gradle file:
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.5'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.5'
compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.5'
You have to add an implementation of slf4j Logger like logback
Add the following to your gradle build
compile 'ch.qos.logback:logback-classic:1.1.7'
You have two options:
If your app is a webapp, add spring-boot-starter-web as a dependency and all logging dependencies will be added.
If your app is no webapp, add spring-boot-starter-logging as a dependency.
Source: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html

persistence.xml not found - Gradle-Spring-MVC Project with NoSql Database

I am creating an annotation driven Spring MVC application using Intellij 2016 and Gradle. My project structure looks like this:
I deliberately copied the persistence.xml into the folder src/main/java/META-INF/persistence.xml and src/main/resources/META-INF/persistence.xml, but when executing the Gradle bootRun task, I get the following error:
11:18:40: Executing external task 'bootRun'...
:compileJava
:processResources
:classes
:findMainClass
:bootRun
11:18:52.960 [main] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named ogm-jpa-tutorial
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at my.app.main.Application.main(Application.java:27)
:bootRun FAILED
It seems that the bootRun tasks is not able to pick up the persistence.xml from the classpath.
Does anyone know whats behind that error and has a fix?
EDIT for javaguy, missing init of EntityManager:
/*
Content of the class my.app.main.Application
*/
package my.app.main;
import my.app.controllers.GreetingController;
import my.app.model.Greeting;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.TransactionManager;
#SpringBootApplication
#ComponentScan({"my.app.*"})
public class Application {
private static final Log logger = LoggerFactory.make();
public static void main(String[] args) {
TransactionManager tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ogm-jpa-tutorial");
SpringApplication.run(Application.class, args);
}
}
EDIT for Asterisk Ninja missing persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="ogm-jpa-tutorial" transaction-type="JTA">
<!-- Use the Hibernate OGM provider: configuration will be transparent -->
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<!-- Here you will pick which NoSQL technology to use, and configure it;
in this example we start a local in-memory Infinispan node. -->
<property name="hibernate.ogm.datastore.provider" value="infinispan"/>
</properties>
</persistence-unit>
</persistence>
EDIT, missing build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'gs-serving-web-content'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-devtools")
compile("org.hibernate.ogm:hibernate-ogm-bom:5.0.2.Final")
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.0.Final'
compile group: 'javax.transaction', name: 'jta', version: '1.1'
compile group: 'org.jboss.narayana.jta', name: 'narayana-jta', version: '5.3.5.Final'
compile group: 'org.hibernate', name: 'hibernate-annotations', version: '3.5.6-Final'
testCompile("junit:junit")
}
I solved my problem by adapting the build.gradle file in the following fashion:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'gs-serving-web-content'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-devtools")
compile("org.hibernate.ogm:hibernate-ogm-bom:5.0.2.Final")
compile group: 'org.hibernate.ogm', name: 'hibernate-ogm-infinispan', version: '5.0.2.Final'
compile group: 'org.jboss.spec.javax.transaction', name: 'jboss-transaction-api_1.2_spec', version: '1.0.0.Final'
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.0.Final'
compile group: 'org.jboss.narayana.jta', name: 'narayana-jta', version: '5.3.5.Final'
compile group: 'org.jboss', name: 'jboss-transaction-spi', version: '7.5.0.Final'
compile group: 'javax.transaction', name: 'jta', version: '1.1'
compile group: 'org.hibernate.common', name: 'hibernate-commons-annotations', version: '5.0.1.Final'
testCompile("junit:junit")
}
Comment on that:
It seems that the persistence.xml was picked up correctly, but the
EntitiyManager could not initialize the <provider>HibernateOgmPersistence correctly
therefore the following changes were done:
added some dependencies for the EntitiyManager specific for the
MongoDB in-memory instance

how to properly configure gradle build to avoid including log4j and slf4j from the resulting jar?

I'm having an issue with my spring-boot application: I'm able to run it within Eclipse, but unable to run the jar file (built with gradle).
I run the following command to build my project:
gradle buid
The build is successful:
gradle build
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:findMainClass
:jar
:bootRepackage
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build
BUILD SUCCESSFUL
Total time: 1.214 secs
This is a fragment of the resulting jar file:
jar -tvf build/libs/springboot-receiver-api-0.1.0.jar | grep log
9988 Mon Apr 04 20:37:48 CDT 2016 BOOT-INF/lib/slf4j-log4j12-1.7.21.jar
2308 Wed Sep 21 07:11:50 CDT 2016 BOOT-INF/lib/spring-boot-starter-logging-1.4.1.RELEASE.jar
66802 Thu May 28 09:49:34 CDT 2015 BOOT-INF/lib/jboss-logging-3.3.0.Final.jar
304075 Tue Mar 29 22:24:50 CDT 2016 BOOT-INF/lib/logback-classic-1.1.7.jar
23646 Mon Apr 04 20:39:02 CDT 2016 BOOT-INF/lib/log4j-over-slf4j-1.7.21.jar
470782 Tue Mar 29 22:23:42 CDT 2016 BOOT-INF/lib/logback-core-1.1.7.jar
489884 Sun May 06 13:24:48 CDT 2012 BOOT-INF/lib/log4j-1.2.17.jar
when I attempt to run this jar file, I get this error:
java -jar build/libs/springboot-receiver-api-0.1.0.jar
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/eugene/.Trash/springboot-receiverapi/build/libs/springboot-receiver-api-0.1.0.jar!/BOOT-INF/lib/slf4j-log4j12-1.7.21.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/eugene/.Trash/springboot-receiverapi/build/libs/springboot-receiver-api-0.1.0.jar!/BOOT-INF/lib/logback-classic-1.1.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError.
Exception in thread "main" 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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:58)
Caused by: java.lang.ExceptionInInitializerError
at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:72)
Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
at org.slf4j.impl.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:54)
... 19 more
Here is my build.gradle file:
apply plugin: 'java'
apply plugin: 'maven'
group = 'uptake'
version = '0.0.1-snapshot'
description = """Spring-Boot-ReceiverAPI"""
sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
compile(group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'1.2.3.RELEASE') {
exclude(module: 'log4j-over-slf4j')
}
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version:'1.2.3.RELEASE'
compile group: 'org.postgresql', name: 'postgresql', version:'9.3-1102-jdbc41'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate4', version:'2.8.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version:'2.8.3'
compile group: 'org.apache.kafka', name: 'kafka_2.10', version:'0.9.0.0'
compile group: 'org.springframework.integration', name: 'spring-integration-kafka', version:'2.0.1.RELEASE'
compile group: 'org.apache.zookeeper', name: 'zookeeper', version:'3.4.5'
compile(group: 'commons-beanutils', name: 'commons-beanutils', version:'1.9.2') {
exclude(module: 'commons-logging')
}
compile group: 'org.json', name: 'json', version:'20090211'
compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.5.0'
compile(group: 'org.springframework', name: 'spring-core', version:'4.3.3.RELEASE') {
exclude(module: 'commons-logging')
}
compile group: 'com.spotify', name: 'docker-maven-plugin', version:'0.4.13'
}
configurations.all {
exclude group: "org.slf4j", module: "slf4j-log4j12"
exclude group: "log4j", module: "log4j"
}
What can I do, to avoid this clash of logging libraries, and to be able to run my jar file stand-alone?
Couple things, it seems to me that your build.gradle should declare :
spring boot gradle plugin
apply spring boot plugin
let spring boot manage most of your dependency versions
This script works for me:
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
group = 'uptake'
version = '0.0.1-snapshot'
description = """Spring-Boot-ReceiverAPI"""
sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE'
}
}
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
compile 'org.springframework.boot:spring-boot-starter-logging'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.postgresql:postgresql'
compile 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate4'
compile 'com.fasterxml.jackson.core:jackson-core'
compile 'org.apache.kafka:kafka_2.10:0.9.0.0'
compile 'org.springframework.integration:spring-integration-kafka:2.0.1.RELEASE'
compile 'org.apache.zookeeper:zookeeper:3.4.5'
compile 'commons-beanutils:commons-beanutils'
compile 'org.json:json'
compile 'org.codehaus.jackson:jackson-mapper-asl:1.5.0'
compile 'org.springframework:spring-core'
compile 'com.spotify:docker-maven-plugin:0.4.13'
}
configurations.all {
exclude module: 'slf4j-log4j12'
exclude module: 'jms'
exclude module: 'jmxtools'
exclude module: 'jmxri'
}
Now, if you check both modules with gradle dependencyInsight, only log4j-over-slf4j will be found:
$ gradle dependencyInsight --dependency slf4j-log4j12
$ No dependencies matching given input were found...
$ gradle dependencyInsight --dependency log4j-over-slf4j
:dependencyInsight
org.slf4j:log4j-over-slf4j:1.7.21 (selected by rule)
\--- org.springframework.boot:spring-boot-starter-logging:1.4.1.RELEASE
+--- compile
\--- org.springframework.boot:spring-boot-starter:1.4.1.RELEASE
+--- compile
+--- org.springframework.boot:spring-boot-starter-web:1.4.1.RELEASE
| \--- compile
+--- org.springframework.boot:spring-boot-starter-data-jpa:1.4.1.RELEASE
| \--- compile
+--- org.springframework.boot:spring-boot-starter-aop:1.4.1.RELEASE
| \--- org.springframework.boot:spring-boot-starter-data-jpa:1.4.1.RELEASE (*)
\--- org.springframework.boot:spring-boot-starter-jdbc:1.4.1.RELEASE
\--- org.springframework.boot:spring-boot-starter-data-jpa:1.4.1.RELEASE (*)
I solved this problem updating kafka to a new version.
Some old versions of Kafka had dependecies with jmxtools and jmxri (from log4j < 1.2.16). And this dependecies doesn't have available licences in maven and gradle.
You can resolve this doing one of this three options:
Setting kafka in a major version(2.12 works well!)
Setting log4j in a version upper to 1.2.16
Excluding jmxtools and jmxri
Like I previously said, I resolved this setting the kafka version in my build.gradle:
compile group: 'org.apache.kafka', name: 'kafka_2.12', version: '2.4.0'

Categories

Resources