Gradle copy dependencies in built jar - java

I'm searching a solution for adding my gradle dependencies in my built jar file.
For example, I've the dependency com.fazecast:jSerialComm and wanting to add the library in specific folder in the jar, library path should belibs/jserialcomm/jSerialComm-2.0.2.jar

Add the following to your build.gradle:
jar {
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
This will merge the content of all dependencies into the output jar.
See also http://www.baeldung.com/gradle-fat-jar.
In a different approach, one would copy the jars of the dependencies into the output jar (jars in jar), but that also requires writing a custom class loader.
UPDATE after edit of question:
The OP wants to take the second approach, which is employed as follows:
plugins {
id "com.github.onslip.gradle-one-jar" version "1.0.5"
}
task awesomeFunJar(type: OneJar) {
mainClass = 'com.github.rholder.awesome.MyAwesomeMain'
}
This will include all dependent jars into a lib directory in the output jar. It will also install a custom class loader, which loads jars from the lib directory in the jar. This is something that the standard class loader does not do, no matter how you tweak the class path.
See also https://github.com/Onslip/gradle-one-jar/

Related

How to create a JAR file from gradle that contains the .java fields (source code) as well

I am using gradle to build some a uber jar file, this jar file has dependencies and I used this guide to create the task that I can run
My task is like this btw I am using kotlin
tasks.register<Jar>("uberJar") {
archiveClassifier.set("uber")
from(sourceSets.main.get().output)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE;
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
}})
What can I add to this task to add my .java files as well.
Also I don't really understand much of what is going on here like what actually is SourceSets?
Try adding this to your build.gradle.kts and see if it works:
tasks.named<ProcessResources>("processResources") {
from("src/main/java")
}
When your uber-JAR builds, it should contain the source files. Though this will also add the source files to any JAR. If that is not what you want, then you will need to configure something similar in the uber-JAR setup.

Dependencies path difference in Gradle vs in Maven

