Compilation fails using Gradle and Kotlin - compilation

I am going through the examples in Kotlin in Action book. The gradle buid script is as follows:
group 'kotlin-in-action'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.1.2-2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
repositories {
mavenCentral()
}
apply plugin: 'java'
dependencies {
testCompile 'junit:junit:4.12'
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "junit:junit:4.12"
compile 'junit:junit:4.12'
compile 'junit:junit:4.12'
}
sourceSets {
main.kotlin.srcDirs += 'src'
}
All the scripts compile except for two classes that uses junit.
package ch06.ex1_8_1_LateinitializedProperties
import org.junit.Before
import org.junit.Test
import org.junit.Assert
class MyService {
fun performAction(): String = "foo"
}
class MyTest {
private var myService: MyService? = null
#Before fun setUp() {
myService = MyService()
}
#Test fun testAction() {
Assert.assertEquals("foo",
myService!!.performAction())
}
}
The compiler says it can't find junit. I have tried adding the jar files in IntelliJ, but this has not resolved the problem. The jar files I have added are junit and hamscrest-core. This is all version 4.12.

I have resolved this. I had to add the Junit and hamcrest-core jar files from the mavan depository.

Related

gradle integrationTest and testFixtures

I'm using gradle 7.4.2 so I decided to split the tests to proper unit-test and integration-tests. I moved one class from src/test/java/com/example to src/integrationTest/java/com/example, and started to add the missing dependencies.
The problem is that I couldn't find how to use the testFixtures of :project-with-fixture . Is there a way to do that in integrationTest?
I had the following dependencies:
testImplementation project(':other-project')
testImplementation project(':project-with-fixture')
testImplementation testFixtures(project(':project-with-fixture'))
testImplementation project(':common')
testImplementation "com.google.guava:guava:${com_google_guava_version}"
And here's the new part of the build.gradle:
testing {
suites {
integrationTest(JvmTestSuite) {
dependencies {
implementation project
implementation project(':other-project')
implementation project(':project-with-fixture')
// testImplementation testFixtures(project(':project-with-fixture'))
implementation project(':common')
implementation "com.google.guava:guava:${com_google_guava_version}"
}
targets {
all {
testTask.configure {
shouldRunAfter(test)
}
}
}
}
}
}
tasks.named('check') {
dependsOn testing.suites.integrationTest
}
When using the current Gradle version 7.5.1 you can do this:
testing {
suites {
integrationTest(JvmTestSuite) {
dependencies {
implementation(project.dependencies.testFixtures(project(':project-with-fixture')))
...

How to configure spock in spring boot with gradle 6+ and java 11+

I want to use spock in my spring-boot project (using groovy, not java). I have some projects with spock already working in java 8 and lower versions of gradle but I can't find documentation about the newest versions.
This is my OLD build.gradle
buildscript {
ext {
springBootVersion = '2.1.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'groovy'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-mongodb')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.codehaus.groovy:groovy')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testCompile(
'junit:junit:4.12',
'org.codehaus.groovy:groovy-all:2.4.4',
'org.spockframework:spock-core:1.2-groovy-2.4',
'cglib:cglib:2.2',
'org.spockframework:spock-spring:1.2-groovy-2.4',
)
}
this works and I can create spock tests but when I create a project with java 11 and gradle 6.4, nothing works anymore (the gradle syntax is way different and the spock libraries don't work anymore),
this is my CURRENT (and failing) build.gradle:
plugins {
id 'org.springframework.boot' version '2.3.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'groovy'
}
group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.codehaus.groovy:groovy'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'org.postgresql:postgresql'
testImplementation("org.spockframework:spock-core") {
exclude group: "org.codehaus.groovy", module: "groovy-all"
}
testImplementation group: 'org.spockframework', name: 'spock-spring', version: '2.0-M3-groovy-3.0'
testImplementation(enforcedPlatform("org.spockframework:spock-bom:2.0-M1-groovy-2.5"))
}
test {
useJUnitPlatform()
}
With this, nothing works but the gradle build doesn't found the spock-spring libraries.
How can I apply the spock libraries to spring boot with the newest versions of java and gradle?
Think you got into a muddle of Groovy Versions with the dependencies:
I tested with this build:
plugins {
id 'org.springframework.boot' version '2.3.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'groovy'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.codehaus.groovy:groovy:3.0.5'
testImplementation('org.spockframework:spock-core:2.0-M3-groovy-3.0')
testImplementation('org.spockframework:spock-spring:2.0-M3-groovy-3.0')
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
And this test ran and passed:
package test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ApplicationContext
import spock.lang.Specification
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = Application)
class ContextSpec extends Specification {
#Autowired
ApplicationContext context
def "context is as expected"() {
expect:
context
context.getBean("echoService")
}
}
(Obviously, I had an echoService in my context)
For completeness, here's the service:
package test
import org.springframework.stereotype.Service
#Service("echoService")
class EchoService {
String echo(String value) {
value?.reverse()
}
}
The controller:
package test
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
#RestController
class EchoController {
final EchoService echoService
EchoController(EchoService echoService) {
this.echoService = echoService
}
#RequestMapping(
value = "/echo/{message}",
method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE
)
String doEcho(#PathVariable String message) {
return echoService.echo(message)
}
}
And the application class:
package test
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
#SpringBootApplication
class Application {
static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And proof 😉
➜ curl localhost:8080/echo/hello
olleh%

Gradle not creating a Tomcat deployable war

I'm running into an issue with building a war with Gradle 4.8.1. Here is the build.gradle:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
apply plugin: 'idea'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
archivesBaseName = 'sample'
//war {
// archiveName = 'sample.war'
// group = 'my.group'
// version = '2.0.0-SNAPSHOT'
//}
sourceCompatibility = 1.8
repositories {
jcenter()
maven { url "${nexusUrl}/content/groups/public" }
}
dependencies {
// Spring
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-log4j2'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
compile 'org.springframework.boot:spring-boot-starter-web'
testCompile 'org.springframework.boot:spring-boot-starter-test'
// Lombok
compile "org.projectlombok:lombok:1.18.0"
// Data
compile ('org.postgresql:postgresql') {
exclude module: 'slf4j-simple'
}
// Http
compile "org.apache.httpcomponents:httpclient:4.5.5"
}
configurations {
all*.exclude module: 'spring-boot-starter-logging'
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "${nexusUrl}/content/groups/public/") {
authentication(userName: nexusUsername, password: nexusPassword)
}
snapshotRepository(url: "${nexusUrl}/content/repositories/snapshots") {
authentication(userName: nexusUsername, password: nexusPassword)
}
pom.version = '2.0.0-SNAPSHOT'
pom.artifactId = 'sample'
pom.groupId = 'my.group'
}
}
}
I also tried removing the 'maven' plugin, archivesBaseName, and the uploadArchive task while uncommenting the war task and I get the same result. When using uploadArchive the war deploys to the nexus server fine and I get no errors. When deploying the war to tomcat (in both instances) tomcat 7 and 8 throw no errors and I receive no logs from either catalina or the project, although archiveName inside the war task does not properly rename the war. I have tried this on two other machines/tomcat instances with the same result. When building this as a fat jar, or running this in IntelliJ, everything works as expected (including the logging).
Any help or direction would be greatly appreciated.
It sounds like it is not initializing the servlet at all. Make sure to extend the SpringBootServletInitializer for WAR deployment.
Spring Boot Docs - Traditional Deployment
I was also facing the same issue. The issue is Spring application doesnt get initialized when the war is deployed on tomcat.
After a lot of struggle, I figured out that I needed to extend SpringBootServletInitializer in my application. So my effective code looks like
public class SyncApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SyncApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SyncApplication.class, args);
}
}
Looks like this SpringBootServletInitializer directs war plugins generate bootstrapping code while building the war, and thus spring context is initialized while deploying the app.

