Make clean task before any other - java

I would like to make releaseBuild task that will execute clean task before building project.
I have prepared script that works great to do clean before releaseBuild task, not cleaning just before finishing thanks to jar.mustRunAfter(clean).
However, I would like also to have possibility to execute publishToMavenLocal task that will be done only after releaseBuild finish successfully (so cleaning and building). Then there is problem.
plugins {
id 'java'
id 'maven-publish'
}
group 'com.example'
version '1.0-SNAPSHOT'
task releaseBuild {
outputs.upToDateWhen { false }
// generatePomFileForMavenJavaPublication.mustRunAfter(clean)
jar.mustRunAfter(clean)
releaseBuild.dependsOn(clean, build)
}
publishToMavenLocal.dependsOn(releaseBuild)
publishing {
publications {
mavenJava(MavenPublication) {
pom {
from components.java
packaging 'jar'
}
}
}
}
gradle releaseBuild works well.
gradle publishToMavenLocal shows the error:
> Task :generatePomFileForMavenJavaPublication
> Task :clean
> Task :compileJava NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar
> Task :publishMavenJavaPublicationToMavenLocal FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':publishMavenJavaPublicationToMavenLocal'.
> Failed to publish publication 'mavenJava' to repository 'mavenLocal'
> java.io.FileNotFoundException: __path__\build\publications\mavenJava\pom-default.xml (System nie może odnaleźć określonej ścieżki -- File not found)
The clean is after generating pom file.
When I uncomment line with generatePomFileForMavenJavaPublication.mustRunAfter(clean), I've got error:
> Could not get unknown property 'generatePomFileForMavenJavaPublication' for task ':releaseBuild' of type org.gradle.api.DefaultTask.

Add at the end of your script.
publishMavenJavaPublicationToMavenLocal.mustRunAfter(clean)
There is a task-tree plugin which is very helpful in such situations.
It is handy to distinguish between Configuration and Execution phases of Gradle build when fine-tuning tasks configuration. It will help if you read about Build Lifecycle.
Adding dependencies to the clean task usually gives more headache than benefit. Consider adding only "soft" dependencies like mustRunAfter and add clean task explicitly to your command line:
gradle clean releaseBuild publishToMavenLocal

Related

Gradle test filter doesn't work for complex test task

I have a project with unit tests.
We decided to migrate from testng to JUnit 5 but do it in a couple of iterations.
And now in our project tests for both platforms are present.
I handle it using the following build script:
def commonTestConfig =
{
ignoreFailures = true
...
}
task testNGTests(type: Test) {
useTestNG()
configure commonTestConfig
reports.html.destination = file("$buildDir/reports/testng")
}
task junitTests(type: Test) {
useJUnitPlatform()
configure commonTestConfig
reports.html.destination = file("$buildDir/reports/junit")
}
test {
dependsOn testNGTests
dependsOn junitTests
}
But if I try to run specific test from command line then build fails:
call gradle --warning-mode all test --tests my.package.LicenseTests
Task :compileJava UP-TO-DATE
Task :processResources UP-TO-DATE
Task :classes UP-TO-DATE
Task :compileTestJava UP-TO-DATE
Task :processTestResources UP-TO-DATE
Task :testClasses UP-TO-DATE
Task :testNGTests UP-TO-DATE
Task :junitTests UP-TO-DATE
Task :test FAILED
FAILURE: Build failed with an exception.
* What went wrong: Execution failed for task ':test'.
No tests found for given includes: [my.package.LicenseTests](--tests filter)
I.e. the command above runs all tests(tasks testNGTests and junitTests) without applying provided filter.
And after that tries to find tests to run in test task where no any one are supposed to run.
Is there a way to run both JUnit 5 and testng tests in Gradle cleanly, in a way preserving possibility to pass test filter from command line?

IntelliJ Main Error Migrating Projects: Exception in thread "Timer-0"

