[java] How to create Java gradle project

How to create Java Gradle project from command line?

It should create standard maven folder layout like on the picture below.

Java Gradle created with Eclipse plugin

UPDATE:

.1. From http://www.gradle.org/docs/current/userguide/tutorial_java_projects.html I need to create file build.gradle with 2 lines

apply plugin: 'java'
apply plugin: 'eclipse'

.2. Add to build.gradle task below, than execute gradle create-dirs

task "create-dirs" << {
   sourceSets*.java.srcDirs*.each { it.mkdirs() }
   sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

.3. Then run gradle eclipse (or corresponding string to other IDE plugin configured)

So is there way to do it in one command?

This question is related to java gradle

The answer is


If you are using Eclipse, for an existing project (which has a build.gradle file) you can simply type gradle eclipse which will create all the Eclipse files and folders for this project.

It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.


I just tried with with Eclipse Neon.1 and Gradle:

------------------------------------------------------------
Gradle 3.2.1
------------------------------------------------------------

Build time:   2016-11-22 15:19:54 UTC
Revision:     83b485b914fd4f335ad0e66af9d14aad458d2cc5

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_112 (Oracle Corporation 25.112-b15)
OS:           Windows 10 10.0 amd64

enter image description here

On windows 10 with Java Version:

C:\FDriveKambiz\repo\gradle-gen-project>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)

And it failed miserably as you can see in Eclipse. But sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project. That is not good enough. I am switching to Intellij for gradle projects:

enter image description here


Unfortunately you cannot do it in one command. There is an open issue for the very feature.

Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.

EDIT

The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.


Finally after comparing all solution, I think starting from build.gradle file can be convenient.

Gradle distribution has samples folder with a lot of examples, and there is gradle init --type basic comand see Chapter 47. Build Init Plugin. But they all needs some editing.

You can use template below as well, then run gradle initSourceFolders eclipse

/*
* Nodeclipse/Enide build.gradle template for basic Java project
*   https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
*   http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
*   1. create folder (or general Eclipse project) and put this file inside
*   2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest; 
* based on `gradle init --type basic`, that does not create source folders 
*/

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

task initSourceFolders { // add << before { to prevent executing during configuration phase
   sourceSets*.java.srcDirs*.each { it.mkdirs() }
   sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use Maven Central for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    //compile fileTree(dir: 'libs', include: '*.jar')
    // The production code uses the SLF4J logging API at compile time
    //compile 'org.slf4j:slf4j-api:1.7.5'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile "junit:junit:4.11"
}

The result is like below.

overview

That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse

editbox


The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.

See: build init plugin documentation


Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.

  1. The application has external jar dependencies
  2. Create a runnable fat jar with all dependent classes copied to the jar
  3. Create a runnable jar with all dependent libraries copied to a directory "dependencies" and add the classpath in the manifest.

Here is the solution :

  • Install the latest gradle ( check gradle --version . I used gradle 6.6.1)
  • Create a folder and open a terminal
  • Execute gradle init --type java-application
  • Add the required data in the command line
  • Import the project into an IDE (IntelliJ or Eclipse)
  • Edit the build.gradle file with the following tasks.

Runnable fat Jar

task fatJar(type: Jar) {
 clean
 println("Creating fat jar")
 manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
 }
 archiveName "${runnableJar}"
 from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
 println("Fat jar is created")
}

Copy Dependencies

task copyDepends(type: Copy) {
   from configurations.default
   into "${dependsDir}"
}

Create jar with classpath dependecies in manifest

task createJar(type: Jar) {
   println("Cleaning...")
   clean
   manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
             it.getName() }.join(' ')
    )
}
  from {
      configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println "${outputJar} created"
}

Here is the complete build.gradle

plugins {
    id 'java'
   id 'application'
}
repositories {
    mavenCentral()
}
dependencies {
  implementation 'org.slf4j:slf4j-api:1.7.30'
  implementation 'ch.qos.logback:logback-classic:1.2.3'
  implementation 'ch.qos.logback:logback-core:1.2.3'
  testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";

//Create runnable fat jar
task fatJar(type: Jar) {
   clean
   println("Creating fat jar")
   manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
  }
  archiveName "${runnableJar}"
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println("Fat jar is created")
}

//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
 from configurations.default
 into "${dependsDir}"
}

//Create runnable jar with dependencies
task createJar(type: Jar) {
 println("Cleaning...")
 clean
 manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
            it.getName() }.join(' ')
    )
 }
 from {
     configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
  println "${outputJar} created"
}

Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar

More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d


I could handle it using a groovy method in build.gradle to create all source folders for java, resources and test. Then I set it to run before gradle eclipse task.

eclipseClasspath.doFirst {
    initSourceFolders()
}

def initSourceFolders() {
    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

Now we can setup a new gradle Java EE project to eclipse with only one command. I put this example at GitHub