[Jakarta EE 8 application development with Gradle] 2. Project creation

Introduction

This article is a continuation of [Jakarta EE 8 application development with Gradle] 1. Environment construction. In the previous article, we built a development environment. In this article, we will create a Gradle project.

Eclipse Gradle settings

When using the Gradle project in Eclipse, make the following settings to use the Gradle installed in the previous environment settings. Start Eclipse, open Window> Settings, select Gradle and make the following changes:

item Contents
Local installation directory Gradle installation folder
Java home Jakarta EE 8

image.png

After making changes, click Apply and Close.

Creating a Gradle project

There are two ways to create a Gradle project, one is to use Eclipse and the other is to create it on the command line. I will introduce each of them.

Create Gradle project in Eclipse

In Eclipse, click File> New> Gralde Project. image.png

Enter the project name and click Next. image.png

Leave the settings as they are and click Next. image.png

After a while, the following screen will be displayed. Click Finish. image.png

The Gradle project is created and displayed on the Package Explorer. image.png

Create Gradle project on command line

Open a command line and go to the folder where you want to create your project. Create a folder that will be the project name.

c:\projects>mkdir jakartaeesample2

c:\projects>dir
The volume label on drive C is Windows
Volume serial number is F06A-A652

 c:\projects directory

2020/03/29  12:11    <DIR>          .
2020/03/29  12:11    <DIR>          ..
2020/03/29  12:11    <DIR>          jakartaeesample2
0 files 0 bytes
3 directories 134,858,534,912 bytes of free space

c:\projects>

Go to the folder you created and run gradle init --type java-library. Enter 1 for the build script DSL choice and 1 for the test framework choice. The Project name and Source package will be left as default, so leave them blank and enter Enter.

c:\projects>cd jakartaeesample2

c:\projects\jakartaeesample2>gradle init --type java-library
Starting a Gradle Daemon (subsequent builds will be faster)

Select build script DSL:
  1: Groovy
  2: Kotlin
Enter selection (default: Groovy) [1..2] 1

Select test framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit 4) [1..4] 1

Project name (default: jakartaeesample2):
Source package (default: jakartaeesample2):

> Task :init
Get more help with your project: https://docs.gradle.org/6.2.2/userguide/java_library_plugin.html

BUILD SUCCESSFUL in 3m 57s
2 actionable tasks: 2 executed
c:\projects\jakartaeesample2>

When BUILD SUCCESSFUL is displayed, the project creation is complete. Import the created project from Eclipse. Start Eclipse and click File> Import. image.png

Gradle> Select an existing Gradle project and click Next.

image.png

Select the project folder you just created in the project root directory and click Next. image.png

Keep the default settings and click Next. image.png

After a while, the following screen will be displayed. Click Finish. image.png

The imported Gradle project is displayed in the Package Explorer. image.png

Add gradle.properties

After creating your Gradle project, add a properties file, gradle.properties, to your build.gradle for use. Right-click on the project name in Package Explorer and select New> File.

Enter gradle.properties for the file name and click Finish. image.png

The gradle.properties file will be added and displayed in the editor. Enter the following contents.

gradle.properties


#########################
 # gradle.properties for jakartaeesample2
 # author:         sunnycloudy764
 # since:          2020/03/27
 # Gradle version: 6.2.2
#########################

#########################
# base setting
#########################
groupName=jakartaeesample2
artifactid=jakartaeesample2
buildVersion=0.0.1
appName=jakartaeesample2
encoding=UTF-8
jdkVersion=11

#####################
# plugin version
#####################
spotbugsVersion = 4.0.5
flywayVersion = 6.3.2

#####################
# plugin tool version
#####################
checkstyleToolVersion = 8.31
spotbugsToolVersion = 4.0.1

#####################
# library version
#####################
JakartaEEAPIVersion = 8.0
PostgreSQLVersion=42.2.11

slf4jVersion = 1.7.30
logbackVersion = 1.2.3

commonsCollections4Version = 4.4
commonsLang3Version = 3.10
commonsIoVersion = 2.6

lombokVersion=1.18.12

junitVersion = 4.13
hamcrestVersion = 1.3
assertjVersion = 3.15.0
assertjdbVersion = 1.3.0
mockitoVersion = 3.3.3
jacocoCoreVersion=0.8.5

h2Version = 1.4.200
dbSetupVersion = 2.1.0

arquillianJunitContainerVersion=1.6.0.Final
arquillianJacocoVersion=1.1.0
arquillianPayaraEmbeddedVersion=2.2
payaraEmbeddedAllVersion=5.201

#####################
# flyway settings
#####################
flywayuser=postgresql
flywaypassword=xxxxxxx
flywaydriver = org.postgresql.Driver
flywayurl = jdbc:postgresql://localhost:5432/testdb
flywaytarget = 0.0.1
outOfOrder = false
validateOnMigrate = true

#####################
# project facet
#####################
javaFacet = 11
webFacet = 4.0
jsfFacet = 2.3
glassfishFacet = 5.0

