Unable to get classpath in Gradle - gradle

I need to get the classpath for our Java project in the build.gradle file. I have seen answers saying to use sourceSets.main.runtimeClasspath or configurations.runtime.asPath but those don't work.
When I try:
task fortify(type: Exec) {
def classpath = sourceSets.main.runtimeClasspath
}
Running gradle fortify results in Could not get unknown property 'sourceSets' for task ':fortify' of type org.gradle.api.tasks.Exec.
When I try:
task fortify(type: Exec) {
def classpath = configurations.runtime.asPath
}
Running gradle fortify results in Could not get unknown property 'runtime' for configuration container of type org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.

So we actually have 2 build.gradle files. One of them is at the top level of the project and contains few lines:
plugins {
id 'org.sonarqube' version '2.7.1'
id 'jacoco'
}
group = 'com.mycompany.project'
version = '1.0.1'
sonarqube {
properties {
property "sonar.sources", "ci-cd"
}
}
This is the file I added the task to, which didn't work.
Then in the main project folder, there is a subdirectory that contains another build.gradle file, a src folder, and some other things. This build.gradle file contains a lot more:
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'java'
id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}
group = 'com.mycompany.project.api'
version = '1.0.2'
sourceCompatibility = '11.0.4'
if (project.hasProperty('buildNum')) {
version(project.version + '.' + buildNum)
}
apply from: 'gradle/docker.gradle'
apply from: 'gradle/jlink.gradle'
apply from: '../gradle/artifactory.gradle'
springBoot {
buildInfo()
}
repositories {
maven {
url 'https://artifactory.mycompany.com/artifactory/dept-group-gradle-cache'
credentials {
username project.artifactory_user
password project.artifactory_apikey
}
}
}
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Greenwich.RELEASE'
}
}
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.3.RELEASE'
implementation 'org.springframework.cloud:spring-cloud-config-client:2.1.0.RELEASE'
implementation 'org.springframework.data:spring-data-jpa'
implementation 'mysql:mysql-connector-java'
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
implementation 'io.springfox:springfox-bean-validators:2.9.2'
implementation group: 'org.latencyutils', name: 'LatencyUtils', version: '2.0.3'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-inline:2.23.4'
testImplementation 'com.h2database:h2'
}
bootJar.dependsOn 'cleanDocker'
copyDockerFiles.dependsOn 'bootJar'
copyDockerFiles.dependsOn 'packageJRE'
copyDockerFiles {
from files(bootJar)
from files(packageJRE.outputs)
into "${project.buildDir}/docker"
}
sonarqube {
properties {
property "sonar.sources", "src/main"
property "sonar.java.binaries", "src/main"
property "sonar.java.libraries", "/usr/java/latest/lib"
}
}
I added the task without (type: Exec) to this build.gradle file, and sourceSets.main.runtimeClasspath.asPath successfully returned the classpath.

Related

Open webpages generated by restdocs

I want to display static pages using Spring Boot. I tried this configuration:
plugins {
id "java"
id "org.asciidoctor.jvm.convert" version "3.3.2"
}
repositories {
maven { url 'https://repo.spring.io/milestone' }
maven { url 'https://repo.spring.io/snapshot' }
mavenCentral()
mavenLocal()
}
group = 'com.example'
sourceCompatibility = 11
targetCompatibility = 11
ext {
restdocsVersion = '3.0.0-SNAPSHOT'
snippetsDir = file('src/static/docs')
}
configurations {
asciidoctorExtensions
}
dependencies {
asciidoctorExtensions "org.springframework.restdocs:spring-restdocs-asciidoctor:$restdocsVersion"
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.6.3'
implementation 'io.projectreactor.netty:reactor-netty-http:1.0.15'
testImplementation 'io.rest-assured:rest-assured:4.5.0'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0'
testImplementation "org.springframework.restdocs:spring-restdocs-restassured:$restdocsVersion"
testImplementation 'org.springframework:spring-test'
testImplementation('org.junit.vintage:junit-vintage-engine') {
exclude group: 'org.hamcrest', module: 'hamcrest-core'
}
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0'
}
test {
outputs.dir snippetsDir
useJUnitPlatform()
}
asciidoctor {
configurations "asciidoctorExtensions"
inputs.dir snippetsDir
dependsOn test
}
jar {
dependsOn asciidoctor
from ("${asciidoctor.outputDir}/html5") {
into 'static/docs'
}
}
I placed several .adoc files under this file location:
I started the project as a Spring Boot project but when I open http://localhost:8080/docs/index.html I get white label error:
Do you know how I can serve this content as web pages?