I have a question regarding to the difference between Gradle depedencies mechanism vs Maven dependency mechanism:
My project structure is following and app is dependent on common:
project
common
conf
src
java
test
app
conf
src
java
test
and build.gradle in app is:
dependencies {
compile project(':common')
....
}
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'conf'
}
}
test {
java {
srcDir 'src/test'
}
}
}
When I use ant dist. The class paths contain /common/conf folder, which contains lots of configuration files.
When I use Gradle build. The class paths contain build/common.jar instead of /common/conf.
Is there a way I could make Gradle do the same thing as Maven does (make class paths contain /common/conf instead of build/common.jar)?
Because app will read xml configuration files under common/conf folder when I run test cases under app but app is not able to read xml from a jar file. Because right now my code is not able to handle the inputStream from Jar.
Is it using:
res.getFile()
where res is the reference to xml configuration files.
I am a newbie to both Maven and Gradle. Could someone please help? Really appreciate!
If what you're trying to achieve is have those xml files available at runtime from within the Jar, then just add your XML files to /src/main/resources.
Anything in that directory automatically gets added to the Jar file and available as classpath resources. Both Maven and Gradle use convention over configuration, where it's a convention to put classpath resources into /src/main/resources as it is to put application Java code in /src/main/java and unit test classpath resources in /src/test/resources and unit test Java code in /src/test/java.
Following Mavan/Gradle conventions will make your configuration simpler too. Unlike Ant where everything needed to be configured.
If your xml files are in common.jar (by putting the xml in common/src/main/resources, and common is on the class path for for app then you should be able to read those files by getting via class loader. E.g SomeClassFromCommon.class.getClassLoader().getResourceAsStream("somefile.xml")

Does JWS load JARs inside JAR for applets?

I'm maintaining a Java applet launched via Java Web Start but I know little about this technology (we are in the process of moving away from applets but we need some maintenance on it). This applet depends on some external JAR files (batik, etc.).
We use gradle as the build system. We build a normal JAR and a fat JAR (with the com.github.johnrengelman.shadow plugin) as follows:
sourceSets {
main {
java {
}
}
}
repositories {
flatDir {
dirs 'lib'
}
}
dependencies {
compile 'commons-lang:commons-lang:2.0',
'jargs:jargs:1.0',
'org.apache.xmlgraphics:batik-svggen:1.7',
'org.apache.xmlgraphics:batik-dom:1.7',
'org.apache.xmlgraphics:batik-awt-util:1.7',
'org.apache.xmlgraphics:batik-util:1.7',
'org.apache.xmlgraphics:batik-xml:1.7',
'xerces:xercesImpl:2.8.0'
}
jar {
manifest {
attributes 'Application-Name': project.name,
'Permissions': 'all-permissions',
'Implementation-Title': project.name,
'Implementation-Version': version,
'Main-Class': 'Foo',
'Class-Path': configurations.compile.files.collect{ "lib/${it.name}" }.join(' ')
}
baseName project.name
// include dependencies into lib dir in produced jar
into('lib') {
from configurations.runtime
}
from "README.md"
}
shadowJar {
baseName project.name
}
gradle includes the JAR files in lib/ folder inside the main JAR and they are added to the Class-Path in MANIFEST.MF.
The applet works on client computers with the normal JAR but I don't fully understand why.
Somehow, the JAR files are loaded when Java Web Start launches the applet. They are not mentioned in the JNLP file (no <resource>) and there is no class loader (we don't use JarRsrcLoader or similar) so I guess it's because they are in Class-Path but I am not sure and I haven't been able to produce a MWE. In fact all the information that I have found states the opposite (at least for applications as opposed to applets).
Does anybody know if it's the case or a simple explanation/tutorial ?
Well, I was wrong. In fact the JAR files are not loaded: when one tries to access the functionality that needs batik, it fails. This confirms my readings and #eckes and #zakki comments.
I also discovered that I can simplify our build.gradle file.

Access MANIFEST.MF files of project dependencies using maven

I have a maven project with several dependencies that are developed internally by my team. I need some information contained on the MANIFEST.mf files of those dependencies at build time of my current project.
Just to be clear. I don't want to get information from my own MANIFEST.mf file (the one from the project I am building). I want to access information contained inside the MANIFEST.mf files of the dependencies of my project at build time.
I built a maven plugin where I can check the dependency tree and retrieve some basic information about the dependencies, however I haven't found a straight forward way of getting to the MANIFEST.mf files.
Do you have any clues on how I can access them (programatically)?
Thanks!
Use the file of the artifact to create a https://docs.oracle.com/javase/8/docs/api/java/util/jar/JarFile.html , which gives you access to the Manifest
Maybe something like this would work for you
public void readManifests() throws IOException {
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for(URL url: classLoader.getURLs()) {
Manifest manifest = new JarFile(url.getFile()).getManifest();
}
}

How do I specify an extra folder to be on the classpath for gradle's application plugin 'run' task?

I've successfully configured my gradle build script to create a zip distribution of my application with an extra 'config' folder at the root. This folder contains (at least right now) only one properties file in use by the application, and is on the classpath for the application.
What I'm looking for now, however, is a way to do the same with the 'run' task in the application plugin. When I try to run my application this way, (for testing), my program fails to run because of a class trying to access this properties file on the root of the classpath.
A bonus would be if I could get IntelliJ or Eclipse to also add this folder to its classpath just like the other folders (src/main/java, src/main/resources, ...) so I can run and debug my code from within the IDE without invoking a gradle task. I want to try to avoid as much as possible tying this code to any one IDE, so that when anybody needs to work on the project, they just need to import the build.gradle file and have the IDE make the appropriate config files it needs.
Here is my build.gradle file:
apply plugin: 'application'
mainClassName = "MainClass"
startScripts {
// Add config folder to classpath. Using workaround at
// https://discuss.gradle.org/t/classpath-in-application-plugin-is-building-always-relative-to-app-home-lib-directory/2012
classpath += files('src/dist/config')
doLast {
def windowsScriptFile = file getWindowsScript()
def unixScriptFile = file getUnixScript()
windowsScriptFile.text = windowsScriptFile.text.replace('%APP_HOME%\\lib\\config', '%APP_HOME%\\config')
unixScriptFile.text = unixScriptFile.text.replace('$APP_HOME/lib/config', '$APP_HOME/config')
}
}
repositories {
...
}
dependencies {
...
}
Likely what needs to happen is that I need to have the /src/dist/config folder to be copied into the build directory and added to the classpath, or have its contents be copied into a folder that is already on the classpath.
I ended up taking Opal's suggestion as a hint, and came up with the following solution. I added the following to my build.gradle file:
task processConfig(type: Copy) {
from('src/main/config') {
include '**/*'
}
into 'build/config/main'
}
classes {
classes.dependsOn processConfig
}
run {
classpath += files('build/config/main')
}
Alternatively, a simpler approach would be to add a runtime dependency to my project as such:
dependencies {
...
runtime files('src/main/config')
}
I didn't end up doing it this way, however, because my distribution package ended up having .properties files in the lib folder... and I'm just picky that way.
As you can see in the docs run is a task of type JavaExec. So classpath for it can be modified. Try to add config folder to the classpath. See here.

Categories

Resources