#####################
# glassfish settings
#####################
glassfishHome = C:/payara/payara-5.201/payara5/glassfish
glassfishDomain = domain1
isRemote = false
remoteIP = 127.0.0.1

Modify build.gradle

Then modify build.gradle to develop your Jakarta EE application. Please change as follows.

build.gradle


/*
 ******************************
 * build.gradle for jakartaeesample2
 * author:         sunnycloudy764
 * since:          2020/03/27
 * Gradle version: 6.2.2
 ******************************
 */
plugins {
  id "com.github.spotbugs" version "${spotbugsVersion}"
  id "org.flywaydb.flyway" version "${flywayVersion}"
}

apply plugin: 'project-report'
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'
apply plugin: 'checkstyle'
apply plugin: 'jacoco'

sourceCompatibility = "${jdkVersion}"
targetCompatibility = "${jdkVersion}"

tasks.withType(AbstractCompile)*.options*.encoding = "${encoding}"
tasks.withType(GroovyCompile)*.groovyOptions*.encoding = "${encoding}"
[compileJava, compileTestJava, javadoc].each { it.options.encoding = "${encoding}" }

version = "${buildVersion}"
group = "${groupName}"

configurations {
	all*.exclude module: 'slf4j-jdk12'
	all*.exclude module: 'slf4j-jdk14'
    all*.exclude module: 'servlet-api'
    assertj
}

repositories {
   mavenCentral()
   maven { url 'http://repository.jboss.org/nexus/content/groups/public' }
}

dependencies {
	//Jakarta EE API
	compileOnly group: 'jakarta.platform', name: 'jakarta.jakartaee-api', version: "${JakartaEEAPIVersion}"
	testCompileOnly group: 'jakarta.platform', name: 'jakarta.jakartaee-api', version: "${JakartaEEAPIVersion}"

	//JDBC driver (PostgreSQL)
	implementation group: 'org.postgresql', name: 'postgresql', version: "${PostgreSQLVersion}"

	//SLF4j + logback
	implementation group:'org.slf4j', name: 'slf4j-api', version: "${slf4jVersion}"
	implementation group:'ch.qos.logback', name: 'logback-classic', version: "${logbackVersion}"
	implementation group:'ch.qos.logback', name: 'logback-core', version: "${logbackVersion}"

	//Apache Commons
	implementation group:'org.apache.commons', name: 'commons-collections4', version: "${commonsCollections4Version}"
	implementation group:'org.apache.commons',name:'commons-lang3',version:"${commonsLang3Version}"
	implementation group:'commons-io', name:'commons-io',version:"${commonsIoVersion}"

	//Lombok
	annotationProcessor group: 'org.projectlombok', name: 'lombok', version: "${lombokVersion}"
	compileOnly group: 'org.projectlombok', name: 'lombok', version: "${lombokVersion}"
	testAnnotationProcessor  group: 'org.projectlombok', name: 'lombok', version: "${lombokVersion}"
	testCompileOnly group: 'org.projectlombok', name: 'lombok', version: "${lombokVersion}"

	//Test libraries
	//JUnit
	testImplementation (group: 'junit', name: 'junit', version: "${junitVersion}"){
        exclude module: 'hamcrest-core'
	}
	testImplementation group:'org.hamcrest', name: 'hamcrest-all', version: "${hamcrestVersion}"
	testImplementation group: 'org.assertj', name: 'assertj-core', version: "${assertjVersion}"
	testImplementation group: 'org.assertj', name: 'assertj-db', version: "${assertjdbVersion}"

	//Mock libraries
	testImplementation group:'org.mockito', name:'mockito-inline', version: "${mockitoVersion}"

	//jacoco
	testImplementation group: 'org.jacoco', name: 'org.jacoco.core', version: "${jacocoCoreVersion}"

	//for DB Test
	testImplementation group: 'com.h2database', name: 'h2', version: "${h2Version}"
	testImplementation group: 'com.ninja-squad', name: 'DbSetup', version: "${dbSetupVersion}"

	//CDI Test(Arquillian)
	testImplementation group: 'org.jboss.arquillian.junit', name: 'arquillian-junit-container', version: "${arquillianJunitContainerVersion}"
	testImplementation group:'org.jboss.arquillian.extension', name: 'arquillian-jacoco', version: "${arquillianJacocoVersion}"
	testImplementation group:'fish.payara.arquillian', name: 'arquillian-payara-server-embedded', version: "${arquillianPayaraEmbeddedVersion}"
   	testImplementation group: 'fish.payara.extras', name: 'payara-embedded-all', version: "${payaraEmbeddedAllVersion}"

	//assertj assertion generator
	assertj 'org.assertj:assertj-assertions-generator:2.2.0'
    assertj project
}

// flyway settings
flyway {
    driver = "${flywaydriver}"
    url = "${flywayurl}"
    user = "${flywayuser}"
    password = "${flywaypassword}"
    target = "${flywaytarget}"
    outOfOrder = false
    validateOnMigrate = true
    cleanOnValidationError = false
}

