Need to exclude a dependency from eclipse using a gradle build file - eclipse

I'm trying to exclude a dependency, mainly "slf4j-simple" from my gradle build. It works well, but is not reflected when I run "gradle eclipse".
I have the following code in my gradle build file:
apply plugin:'war'
apply plugin:'eclipse'
apply plugin:'jetty'
...
dependencies {
compile 'mysql:mysql-connector-java:5.1.16'
compile 'net.sourceforge.stripes:stripes:1.5'
compile 'javax.servlet:jstl:1.2'
... (Rest of the dependencies)
}
configurations {
all*.exclude group:'org.slf4j',module:'slf4j-simple'
}
Now, when I run 'gradle build', the slf4j-simple is excluded from the war file created which is fine.
When I run 'gradle eclipse', the slf4j-simple is not excluded from the eclipse classpath.
A solution to the problem is mentioned in the gradle cookbook but I don't understand how to apply it:
http://docs.codehaus.org/display/GRADLE/Cookbook#Cookbook-ExcludingdependenciesfromEclipseProjects

Try adding this to your build.gradle:
eclipseClasspath{
plusConfigurations.each{
it.allDependencies.each{ it.exclude group: 'org.slf4j', module: 'slf4j-simple' }
}
}

With gradle 1.0-milestone-3 I had to do a modification from rodion's answer to make it work:
eclipseClasspath{
doFirst{
plusConfigurations.each{
it.allDependencies.each{ it.exclude group: 'org.slf4j', module: 'slf4j-simple' }
}
}
}

