gradle use class from maven build - gradle

Hy i have written a java Library an I want to use it in the Gradle script. What I have done:
Added the repository:
repositories {
maven {
url "../Projectname/maven_repo"
}
}
Added the Dependency:
dependencies {
classpath group: 'my.group.id', name: 'Projectname', version: '0.0.1-SNAPSHOT'
}
And now i want to use the Library in a Task:
task myTask () {
def file = file("${buildDir}/ws/.metadata/.log")
def htmlParser = new my.package.Projectname()
}
Now I always get the exception on the Buildserver that he isn’t able to find the class.
Thx for the Help.

Related

gradle: how to create 2 jars with different java versions using Springboot bootJar task and java toolchain

springboot gradle plugin version: org.springframework.boot:spring-boot-gradle-plugin:2.7.2
I have defined different versions of Java for compilation and test as mentioned here but thats just for compile and test.
tasks.withType(JavaCompile).configureEach {
javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(8)
}
}
task('testsOn14', type: Test) {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(14)
}
}
Ref: https://docs.gradle.org/current/samples/sample_jvm_multi_project_with_toolchains.html
The jar task is defined simply as jar.dependsOn(bootJar)
I want this task to create 2 jars: myproject-j8.jar and myproject-j14.jar meaning one build with Java-8 and other with Java-14. No idea how to do that. Thanks for taking a look.

Can a standalone gradle plugin export a custom task type?

I have a standalone Gradle plugin that includes a custom task type:
gradle-conventions/build.gradle
plugins {
id 'groovy-gradle-plugin'
id 'maven-publish'
}
group = 'com.example'
version = '1.0'
publishing {
repositories {
maven {
url = uri('/path/to/repo')
}
}
}
gradle-conventions/src/main/groovy/com.example.my-conventions.gradle
abstract class CustomTask extends DefaultTask {
#TaskAction
def hello() {
println "hello"
}
}
I can consume the plugin from another project, but how can I register a CustomTask? Something like this:
project/build.gradle
plugins {
id 'com.example.my-conventions' version '1.0'
}
// how do I reference CustomTask here?
tasks.register('myCustomTask', com.example.CustomTask) {
// ...
}
Is it possible to export a custom task from a custom plugin? Or must I consume custom tasks using the buildscript mechanism?
Having inspected gradle-conventions-1.0.jar, it seems that the custom task class belongs to the default package, so I can register the task as follows:
project/build.gradle
plugins {
id 'com.example.my-conventions' version '1.0'
}
tasks.register('myCustomTask', CustomTask) {
// ...
}
But this only works com.example.my-conventions.gradle contains groovy code besides the class itself, otherwise I get the error:
An exception occurred applying plugin request [id: 'com.example.my-conventions', version: '1.0']
> Failed to apply plugin 'com.example.my-conventions'.
> java.lang.ClassNotFoundException: precompiled_ComExampleMyConventions
This approach avoids relying on the buildscript mechanism (which is not recommended in the Gradle documentation).

How to define dependency version only once for whole Gradle multi-module project?

