I have the following in my gradle build file. My problem is that log4j.properties is being added as an ejb module in application.xml, despite my attempt to remove it from the xml per the thread here:
http://forums.gradle.org/gradle/topics/ear_plugin_inserts_unneeded_ejb_modules_in_the_application_xml_ear_descriptor
apply plugin: 'ear'
ear {
deploymentDescriptor {
applicationName = 'ourapp'
displayName = 'ourapp'
initializeInOrder = true
//This doesn't work:
withXml { xml ->
xml.asNode().module.removeAll { it.ejb.text.equals('log4j.properties') }
}
}
//Add log4j.properties to ear root
from('../../lib/log4j.properties', 'log4jProperties')
}
dependencies
{
deploy 'javax:javax.jnlp:1.2'
deploy 'com.oracle:ojdbc6:1.6.0'
earlib 'org.apache:apache-log4j:1.2.16'
}
How can I get the gradle to exclude log4j.properties from application.xml?
EDIT
This is causing a failure to start up in my application server (JBoss 6.0.0) because it doesn't know what to do with log4j.properties. I can work around it by manually creating my application.xml file, but that makes for another thing that has to be maintained. Any assistance would be welcome!
This code works for me. You need to protect the 'remove' method with an 'if' block because the closure is called multiple times. I found that the first time its called, log4jNode is set to 'null'.
withXml {
def log4jNode = asNode().module.find { it.ejb.text() == 'log4j.properties' }
if (log4jNode) {
asNode().remove( log4jNode )
}
}
Related
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")
}
}
}
I was trying plugins:
io.freefair.war-overlay - but it just overlay one war to another,
waroverlay - it has appropriate option "includeWarJars true" but it
does't works for me.
Currently I'm trying write script:
dependencies {
/* jar, his files I would like to include in war */
compile project(':my_jar_1')
}
war {
/* Step 1. Copy all from my_jar_1 into WEB-INF/classes */
into('WEB-INF/classes') {
from configurations.compile
.filter { it.name.startsWith("my_jar_1") }
.collect { zipTree(it).matching { exclude 'META-INF/**/*.*' }}
}
/* Step 2. Deleting jar from war WEB-INF/lib. I got stuck here. It println, but doesn't delete jar */
doLast {
zipTree('build/libs/war_1-0.0.0.war').files.each {
if (it.path.endsWith('.jar')) {
delete it
println 'DELETED ' + it.path
}
}
}
}
Could somebody tell me how to make it work?
Or maybe smb know more elegant solution?
Also I was trying to declare my own configuration
configurations { overlay }
dependencies {
overlay project(':my_jar_1')
}
war {
into('WEB-INF/classes') {
from configurations.overlay
...
But it shows error
FAILURE: Build failed with an exception.
What went wrong: Failed to capture snapshot of input files for task 'war' property 'rootSpec$1$1' during up-to-date check.
Failed to create MD5 hash for file '/home/user/projects/OveralJarToWar/my_jar_1/build/libs/my_jar_1-1.0-SNAPSHOT.jar'.
The content of WEB-INF/lib and WEB-INF/classes is configured by single property classpath of war task. According to documentation:
Any JAR or ZIP files in this classpath are included in the WEB-INF/lib directory. Any directories in this classpath are included in the WEB-INF/classes directory
So, in your case, the classpath should be modified as follow
war {
def myJar = project(':my_jar_1').jar.outputs
def myClassesAndResources = project(':my_jar_1').sourceSets.main.output
classpath = classpath - myJar + myClassesAndResources
}
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)
}
}
Set Up
I'm using Gradle and have a multi-project build using Java EE with IBM WebSphere Application Server. The project directory structure looks like this:
--/build.gradle
--/defaults.gradle
--/settings.gradle
--/common-ejb
--/common-ejb/build.gradle
--/logging
--/logging/build.gradle
--/project1
--/project1/build.gradle
--/project1-ejb
--/project1-ejb/build.gradle
--/project2
--/project2/build.gradle
--/project2-ejb
--/project2-ejb/build.gradle
project1 and project2 are individual ears that get deployed. They both reuse a number of EJBs from common-ejb and share some other library dependencies that aren't relevant for this question.
After performing the build: project1.ear looks like:
--/lib/log4j.jar
--/lib/logging.jar
--/META-INF/application.xml
--/META-INF/MANIFEST.MF
--/common-ejb.jar
--/project1-ejb.jar
Gradle properly creates the application.xml to load EJBs from both projects. Unfortunately, project1-ejb.jar will fail to load due to dependencies on common-ejb.jar. The project1-ejb.jar/META-INF/MANIFEST.MF needs to have the Class-Path set with common-ejb.jar since it's not in the lib/ directory.
I was able to set it by explicitly defining it as done below. Gradle knows the dependencies for the Class-Path, so it should be able do this automatically. Is there a way to set this up?
Gradle Files
Not including project2, but you can guess what it looks like.
--/build.gradle
apply from: 'defaults.gradle'
defaultTasks 'clean', 'build'
--/defaults.gradle
defaultTasks 'build'
repositories {
mavenCentral()
}
--/settings.gradle
include 'common-ejb'
include 'project1'
include 'project1-ejb'
include 'logging'
--/logging/build.gradle
apply from: '../defaults.gradle'
apply plugin: 'java'
dependencies {
compile 'log4j:log4j:1.2.+'
}
--/common-ejb/build.gradle
apply from: '../defaults.gradle'
apply plugin: 'java'
dependencies {
compile 'javax:javaee-api:6.0'
compile project(':logging')
}
--/project1-ejb/build.gradle
apply from: '../defaults.gradle'
apply plugin: 'java'
dependencies {
compile 'javax:javaee-api:6.0'
compile project(':common-ejb')
compile project(':logging')
}
// THIS IS THE WORKAROUND, I don't want to explicitly modify the Class-Path for each EJB based on the EAR the EJB is going to be included in.
jar {
manifest {
attributes("Class-Path": project(':common-ejb').jar.archiveName)
}
}
--/project1/build.gradle
apply from: '../defaults.gradle'
apply plugin: 'ear'
apply plugin: 'java'
dependencies {
deploy project(':project1-ejb')
deploy project(':common-ejb')
earlib project(':logging')
}
Using some information from and modifying code from a question about getting all dependencies of a project from the Gradle forums.
Essentially, you want to take the EAR's deploy dependencies and see if any deploy dependencies depend on each other. If they do, you set the Class-Path to include the referenced jars.
Remove the manifest lines from project1-ejb and project2-ejb. Add the following to your defaults.gradle:
def getAllDependentProjects(project) {
if ( !project.configurations.hasProperty("runtime") ) {
return []
}
def projectDependencies = project.configurations.runtime.getAllDependencies().withType(ProjectDependency)
def dependentProjects = projectDependencies*.dependencyProject
if (dependentProjects.size > 0) {
dependentProjects.each { dependentProjects += getAllDependentProjects(it) }
}
return dependentProjects.unique()
}
gradle.projectsEvaluated {
if (plugins.hasPlugin('ear')) {
def deployProjectDependencies = configurations.deploy.getAllDependencies().withType(ProjectDependency)*.dependencyProject
deployProjectDependencies.each {
def cur = it
def cur_deps = getAllDependentProjects(cur)
def depJars = []
deployProjectDependencies.each {
def search = it
if ( cur_deps.contains(search)) {
depJars += search.jar.archiveName
}
}
depJars = depJars.unique()
if ( depJars.size() > 0 ) {
logger.info("META-INF Dependencies for deploy dependency " + cur.name + ": " + depJars)
cur.jar.manifest.attributes(
'Class-Path': depJars.join(' ')
)
}
}
}
}
This will have the desired affect. Directly after the configuration step and before build, the EAR projects will reevaluate their dependencies to see if any are cross-referenced. There may be a more efficient way, but this gets the job done.
WAR
- META-INF
- WEB-INF
- classes
- META-INF
- myApp.properties <-- Needs added
How do I add a .properties file into my WAR using gradle?
The file was later introduced into the project but doesn't
get added?
build.gradle
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod
group = 'gradle'
version = '1.0'
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'eclipse'
eclipseProject
{
projectName = 'crap'
}
defaultTasks 'build'
dependencies
{
//all my dependencies
}
war
{
classpath fileTree('lib')
}
jar.enabled = true
[jettyRun, jettyRunWar]*.daemon = true
stopKey = 'stoppit'
stopPort = 9451
httpPort = 8080
scanIntervalSeconds = 1
war {
from('<path-to-props-file>') {
include 'myApp.properties'
into('<target-path>')
}
}
Something like this should work:
war {
from('<path-to-props-file>') {
include 'myApp.properties'
}
}
If you want to specify which directory you want the properties file to be located in:
war {
from('<path-to-props-file>') {
include 'myApp.properties'
into('<targetDir>')
}
}
eg1:
war {
webInf{
from('PATH_TO_SOURCE_FOLDER') {
include 'FILE_TO_BE_INCLUDED'
into('TARGET_FOLDER_RELATIVE_TO_WEB_INF_DIR')
}
}
}
eg2:
war {
webInf{
from('src/META-INF') {
include 'persistence.xml'
into('classes/META-INF/')
}
}
}
For more information check the online documentation: Chapter 26. The War Plugin
I normally use an environments folder from which I pick a given configuration file based on the deploy variable. Ex.:
from("environments/system.${env}.properties"){
include "system.${env}.properties"
into 'WEB-INF'
rename("system.${env}.properties", 'system.properties')
}
the property is passed through gradle as:
./gradlew buildDocker -Penv=prod