emacs debugging and setting breakpoints in java code built with gradle - emacs

GNU Emacs 24.3.1
Gradle 2.2
Hello,
I am using emacs for writing java applications. I have created some java library and building using gradle and testing with spockframework where I have all my test cases.
However, now I want to debug my java code using emacs. However, I haven't found any way of doing this. I would like to set a breakpoint and step through my java code.
Here is my gradle build file:
apply plugin: 'java'
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.igniterealtime.smack:smack-core:4.1.0'
compile 'org.igniterealtime.smack:smack-tcp:4.1.0'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
testCompile 'org.codehaus.groovy:groovy:2.3.6'
}
jar {
baseName = 'SunSmackClient'
version = '1.0.0'
}
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << '-Xlint:unchecked'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.1'
}
Example of my spockframework using test:
public class SmackClientSpec extends Specification {
private SmackClient smackClient;
/* Test 1 */
#IgnoreRest
def 'Create a connection to XMPP server'() {
setup: /* Setup connection object */
def domain = 'domain'
def username = 'username'
def password = 'password'
SmackClient smackClient = new SmackClient()
expect: /* Connection to return true */
smackClient.createConnection(domain, username, password) == true
}
}
Many thanks in advance

Related

SonarQube does not calculate code coverage

I am using postgres sql as my DB in my springboot application .
My SonarQube is unable to calculate code coverage.can someone please guide me in this
build.gradle
plugins {
id 'org.springframework.boot' version "${springBootVersion}"
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'java'
id 'eclipse'
id 'jacoco'
id 'org.sonarqube' version "3.3"
id 'com.google.cloud.tools.jib' version "${jibVersion}"
}
group = 'com.vsi.postgrestoattentive'
if (!project.hasProperty('buildName')) {
throw new GradleException("Usage for CLI:"
+ System.getProperty("line.separator")
+ "gradlew <taskName> -Dorg.gradle.java.home=<java-home-dir> -PbuildName=<major>.<minor>.<buildNumber> -PgcpProject=<gcloudProject>"
+ System.getProperty("line.separator")
+ "<org.gradle.java.home> - OPTIONAL if available in PATH"
+ System.getProperty("line.separator")
+ "<buildName> - MANDATORY, example 0.1.23")
+ System.getProperty("line.separator")
+ "<gcpProject> - OPTIONAL, project name in GCP";
}
project.ext {
buildName = project.property('buildName');
}
version = "${project.ext.buildName}"
sourceCompatibility = '1.8'
apply from: 'gradle/sonar.gradle'
apply from: 'gradle/tests.gradle'
apply from: 'gradle/image-build-gcp.gradle'
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
implementation("org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}")
implementation 'org.springframework.boot:spring-boot-starter-web:2.7.0'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.integration:spring-integration-test'
testImplementation 'org.springframework.batch:spring-batch-test:4.3.0'
implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
implementation 'org.postgresql:postgresql:42.2.16'
implementation 'org.springframework.batch:spring-batch-core:4.1.1.RELEASE'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.1'
implementation group: 'io.micrometer', name: 'micrometer-registry-datadog', version: '1.7.0'
implementation 'com.google.cloud:libraries-bom:26.3.0'
implementation 'com.google.cloud:google-cloud-storage:2.16.0'
testImplementation('org.mockito:mockito-core:3.7.7')
//Below 4 dependencies should be commented in local
implementation 'org.springframework.cloud:spring-cloud-starter-kubernetes-client-all:2.0.4'
implementation 'io.kubernetes:client-java:12.0.0'
implementation("org.springframework.cloud:spring-cloud-gcp-starter-metrics:${gcpSpringCloudVersion}")
implementation 'org.springframework.cloud:spring-cloud-gcp-logging:1.2.8.RELEASE'
testImplementation('org.mockito:mockito-core:3.7.7')
testImplementation 'org.springframework.boot:spring-boot-test'
testImplementation 'org.springframework:spring-test'
testImplementation 'org.assertj:assertj-core:3.21.0'
testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") {
exclude group: "org.junit.vintage", module: "junit-vintage-engine"
}
}
bootJar {
archiveFileName = "${project.name}.${archiveExtension.get()}"
}
springBoot {
buildInfo()
}
test {
finalizedBy jacocoTestReport
}
jacoco {
toolVersion = "0.8.8"
}
jacocoTestReport {
dependsOn test
}
//: Code to make build check code coverage ratio
project.tasks["bootJar"].dependsOn "jacocoTestReport","jacocoTestCoverageVerification"
tests.gradle
test {
finalizedBy jacocoTestReport
useJUnitPlatform()
testLogging {
exceptionFormat = 'full'
}
afterSuite { desc, result ->
if (!desc.parent) {
println "Results: (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
boolean skipTests = Boolean.parseBoolean(project.findProperty('SKIP_TESTS') ?: "false")
if (result.testCount == 0 && !skipTests) {
throw new IllegalStateException("No tests were found. Failing the build")
}
}
}
jacocoTestCoverageVerification {
dependsOn test
violationRules {
rule{
limit {
//SMS-28: Since project is in nascent stage setting code coverage ratio limit to 1%
minimum = 0.5
}
}
}
}
}
sonar.gradle
apply plugin: "org.sonarqube"
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.5"
reportsDir = file("$buildDir/jacoco")
}
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
csv.enabled false
}
}
JenkinsBuildFile
pipeline {
agent any
environment {
// TODO: Remove this
GIT_BRANCH_LOCAL = sh (
script: "echo $GIT_BRANCH | sed -e 's|origin/||g'",
returnStdout: true
).trim()
CURRENT_BUILD_DISPLAY="0.1.${BUILD_NUMBER}"
PROJECT_FOLDER="."
PROJECT_NAME="xyz"
//Adding default values for env variables that sometimes get erased from GCP Jenkins
GRADLE_JAVA_HOME="/opt/java/openjdk"
GCP_SA="abc"
GCP_PROJECT="efg"
SONAR_JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"
SONAR_HOST="http://sonar-sonarqube:9000/sonar"
}
stages {
stage('Clean Workspace') {
steps {
echo "Setting current build to ${CURRENT_BUILD_DISPLAY}"
script {
currentBuild.displayName = "${CURRENT_BUILD_DISPLAY}"
currentBuild.description = """Branch - ${GIT_BRANCH_LOCAL}"""
}
dir("${PROJECT_FOLDER}") {
echo "Changed directory to ${PROJECT_FOLDER}"
echo 'Cleaning up Work Dir...'
// Had to add below chmod command as Jenkins build was failing stating gradlew permission denied
sh 'chmod +x gradlew'
//gradlew clean means deletion of the build directory.
sh './gradlew clean -PbuildName=${CURRENT_BUILD_DISPLAY} -Dorg.gradle.java.home=${GRADLE_JAVA_HOME}'
//mkdir -p creates subdirectories
//touch creates new empty file
sh 'mkdir -p build/libs && touch build/libs/${PROJECT_NAME}-${CURRENT_BUILD_DISPLAY}.jar'
}
}
}
stage('Tests And Code Quality') {
steps {
dir("${PROJECT_FOLDER}") {
echo 'Running Tests and SonarQube Analysis'
withCredentials([string(credentialsId: 'sonar_key', variable: 'SONAR_KEY')]) {
sh '''
./gradlew -i sonarqube -Dorg.gradle.java.home=${SONAR_JAVA_HOME} \
-Dsonar.host.url=${SONAR_HOST} \
-PbuildName=${CURRENT_BUILD_DISPLAY} \
-Dsonar.login=$SONAR_KEY \
-DprojectVersion=${CURRENT_BUILD_DISPLAY}
'''
}
echo 'Ran SonarQube Analysis successfully'
}
}
}
stage('ECRContainerRegistry') {
steps {
withCredentials([file(credentialsId: 'vsi-ops-gcr', variable: 'SECRET_JSON')]) {
echo 'Activating gcloud SDK Service Account...'
sh 'gcloud auth activate-service-account $GCP_SA --key-file $SECRET_JSON --project=$GCP_PROJECT'
sh 'gcloud auth configure-docker'
echo 'Activated gcloud SDK Service Account'
dir("${PROJECT_FOLDER}") {
echo "Pushing image to GCR with tag ${CURRENT_BUILD_DISPLAY}..."
sh './gradlew jib -PbuildName=${CURRENT_BUILD_DISPLAY} -PgcpProject=${GCP_PROJECT} -Dorg.gradle.java.home=${GRADLE_JAVA_HOME}'
echo "Pushed image to GCR with tag ${CURRENT_BUILD_DISPLAY} successfully"
}
echo 'Revoking gcloud SDK Service Account...'
sh "gcloud auth revoke ${GCP_SA}"
echo 'Revoked gcloud SDK Service Account'
}
}
}
}
post {
/*
TODO: use cleanup block
deleteDir is explicit in failure because always block is run
before success causing archive failure. Also cleanup block is not
available in this version on Jenkins ver. 2.164.2
*/
success {
dir("${PROJECT_FOLDER}") {
echo 'Archiving build artifacts...'
archiveArtifacts artifacts: "build/libs/*.jar, config/**/*", fingerprint: true, onlyIfSuccessful: true
echo 'Archived build artifacts successfully'
echo 'Publising Jacoco Reports...'
jacoco(
execPattern: 'build/jacoco/*.exec',
classPattern: 'build/classes',
sourcePattern: 'src/main/java',
exclusionPattern: 'src/test*'
)
echo 'Published Jacoco Reports successfully'
}
echo 'Cleaning up workspace...'
deleteDir()
}
failure {
echo 'Cleaning up workspace...'
deleteDir()
}
aborted {
echo 'Cleaning up workspace...'
deleteDir()
}
}
}
Below is the error which i get in Jenkins console
> Task :sonarqube
JaCoCo report task detected, but XML report is not enabled or it was not produced. Coverage for this task will not be reported.
Caching disabled for task ':sonarqube' because:
Build cache is disabled
Task ':sonarqube' is not up-to-date because:
Task has not declared any outputs despite executing actions.
JaCoCo report task detected, but XML report is not enabled or it was not produced. Coverage for this task will not be reported.
User cache: /var/jenkins_home/.sonar/cache
Default locale: "en", source code encoding: "UTF-8"
Load global settings
Load global settings (done) | time=101ms
Server id: 4AE86E0C-AX63D7IJvl7jEHIL9nIz
User cache: /var/jenkins_home/.sonar/cache
Load/download plugins
Load plugins index
Load plugins index (done) | time=48ms
Load/download plugins (done) | time=91ms
Process project properties
Process project properties (done) | time=9ms
Execute project builders
Execute project builders (done) | time=1ms
Java "Test" source files AST scan (done) | time=779ms
No "Generated" source files to scan.
Sensor JavaSensor [java] (done) | time=8057ms
Sensor JaCoCo XML Report Importer [jacoco]
'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml
No report imported, no coverage information will be imported by JaCoCo XML Report Importer
Sensor JaCoCo XML Report Importer [jacoco] (done) | time=4ms
Can someone please guide me how to resolve this issue of sonar not calculating code coverage
While it could be caused by a number of things, from the logs, it seems likely that it couldn't find the report.
As the first comment says, check to verify that the report is being generated (but not found). If it is generated, then its likely SQ can't find the XML Jacoco report.
Note the error line, near the end:
'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml
An example of defining this location this would be putting this line in sonar-project.properties:
sonar.coverage.jacoco.xmlReportsPaths=build/reports/jacoco.xml
It can also be defined directly in a *.gradle file:
sonarqube {
properties {
property "sonar.coverage.jacoco.xmlReportsPaths", "build/reports/jacoco.xml"
}
}

