Add Library to Gradle Kotlin app - java

I converted simple Kitlon file into Library, the file is:
Display.kt:
package hello
fun main(args: Array<String>) {
println("Hello World!")
}
had been compiled into library using the command:
kotlinc Display.kt -d Display.jar
The output had been cross checked to be worked using the command:
kotlin -classpath Display.jar hello.DisplayKt
Then I moved it to folder src/main/resources, then tried calling it from another app, using the below code:
Hello.kt:
package hello
import hello.DisplayKt
fun main(args: Array<String>) {
println("Hi")
}
and defined the build.gradle file as below (tried to put all option I read about to solve my case):
// set up the kotlin-gradle plugin
buildscript {
ext.kotlin_version = '1.1.2-2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
// apply the kotlin-gradle plugin
apply plugin: "kotlin"
// add kotlin-stdlib dependencies.
repositories {
mavenCentral()
}
dependencies {
//dependencies from a remote repositor
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
//local file
compile files('src/main/resources/Display.jar')
compile fileTree(dir: 'src/main/resources', include: '*.jar')
}
jar {
manifest {
//Define mainClassName as: '[your_namespace].[your_arctifact]Kt'
attributes ('Main-Class': 'hello.HelloKt', "Implementation-Title": "Gradle",
"Implementation-Version": 1)
}
// NEW LINE HERE !!!
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
sourceSets {
main {
java {
srcDirs = ['src/kotlin']
}
resources {
srcDirs = ['src/resources']
}
}
}
but, after running gradle build command, I got the below error:
Unresolved reference: DisplayKt
Note: I'm very very new to JAVA/KOTLIN and GRADLE

I found the answer, the full path of the function is hello.main

Related

ClassNotFoundException When running jar file but runs fine in Intellij

I created a small mqtt application using eclipse paho mqtt library in kotlin with Gradle in Intellij IDE. it runs fine when running it through Intellij but when I build it and run the jar file that gets created I get a NoClassDefFoundError error.
From other questions I have seen about this it looks like it has something to do with the class path but I am not sure what needs to be done if that is indeed the issue because I am using gradle and not jar files for libraries.
I was following this tutorial
Here is my gradle file
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.31'
id 'application'
}
group = 'me.package'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
test {
useJUnit()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
application {
mainClassName = 'com.publisher.MainKt'
}
tasks.jar {
manifest {
attributes 'Main-Class': 'com.publisher.MainKt'
}
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
And my MainKt file
package com.publisher
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import java.io.File
fun main(args: Array<String>) {
val client = MqttClient("tcp://192.168.0.55:1883","publisher", MemoryPersistence())
val connOpts = MqttConnectOptions()
connOpts.isCleanSession = false
connOpts.isAutomaticReconnect = true
client.setCallback(object: MqttCallback {
override fun connectionLost(cause: Throwable?) {
println("Connection lost")
println(cause!!.message)
}
override fun messageArrived(topic: String?, message: MqttMessage?) {
println("Message Received for topic: $topic")
println("Message: ${message!!.payload}")
}
override fun deliveryComplete(token: IMqttDeliveryToken?) {
println("Message delivered")
}
})
try{
client.connect(connOpts)
println("Connected")
client.subscribe("config/+", 1) { topic, message ->
println("Getting configuration for $message")
val path = System.getProperty("user.dir")
val file = File("$path/${message}.json")
if(file.exists()){
client.publish("/devices/ + $message + /config", MqttMessage(file.readBytes()))
}
}
}catch (e: MqttException){
println("Error: ${e.localizedMessage}")
e.printStackTrace()
}
}
The way you start your application does not include the dependencies, meaning your MQTT driver and the Kotlin dependencies are not included.
Do the following:
gradle distZip
# alternatively
gradle distTar
This will create a zip/tar file containing all the dependencies and a start script. Use that to start your application.
You could consider the Shadow plugin, as it is straightforward to use. Your build.gradle would look something like this:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.31'
// Shadow plugin
id 'com.github.johnrengelman.shadow' version '6.1.0'
id 'java'
}
group = 'me.package'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
test {
useJUnit()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
application {
mainClassName = 'com.publisher.MainKt'
}
tasks.jar {
manifest {
attributes 'Main-Class': 'com.publisher.MainKt'
}
}
So your fat JAR is generated in the /build/libs directory with all the dependencies included.

Building a project and a Spock test suite with gradle

I'm trying to build a Springboot web application that creates a WAR and also a suite of tests using the Spock framework but every time I try to run gradle build the console will execute the tests but will not create the web app WAR although it mentions a file in the web app source code saying a deprecation warning so I know it is at least doing something with it. Is there some kind of configuration I'm missing from my build.gradle or concept about how sourceSets work? I can compile the web app fine and the tests when I do them separately with their own build.gradle files but I was hoping that the code below could build the WAR and execute the tests in the same file.
plugins {
id 'java'
id 'maven-publish'
id 'war'
id 'groovy'
}
repositories {
mavenLocal()
maven {
url = 'https://repo.spring.io/libs-release'
}
maven {
url = 'http://repo.maven.apache.org/maven2'
}
}
sourceSets{
main {
java { srcDir "src\\TestingWebAppSpringBoot\\src\\main\\java" }
resources {srcDir "src\\TestingWebAppSpringBoot\\src\\main\\resources" }
groovy { srcDirs = [] }
}
test{
groovy {
srcDirs = ["src\\test_pack\\com\\example\\diag\\test\\spock\\main", "src\\test_pack\\com\\example\\diag\\test\\spock\\test" ]
}
}
}
test{
reports.html.destination = file("build\\spockTestResults")
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-thymeleaf:2.0.0.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-web:2.0.0.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-security:2.0.0.RELEASE'
compile 'org.codehaus.groovy:groovy-all:2.4.14'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
testCompile (
fileTree(dir: 'build\\server\\_archives\\_release', include: '*.jar'),
fileTree(dir: 'build\\common\\_archives\\_release', include: '*.jar'),
'net.sourceforge.htmlunit:htmlunit:2.26',
"org.codehaus.groovy:groovy-all:2.4.5",
"org.spockframework:spock-core:1.0-groovy-2.4"
)
}
group = 'com.something.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
publishing {
publications {
maven(MavenPublication) {
from(components.java)
}
}
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}

Kotlin+Gradle runnable jar - dependency causing "Could not find or load main class"

Gradle build file:
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
group 'com.anivive'
version '0.1'
apply plugin: 'kotlin'
sourceSets {
main.java.srcDirs += 'src/main/kotlin/'
test.java.srcDirs += 'src/test/kotlin/'
}
repositories {
mavenLocal()
maven {
url "https://packagecloud.io/anivive/anivive/maven2"
}
mavenCentral()
}
dependencies {
compile 'anivive:Import_Utils:1.2.44'
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
jar {
baseName = 'XMLModelBuilder'
version = '0.1'
manifest {
attributes 'Main-Class': 'com.anivive.Main'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
File structure:
src
- main
- kotlin
- com
- anivive
- Main.kt
Main.kt:
package com.anivive
import com.anivive.util.ExampleClass
object Main {
#JvmStatic
fun main(args: Array<String>) {
ExampleClass.exampleMethod()
}
}
So, I'm trying to build a runnable jar file that will call a single method from a class in the dependency 'anivive:Import_Utils:1.2.44'.
If I remove the dependency, and change my main method to just println("Test"), the jar will run fine via java -jar build/libs/jarFile.jar and it will print out Test.
However, with the dependency included and when trying to call a function from it, I will get Error: Could not find or load main class com.anivive.Main whenever I try to run the Jar file. I suspect it has something to do with hosting the jar file on packagecloud, but I'm surprised this is a problem, considering I can run the program just fine from IntelliJ.
What gives?

Building a Kotlin + Java 9 project with Gradle

I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.
I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.
Filesystem schema is:
+ src
+ main
+ java
+ some.package
- Roundabout.java [an interface]
- module-info.java
+ kotlin
+ some.package.impl
- RoundaboutImpl.kt [implementing the interface]
module-info.java is:
module some.package {
requires kotlin.stdlib;
exports some.package;
}
and build.gradle is:
buildscript {
ext.kotlin_version = '1.2.0'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
group 'some.package'
version '1.0-PRE_ALPHA'
apply plugin: 'java-library'
apply plugin: 'kotlin'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
sourceCompatibility = 9
compileJava {
dependsOn(':compileKotlin')
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
]
classpath = files()
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
Notice that I had to specify a module path on the java compile task, or the compilation fails with:
error: module not found: kotlin.stdlib
requires kotlin.stdlib;
Anyway, now this build fails with this error, and I can't figure out how to solve it:
error: package some.package.impl does not exist
import some.package.impl.RoundaboutImpl;
error: cannot find symbol
return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);
I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.
I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.
How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.
Thanks in advance!
Solved! It was sufficient to set the kotlin compilation dir to the same dir as Java:
compileKotlin.destinationDir = compileJava.destinationDir
It works now, both with the sources in the same tree or in different trees; but with a quirk: the jar task produces a jar with all the entries duplicated. I'll work on fix this, next.
Thanks to everyone!
I am using the following gradle script where I put the module-info.java under src/module. It gets automatically included in the jar (without duplicates):
if (JavaVersion.current() >= JavaVersion.VERSION_1_9) {
subprojects {
def srcModule = "src/module"
def moduleInfo = file("${project.projectDir}/$srcModule/module-info.java")
if (moduleInfo.exists()) {
sourceSets {
module {
java {
srcDirs = [srcModule]
compileClasspath = main.compileClasspath
sourceCompatibility = '9'
targetCompatibility = '9'
}
}
main {
kotlin { srcDirs += [srcModule] }
}
}
compileModuleJava.configure {
dependsOn compileKotlin
destinationDir = compileKotlin.destinationDir
doFirst {
options.compilerArgs = ['--module-path', classpath.asPath,]
classpath = files()
}
}
jar.dependsOn compileModuleJava
}
}
}
I won't update it any longer, have a look at https://github.com/robstoll/atrium/blob/master/build.gradle
to see the current version in use.
The accepted answer did not work for me (atleast not the way it was presented), but this is what worked:
plugins {
id "org.jetbrains.kotlin.jvm" version "1.3.50"
}
compileKotlin {
doFirst {
destinationDir = compileJava.destinationDir
}
}
jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
Doing it the way the accepted answer suggests led to me getting this error:
Directory '/path/to/project/build/classes/kotlin/main' specified for
property 'compileKotlinOutputClasses' does not exist.
Gradle version: 5.6
I ran into the same problem and the existing answers fixed only part of the issue for me, so I searched over all internet and ended up with a working solution. I don't know exactly why this works, but I decided to share my build.gradle.kts file here to help other people to find they way. This file is a combination of many pieces that I found on the internet.
I'm using Java 16, Kotlin 1.5.31 and Gradle 7.1.
The file tree is:
+ project
- build.gradle.kts
+ src
+ main
+ java
- module-info.java
+ my
+ package
- SomeClasses.java
+ kotlin
+ my
+ package
- MoreClasses.kt
module-info.java
module name.of.your.javamodule {
requires kotlin.stdlib;
requires kotlinx.coroutines.core.jvm;
requires org.jetbrains.annotations;
exports my.pacakge;
}
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
application
kotlin("jvm") version "1.5.31"
id("org.jetbrains.kotlin.plugin.serialization") version "1.5.31"
}
val kotlinVersion = "1.5.31"
group = "your.group.id"
version = "0.0.1-SNAPSHOT"
application {
mainClass.set("full.name.of.your.MainClass")
mainModule.set("name.of.your.javamodule") // Same defined in module-info.java
executableDir = "run"
}
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8", kotlinVersion))
implementation("com.michael-bull.kotlin-inline-logger:kotlin-inline-logger:1.0.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt")
implementation("org.jetbrains:annotations:22.0.0")
testImplementation(kotlin("test", kotlinVersion))
}
java {
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
}
tasks {
run.configure {
dependsOn(jar)
doFirst {
jvmArgs = listOf(
"--module-path", classpath.asPath
)
classpath = files()
}
}
compileJava {
dependsOn(compileKotlin)
doFirst {
options.compilerArgs = listOf(
"--module-path", classpath.asPath
)
}
}
compileKotlin {
destinationDirectory.set(compileJava.get().destinationDirectory)
}
jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = "16"
}
}
On gradle 7.4 with kotlin DSL, I need to:
move the module-info.java to src/main/java
create any java file inside each package to export under src/main/java, at least empty package-info.java
In build.gradle.kts:
val compileKotlin: KotlinCompile by tasks
val compileJava: JavaCompile by tasks
compileKotlin.destinationDirectory.set(compileJava.destinationDirectory)
Also discussed here:
https://github.com/gradle/gradle/issues/17271

AspectJ + Gradle configuration

I'd like to use AspectJ in Gradle project (it's not an Android project - just a simple Java app).
Here is how my build.gradle looks like:
apply plugin: 'java'
buildscript {
repositories {
maven {
url "https://maven.eveoh.nl/content/repositories/releases"
}
}
dependencies {
classpath "nl.eveoh:gradle-aspectj:1.6"
}
}
repositories {
mavenCentral()
}
project.ext {
aspectjVersion = "1.8.2"
}
apply plugin: 'aspectj'
dependencies {
//aspectj dependencies
aspectpath "org.aspectj:aspectjtools:${aspectjVersion}"
compile "org.aspectj:aspectjrt:${aspectjVersion}"
}
The code compiles, however the aspect seems to not be weaved. What could be wrong?
I have been struggled with this for a while, so this the config I use and works well.
In your configuration do this.
configurations {
ajc
aspects
aspectCompile
compile{
extendsFrom aspects
}
}
In your dependencies use the following configuration. Spring dependencies are not needed if you are not using spring fwk.
dependencies {
//Dependencies required for aspect compilation
ajc "org.aspectj:aspectjtools:$aspectjVersion"
aspects "org.springframework:spring-aspects:$springVersion"
aspectCompile "org.springframework:spring-tx:$springVersion"
aspectCompile "org.springframework:spring-orm:$springVersion"
aspectCompile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:$hibernateJpaVersion"
}
compileJava {
sourceCompatibility="1.7"
targetCompatibility="1.7"
//The following two lines are useful if you have queryDSL if not ignore
dependsOn generateQueryDSL
source generateQueryDSL.destinationDir
dependsOn configurations.ajc.getTaskDependencyFromProjectDependency(true, "compileJava")
doLast{
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc(source:"1.7", target:"1.7", destDir:sourceSets.main.output.classesDir.absolutePath, maxmem:"512m", fork:"true",
aspectPath:configurations.aspects.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",classpath:configurations.compile.asPath){
sourceroots{
sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
}
}
}
}
I dont use the plugin I use the ant and aspectj compiler to do that, probably there will be an easy way
Just want to add the so called "official" plugin for AspectJ mentioned by Archie.
Here's some gradle script example on how to do it:
apply plugin: 'java'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.aspectz.Main'
}
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
//classpath "gradle.plugin.aspectj:plugin:0.1.1"
//classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.1"
}
}
ext {
aspectjVersion = '1.8.5'
}
apply plugin: "aspectj.gradle"
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.10'
compile("log4j:log4j:1.2.16")
compile("org.slf4j:slf4j-api:1.7.21")
compile("org.slf4j:slf4j-log4j12:1.7.21")
compile("org.aspectj:aspectjrt:1.8.5")
compile("org.aspectj:aspectjweaver:1.8.5")
}
However, it seems that it only supports Java 8 and above. As when you use java 7 to build it, it got error :
java.lang.UnsupportedClassVersionError: aspectj/AspectJGradlePlugin : Unsupported major.minor version 52.0
Looks like there is a new "official" gradle plugin for AspectJ:
https://plugins.gradle.org/plugin/aspectj.gradle
Unfortunately the documentation is minimal. I haven't tried it myself.
This plugin worked for me (gradle 5.6):
plugins {
id 'java'
id "io.freefair.aspectj.post-compile-weaving" version "4.1.4"
}
A bit ugly, but short and does not require additional plugins or configurations.
Works for me:
Add aspectjweaver dependency ti Gradle build script. Then in the task you need it find the path to its jar and pass as javaagent in jvmArgs:
dependencies {
compile "org.aspectj:aspectjweaver:1.9.2"
}
test {
group 'verification'
doFirst {
def weaver = configurations.compile.find { it.name.contains("aspectjweaver") }
jvmArgs = jvmArgs << "-javaagent:$weaver"
}
}
Add aop.xmlfile to the resources\META-INF\ folder with the specified Aspect class:
<aspectj>
<aspects>
<aspect name="utils.listener.StepListener"/>
</aspects>
</aspectj>
Example of an aspect:
package utils.listener
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.*
import org.aspectj.lang.reflect.MethodSignature
#Aspect
#SuppressWarnings("unused")
public class StepListener {
/* === Pointcut bodies. Should be empty === */
#Pointcut("execution(* *(..))")
public void anyMethod() {
}
#Pointcut("#annotation(org.testng.annotations.BeforeSuite)")
public void withBeforeSuiteAnnotation() {
}
}
Adding this in my build.gradle file worked for me.
project.ext {
aspectjVersion = '1.8.12'
}
apply plugin: "aspectj.gradle"
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
}
}
Doing a gradle assemble injected the code defined in the aspect.

Categories

Resources