Gradle build using plugins and dependencies from "flatDir"

How to make a Gradle build if all the required jars to build the project (plugins+dependencies) are present in flatDir?
I have all the required jars in my D drive under D:/path/to/local/directory. Now when I am trying to do a Gradle build, it fails every time for different reasons. Need help in fixing the same (Gradle version 6.3).
Code in my build.gradle:
buildscript {
repositories {
// If you want to use a (flat) filesystem directory as a repository
flatDir {
dirs 'D:/path/to/local/directory'
}
}
}
plugins {
id "jacoco"
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'war'
id "org.sonarqube" version "2.8"
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web-services'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'wsdl4j:wsdl4j:1.6.3'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.ws:spring-ws-test'
testImplementation 'org.apache.httpcomponents:httpclient:4.5.9'
testImplementation 'com.h2database:h2:1.4.199'
}
bootWar {
baseName = 'web-service'
version = '1.0.0'
}
jacocoTestReport {
reports {
xml.enabled true
}
}
sonarqube {
properties {
property 'sonar.projectName', 'Sonar-Gradle-Integration'
}
}
Code in my settings.gradle:
pluginManagement {
flatDir {
dirs 'D:/path/to/local/directory'
}
}
I found out how to build a project from flat directory after some tries (Gradle 6.3).
You must have all the dependencies in the flatDir repository (transitive dependencies as well). I kept all the jars in a single directory inside the root folder named "lib" of my project and modified the build.gradle and settings.gradle like below.
build.gradle:
plugins {
id "org.sonarqube"
id "jacoco"
id 'java'
id 'war'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
// If you want to use a (flat) filesystem directory as a repository
flatDir {
dirs 'lib'
}
}
dependencies {
implementation fileTree(dir: 'lib', include: '*.jar')
testImplementation fileTree(dir: 'lib', include: '*.jar')
}
jacocoTestReport {
reports {
xml.enabled true
}
}
settings.gradle
pluginManagement {
buildscript {
repositories {
flatDir {
dirs 'lib'
}
}
dependencies {
classpath fileTree(dir: 'lib', include: '*.jar')
}
}
}
rootProject.name = 'gradleproj'

Gradle multiple project gradle build fail with lombok 1.8.10 but compile well