I made a decision to migrate from Dependency Management Plugin to Gradle built-in BOM import support. Since Gradle built-in BOM import support has better performance But
I run into the issue:
I cannot find alternatives for dependency and dependencySet in native Gradle:
dependencyManagement {
dependencies {
dependency("org.springframework:spring-core:4.0.3.RELEASE")
}
}
//or
dependencyManagement {
dependencies {
dependencySet(group:'org.slf4j', version: '1.7.7') {
entry 'slf4j-api'
entry 'slf4j-simple'
}
}
}
and then I could use dependency without version
dependencies {
compile 'org.springframework:spring-core'
}
How can I get the same behavior in naive Gradle? I mean: I'd like to define a version once as I did it when using Dependency Management Plugin
Solution below helps to avoid versions copy-paste. However it isn't the same with Dependency Management plugin.
For Gradle Kotlin Dsl:
You can create buildSrc with you own code, when you can place any constants.
Algorithm:
Create folder buildSrc/src/main/kotlin
Create file buildSrc/src/main/kotlin/Versions.kt with content:
object Versions {
const val junitVersion = "5.5.5" // just example
}
Create file buildSrc/build.gradle.kts with content:
plugins {
`kotlin-dsl`
}
Use the following syntax in your gradle.kts files:
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:${Versions.junitVersion}")
}
For Gradle Groovy:
Create file gradle.properties
Put versions there with syntax like okhttp_version=4.2.0
Use the following syntax in your gradle files:
dependencies {
compile group: 'com.squareup.okhttp3', name: 'okhttp', version: okhttp_version
}
You can do so on the gradle.properties file. I.e.:
# APPLICATION PROPERTIES
name=projectName
group=com.domain
version=1.0.0
description=A brief description
gradleScripts=https://raw.githubusercontent.com/hexagonkt/hexagon/1.2.0/gradle
# DEPENDENCIES VERSIONS
kotlinVersion=1.3.61
kotlinCoroutinesVersion=1.3.2
Or in settings.gradle if you don't want to create another file:
rootProject.name = "hexagon-contact-application"
gradle.rootProject {
allprojects {
version = "1.0.0"
group = "org.hexagonkt"
description = "Contact application backend api"
}
extensions.gradleScripts = "https://raw.githubusercontent.com/hexagonkt/hexagon/1.0.18/gradle"
extensions.kotlinVersion = "1.3.50"
extensions.kotlinCoroutinesVersion = "1.3.2"
extensions.hexagonVersion = "1.0.21"
extensions.logbackVersion = "1.2.3"
extensions.bcryptVersion="0.8.0"
extensions.javaJwtVersion="3.8.2"
}
And if you want to avoid adding the version variable to all related dependencies, you can create a method in the build file:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.50'
}
apply from: "$gradleScripts/kotlin.gradle"
apply from: "$gradleScripts/service.gradle"
apply from: "$gradleScripts/junit.gradle"
defaultTasks("test")
mainClassName = 'com.hexagonkt.contact.ApplicationKt'
applicationDefaultJvmArgs = ["-Xms64M", "-Xmx2G", "-XX:+UseNUMA", "-XX:+UseParallelGC"]
dependencies {
httpkt(it, "http_server_jetty")
httpkt(it, "store_mongodb")
httpkt(it, "hexagon_web")
implementation("at.favre.lib:bcrypt:$bcryptVersion")
implementation("com.auth0:java-jwt:$javaJwtVersion")
testImplementation("com.hexagonkt:port_http_client:$hexagonVersion")
}
private void httpkt(final def dependencies, final String artifact) {
dependencies.implementation("com.hexagonkt:$artifact:$hexagonVersion")
}

I got an error using this build.grafle file and don't know how to fix it