spring integration RedisLockRegistry with spring-context

We have decided to use RedisLockRegistry by adding spring-integration to my project developed with Spring boot 1.5.7.
But when we add spring-integration-starter and spring-integration-redis to the project, quartz gives an error.
If I change the spring-context with spring-context-support or if I add spring-context-support, it is not an error.
Why should I add spring-context-support instead of spring-context or change it either?
gradle
buildscript {
ext {
springBootVersion = '1.5.7.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
allprojects {
repositories {
mavenCentral()
mavenLocal()
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: "io.spring.dependency-management"
apply plugin: 'maven'
apply plugin: 'idea'
sourceCompatibility = 1.8
idea {
module {
sourceDirs += file('build/classes/main/generated')
generatedSourceDirs += file('build/classes/main/generated')
}
}
dependencies {
compileOnly 'org.projectlombok:lombok'
testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'com.h2database:h2'
testCompile 'org.springframework.security:spring-security-test'
}
}
group = 'com.example.redislock'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
compileJava.dependsOn(processResources)
dependencies {
compile 'org.springframework.boot:spring-boot-starter-aop'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-integration'
compile 'org.quartz-scheduler:quartz:2.3.0'
compile 'org.springframework:spring-core'
//compile 'org.springframework:spring-context'
compile 'org.springframework:spring-context-support'
compile 'org.springframework.integration:spring-integration-redis'
compile 'org.hibernate:hibernate-java8'
compile 'io.springfox:springfox-swagger2:2.6.1'
compile 'io.springfox:springfox-swagger-ui:2.6.1'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.flywaydb:flyway-core:4.2.0'
compileOnly 'org.springframework.boot:spring-boot-configuration-processor'
runtime 'org.postgresql:postgresql:42.2.1'
}
This is error giving class:
package com.example.redislock.DemoRedisLockGradle.scheduler;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
#Configuration
public class ExampleScheduler {
#Bean(name = "asdTrigger")
public CronTriggerFactoryBean triggerFactoryBean(#Qualifier("asdJobFactory") JobDetailFactoryBean jobFactory) {
return createTriggerFactoryBean(jobFactory.getObject());
}
#Bean(name = "asdJobFactory")
public JobDetailFactoryBean asd() {
return createJobDetailFactoryBean(ExampleJob.class);
}
CronTriggerFactoryBean createTriggerFactoryBean(JobDetail jobDetail) {
CronTriggerFactoryBean ctFactory = new CronTriggerFactoryBean();
ctFactory.setName("Example Factory");
ctFactory.setCronExpression("0 0/1 * * * ?");
ctFactory.setJobDetail(jobDetail);
return ctFactory;
}
JobDetailFactoryBean createJobDetailFactoryBean(Class<? extends Job> jobClass) {
JobDetailFactoryBean factory = new JobDetailFactoryBean();
factory.setJobClass(jobClass);
return factory;
}
}
It cant find quartz.CronTriggerFactoryBean and quartz.JobDetailFactoryBean
Thanks in advance
I found the solution. If ı exclude spring-data-redis on spring-integration-redis it's not need adding spring-context-support
compile('org.springframework.boot:spring-boot-starter-integration')
compile('org.springframework.integration:spring-integration-redis') {
exclude group: 'org.springframework.data', module: 'spring-data-redis'
}

Ktor startup example errors

I'm very new to Kotlin and Ktor and Gradle, wanted to try Ktor, so gone through the steps explained here, and ended up with this code, and structure shown in the screenshot:
As seen there are lots of error, how to fix them?
package blog
import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("My Example Blog", ContentType.Text.Html)
}
}
}.start(wait = true)
}
The build.gradle file is auto generated as:
group 'Example'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
You have incomplete build.gradle script (missing dependencies) - see here for details. Here's the good one:
group 'Example'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
sourceCompatibility = 1.8
ext.ktor_version = '0.4.0'
repositories {
mavenCentral()
maven { url "http://dl.bintray.com/kotlin/ktor" }
maven { url "https://dl.bintray.com/kotlin/kotlinx" }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
compile "org.jetbrains.ktor:ktor-core:$ktor_version"
compile "org.jetbrains.ktor:ktor-netty:$ktor_version"
compile "ch.qos.logback:logback-classic:1.2.1"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
kotlin {
experimental {
coroutines "enable"
}
}
I would recommend using the IntelliJ Ktor plugin to bootstrap your app. The ./gradlew run script runs right out of the box with this configuration without you needing to fiddle with the Gradle configuration. It's the easiest way to get started.
Here is an example Ktor app that uses the configuration: https://gitlab.com/tinacious/ktor-example
If you'd like to run your application from IntelliJ, check out this answer for the run configuration I use: https://stackoverflow.com/a/65350680/1870884

Resources