gradle publishing multi module project to AWS Artifact only publishes META-INF

I recently started using gradle and trying to publish a multi module project to AWS Artifact. My build file for submodules looks like below
Module: core
buildscript {
dependencies {
classpath "org.jsonschema2pojo:jsonschema2pojo-gradle-plugin:0.4.34"
}
}
plugins {
id "net.researchgate.release" version "2.8.0"
}
group "com.local"
apply plugin: "java"
apply plugin: "jsonschema2pojo"
apply plugin: "maven"
apply plugin: "net.researchgate.release"
jar {
baseName "core-schema"
}
release {
tagTemplate = 'core-${version}'
}
jsonSchema2Pojo {
source files("${projectDir}/src/main/resources/json")
generateBuilders = true
}
dependencies {
compile 'commons-lang:commons-lang:2.6'
compile 'javax.validation:validation-api:2.0.0.Final'
compile 'com.fasterxml.jackson.core:jackson-databind:2.9.9'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.9'
}
afterReleaseBuild.dependsOn uploadArchives
spark-example
plugins {
id 'java'
id 'java-library'
id 'scala'
id 'com.github.johnrengelman.shadow' version '1.2.4'
}
apply plugin: 'scalaStyle'
scalaStyle {
configLocation = "${project.rootDir}/scalastyle_config.xml"
includeTestSourceDirectory = true
source = "src/main/scala"
testSource = "src/test/scala"
}
dependencies {
compile group: 'org.apache.spark', name: "spark-core_2.11", version: '2.4.2'
compile group: 'org.apache.spark', name: "spark-sql_2.11", version: '2.4.2'
}
configurations {
runtime.exclude module: 'spark-core_2.11'
runtime.exclude module: 'spark-sql_2.11'
}
compileScala.dependsOn(scalaStyle)
jar {
mainClassName = 'NONE'
baseName "spark-sample"
}
tasks.withType(ScalaCompile) {
ScalaCompileOptions.metaClass.daemonServer = true
ScalaCompileOptions.metaClass.fork = true
ScalaCompileOptions.metaClass.useAnt = false
ScalaCompileOptions.metaClass.useCompileDaemon = false
}
tasks.withType(ScalaCompile) {
configure(scalaCompileOptions.forkOptions) {
memoryMaximumSize = '1g'
jvmArgs = ['-XX:MaxPermSize=512m']
}
}
And main application build file looks like below:
plugins {
id 'java-library'
id 'maven-publish'
}
group "com.local"
subprojects { subproject ->
configurations {
deployer
}
dependencies {
deployer 'org.kuali.maven.wagons:maven-s3-wagon:1.2.1'
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
maven {
url "${aws_url}"
credentials {
username "aws"
password System.env.CODEARTIFACT_AUTH_TOKEN
}
}
}
}
publishing {
publications {
mavenJava(MavenPublication) {
groupId = group
artifactId = artifactName
version = version
from components.java
}
}
repositories {
maven {
url "${aws_url}"
credentials {
username "aws"
password System.env.CODEARTIFACT_AUTH_TOKEN
}
}
}
}
now when I run gradle build I can see jars getting created for all the modules and root project under corresponding build/libs/ directory with code files. However when I do gradle publish I only see root jar getting published with only MANIFEST.NF file as shown below:
Update:
As suggested by #nico I have tried adding the publishing block in allprojects{} block but it is publishing each project with the root project name and overriding all of them as seen in below log. I have also tried adding the publishing block in subproject like mentioned in this post but still same output.
2030009268:spark-store user$ gradle publishAllPublicationsToMavenRepository
> Task :core:publishMavenJavaPublicationToMavenRepository
Multiple publications with coordinates 'com.local:spark-sample:0.0.5-SNAPSHOT' are published to repository 'maven'. The publications will overwrite each other!
> Task :spark-sample:publishMavenJavaPublicationToMavenRepository
Multiple publications with coordinates 'com.local:spark-sample:0.0.5-SNAPSHOT' are published to repository 'maven'. The publications will overwrite each other!
Multiple publications with coordinates 'com.local:spark-sample:0.0.5-SNAPSHOT' are published to repository 'maven'. The publications will overwrite each other!
Updated root project build:
plugins {
id 'java-library'
id 'maven-publish'
}
group "com.local"
subprojects { subproject ->
configurations {
deployer
}
dependencies {
deployer 'org.kuali.maven.wagons:maven-s3-wagon:1.2.1'
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
maven {
url "${aws_url}"
credentials {
username "aws"
password System.env.CODEARTIFACT_AUTH_TOKEN
}
}
}
}
allprojects {
apply plugin: 'maven-publish'
apply plugin: 'java-library'
publishing {
publications {
mavenJava(MavenPublication) {
groupId = group
artifactId = artifactName
version = version
from components.java
}
}
repositories {
maven {
url "${aws_url}"
credentials {
username "aws"
password System.env.CODEARTIFACT_AUTH_TOKEN
}
}
}
}
}
Regarding your main application build file:
Try including the publishing{} block inside of an allprojects{} block or add it to the above subprojects{} block as well. Currently the publishing-specification is only applied on root-project level.