//assertj assertion generator
def assertjOutput = file('src-gen/test/java')
task assertjClean(type: Delete) {
    delete assertjOutput
}

task assertjGen(dependsOn: assertjClean, type: JavaExec) {
    doFirst {
        if (!assertjOutput.exists()) {
            if (!assertjOutput.mkdirs()) {
                throw new InvalidUserDataException("Unable to create `$assertjOutput` directory")
            }
        }
    }
    main 'org.assertj.assertions.generator.cli.AssertionGeneratorLauncher'
    classpath = files(configurations.assertj)
    workingDir = assertjOutput
    args = [    ]
}
compileTestJava.dependsOn(assertjGen)

//Add the code for assertj generator generation to sourceSets
sourceSets {
    test {
        java {
            srcDir 'src/test/java'
            srcDir 'src-gen/test/java'
        }
    }
}

war {
	webAppDirName = "WebContent"
	baseName = "${artifactid}"
}

test {
    systemProperties 'property': 'value'
    ignoreFailures = true
    reports {
    	html.enabled = true
    	junitXml.enabled = true
	}
}

jacoco {
	toolVersion = "${jacocoCoreVersion}"
}
jacocoTestReport {
	reports {
		html.enabled = true
		xml.enabled = true
		csv.enabled = false
	}
}

checkstyle {
    toolVersion = "${checkstyleToolVersion}"
    ignoreFailures = true
    sourceSets = subprojects.sourceSets.main
	configFile file("$rootDir/config/checkstyle.xml")
}

spotbugs {
    toolVersion =  "${spotbugsToolVersion}"
    ignoreFailures = true
    effort = "max"
    reportLevel = 'low'
}

//Settings for the Eclipse IDE
eclipse {
  wtp {
	facet {
        facet name: 'jst.java', version: "${javaFacet}"
        facet name: 'jst.web', version: "${webFacet}"
        facet name: 'jst.jsf', version: "${jsfFacet}"
        facet name: 'glassfish.web', version: "${glassfishFacet}"
    }
    component {
      contextPath = 'WebContent'
    }
  }
}

//Check the OS.
def isWindows() {
    return System.properties['os.name'].toLowerCase().contains('windows')
}

//Payara Server settings
ext {
	asadmin = "${glassfishHome}" + (isWindows() ? '/bin/asadmin.bat' : '/bin/asadmin')
	domain = "${glassfishDomain}"
}

//Start Payara Server.
task startServer(type: Exec) {
	description 'Start the application server.'
    commandLine asadmin, 'start-domain', '--debug=true', domain
}

//Stop Payara Server.
task stopServer(type: Exec) {
	description 'Stop the application server.'
    commandLine asadmin, 'stop-domain', domain
}

//Deploy the WAR file on Payara Server.
task deploy(type: Exec, dependsOn: ':war') {
	appName = "${appName}"
	description 'Deploy the WAR file.'
	if("${isRemote}" == 'true'){
		commandLine asadmin, '--host', "${remoteIP}", '--user', 'admin', '--passwordfile', '..\\glassfishpassword.txt', '--port', '4848' , 'deploy', '--force=true', '--contextroot', appName, '--name', appName, war.archivePath
	}else{
	    commandLine asadmin, 'deploy', '--force=true', "--contextroot", appName, "--name", appName, war.archivePath
    }
}

In order to develop Jakarta EE, it is OK to add Jakarta EE API to dependency, but here we have added various libraries for normal development.

--JDBC driver: PostgreSQL this time --Logger: slf4j + logback

In addition, flywayDB plugin is added for DB creation, and checkstyle and spotbugs are added as static analysis. And I am creating a deploy task so that it can be deployed with the Gradle task.

checkstyle definition file creation

Since checkstyle is used as one of the static analysis tools in this project, it is necessary to place the checkstyle definition file in the project. First, create the config folder where the definition file will be placed. Right-click on the project name in Package Explorer and select New> Folder. Enter config for the folder name and click Finish.

image.png

Once the config folder is created, right-click on the config folder and select New> File. Enter checkstyle.xml for the file name and click Finish. For checkstyle.xml, you should refer to Official google_check.xml.

Create checkstyle.xml, and if no error occurs on Eclipse, the project creation is complete.

Recommended Posts

[Jakarta EE 8 application development with Gradle] 2. Project creation
[Jakarta EE 8 application development with Gradle] 1. Environment construction
Java multi-project creation with Gradle
Web application creation with Nodejs with Docker
One-JAR Java EE application with WebSphere Liberty
Spring Boot2 Web application development with Visual Studio Code Hello World creation
Start web application development with Spring Boot
Spring5 MVC Web application development with Visual Studio Code Maven template creation
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 2/3 [Page creation 1/2]
Java Development Basics ~ Development Environment Settings and Project Creation ~
Build Spring Boot project by environment with Gradle
Add a project in any folder with Gradle
Personal application creation # 3
Personal application creation # 1
JavaFX application development with IntelliJ IDEA and Gradle ~ From environment construction to sample code ~
Experienced Java users get started with Android application development
Roughly the flow of web application development with Rails.