How to supply list of dependencies to ejbdeploy.bat using Gradle - gradle

We have recently started using Gradle(1.12) to build our application components and the first place we have started is by doing EJB Deploy. This is what we are trying to achieve:
compile a sourceSet which is located at project directory /ejbModule ( This consists of the java classes and META-INF folder which contains ejb-jar.xml and other websphere related xml's.
Create a jar which will contain the above package and resources
run ejbdeploy.bat located at %WAS_HOME%\bin which takes input as jar created in step 2 which will create stubs / skeletons and re-package the jar at a different directory.
Now this is my gradle build file
def wasHome = 'C:/Data/IBM/WebSphere/AppServer'
def internalClasses = 'C:/GoldCopy1/Workspace/chimessharedlib'
def appPath = 'C:/GoldCopy1/Workspace/IEApp'
apply plugin:'java'
repositories {
flatDir {
dirs wasHome + '/lib'
dirs internalClasses
dirs appPath
}
}
dependencies {
compile name : 'j2ee'
compile name : 'commons-lang-2.3'
compile name : 'FW'
compile name : 'Common'
compile name : 'DA'
compile name : 'ST'
}
sourceSets {
main {
java {
srcDir '/ejbModule'
}
resources {
srcDir '/ejbModule'
}
}
}
task runEJBDeploy (type:Exec) {
commandLine wasHome + '/bin/ejbdeploy.bat', '/C'
def inputJar = "" + libsDir + File.separator + 'AR.jar';
println inputJar;
def argsList = [inputJar, "C:\\tpp" , "C:\\tpp\\deploy\\AR.jar" , "-complianceLevel", "5.0"]
args = argsList;
}
So by running the runEJBDeploy task above, I want to generate a command like below:
ejbdeploy.bat -cp "C:\tpp\FW.jar;C:\tpp\DA.jar;C:\tpp\Common.jar" C:\tpp\AR.jar C:\tpp C:\tpp\deployed\AR.jar -complianceLevel 5.0
So since FW, DA and Common are already provided in the dependencies { } section of the build.gradle file, is there a way to use those dependencies for appending it after "-cp " and then run the command?
I am very new to gradle so please also point out any other wrong approach taken which should be improved.
Thanks in advance

Related

Fat Jar expands dependencies with Gradle Kotlin DSL

I am trying to build a fat jar using the following in my Kotlin based gradle file.
val fatJar = task("fatJar", type = Jar::class) {
baseName = "safescape-lib-${project.name}"
// manifest Main-Class attribute is optional.
// (Used only to provide default main class for executable jar)
from(configurations.runtimeClasspath.map({ if (it.isDirectory) it else zipTree(it) }))
with(tasks["jar"] as CopySpec)
}
tasks {
"build" {
dependsOn(fatJar)
}
}
However, the fat jar has all the dependencies expanded out. I would like to have the jars included as is in a /lib directory but I cannot work out how to achieve this.
Can anyone give any pointers as to how I can achieve this?
Thanks
Well you are using zipTree in that map part of the spec, and it behaves according to the documentation: it unzips the files that are not a directory.
If you want the jars in /lib, replace your from with:
from(configurations.runtimeClasspath) {
into("lib")
}
In case anyone is using kotlin-multiplatform plugin, the configuration is a bit different. Here's a fatJar task configuration assuming JVM application with embedded JS frontend from JS module:
afterEvaluate {
tasks {
create("jar", Jar::class).apply {
dependsOn("jvmMainClasses", "jsJar")
group = "jar"
manifest {
attributes(
mapOf(
"Implementation-Title" to rootProject.name,
"Implementation-Version" to rootProject.version,
"Timestamp" to System.currentTimeMillis(),
"Main-Class" to mainClassName
)
)
}
val dependencies = configurations["jvmRuntimeClasspath"].filter { it.name.endsWith(".jar") } +
project.tasks["jvmJar"].outputs.files +
project.tasks["jsJar"].outputs.files
dependencies.forEach { from(zipTree(it)) }
into("/lib")
}
}
}

JavaFX 11 : Create a jar file with Gradle

I am trying to upgrade a JavaFX project from the 8 Java version to the 11 version. It works when I use the "run" Gradle task (I followed the Openjfx tutorial), but when I build (with the "jar" Gradle task) and execute (with "java -jar") a jar file, the message "Error: JavaFX runtime components are missing, and are required to run this application" appears.
Here is my build.gradle file :
group 'Project'
version '1.0'
apply plugin: 'java'
sourceCompatibility = 1.11
repositories {
mavenCentral()
}
def currentOS = org.gradle.internal.os.OperatingSystem.current()
def platform
if (currentOS.isWindows()) {
platform = 'win'
} else if (currentOS.isLinux()) {
platform = 'linux'
} else if (currentOS.isMacOsX()) {
platform = 'mac'
}
dependencies {
compile "org.openjfx:javafx-base:11:${platform}"
compile "org.openjfx:javafx-graphics:11:${platform}"
compile "org.openjfx:javafx-controls:11:${platform}"
compile "org.openjfx:javafx-fxml:11:${platform}"
}
task run(type: JavaExec) {
classpath sourceSets.main.runtimeClasspath
main = "project.Main"
}
jar {
manifest {
attributes 'Main-Class': 'project.Main'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
compileJava {
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.controls,javafx.fxml'
]
}
}
run {
doFirst {
jvmArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.controls,javafx.fxml'
]
}
}
Do you know what I should do ?
With Java/JavaFX 11, the shadow/fat jar won't work.
As you can read here:
This error comes from sun.launcher.LauncherHelper in the java.base module. The reason for this is that the Main app extends Application and has a main method. If that is the case, the LauncherHelper will check for the javafx.graphics module to be present as a named module:
Optional<Module> om = ModuleLayer.boot().findModule(JAVAFX_GRAPHICS_MODULE_NAME);
If that module is not present, the launch is aborted.
Hence, having the JavaFX libraries as jars on the classpath is not allowed
in this case.
What's more, every JavaFX 11 jar has a module-info.class file, at the root level.
When you bundle all the jars content into one single fat jar, what happens to those files with same name and same location? Even if the fat jar keeps all of them, how does that identify as a single module?
There is a request to support this, but it hasn't been addressed yet: http://openjdk.java.net/projects/jigsaw/spec/issues/#MultiModuleExecutableJARs
Provide a means to create an executable modular “uber-JAR” that contains more than one module, preserving module identities and boundaries, so that an entire application can be shipped as a single artifact.
The shadow plugin still does make sense to bundle all your other dependencies into one jar, but after all you will have to run something like:
java --module-path <path-to>/javafx-sdk-11/lib \
--add modules=javafx.controls -jar my-project-ALL-1.0-SNAPSHOT.jar
This means that, after all, you will have to install the JavaFX SDK (per platform) to run that jar which was using JavaFX dependencies from maven central.
As an alternative you can try to use jlink to create a lightweight JRE, but your app needs to be modular.
Also you could use the Javapackager to generate an installer for each platform. See http://openjdk.java.net/jeps/343 that will produce a packager for Java 12.
Finally, there is an experimental version of the Javapackager that works with Java 11/JavaFX 11: http://mail.openjdk.java.net/pipermail/openjfx-dev/2018-September/022500.html
EDIT
Since the Java launcher checks if the main class extends javafx.application.Application, and in that case it requires the JavaFX runtime available as modules (not as jars), a possible workaround to make it work, should be adding a new Main class that will be the main class of your project, and that class will be the one that calls your JavaFX Application class.
If you have a javafx11 package with the Application class:
public class HelloFX extends Application {
#Override
public void start(Stage stage) {
String javaVersion = System.getProperty("java.version");
String javafxVersion = System.getProperty("javafx.version");
Label l = new Label("Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + ".");
Scene scene = new Scene(new StackPane(l), 400, 300);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Then you have to add this class to that package:
public class Main {
public static void main(String[] args) {
HelloFX.main(args);
}
}
And in your build file:
mainClassName='javafx11.Main'
jar {
manifest {
attributes 'Main-Class': 'javafx11.Main'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
Now you can run:
./gradlew run
or
./gradlew jar
java -jar build/libs/javafx11-1.0-SNAPSHOT.jar
The final goal is to have the JavaFX modules as named modules on the module path, and this looks like a quick/ugly workaround to test your application. For distribution I'd still suggest the above mentioned solutions.
With the latest versions of JavaFX, you can use two Gradle plugins to easily distribute your project (javafxplugin and jlink).
With these plugins, you can:
Create a distributable zip file that contains all the needed jar files: it requires a JRE to be executed (with the bash or batch script)
Create a native application with Jlink for a given OS: a JRE is not needed to execute it, as Jlink includes a "light" JRE (including only the needed java modules and dependencies) in the distribution folder
I made an example on bitbucket, if you want an example.
[Edit: For the latest versions of JavaFX, please check my second answer]
If someone is interested, I found a way to create jar files for a JavaFX11 project (with Java 9 modules). I tested it on Windows only (if the application is also for Linux, I think we have to do the same steps but on Linux to get JavaFX jars for Linux).
I have a "Project.main" module (created by IDEA, when I created a Gradle project) :
src
+-- main
| +-- java
| +-- main
| +-- Main.java (from the "main" package, extends Application)
| +-- module-info.java
build.gradle
settings.gradle
...
The module-info.java file :
module Project.main {
requires javafx.controls;
exports main;
}
The build.gradle file :
plugins {
id 'java'
}
group 'Project'
version '1.0'
ext.moduleName = 'Project.main'
sourceCompatibility = 1.11
repositories {
mavenCentral()
}
def currentOS = org.gradle.internal.os.OperatingSystem.current()
def platform
if (currentOS.isWindows()) {
platform = 'win'
} else if (currentOS.isLinux()) {
platform = 'linux'
} else if (currentOS.isMacOsX()) {
platform = 'mac'
}
dependencies {
compile "org.openjfx:javafx-base:11:${platform}"
compile "org.openjfx:javafx-graphics:11:${platform}"
compile "org.openjfx:javafx-controls:11:${platform}"
}
task run(type: JavaExec) {
classpath sourceSets.main.runtimeClasspath
main = "main.Main"
}
jar {
inputs.property("moduleName", moduleName)
manifest {
attributes('Automatic-Module-Name': moduleName)
}
}
compileJava {
inputs.property("moduleName", moduleName)
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.controls'
]
classpath = files()
}
}
task createJar(type: Copy) {
dependsOn 'jar'
into "$buildDir/libs"
from configurations.runtime
}
The settings.gradle file :
rootProject.name = 'Project'
And the Gradle commands :
#Run the main class
gradle run
#Create the jars files (including the JavaFX jars) in the "build/libs" folder
gradle createJar
#Run the jar file
cd build/libs
java --module-path "." --module "Project.main/main.Main"

Gradle jar doLast

How to make a copy in the resources/app folder. After the other module is compiled
jar {
dependsOn(project(':portal-frontend').tasks.findByName("compileGwt"))
into("app") {
File configFile = file(project(':portal-frontend').tasks.findByName("compileGwt").buildDir)
println configFile.listFiles()
from project(':portal-frontend').tasks.findByName("compileGwt").buildDir
//from compileGwt.buildDir
}
}
}
I have 2 submodule portal-backend and portal-frontend
portal-backend - spring boot project
portal-frontend - gwt project
So I want. When portal-frontend compile. Copy build resource from portal-frontend to portal-ackend
Something like this https://gist.github.com/marcokrikke/5481001
But I have multimodule structure

How to add gradle generated source folder to Eclipse project?

My gradle project generates some java code inside gen/main/java using annotation processor. When I import this project into Eclipse, Eclipse will not automatically add gen/main/java as source folder to buildpath. I can do it manually. But is there a way to automate this?
Thanks.
You can easily add the generated folder manually to the classpath by
eclipse {
classpath {
file.whenMerged { cp ->
cp.entries.add( new org.gradle.plugins.ide.eclipse.model.SourceFolder('gen/main/java', null) )
}
}
}
whereby null as a second constructor arg means that Eclipse should put the compiled "class" files within the default output folder. If you want to change this, just provide a String instead, e.g. 'bin-gen'.
I think it's a little bit cleaner just to add a second source directory to the main source set.
Add this to your build.gradle:
sourceSets {
main {
java {
srcDirs += ["src/gen/java"]
}
}
}
This results in the following line generated in your .classpath:
<classpathentry kind="src" path="src/gen/java"/>
I've tested this with Gradle 4.1, but I suspect it'd work with older versions as well.
Andreas' answer works if you generate Eclipse project from command line using gradle cleanEclipse eclipse. If you use STS Eclipse Gradle plugin, then you have to implement afterEclipseImport task. Below is my full working snippet:
project.ext {
genSrcDir = projectDir.absolutePath + '/gen/main/java'
}
compileJava {
options.compilerArgs += ['-s', project.genSrcDir]
}
compileJava.doFirst {
task createGenDir << {
ant.mkdir(dir: project.genSrcDir)
}
createGenDir.execute()
println 'createGenDir DONE'
}
eclipse.classpath.file.whenMerged {
classpath - >
def genSrc = new org.gradle.plugins.ide.eclipse.model.SourceFolder('gen/main/java', null)
classpath.entries.add(genSrc)
}
task afterEclipseImport(description: "Post processing after project generation", group: "IDE") {
doLast {
compileJava.execute()
def classpath = new XmlParser().parse(file(".classpath"))
new Node(classpath, "classpathentry", [kind: 'src', path: 'gen/main/java']);
def writer = new FileWriter(file(".classpath"))
def printer = new XmlNodePrinter(new PrintWriter(writer))
printer.setPreserveWhitespace(true)
printer.print(classpath)
}
}

how can I override source dirs in gradle BUT only for this one annoying subproject

We have one main project and two subprojects. One of the subprojects is the playframework which has a "unique" build structure. How can I override the source directories BUT only for that one subproject such that all other projects are using the standard layout of source directories src/main/java, etc.
I tried the first answer which is not working and for my directory structure
stserver
build.gradle (1)
project1
webserver
build.gradle (2)
The 2nd gradle file is this
sourceSets.main{
java.srcDirs = ['app']
}
task build << {
println "source sets=$sourceSets.main.java.srcDirs"
}
When I run this, it prints out stserver/app as my srcDir instead of stserver/webserver/app???? What am I doing wrong here?
thanks,
Dean
Please have a look at the docs Peter has suggested. I have a ready build.gradle that I have working with Play Framework 2.0~, so I'll share it here in hope you'll find some useful setup tips.
My project structure:
+- master/
+- build.gradle <-- contains common setup,
and applies 'java' plugin to all subprojects
+- ui/ <-- project using Play framework
+- build.gradle <-- excerpt from this file is posted below
The excerpt from build.gradle
repositories{
maven{
//Play dependencies will be downloaded from here
url " http://repo.typesafe.com/typesafe/releases"
}
}
//Optional but useful. Finds 'play' executable from user's PATH
def findPlay20(){
def pathEnvName = ['PATH', 'Path'].find{ System.getenv()[it] != null }
for(path in System.getenv()[pathEnvName].split(File.pathSeparator)){
for(playExec in ['play.bat', 'play', 'play.sh']){
if(new File(path, playExec).exists()){
project.ext.playHome = path
project.ext.playExec = new File(path, playExec)
return
}
}
}
throw new RuntimeException("""'play' command was not found in PATH.
Make sure you have Play Framework 2.0 installed and in your path""")
}
findPlay20()
configurations{
//Configuration to hold all Play dependencies
providedPlay
}
dependencies{
providedPlay "play:play_2.9.1:2.0+"
//Eclipse cannot compile Play template, so you have to tell it to
//look for play-compiled classes
providedPlay files('target/scala-2.9.1/classes_managed')
//other dependencies
}
sourceSets.main{
java.srcDirs = ['app', 'target/scala-2.9.1/src_managed/main']
//Make sure Play libraries are visible during compilation
compileClasspath += configurations.providedPlay
}
//This task will copy your project dependencies (if any) to 'lib'
//folder, which Play automatically includes in its compilation classpath
task copyPlayLibs(type: Copy){
doFirst { delete 'lib' }
from configurations.compile
into 'lib'
}
//Sets up common play tasks to be accessible from gradle.
//Can be useful if you use gradle in a continuous integration
//environment like Jenkins.
//
//'play compile' becomes 'gradle playCompile'
//'play run' becomes 'gradle playRun', and so on.
[ ['run', [copyPlayLibs]],
['compile', [copyPlayLibs]],
['clean', []],
['test', []],
['doc', [copyPlayLibs]],
['stage', [copyPlayLibs]] ].each { cmdSpec ->
def playCommand = cmdSpec[0]
def depTasks = cmdSpec[1]
task "play${playCommand.capitalize()}" (type: Exec,
dependsOn: depTasks,
description: "Execute 'play ${playCommand}'") {
commandLine playExec, playCommand
}
}
//Interate playClean and playCompile task into standard
//gradle build cycle
clean.dependsOn "playClean"
[compileScala, compileJava]*.dependsOn "playCompile"
//Include Play libraries in Eclipse classpath
eclipse {
classpath {
plusConfigurations += configurations.providedPlay
}
}
Note: I have just extracted the above from an existing bigger gradle file, so it might be missing some things, so no guarantees:) Hope it's useful anyway. Good luck.

Resources