Compile groovy project and run JUnit tests via Jenkins - jenkins

I googled for ages now and I give up, the buzz word Groovy + Jenkins is bringing up so many false flags...
I have a Groovy project I developed in IntelliJ, it contains also a JUnit.groovy with unit tests. Now this is a script for SoapUI, no need for Maven, Ant nor Grails, but I would like to be able to compile those files on Jenkins and run the unit tests after. Is it possible to build and test those files on Jenkins? So far all solutions seem to be me manually running groovyc (commited with my repository) and then running JUnit on the JUnit.class.
So before I start to dig deeper and write a Maven, Grails or Ant file, is there another way that does not involve me pushing the GroovySDK on my git? Or is there may be a simple build script, not involving 20 libraries and steps that would build the groovy sources and run the JUnit tests :) ?
I'm new to Jenkins obviously ;), thanks for your input.
Update:
So for all as newbie as me, what was required? First I changed my local source code to a gradle project (remember to activate AutoImport in IntelliJ) and also activate the creation of the JUnit xml and since I do not use Maven and the system is "offline" we have the libs in git anyway so my build.gradle is:
version '2.5-SNAPSHOT'
apply plugin: 'groovy'
dependencies {
compile fileTree(dir: '../Library', include: ['*.jar'])
}
test {
reports {
junitXml.enabled = true
html.enabled = true
}
}
sourceCompatibility = 1.8
set up gradle wrapper for the project via gradle wrapper for the gradlew.bat
then I added a post-commit in my git-/.hooks/ so my Jenkins is triggered upon commit via curl http://jenkins:8080/git/notifyCommit?url=https://git.git&branches=dev
finally set up a pipeline on jenkins:
#!groovy
node {
stage('Checkout') {
git branch: 'dev', credentialsId: 'youwish', url: 'https://git.git'
}
stage('Build') {
dir('./Modules') {
gradle('clean')
gradle('compileTestGroovy')
}
}
stage('UnitTest') {
dir('./Modules') {
gradle('test')
junit '/build/test-results/**/TEST-*.xml'
}
}
stage('IntegrationTest') {
stage('CodeTableDownload') {
dir('./SoapUi') {
bat 'AutoRun.bat'
junit '/results/**/*-JUNIT.xml'
}
}
}
}
def gradle(command) {
bat "./gradlew.bat $command"
}

There's a Groovy plugin for Jenkins that will let you execute Groovy scripts on Jenkins.
But, why not let something like Gradle do the build and run the test for you? A minimal Gradle build file for Groovy that will do both is:
apply plugin: 'groovy'
repositories {
jcenter()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.12'
testCompile 'junit:junit:4.12'
}
You don't have to commit the GDK, just declare a dependency.

Related

'.' is not recognized as an internal or external command for Gradle command in Jenkins when gradlew script is executed

I try to run SonarQube analysis for a Gradle project in a Jenkins Pipeline using the following code:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat "./gradlew sonarqube"
}
}
}
The Gradle plugin is installed in Jenkins but I am getting the following error:
05:15:05 D:\*\*\*\*\*\*>./gradlew sonarqube
05:15:05 '.' is not recognized as an internal or external command,
Two things are incorrect in your code. On Windows machines you have to:
use backslashes instead of slashes in paths (./command → .\command)
execute script written for Windows (gradlew is a Unix script, gradlew.bat is a Windows script)
This code should work:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat '.\\gradlew.bat sonarqube'
}
}
}
Gradle Wtapper by default is provided with two script gardlew and gradlew.bat. If your project doesn't have the gradlew.bat file, execute on your Unix machine ./gradlew wrapper. The missing file will be generated.
Btw. You don't need the Jenkins Gradle plugin, when you use Gradlew Wrapper. The plugin is required when you want to provide Gradle installations for jobs, example:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat "${tool(name: 'toolId', type: 'gradle')}\\bin\\gradle.bat sonarqube"
}
}
}
toolId must much the identifiers used in the Jenkins Global Tool Configuration, examples: gradle-6.X, gradle-6.8.3 etc.

Jenkins, Gradle : How to publish Dependency report to Sonar Dashboard

