Gradle: run a specific java class - gradle

My gradle file looks like this:
apply plugin: 'java'
apply plugin:'application'
mainClassName = "com.example.Main"
project.buildDir = 'target'
version = '0.1'
jar{
destinationDir=project.buildDir
}
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.+'
}
When I want to run, I type gradle run and it will execute com.example.Main class. I was wondering if there is a mechanism to execute specific class without changing the build.gradle. What I ultimately want is something similar to mvn exec:java -Dexec.mainClass="com.example.Main", where you can specify the main class.

You can set gradle project properties with -P, for example:
gradle run -PclassToExecute=com.myClass
and in the script:
mainClassName=classToExecute

If you change your build script to:
mainClassName = System.getProperty("exec.mainClass") ?: "default.Main"
You can execute a particular class with: gradle run -Dexec.mainClass=com.example.Main

Related

Maven Project in IntelliJ, include Gradle Plugin

I'm new to IntelliJ and Gradle
I've got a Maven Project with a lot of dependencies which works on it's own.
Now I should use the libraries from that Project and create a Plugin for IntelliJ in Gradle.
I tried various ways to add the dependencies in the IntelliJ Module Settings, which allowed me to use the needed classes to write my code and build it. However, when I tried to start the plugin, it couldn't find the classes anymore.
I think I need to specify these in the build.gradle but I don't understand exactly how, as all the ways I tried didn't worked.
build.gradle:
plugins {
id 'java'
id 'org.jetbrains.intellij' version '0.6.5'
}
group 'com.ast.devmate.intellij'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
**compile 'com.ast.devmate.intellij:root:1.0.0-SNAPSHOT'**
}
// See https://github.com/JetBrains/gradle-intellij-plugin/
intellij {
version '2019.1'
}
patchPluginXml {
changeNotes """
Add change notes here.<br>
<em>most HTML tags may be used</em>"""
}
gets me this:
Could not find com.ast.devmate.intellij:root:1.0.0-SNAPSHOT.
without the line marked with ** I got a lot of
error: package foo does not exist
import foo;
It looks like you're trying to access a custom library using Gradle. You will probably need to use a file dependency: How to add local .jar file dependency to build.gradle file?

Unable to pass argument from gradle command line to Spring project (not Boot)