I'm developing a gradle-multiple-project java application, code works well with lombok in intellij (getter, setter method is visible), but when I run gradle build then fail, get the message:
~/EventStormingWorkShop/sources/coffeeshop/coffee-domain/src/main/java/solid/humank/port/adapter/OrderReceiverAdapter.java:41: error: cannot find symbol
String orderString= mapper.writeValueAsString(orderCreatedEvent.getDetail());
^
symbol: method getDetail()
location: variable orderCreatedEvent of type OrderCreatedEvent
Current environment:
Intellij : 2019.2.3
Gradle : 5.6.2
JDK : GraalVM 19.2.0 (compatible with JDK 1.8_0222)
lombok : 1.8.10
I had checked the lombok dependencies declaration in build.gradle.
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
testCompileOnly "org.projectlombok:lombok:${lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"
at compile time everything wen well.
Here is the build.gradle from my rootProject
buildscript {
ext {
quarkusJunitVersion = '0.22.0'
restAssuredVersion = '3.3.0'
cucumberVersion = '4.7.1'
lombokVersion = '1.18.10'
quarkusVersion = '0.23.1'
awsJavaVersion = '1.11.631'
awsVersion = '2.5.29'
}
}
apply from: file("${rootDir}/gradle/project.gradle")
List testCompilePackage = ["io.quarkus:quarkus-junit5:${quarkusJunitVersion}", "io.rest-assured:rest-assured:${restAssuredVersion}"]
List testImplementPackage = ["io.cucumber:cucumber-java8:${cucumberVersion}", "io.cucumber:cucumber-junit:${cucumberVersion}"]
List implementationPackage = ["io.quarkus:quarkus-resteasy",
"com.amazonaws:aws-java-sdk-lambda",
"com.amazonaws:aws-java-sdk-dynamodb",
"com.amazonaws:aws-lambda-java-core",
"com.amazonaws:aws-lambda-java-events",
"com.amazonaws:aws-java-sdk-events"]
subprojects { dir ->
repositories {
mavenCentral()
}
dependencies {
// Lombok Support
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
testCompileOnly "org.projectlombok:lombok:${lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"
// quarkus test
testCompile testCompilePackage
// cucumber test
testImplementation testImplementPackage
// quarkus
compile group: 'io.quarkus', name: 'quarkus-gradle-plugin', version: "${quarkusVersion}", ext: 'pom'
implementation enforcedPlatform("io.quarkus:quarkus-bom:${quarkusVersion}")
implementation platform("com.amazonaws:aws-java-sdk-bom:${awsJavaVersion}")
implementation platform("software.amazon.awssdk:bom:${awsVersion}")
implementation implementationPackage
}
if (dir.name.endsWith("-domain")) {
dependencies {
implementation project(":ddd-commons")
}
}
if (dir.name.endsWith("-application")) {
String modName = dir.name.substring(0, dir.name.lastIndexOf("-application"))
dependencies {
implementation project(":ddd-commons"), project(":${modName}-domain")
}
}
if (dir.name.endsWith("-web")) {
String modName = dir.name.substring(0, dir.name.lastIndexOf("-web"))
dependencies {
implementation project(":ddd-commons"), project(":${modName}-domain"), project(":${modName}-application")
}
}
}
The build.gradle will apply a project.gradle file
project.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'io.quarkus:quarkus-gradle-plugin:0.23.1'
}
}
defaultTasks 'clean', 'build'
apply plugin: 'idea'
subprojects {
apply plugin: 'java'
apply plugin: io.quarkus.gradle.QuarkusPlugin
group 'solid.humank.coffeeshop'
version '1.0'
sourceCompatibility = 1.8
targetCompatibility = 1.8
idea.module.inheritOutputDirs = true
dependencies{
compileOnly "org.projectlombok:lombok:1.18.10"
annotationProcessor "org.projectlombok:lombok:1.18.10"
testCompileOnly "org.projectlombok:lombok:1.18.10"
testAnnotationProcessor "org.projectlombok:lombok:1.18.10"
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.deprecation = true
options.compilerArgs += ['-Xlint:none', '-proc:none', '-nowarn']
}
repositories {
mavenCentral()
mavenLocal()
}
buildDir = "${rootDir}/build/${rootDir.relativePath(projectDir)}"
tasks.named('test') {
useJUnitPlatform()
failFast = true
testLogging.showStandardStreams = true
testLogging.exceptionFormat 'full'
}
tasks.named('jar') {
// put parent name in final jar name, to resolve collision of child projects with same name under different parents
if (parent.depth > 0) {
archiveBaseName = "${parent.name}-${archiveBaseName.get()}"
}
}
afterEvaluate {
def buildTime = new Date()
tasks.withType(Jar) {
String ClassPathString = ''
configurations.runtime.each { ClassPathString += " lib\\" + it.name }
manifest {
attributes 'Implementation-Title': project.name,
'Implementation-Version': project.version,
'Created-By': "${System.getProperty('java.version')} (${System.getProperty('java.vendor')})",
'Built-With': "gradle-${project.gradle.gradleVersion}, groovy-${GroovySystem.version}",
'Built-By': System.getProperty('user.name'),
'Built-On': "${InetAddress.localHost.hostName}/${InetAddress.localHost.hostAddress}",
'Build-Time': buildTime.format('yyyy/MM/dd HH:mm:ss'),
'Class-Path': ClassPathString
}
}
}
}
Besides, there is the settings.gradle to include sub projects
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
resolutionStrategy {
eachPlugin {
if (requested.id.id == 'io.quarkus') {
useModule("io.quarkus:quarkus-gradle-plugin:0.23.1")
}
}
}
}
rootProject.name = 'coffeeshop'
include 'ddd-commons'
include 'inventory-domain'
include 'inventory-application'
include 'inventory-web'
include 'coffee-application'
include 'coffee-domain'
include 'coffee-web'
include 'orders-application'
include 'orders-domain'
include 'orders-web'
I expect these settings could run gradle build well, but faced seems lombok annotation processer not worked issue in gradle runtime.
Because your project.gradle has '-proc:none'

Spring Boot Test not working with Java 11