Overview
There is an issue when attempting to migrate a Kotlin AppEngine project from an old MacBook Pro (MBP) to a new MBP, when running the Main method and building a .jar file locally.
The Main method in IntelliJ fails intermittently on the new MBP. The old .jar runs as expected on the new MBP, and the new .jar runs as expected on the old MBP.
Expected
Run existing local .jar file from Kotlin project on the old MBP.
Clone Kotlin project from GitHub repository into local IntelliJ project on new MBP.
Build .jar on new MBP.
Run .jar on new MBP.
Host .jar on Google AppEngine instance.
Observed
Running .jar on existing MBP works as expected.
Running main method with the same code runs intermittently on the new MBP after the GitHub repo is cloned locally.
Error
The Main method runs on the old MBP as expected, but not on the new MBP with the following error.
Exception in thread "Timer-0" com.google.cloud.storage.StorageException: 401 Unauthorized
at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:229)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:310)
at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:196)
at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:193)
at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
at com.google.cloud.storage.StorageImpl.internalCreate(StorageImpl.java:192)
at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:154)
at content.SaveContentKt.saveContent(SaveContent.kt:38)
at content.ContentTasks.generateContent(ContentTasks.kt:55)
at content.ContentTasks.run(ContentTasks.kt:41)
at java.base/java.util.TimerThread.mainLoop(Timer.java:556)
at java.base/java.util.TimerThread.run(Timer.java:506)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:554)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:474)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:591)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:307)
... 12 more
Configuration
The gradle-wrapper.properties Gradle, IntelliJ Preferences Gradle JVM, Project SDK, Run/Debug Configurations JRE, and Project language level versions are the same across both machines.
Preferences > Gradle
Use Gradle from: 'gradle-wrapper.properties' file
Gradle JVM: Library/Java/JavaVirtualMachines/12.0.1
File > Project Structure... > Project
Project SDK: 12.0.1
Project language level: 11
Running .jar file: Project Structure > Project Settings > Artifacts > Add > JAR > From modules with dependencies...
Module: coinverse-media.main
Main Class: Initialization
Lastly, build artifact and run .jar file.
build.gradle
buildscript {
ext.kotlin_version = '1.3.61'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation 'com.squareup.retrofit2:retrofit:2.7.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.7.0'
implementation 'com.google.firebase:firebase-admin:6.12.0'
implementation 'com.google.cloud:google-cloud-storage:1.102.0'
implementation 'com.google.apis:google-api-services-youtube:v3-rev20190827-1.30.1'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
Attempted Solutions
Invalidate Caches / Restart...: This appears to fix the issue for a few times running the Main method, then the error continues to show.
./gradlew clean build
Gradle > Reimport All Gradle Projects
Updating to the latest Gradle version.
Ensure existing MBP and new MBP are running on the same IntelliJ/Project/Run configurations.
Potentially related build dependency conflict issue: Guava Dependency Breaking Jar Built With Kotlin.
Build Data
Build scan results
Stack trace
6:09:42 PM: Executing task 'assemble'...
Task :compileKotlin UP-TO-DATE
Task :compileJava NO-SOURCE
Task :processResources NO-SOURCE
Task :classes UP-TO-DATE
Task :inspectClassesForKotlinIC UP-TO-DATE
Task :jar UP-TO-DATE
Task :assemble UP-TO-DATE
BUILD SUCCESSFUL in 75ms
3 actionable tasks: 3 up-to-date
6:09:42 PM: Task execution finished 'assemble'.
Hidden files

Can not publish Java project to Maven via BinTray with Gradle

I have a simple project I'm trying to publish to Maven via BinTray, but have been getting an error.
I have followed a guide to publish to bintray, and appear to have BinTray all set up, as well as access to Sonatype. Signing/etc, all appears to be good.
When I run "./gradlew bintrayUpload" I get an error, but the artifacts do show up on bintray. However I get various POM errors.
adams-MBP:UsedUtil adamhammer2$ ./gradlew clean install
:clean
:compileJava
warning: [options] bootstrap class path not set in conjunction with -source 1.7
Note: /Users/adamhammer2/git/UsedUtil/src/main/java/com/mysaasa/usedutil/CallKeyGenerator.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 warning
:processResources UP-TO-DATE
:classes
:jar
:javadoc
:javadocJar
:sourcesJar
:install
BUILD SUCCESSFUL
Total time: 7.233 secs
adams-MBP:UsedUtil adamhammer2$ ./gradlew bintrayUpload
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:javadoc UP-TO-DATE
:javadocJar UP-TO-DATE
:sourcesJar UP-TO-DATE
:install
:bintrayUpload FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':bintrayUpload'.
> Could not upload to 'https://api.bintray.com/content/adamhammer/maven/used-util/0.9.1/com/mysaasa/used_util/UsedUtil/0.9.1/UsedUtil-0.9.1.pom': HTTP/1.1 400 Bad Request [message:Unable to upload files: Maven group, artifact or version defined in the pom file do not match the file path 'com/mysaasa/used_util/UsedUtil/0.9.1/UsedUtil-0.9.1.pom']
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 12.923 secs
Github project is https://github.com/ahammer/UsedUtil
build.gradle file is
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
}
}
apply plugin: 'java'
sourceCompatibility = 1.7
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.+'
}
ext {
bintrayRepo = 'maven'
bintrayName = 'used-util'
publishedGroupId = 'com.mysaasa.used_util'
libraryName = 'UsedUtil'
artifact = 'usedutil'
libraryDescription = 'A Library for tracking usage in java projects'
siteUrl = 'http://ahammer.github.io/UsedUtil'
gitUrl = 'https://github.com/ahammer/UsedUtil.git'
libraryVersion = '0.9.1'
developerId = 'adamhammer'
developerName = 'Adam Hammer'
developerEmail = 'adamhammer2#gmail.com'
licenseName = 'The Apache Software License, Version 2.0'
licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
allLicenses = ["Apache-2.0"]
}
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'
After publishing I get the error, however in BinTray it registers the upload. When I click add to JCenter however I get another error "- Add a POM file to the latest version of your package."
Instead of using the 3rd party script and out of date plugin, I followed the guide
here https://github.com/bintray/gradle-bintray-plugin
This generated a proper pom file and published to bintray and made my package compatible with jcenter.
For a working build.gradle, you can look at my github for the working version.