Using eclipseClasspath didn't work for me, but this does the trick:
configurations {
compile {
exclude group: 'commons-logging'
exclude module: 'jcl-over-slf4j'
}
}
That excludes commons-logging from being included transitively (from the project's dependency on Spring) and also jcl-over-slf4j from being included in the Eclipse project's build path (I have a Gradle runtime dependency on jcl-over-slf4j but don't want it included on the build (compile) path.

This works in Gradle 4.10
eclipse {
classpath {
file {
whenMerged { cp ->
cp.entries.removeAll { (it instanceof Library) && it.moduleVersion?.group == 'org.slf4j' && it.moduleVersion?.name == 'slf4j-simple' }
}
}
}
}

Related

Gradle - Include external projects as dependencies into .jar

I've two projects as dependencies: A, B. ( NOT SUB-projects but EXTERNAL projects )
My third project C, depends on both A and B.
I've already defined the settings.gradle in this way:
settings.gradle
rootProject.name = 'project_C'
include ':common_library'
project(":project_A").projectDir = file("../project_A")
include ':project_A'
project(":project_B").projectDir = file("../project_B")
build.gradle
// ************** Include dependencies as local .jars
implementation fileTree(include: ['*.jar'], dir: 'lib')
// ************** Compile the project on which this depends on
implementation project(':project_A')
implementation project(':project_B')
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
}
// *********** MODIFY the standard JAR task, including Main file (for executable jars) and pack all it's dependencies
jar {
from {
(configurations.runtime).collect {
configurations.runtime.filter( {! (it.name =~ /.*\.pom/ )}).collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
manifest {
attributes "Main-Class": "Main"
}
}
At this point, it builds with success.
But when i try to execute it as jar, it gives me errors about "not included dependencies" related to the project_A and project_B classes.
Someone that has already faced off this issue?
Thanks!
This might be useful which explains creating a fat jar which includes dependent jar.
https://www.baeldung.com/gradle-fat-jar

Kotlin setup via gradle on eclipse

Struggling to get Kotlin running on eclipse.
I've started new graddle project. Added dependencies as prescribed on kotlin's site.
Build passes without errors.
I've created 'main.kt' file under src/java/main with:
fun main(args: Array<String>) {
println("foo")
}
BUT, I have two problems:
1. anything from kotlin e.g. println highlighted as 'unresolved reference'.
2. I can't run a program - Error: Could not find or load main class MainKt (rightclick on main.kr run as 'kotlin application')
If I create 'new kotlin project' everything works.
my graddle build script:
plugins {
id "org.jetbrains.kotlin.jvm" version "1.1.2-2"
}
repositories {
jcenter()
mavenCentral()
}
dependencies {
//api 'org.apache.commons:commons-math3:3.6.1'
implementation 'com.google.guava:guava:21.0'
testImplementation 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.2-2"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
compile "org.jetbrains.kotlin:kotlin-reflect"
testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"
}
sourceSets {
main.java.srcDirs = ['src/main/java']
main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
main.resources.srcDirs = ['src/main/resources']
}
What did I do wrong?
I've zero Java knowledge if that helps, so probably I've made some trivial error.
UPDATE:
Installed a Spring plugin and generated a new web app via it including gradle.
But Kotlin behaves unpredictably there too.
At first I was not able to run it as run as Kotlin application and it errored with main could not be found, BUT sometimes it run and crashed immediately. It started to launch and crash after I've deleted and edited classes, tried creating it under other package, removing and adding Kotlin (I can't reproduce sequence to make it work again).
Fun part that gradle boot build launches everything and all works it somehow finds Kotlin's main.
Probably some issue with Kotlin plugin itself (it's load probably depends on certain events that doesn't always fire)
Add the following to your configuration:
apply plugin: 'eclipse'
eclipse {
classpath {
containers 'org.jetbrains.kotlin.core.KOTLIN_CONTAINER'
}
}
See https://gitlab.com/frnck/kotlin-gradle-eclipse for a working configuration.
I'd like to add to frnck answer that this is only part of the solution. I also had to add these lines:
eclipse.project {
buildCommand 'org.jetbrains.kotlin.ui.kotlinBuilder'
natures 'org.jetbrains.kotlin.core.kotlinNature'
natures 'org.eclipse.jdt.core.javanature'
linkedResource name: 'kotlin_bin', type: '2', locationUri: 'org.jetbrains.kotlin.core.filesystem:/aio/kotlin_bin'
}
For Eclipse 2018-12 and kotlin 1.3 the solution was a combination of other answers plus some additional settings file:
eclipse {
classpath {
//Adds the kotlin container to the classpath
containers 'org.jetbrains.kotlin.core.KOTLIN_CONTAINER'
//Fixes the right output path
defaultOutputDir = file('bin')
//Make all src folders output in the same output folder (default)
file {
whenMerged {
// use default Output for all source-folders. see also defaultOutputDir per project
entries.each { source ->
// only Source-folders in the project starting with '/' are project-references
if (source.kind == 'src' && !source.path.startsWith('/')) {
source.output = null
}
}
}
}
}
project{
buildCommand 'org.jetbrains.kotlin.ui.kotlinBuilder'
//Fixes the natures
natures 'org.jetbrains.kotlin.core.kotlinNature'
natures 'org.eclipse.jdt.core.javanature'
//Links the kotlin_bin folder (generated class files)
linkedResource name: 'kotlin_bin', type: '2', locationUri: "org.jetbrains.kotlin.core.filesystem:/${project.name}/kotlin_bin".toString()
file{
whenMerged{
def kotlinPrefs = file('.settings/org.jetbrains.kotlin.core.prefs')
def jdkHome = System.properties.'java.home'
if(!(jdkHome)){
throw new GradleException('No JDK home available for setting up Eclipse Kotlin plugin, setup env "java.home" or update this script.')
}
kotlinPrefs.write """\
codeStyle/codeStyleId=KOTLIN_OFFICIAL
codeStyle/globalsOverridden=true
compilerPlugins/jpa/active=true
compilerPlugins/no-arg/active=true
compilerPlugins/spring/active=true
eclipse.preferences.version=1
globalsOverridden=true
jdkHome=$jdkHome
""".stripIndent()
}
}
}
}
I would like to add to Felipe Nascimento's answer that the location of the .settings folder does not yet exist. It works when the line below is inserted into that answer.
def kotlinPrefs = file("../${project.name}/.settings/org.jetbrains.kotlin.core.prefs".toString())
I have found that the JAVA_HOME environment variable that is set when your run this task ;
gradle cleanEclipse eclipse
is the one that is included in the Eclipse BuildPath

1 Eclipse project, 2 artifacts with Gradle

I want to create structure for my new project and I intend to build it with Gradle. I already know that if I place sources and tests in one project plugins like MoreUnit will handle it easily and create tests for my classes right where I want them.
However it creates some awkward dependency issues when my project consists of several subprojects depending on each other - to be precise when I want to use some common code in tests in project A and then reuse it in tests in project B I had to do some workarounds like
project(':B') {
// ...
dependencies {
// ...
if (noEclipseTask) {
testCompile project(':A').sourceSets.test.output
}
}
}
sometimes there were also some evaluation problem so another hack had to be introduced:
project(':B') {
evaluationDependsOn(':A')
}
Splitting this into 2 separate projects got rid of that issue but then MoreUnit no longer was able to trace where it should create new test files, and mark which methods have been tested. I haven't found anything in MoreUnit config that would allow me to fix that, so am trying to fix this from Gradle side.
Can we arrange things so I can have several subprojects, sources and tests are arranged in maven like manner (project/src/java, project/test/java) but tests and sources will create separate artifacts? If I am solving the wrong problem then how should I solve the right one?
You can create some testenv jar for common like:
sourceSets {
testenv {
compileClasspath += main.output
runtimeClasspath += main.output
}
}
configurations {
testenvCompile {
extendsFrom runtime
}
testCompile {
extendsFrom testenvRuntime
}
testenvDefault {
extendsFrom testenvRuntime
}
}
and
task testenvJar(type: Jar, group: 'build', description: 'Assembles a jar archive containing the testenv classes.') {
from sourceSets.testenv.output
appendix = 'testenv'
// add artifacts to testenvRuntime as task 'jar' does automatically (see JavaPlugin#configureArchivesAndComponent:106 and http://www.gradle.org/docs/current/userguide/java_plugin.html, "Figure 23.2. Java plugin - dependency configurations")
configurations.testenvRuntime.artifacts.add new org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact(testenvJar)
}
task testenvSourcesJar(type: Jar, group: 'build', description: 'Assembles a jar archive containing all testenv sources.') {
from sourceSets.testenv.allSource
appendix = 'testenv'
classifier = 'sources'
}
artifacts {
archives testenvJar
archives testenvSourcesJar
}
and use it in your depended projects like
testCompile project(path: ':common', configuration: 'testenvDefault')
I hope this helps!

Eclipse Gradle Import with AspectJ Configuration

I have a Gradle project which leverages AOP (from Spring 3.x.x) which I have imported into Eclipse (STS). When I use the Gradle's context menu to refresh dependencies/rebuild source I then have to convert to a AspectJ project in able for me to run my tests correctly (the AspectJ Runtime library isn't on the build path to fulfill the factory-method in the bean definition). I don't have the spring-aspects.jar located anywhere and this deploys to Tomcat without issue (again no aspectJ in the libs/ folder).
<bean id="fooBarAspect" class="foo.Bar" factory-method="aspectOf" >
This process works but is painful as it makes me rebuild twice anytime I need to refresh dependencies and run integration tests.
dependencies {
ajc 'org.aspectj:aspectjtools:1.7.3'
aspects 'org.springframework:spring-aspects:3.2.4.RELEASE'
compile (
'org.aspectj:aspectjrt:1.7.3'
)
}
Thoughts?
For AspectJ:
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'
ext.aspectjVersion = '1.7.4'
configurations {
ajc
aspects
aspectCompile
ajInpath
compile {
extendsFrom aspects
}
}
compileJava {
sourceCompatibility="1.7"
targetCompatibility="1.7"
doLast{
ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
ant.iajc(
source:sourceCompatibility,
target:targetCompatibility,
destDir:sourceSets.main.output.classesDir.absolutePath,
maxmem: "512m",
fork: "true",
inpath: configurations.ajInpath.asPath,
aspectPath:configurations.aspects.asPath,
sourceRootCopyFilter:"**/.svn/*,**/*.java",
classpath:"${configurations.compile.asPath};${configurations.aspectCompile.asPath}"){
sourceroots{
sourceSets.main.java.srcDirs.each{
pathelement(location:it.absolutePath)
}
}
}
}
}
dependencies {
ajc "org.aspectj:aspectjtools:1.7.3"
compile "org.aspectj:aspectjrt:1.7.3"
aspects group: 'org.springframework', name: 'spring-aspects', version: springVersion
aspectCompile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.0-api', version: '1.0.0.Final'
aspectCompile group: 'org.springframework', name: 'spring-tx', version: springVersion
aspectCompile group: 'org.springframework', name: 'spring-orm', version: springVersion
}
For Eclipse we have to do bit a manual code:
eclipseClasspath {
withXml { xmlProvider ->
def classpath = xmlProvider.asNode()
def parser = new XmlParser()
classpath.classpathentry.findAll{ entry ->
entry.#kind == 'var' && configurations.runtime.find {entry.#path.endsWith(it.name) && !entry.#path.contains('servlet-api')
}.each { entry ->
def attrs = entry.attributes ?: parser.createNode(entry, 'attributes', [:])
parser.createNode(attrs, 'attribute', [name: 'org.eclipse.jst.component.dependency', value: '../'])
}
}
}
The problem is imo, that the project in eclipse must be marked as aspectj project in order to use the ajc compiler instead of the "normal" compiler. How did you declare the aspectj compilation in your build.gradle file? just adding the aspectj-rt to the compile classpath is definitely not enough.
You can manipulate the eclipse project configuration on xml level using gradle. I did this a long time ago using the withXml hook. have a look at the build.gradle file at
https://github.com/breskeby/gradleplugins/blob/0.9-upgrade/aspectjPlugin/aspectJ.gradle#L29
The way the aspectj eclipse plugin works might be outdated and you probably update it to fit your needs, but you should get the idea.

Gradle Api Sources and Doc when writing Gradle Plugins

The question:
How do I get the sources and javadoc/groovydoc for the gradle-api code integrated into an Eclipse project?
Background:
I'm using Gradle to build a Gradle-plugin that I'm writing. I'm using Eclipse as an IDE for this project and my Gradle script for building this plugin is using the 'Eclipse' plugin to generate my Eclipse project. Also, I'm using Spring's Gradle plugin for Eclipse which grabs all my dependencies from my build.gradle file.
The dependencies block for this Gradle script has
dependencies {
compile localGroovy()
compile gradleApi()
// I want something like: 'compile gradleApiSources()' here
// I want something like: 'compile gradleApiDoc()' here as well
}
Justification:
As I'm learning to write Gradle plugins, it would be helpful to be able to see the documentation and even implementation for Gradle to help me learn what I'm doing.
This works for me in Eclipse:
plugins.withType(EclipsePlugin) {
plugins.withType(JavaBasePlugin) {
eclipse {
classpath {
file {
whenMerged { classpath ->
String gradleHome = gradle.getGradleHomeDir()
.absolutePath
.replace(File.separator, '/')
String gradleSourceDirectory = "${gradleHome}/src"
classpath.entries.each { entry ->
if (entry in org.gradle.plugins.ide.eclipse.model.AbstractLibrary
&& entry.library.path.contains('generated-gradle-jars')) {
entry.sourcePath =
new org.gradle.plugins.ide.eclipse.model.internal.FileReferenceFactory()
.fromPath(gradleSourceDirectory)
}
}
}
}
}
}
}
}
Make sure that your Gradle Home contains the source directory. If you use the wrapper this can be done by updating the distributionUrl to an -all version in the wrapper task.
You will also need to stop the Gradle daemons that are running otherwise they will keep their own "home": ./gradlew --stop, then you can go ahead and run the task: ./gradlew eclipse
See GRADLE-2133 (which this answer was adapted from)
I don't have an answer for eclipse but I can tell you how I do this for intellij which might give you some inspiration. It would be nice if this were available more easily.
private void addGradleSourceDeps() {
PathFactory pf = new PathFactory()
pf.addPathVariable('GRADLE_HOME', project.gradle.gradleHomeDir)
project.extensions.idea.module.iml.whenMerged { Module module ->
module.dependencies.grep {
it instanceof ModuleLibrary && ((ModuleLibrary) it).classes.grep { Path path ->
path.relPath.substring(path.relPath.lastIndexOf('/') + 1).startsWith('gradle-')
}
}.each { ModuleLibrary lib ->
// TODO this needs to be fixed for gradle 1.9 which now includes separate sub directory for each jar
// for now a workaround is to execute the following
// cd $GRADLE_HOME
// for each in $(find . -mindepth 2 -maxdepth 2 -type d ! -name META\-INF); do cp -a ${each} .;done
lib.sources.add(pf.path('file://$GRADLE_HOME$/src'))
}
module.dependencies.grep {
it instanceof ModuleLibrary && ((ModuleLibrary) it).classes.grep { Path path ->
path.relPath.substring(path.relPath.lastIndexOf('/') + 1).startsWith('groovy-all')
}
}.each { ModuleLibrary lib -> lib.sources.add(pf.path('file://$GROOVY_SRC_HOME$')) }
}
}
This relies on me having installed a gradle src distribution into a location available via the GRADLE_HOME path variable in intellij (and similar for GROOVY_SRC_HOME). You can also see my plugin currently uses gradle 1.8, the src layout changed in 1.9 so I need to fix this when I upgrade.