I'm trying to upgrade my existing Java 8 multi-project gradle application to Java 11. After fixing a few compilation issues, I ended up getting issues in test cases. When i run a test in Intellij, it throws the following error:
Error:java: Attempt to recreate a file for type {QueryDsl classes}
It is trying to generate the Querydsl classes but since those classes are already there, the test is throwing exception.
I'm using Java11, IntelliJ 2019, Gradle 5 to run the application.
These tests are working as expected in Java8.
I've no idea what is causing this error. Can anybody please help me in understanding this.
Code snippets are given below.
Root project build.gradle:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE)
classpath("net.ltgt.gradle:gradle-apt-plugin:0.21")
}
}
subprojects {
apply plugin: 'java'
repositories {
mavenCentral()
}
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
task allDependencies(type: DependencyReportTask) {}
jar {
baseName = "${parent.name}-${project.name}"
}
sourceSets {
main {
java {
srcDirs 'src/main/java', 'build/generated/sources/main/java', 'build/generated/sources/annotationProcessor/java/main'
}
}
}
}
Sub-project build.gradle:
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'net.ltgt.apt'
bootJar {
baseName = "test"
version = "1.0.0"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa: 2.1.4.RELEASE")
compile("com.querydsl:querydsl-core:4.1.3")
compile("com.querydsl:querydsl-jpa:4.1.3")
annotationProcessor(
"com.querydsl:querydsl-apt:4.1.3:jpa",
"javax.annotation:javax.annotation-api:1.3.2"
)
annotationProcessor("org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final")
testCompile("org.springframework.boot:spring-boot-starter-test:2.1.4.RELEASE")
testCompile("com.h2database:h2:2.1.4.RELEASE")
}
Integration test
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MainClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServiceImplTest {
#Autowired
private Service1Impl service;
#Test
public void getData() {
Data data = service.getData();
Assert.assertEquals(0, data.size());
}
}
I had the same issue and the problem was with the order of the dependencies in gradle. Somehow the java compiler in intellij can not work well.
Be sure you have this dependencies for QueryDSL
annotationProcessor group: 'com.querydsl', name: 'querydsl-apt', version: querydsl_version, classifier: 'jpa'
annotationProcessor group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: hibernate_jpa_version
annotationProcessor group: 'javax.annotation', name: 'javax.annotation-api', version: javax_annotation_version
Delete the out folder in your project just in case and rebuild with Ctrl+f9.
Note aside, executing build from gradle and test command worked fine. Check this out https://blog.jdriven.com/2018/10/using-querydsl-annotation-processor-with-gradle-and-intellij-idea/

Kotlin Gradle Could not find or load main class

I tried to copy the Spring Boot Kotlin sample project https://github.com/JetBrains/kotlin-examples/tree/master/tutorials/spring-boot-restful. I Added some more dependencies and when I tried to build the executable jar and run it, I got the error:
Could not find or load main class...
Gradle build script:
buildscript {
ext.kotlin_version = '1.1.3' // Required for Kotlin integration
ext.spring_boot_version = '1.5.4.RELEASE'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
}
}
/*plugins {
id 'org.springframework.boot' version '2.0.0.RELEASE'
}*/
apply plugin: 'kotlin' // Required for Kotlin integration
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-rest-service'
version = '0.1.0'
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin/'
test.java.srcDirs += 'src/test/kotlin/'
}
repositories {
jcenter()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile("org.springframework.boot:spring-boot-starter-web")
compile group: 'org.apache.camel', name: 'camel-quartz2', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-http4', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-docker', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-aws', version: '2.20.2'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Change Applicationkt to ApplicationKt will work, and BTW you may upgrade Kotlin version to 1.3.50.
By Applicationkt I mean the one in this line:
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
Kotlin compiles the Application file in two different files:
one file called Application.class with the Springboot things
another file called ApplicationKt.class with the main method
In this second file is where the main function is located at, so you have to use this name in the build.gradle file.
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
Update your build.gradle to
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
with an upper case K in ApplicationKt.
This is required because of the way Kotlin compiles to Java Bytecode. The fun main() function in Kotlin is not attached to any class, but Java always requires a class and does not support classless functions.
The Kotlin compiler has to create a Java class. Because you already defined a class Application it created one with the suffix Kt for the functions in your Kotlin file org/jetbrains/kotlin/demo/Application.kt. You have to set this class so that the JVM can find it.
BTW a Jar file is just a Zip file, you can unpack it and see for yourself if the ApplicationKt.class is there.
For me the main function needed to be outside the class body
#SpringBootApplication
#Configuration
class Application
(private val locationRepository: LocationRepository,
) : CommandLineRunner {
override fun run(vararg args: String?) {
whatever()
}
}
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
Indeed, Kotlin create file ApplicationKt.class in the jar if your main class file is named Application.kt. You have to add the following lines:
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
If you use the classic jar plugin, you can do as below (which is described in previous responses):
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
However, my preference is to use bootJar plugin which is much clear and which allow me to use layered jars for example:
bootJar {
layered() // Not useful if you don't want to use layered jars
}

Resources