Here's the Error:
FAILURE: Build failed with an exception.
Where: Build file '/home/wieland/GitGradlePackaging/build.gradle' line: 22
What went wrong: A problem occurred evaluating root project 'GitGradlePackaging'.
Could not get unknown property 'org' for object of type org.gradle.api.internal.initialization.DefaultScriptHandler.
And Here's my build.gradle File:
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/4.6/userguide/tutorial_java_projects.html
*/
//From example: http://mrhaki.blogspot.co.at/2015/04/gradle-goodness-use-git-commit-id-in.html
buildscript {
repositories {
jcenter()
}
dependencies {
//Add dependencies for build script, so we can access Git from our build script
classpath 'org.ajoberstar:grgit:1.1.0'
}
def git = org.ajoberstar.grgit.Grgit.open(file('.'))
//To save Githash
def githash = git.head().abbreviatedId
}
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building an application
id 'application'
// Apply the groovy plugin to also add support for Groovy (needed for Spock)
id 'groovy'
id 'distribution'
}
// Set version
project.version = mainProjectVersion + " - " + githash
project.ext.set("wholeVersion", "$project.version - $githash")
project.ext.set("buildtimestamp", "2000-01-01 00:00")
def versionfilename = "versioninfo.txt"
def GROUP_DEBUG = 'Debug'
// Task to print project infos
task debugInitialSettings {
group = GROUP_DEBUG
doLast {
println 'Version: ' + project.wholeVersion
println 'Timestamp: ' + project.buildtimestamp
println 'Filename: ' + project.name
}
}
// To add the githash to zip
task renameZip {
doLast {
new File ("$buildDir/distributions/$project.name-${project.version}.zip")
.renameTo ("$buildDir/distributions/$project.name-${project.wholeVersion}.zip")
}
}
distZip.finalizedBy renameZip
// To add the githash to tar
task renameTar{
doLast {
new File ("$buildDir/distributions/$project.name-${project.version}.tar")
.renameTo ("$buildDir/distributions/$project.name-${project.wholeVersion}.tar")
}
}
distTar.finalizedBy renameTar
// Define the main class for the application
mainClassName = 'App'
dependencies {
// This dependency is found on compile classpath of this component and consumers.
compile 'com.google.guava:guava:23.0'
// Use the latest Groovy version for Spock testing
testCompile 'org.codehaus.groovy:groovy-all:2.4.13'
// Use the awesome Spock testing and specification framework even with Java
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'junit:junit:4.12'
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
//To generate Testreports as HTML
test {
reports {
junitXml.enabled = false
html.enabled = true
}
}
distributions {
main {
contents {
from { 'build/docs' }
into ('reports') {
from 'build/reports'
}
}
}
}
//To make sure that test and javadoc ran before zip and tar
distTar.dependsOn test
distZip.dependsOn test
distTar.dependsOn javadoc
distZip.dependsOn javadoc
Please keep in mind I have not much knowledge about gradle as I'm just starting to learn it!
Thanks in advance :)
You have to move the githash definition outside the buildscript block
buildscript {
repositories {
jcenter()
}
dependencies {
//Add dependencies for build script, so we can access Git from our build script
classpath 'org.ajoberstar:grgit:1.1.0'
}
}
def git = org.ajoberstar.grgit.Grgit.open(file('.'))
//To save Githash
def githash = git.head().abbreviatedId
The reason is that when the buildscript block is evaluated line by line, its dependencies are not yet loaded. When the rest of the script is evaluated, the dependencies of the buildscript block have already been loaded. This is actually the reason for the buildscript block existence: to be run before the rest of the build and prepare the setup.

How to resolve a dependency extension within a Gradle build script

I'm using the maven-publish plugin in my build.gradle. For each of the compile dependencies, the group, name and version are used to generate the appropriate tags in the generated pom.xml file - and this works fine.
Here are the example dependencies I have:
dependencies {
compile (
[group: 'com.actionbarsherlock', name: 'actionbarsherlock', version: '4.4.0', ext: 'aar'],
[group: 'com.android.support', name: 'support-v4', version: '19.0.+']
)}
Here is the publishing element I have:
publishing {
publications {
// A publication named 'mavenAndroid'
mavenPublishLibrary(MavenPublication) {
// Artifact using the aar from the build output
artifact "${project.projectDir}/build/outputs/aar/${project.name}-${project.version}.aar"
// Generate dependencies manually for POM
pom.withXml {
def dependenciesNode = asNode().appendNode('dependencies')
//Iterate over the compile dependencies, adding a <dependency> node for each
configurations.compile.allDependencies.each {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
// This is what I'd want to do...
if (it.ext != '') {
dependencyNode.appendNode('type', it.ext)
}
// ...but this doesn't work!
}
}
}
}
}
I'd like to be able to add the ext value (e.g. aar) to the pom.xml along with the group, name and version, something like what I have in the above snippet.
I ask these questions when I've been struggling for hours, and then I always seem to answer myself soon after asking it!
I used the following to get the dependency extension, replacing the if() in the question:
it.getArtifacts().each {
dependencyNode.appendNode('type', it.getExtension())
}

Resources