I am developing Spring project.
I would like to load credentials from the command line not storying them in the code. I'm trying to execute this gradle command
gradlew build -Dspring.datasource.username=tester
and when I startup the Spring project, the program stops on a breakpoint and I see whether variable is declared or not. I have tried using -P instead of -D but it still didn't help.
I deploy the spring app remotely using bmuschko plugin I've tried to use, but also without success. I checked in java code Properties by using System.getProperties() and Environment object supported by Spring.
gradlew cargoredeployremote -Dspring.datasource.username=tester
Application properties are loaded succesfully.
IMPORTANT: I saw many tutorials how to make it but using Spring Boot I use just selected components from Spring.
For instance: http://nixmash.com/post/passing-arguments-to-spring-boot - this doesn't work in my case because I have no bootRun task.
Any ideas? Am I missing something in my steps?
Here is my build.gradle
group 'example'
version '1.0.0'
apply plugin: 'application'
apply plugin: 'war'
apply plugin: 'java'
apply plugin: 'com.bmuschko.cargo'
apply plugin: 'org.liquibase.gradle'
compileJava.options.encoding = 'UTF-8'
mainClassName = 'api.optic.config.WebAppInitializer'
sourceCompatibility = 1.8
buildscript {
repositories{
jcenter()
mavenCentral()
}
dependencies{
classpath 'com.bmuschko:gradle-cargo-plugin:2.2.3'
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-RC3'
classpath 'org.liquibase:liquibase-core:3.4.1'
classpath "org.liquibase:liquibase-gradle-plugin:1.2.4"
classpath "mysql:mysql-connector-java:5.1.13"
}
}
project.ext {
springVersion = "4.3.6.RELEASE"
junitVersion = "5.0.0-RC3"
}
repositories {
mavenCentral()
}
dependencies {
compile "org.springframework:spring-core:${springVersion}"
compile "org.springframework:spring-context:${springVersion}"
compile "org.springframework:spring-context-support:${springVersion}"
compile "org.springframework:spring-beans:${springVersion}"
compile "org.springframework:spring-web:${springVersion}"
compile "org.springframework:spring-webmvc:${springVersion}"
compile "org.springframework:spring-orm:${springVersion}"
compile "org.springframework:spring-oxm:${springVersion}"
compile "org.springframework:spring-jdbc:${springVersion}"
compile "org.springframework:spring-test:${springVersion}"
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'
compile group: 'javax.mail', name: 'javax.mail-api', version: '1.5.6'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.2'
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.0.pr2'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jdk8', version: '2.9.0.pr2'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.0.pr2'
compile 'javax.servlet:javax.servlet-api:3.1.0'
testCompile "org.junit.jupiter:junit-jupiter-api:${junitVersion}"
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}
cargo {
containerId = 'tomcat8x'
port = 8080
deployable {
context = 'example'
}
remote {
hostname = 'host.name.com'
username = 'tomcat'
password = 'pass'
}
Basically were 2 issues
1. Name mismatch: in application.properties the name inside the ${} was different than this provided from command-line
Solution:
application.properties
spring.datasource.username=${username}
and in gradle command-line
gradle build -Pusername=tester
2. Dot issue with gradle:
Can't put
gradle build -Pspring.datasource.username=tester
even if you have in application.properties
spring.datasource.username=${spring.datasource.username}
because you get an exception:
Execution failed for task ':processResources'.
Could not copy file '.\src\main\resources\application.properties' to '.\build\resources\main\application.properties'.
Solution:
Instead of dots use _ sign
gradle build -Pspring_datasource_username=tester
and in Application properties
spring.datasource.username=${spring_datasource_username}

Can I remove the 'jar' task in gradle build?

When I use the code below, a file of jar will generate after gradle build.
apply plugin 'java'
Is there any settings won't generate the file of jar??
I can write a custom plugins,but the code below was wrong.
dependencies {
compile project(':crm.common')
testCompile group: 'junit', name: 'junit', version: '4.12'
}
I want find a way that donot generate the file of jar.
And can run compile in dependencies.
Is there any way can do that???
You can do that by 2 ways:
explicitly exclude the jar task from execution:
gradle build -x jar
disable the jar task in build.gradle:
apply plugin: 'java'
jar.enabled = false
This worked for me:
configurations.archives.with {
artifacts.remove artifacts.find { it.toString().contains("jar") }
}

Gradle dependency for compile time only and test

I am basically looking for a way to mimic the maven dependency provided. I am building a jar (an extension to a db driver), which depends on another jar (the db driver), but I do not want to include that jar.
I am able to use compileOnly to achieve that, however now the tests won't run or compile as the required jar is not included in tests.
I tried through the list of available dependencies like testCompile, however I could not find one that makes the jar available at compile time and when the tests run and compile.
How would I include that jar properly?
Edit: As requested, the build.gradle file:
group 'com.mygroup'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compileOnly "org.mongodb:mongodb-driver:3.3.0"
testCompile "org.mongodb:mongodb-driver:3.3.0"
}
Listing the dependency twice does work, however obviously is not a very nice solution
You can extend your testCompile configuration from the compileOnly configuration:
configurations {
testCompile.extendsFrom compileOnly
}
I use the following;
sourceSets {
// Make the compileOnly dependencies available when compiling/running tests
test.compileClasspath += configurations.compileOnly
test.runtimeClasspath += configurations.compileOnly
}
which is a line longer than the answer from tynn, but makes the intent clearer IMHO,

Applying Gradle Dependency-Check plugin