How can I use the full ksqldb client api with gradle?

How can I use the full ksqldb client api with gradle? Why are there 2 different packages?
repositories {
mavenCentral()
jcenter()
maven {
url "https://packages.confluent.io/maven/"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib"
compile group: 'io.confluent.ksql', name: 'ksqldb-api-client', version: '6.0.0'
}
I would like to reference v0.11.0. It contains more methods:
https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-clients/java-client/api/io/confluent/ksql/api/client/Client.html
https://docs.ksqldb.io/en/0.10.0-ksqldb/developer-guide/ksqldb-clients/java-client/api/io/confluent/ksql/api/client/Client.html
import io.confluent.ksql.api.client.ClientOptions
import io.confluent.ksql.api.client.*
fun main()
{
val KSQLDB_SERVER_HOST = "localhost"
val KSQLDB_SERVER_HOST_PORT = 8089
val clientOptions = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT)
val client: Client = io.confluent.ksql.api.client.Client.create(clientOptions)
val topics = client.listTopics() //not available in 6.0.0
}
Edit:
Based on #Hellmar Becker's post I would like to use the standalone (community) version not the commercial Confluent Platform version. It looks like that the CP version uses an older API version anyway.
I found an example how to do this with pom.xml on Github developer guide, but I would like to use a build.gradle file
There are different numbering schemes for the community licensed KSQLDB (currently v0.12) and the commercial Confluent Platform (currently v6.0.1). Maybe this comparison helps: https://docs.confluent.io/platform/current/ksqldb/index.html#ksqldb-standalone-and-ksqldb-for-cp.
I managed to convert the pom.xml to gradle.build file from the developers guide in the following manner:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.4.21'
}
version '1.0-SNAPSHOT'
repositories {
jcenter()
maven() {
url "https://ksqldb-maven.s3.amazonaws.com/maven/"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation "org.jetbrains.kotlin:kotlin-stdlib"
implementation "io.confluent.ksql:ksqldb-api-client:0.11.0"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}

Gradle artifactory plugin * How does one specify the artifact to be sent to Artifactory

I am building an android apk: app/build/outputs/apk/app-debug.apk and would like to have it uploaded to Artifactory.
The build.gradle (see below) generates an entry in my local Artifactory when invoked with: gradlew artifactoryPublish, but, the apk file is not uploaded.
Would someone be so kind as to show me what to add to this script so that the file named above is sent over to Artifactory. Thank you.
Here is build.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
}
}
plugins {
id "com.jfrog.artifactory" version "3.0.1"
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: "com.jfrog.artifactory"
apply plugin: 'maven-publish'
apply plugin: 'java'
artifactory {
contextUrl = 'http://localhost:8081/artifactory'
publish {
repository {
repoKey = 'libs-releases-local'
username = 'admin' //The publisher user name
password = 'password' //The publisher password
maven = true
}
}
}
publishing {
publications {
maven(MavenPublication) {
from components.java
artifact(file('app/build/outputs/apk/app-debug.apk'))
}
}
}

Gradle: illegal repetition error

just started to use artifactory so as to manage all the libraries that i use..therefore i had to have the artifactory plugin. I used the screencast tutorial at http://www.jfrog.com/confluence/display/RTF/Gradle+Artifactory+Plugin and added the buildScript as follows to download the plugin..
buildscript {
repositories {
maven { url 'http://localhost:8081/artifactory/plugins-release'
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
}
}
dependencies {
classpath (
group: 'org.jfrog.buildinfo', name:
'build-info-extractor-gradle', version: '2.1.0'
)
}
}
then in gradle.properties file in my gradleUserHomeDir, i have the following, the password is encrypted by artifactory.
artifactory_user=admin
artifactory_password={DESede}ifW8DYgu849GR8EnzUMOlj/L8cwy6FQfRZgHHTyj9L0=
artifactory_contextUrl=http://localhost:8081/artifactory
Then i ran gradle tasks. the plugin was downloaded yes, but something is going wrong. this is the output
The TaskContainer.add() method has been deprecated and is scheduled to be removed in Gradle 2.0. Please use the create() method instead.
FAILURE: Build failed with an exception.
Where:
Build file 'S:\src\JEE-Workspace\movieplex7\build.gradle' line: 47
What went wrong:
A problem occurred evaluating root project 'movieplex7'.
Illegal repetition
{DESede}ifW8DYgu849GR8EnzUMOlj/L8cwy6FQfRZgHHTyj9L0=
here is the build.gradle
buildscript {
repositories {
maven { url 'http://localhost:8081/artifactory/plugins-release'
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
}
}
dependencies {
classpath (
group: 'org.jfrog.buildinfo',
name: 'build-info-extractor-gradle', version: '2.1.0'
)
}
}
apply plugin: 'war'
apply plugin: 'maven'
apply plugin: 'eclipse-wtp'
apply plugin: 'artifactory'
project.description = 'Java EE 7 Hands-on Lab'
version= '1.0'
group = 'org.glassfish.movieplex7'
artifactory {
contextUrl = "${artifactory_contextUrl}"
publish {
repository {
repoKey = 'libs-release-local'
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
resolve {
repository {
repoKey = 'libs-release' username = "${artifactory_user}"
password = "${artifactory_password}" maven = true
}
}
}
dependencies {
providedCompile 'javax:javaee-api:7.0'
//providedCompile 'org.glassfish.main.extras:glassfish-embedded-web:4.0'
}
it suddenly worked when i put each property in its own line like this
`repoKey = 'libs-release'
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true`