Getting NoClassDefFoundError while running PMD task from Gradle

I am getting NoClassDefFoundError while running PMD task via Gradle.
I am having pmd-5.1.1.jar, commons-io-1.4.jar as well as all the other jars in WebContent/WEB-INF/lib directory. My java files are in the directory src\com\company\project
Gradle Build file
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'pmd'
sourceSets.main.java.srcDirs = ['src']
webAppDirName = 'WebContent'
repositories {
flatDir { dirs "WebContent/WEB-INF/lib" }
}
dependencies {
providedCompile fileTree(dir: "WebContent/WEB-INF/lib", include: '*.jar')
}
war {
archiveName "ROOT.war"
}
Error Log
C:\MyWorkspace\MyProject>gradle build
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:war UP-TO-DATE
:assemble UP-TO-DATE
:pmdMain FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':pmdMain'.
> java.lang.NoClassDefFoundError: org/apache/commons/io/IOUtils
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.
BUILD FAILED
Total time: 5.275 secs
This is the first time I am trying Gradle. I am able to build as well as generate WAR but PMD is failing me. Can someone please tell me what am I doing wrong? Thanks in advance :)
I know that You've already found the answer but FYI I'm adding solution to the problem.
Basically You have non standard project structure. First of all, web content should be placed under src/main/webapp (sources under src/main/java and so on). Secondly You should not put diagnostics tools (pmd) under WEB-INF/lib. There's no need to have this jars deployed along with the whole application to the application server.
There was also no declaration of maven repo, so the dependencies could not be resolved (commons-io, asm, jaxen, etc.) and the were missing dependencies under pmd classpath (commons-io, etc.) - note the pmd scope in dependencies block.
Here you can find two projects - with standard and non-standard project layout. Both are configured correctly.
At last found the issue. I needed to resolve pmd and all it's transitive dependencies from a remote repo like Maven Central.
repositories {
mavenCentral()
}
pmd {
toolVersion = "5.1.1"
ignoreFailures = true
}

Cucumber app with gradle runs fine locally but fails on Jenkins

When i run my cucumber based project it behaves as though it cannot find the Steps classes - I can tell because the log on Jenkins is offering code snippets for implementation.
I'm using Gradle and I know there are issues with cucumber-jvm.
The relevant part of the build file:
task cucumber(type: JavaExec) {
dependsOn assemble, compileTestJava
main = "cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['-f', 'pretty', '--glue', 'steps', 'src/test/resources']
systemProperties = System.getProperties()
}
I can't see why running the same command (./gradlew clean cucumber) via Jenkins fails?
Here's the output from Jenkins:
+ ./gradlew -Dapk=/Users/rakesh/workspace1/AcmeApp_4_10_Tiles/bin/AcmeApp_4_10_Tiles.apk clean cucumber
:clean
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar
:assemble
:compileTestJava
:cucumber
Feature: Thrid party request for the Landing page.
TODO: additional requests for box connection
...
You can implement missing steps with the snippets below:
#Given("^the user chooses not to login$")
...
BUILD SUCCESSFUL
Total time: 8.074 secs
$ /Users/rakesh/Apps/adt-bundle-mac-x86_64-20131030/sdk/platform-tools/adb disconnect emulator-5812
[android] Stopping Android emulator
[android] Archiving emulator log
$ /Users/rakesh/Apps/adt-bundle-mac-x86_64-20131030/sdk/platform-tools/adb kill-server
Finished: SUCCESS
I would also like to mention that sometimes this problem occurs,if there are dependencies missing in build.gradle.
In my case,the following statement was missing in main task in build.gradle..
dependsOn assemble, compileTestJava
Adding this,resolved the issue.
I solved the problem and it had nothing to do with cucumber, gradle or Jenkins! I had renamed the steps classes (case change) which completely confused subversion and the java step classes were actually missing!!

Categories

Resources