I am trying to use the dependency.check from the following link and have been unable to get it to run properly (at all) when following the instructions given.
https://github.com/jeremylong/DependencyCheck/tree/master/dependency-check-gradle
When trying to build with the apply plugin and additional dependency the fails on startup and it throws the following error.
Where:
Build file '/Users/aaron/work/backups/eiss/build.gradle' line: 25
What went wrong:
A problem occurred evaluating root project 'eiss'.
Failed to apply plugin [id 'dependency.check']
Plugin with id 'dependency.check' not found.
I made a little progress when making some changes but was still ultimately unsuccessful.
First, I commented out the apply plugin line.
Next, I switched:
classpath "com.thoughtworks.tools:dependency-check:0.0.7"
over to:
compile "com.thoughtworks.tools:dependency-check:0.0.7"
After these two changes it began recognizing the path and I was able to see it grabbing the items from the repository.
Even with the path correct I am still having issues with the apply plugin line with it throwing the same error whenever I place it into the script or even try to change the '.' in it into a '-' (both are used in the instructions and in different repository examples).
Any help on this issue would be appreciated! Thanks
lastly here is the build.gradle script. I didn't want to just leave this blob right in the center of the post.
defaultTasks 'assemble'
// For third party libs that are widely used, keep versions in one place
ext {
MONGO_JAVA_DRIVER = "org.mongodb:mongo-java-driver:2.12.3"
RABBITMQ_VERSION = "com.rabbitmq:amqp-client:3.4.3"
LOG4J = "log4j:log4j:1.2.16"
// For groovy there are multiple libs, just capture version number and use lib-name-$GROOVY_VERSION
GROOVY_VERSION = "2.3.6"
}
//
// Common settings for all projects
//
subprojects {
defaultTasks 'assemble'
apply plugin: 'groovy'
apply plugin: 'maven'
apply plugin: 'codenarc'
apply plugin: 'dependency.check'
targetCompatibility = "1.6"
sourceCompatibility = "1.6"
repositories {
mavenCentral()
}
dependencies {
compile LOG4J
compile "org.codehaus.groovy:groovy:${GROOVY_VERSION}"
compile "org.codehaus.groovy:groovy-json:${GROOVY_VERSION}"
compile "org.codehaus.groovy:groovy-templates:${GROOVY_VERSION}"
compile "com.thoughtworks.tools:dependency-check:0.0.7"
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile "org.codehaus.groovy:groovy-test:${GROOVY_VERSION}"
testCompile "org.hamcrest:hamcrest-core:1.3"
}
clean.doLast {
// The archive path is configured via the jar tasks. Can't use
// delete jar.archivePath because that will configure the delete with
// the wrong (default) path of build/libs/<component.jar>
jar.archivePath.delete()
jarSources.archivePath.delete()
}
//--------------------------------------------------------------------
// Run and test
//--------------------------------------------------------------------
test {
// Uncomment to see standard output when running tests
testLogging.showStandardStreams = true
// This causes tests to run even when nothing has changed
outputs.upToDateWhen { false }
maxParallelForks = 1
}
task runClass(dependsOn: 'classes', type: JavaExec) {
if (project.hasProperty('classToRun')) {
if (project.hasProperty('arguments')) {
args(arguments.split(','))
}
classpath = sourceSets.main.runtimeClasspath
main=classToRun
}
}
//run this task to create source jars
task jarSources(type:Jar){
destinationDir = new File(projectDir.parent + "/sourcelibs")
from sourceSets.main.allSource
classifier 'sources'
}
}
You added plugin dependency in a wrong place, to the dependencies of your project, not a build script itself, which will use it. Try to add buildscript dependencies, as it's made in the example of plugin installation
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.thoughtworks.tools:dependency-check:0.0.7'
}
}
And then return your apply plugin
apply plugin: 'dependency.check'
Though this is very old post, accepted answer is using legacy plugin application, whereas below could be used while using the plugins DSL: https://plugins.gradle.org/plugin/org.owasp.dependencycheck
plugins {
id "org.owasp.dependencycheck" version "7.3.0"
}
With recent version of gradle it is below steps
add id 'com.diffplug.spotless' version '6.3.0' in plugins section like
plugins {
id 'com.diffplug.spotless' version '6.3.0'
}
And define your task to generate required format reports. Here for e.g. xml and json will be generated along with the html report
dependencyCheck{
formats=['xml','json']
check.dependsOn(dependencyCheckAnalyze)
}
And this can be integrated with Sonar by adding below properties to sonare.properties file (Provide dependency plugin is installed already on the sonar)
sonar.dependencyCheck.xmlReportPath=build/reports/dependency-check-report.xml
sonar.dependencyCheck.jsonReportPath=build/reports/dependency-check-report.json
sonar.dependencyCheck.htmlReportPath=build/reports/dependency-check-report.html

Resources