Currently we're using Jenkins free style job for Gradle project and using following commands to run Sonar and Dependencycheck
./gradlew clean build sonarqube dependencyCheckAnalyze \
and I'm getting following message
Analyzing /opt/jenkins_slave_home/workspace/AA/package-lock.json - however, the node_modules directory does not exist. Please run npm install prior to running dependency-check
Generating report for project AA_ArbitraryBuild
Found 0 vulnerabilities in project AA
and we can able to see a file inside "ws/build/reports/" but it dint scanned anything.
Following are the "build.gardle" file
buildscript {
repositories {
maven { url artifactoryRepoUrl }
mavenCentral()
}
dependencies {
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7'
classpath 'org.owasp:dependency-check-gradle:6.0.3'
}
}
apply plugin: 'org.sonarqube'
apply plugin: 'org.owasp.dependencycheck'
sonarqube {
properties {
property 'sonar.projectName', sonarProjectName
property 'sonar.projectKey', sonarProjectKey
property 'sonar.host.url', sonarHostUrl
property 'sonar.login', sonarAuthToken
property 'sonar.dependencyCheck.reportPath', sonarDependencyCheckReport
property 'sonar.dependencyCheck.htmlReportPath', sonarDependencyCheckHTMLReport
}
}
Can you plz help on what are the additional steps that I need to add.
You've got all you need to push result to sonar. Make sure that you provide right path for your owasp vulnerabilities report for sonar plugin. It's sonar.dependencyCheck.reportPath and should point to build/reports directroy, and if you produce html report file you can point it with sonar.dependencyCheck.htmlReportPath.

How to publish a WAR file to maven (Nexus) repository with Jenkins via Gradle task

I'm struggling with deploying the war file to Nexus repository using Jenkinsfile via Gradle task.
The war is being created successfully. I have also no problem with deploying JARs (since there are examples everywhere how to do it).
So I have this publishing section in my build.grade:
publishing {
repositories {
maven {
URI releasesUrl = new URI("${UploadURL}/repository/releases")
URI snapshotsUrl = new URI("${UploadURL}/repository/snapshots")
afterEvaluate {
url version.endsWith("SNAPSHOT") ? snapshotsUrl : releasesUrl
}
credentials {
username "${user}"
password "${password}"
}
}
}
publications {
mavenWeb(MavenPublication) {
from components.web
artifact war.archivePath
}
}
}
With pluggins:
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
The URL for repositories is also specified in the build script correctly (test publish with the jar works just fine)
And the Jenkinsfile:
stage ('Publish war') {
steps {
sh "sh gradlew publish"
}
}
Currently I'm getting this error from jenkins build:
Task :publishMavenWebPublicationToMavenRepository FAILED
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':publishMavenWebPublicationToMavenRepository'.
Failed to publish publication 'mavenWeb' to repository 'maven'
Invalid publication 'mavenWeb': multiple artifacts with the identical extension and classifier ('war', 'null').
I'm quite sure that the problem is within "publications" part of Gradle task.
For publishing the Jars I have been using it like this:
[...]
publications {
mavenJava(MavenPublication) {
from components.java
artifact sourceJar
}
}
[...]
task sourceJar(type: Jar) {
classifier 'sources'
from sourceSets.main.java
}
I do not know how to configure from, artifact and classifier for this task. I do not even know if all of these parameters should be configured... Could anyone help me with that?
It turned out, that the origin of the problem was this section:
afterEvaluate {
url version.endsWith("SNAPSHOT") ? snapshotsUrl : releasesUrl
}
This feature works with Gradle 5.X version however, I was using Gradle 4.8. That lead to null instead of propper url value...
Unfortunately, it took a while since the exception message does not suggest where the problem was.

gradle artifactorypublish: jenkins pipeline does not publish properties

I'm trying to set up a jenkins pipeline for publishing a zip file to jfrog artifactory.
I am using com.jfrog.artifactory plugin to do so. This works great from command line gradle and I can run the artifactoryPublish task to publish the artifacts and tie them back to the module, which then has a tie back to the artifacts.
The artifacts show up with the properties:
build.name = `projectname`
build.number = `some large number`
And I can click from them to the build/module and back to the artifact.
However, when I run this from a jenkinsfile pipeline, the artifacts get published and get tied back to the module, but then the module does not successfully tie the module back to the artifacts.
The artifacts do not receives the build.name and build.number properties and i cannot click from the module back to the artifacts, as the module cannot find or resolve the paths back to the artifacts(a zip file and a generated pom).
I am passing the params from jenkins like:
ORG_GRADLE_PROJECT_buildInfo.build.number=${env.BUILD_NUMBER} which seems to work on other projects... but for whatever reason I cannot shake it.
I can include more jenkinsfile if that would help debug, but i'm really just checking out a repository and trying to publish it.
I have been reading heavily the documentation here:
https://www.jfrog.com/confluence/display/RTF/Gradle+Artifactory+Plugin
and haven't been able to make it work through -Pproject stuff.
Does anyone have any idea what else I can try? i don't really want to use the jenkins pipeline artifactory plugin directly because it's so nice to be able to deploy from the command line too.
build.gradle:
publishing {
publications {
ManualUpdaterPackage(MavenPublication){
artifact assembleManualUpdaterPackage
}
}
}
artifactory {
contextUrl = "${artifactoryUrl}" //The base Artifactory URL if not overridden by the publisher/resolver
publish {
defaults {
publications('ManualUpdaterPackage')
}
repository {
repoKey = project.version.endsWith('-SNAPSHOT') ? snapshotRepo : releaseRepo
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
}
task assembleManualUpdaterPackage (type: Zip){
dependsOn anotherTask
from (packageDir + "/")
include '**'
// archiveName "manualUpdaterPackage-${version}.zip"
destinationDir(file(manualUpdaterZipDir))
}
jenkinsfile snip:
withCredentials(
[
[
$class : 'UsernamePasswordMultiBinding',
credentialsId : 'validcreds',
passwordVariable: 'ORG_GRADLE_PROJECT_artifactory_password',
usernameVariable: 'ORG_GRADLE_PROJECT_artifactory_user'
]
]
) {
withEnv(
[
"ORG_GRADLE_PROJECT_buildInfo.build.number=${env.BUILD_NUMBER}",
"ORG_GRADLE_PROJECT_buildInfo.build.name=${artifactName}",
"ORG_GRADLE_PROJECT_buildInfo.build.url=${env.JOB_URL}"
]
) {
sh 'chmod +x gradlew'
sh "./gradlew --no-daemon clean artifactoryPublish"
}
}
https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins#WorkingWithPipelineJobsinJenkins-GradleBuildswithArtifactory
Eventually my coworker recommended looking into the Artifactory Pipeline Gradle plugin instead. It is very nice to work with and we've had much quicker success with it.

Running shell scripts in a Jenkins DSL mavenJob

I'm writing a Jenkins (version 2.6) DSL that will allow me to check out and build a Maven project, run a shell script and deploy it to Artifactory.
mavenJob("test-build") {
multiscm {
...
}
steps {
shell ("bash build-scripts/script.sh")
}
goals("clean install")
configure{ project ->
project/publishers << 'org.jfrog.hudson.ArtifactoryRedeployPublisher' {
details {
artifactoryUrl('<url>')
artifactoryName('<name>')
repositoryKey('libs-release-local')
snapshotsRepositoryKey('libs-snapshot-local')
}
deployBuildInfo(true)
deployArtifacts(true)
evenIfUnstable(false)
}
publishers {
archiveJunit('target/*/.xml')
publishBuilder {
discardOldBuilds(7,10)
}
}
}
The job only works if I remove the steps{} block as steps aren't permitted in a mavenJob. I've tried using a freeStyleJob, but ArtifactoryRedeployPublisher doesn't work.
What do I have to do to run my shell script?
If you want shell script to be run ahead of maven goal, you can use this
preBuildSteps {
// Runs a shell script.
shell(String command)
}
Or if you want the shell script run after the maven goal, you can use this one
mavenJob('example-1') {
postBuildSteps {
shell("echo 'run after Maven'")
}
}
For detail, you can check the job dsl api viewer
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.jobs.MavenJob.postBuildSteps
It is very easy and handy tool.
Br,
Tim

Resources