Use local jar as a dependency in my Gradle Java project - java

I have a local jar file named mylib.jar. I want to used it as a dependency in my Gradle Java project.
This is what I tried:
I created a libs/ folder under project root. I put the jar file under libs/ folder.
MyProject
->libs/mylib.jar
->build.gradle
->src/...
In my build.gradle:
apply plugin: 'java-library'
group 'com.my.app'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
api files('libs/mylib.jar')
}
But I can't access the public classes defined in mylib.jar in my project code. Why?
===== More information =====
The content of my jar:
mylib.jar
> com.my.jar.package
>ClassFromJar.class
Here is how I use the jar:
// Compilation error: Cannot resolve symobl 'ClassFromJar'
import com.my.jar.package.ClassFromJar;
public class MyEntryPoint {
// Compilation error: Cannot resolve symbol 'ClassFromJar'
ClassFromJar instance = new ClassFromJar();
}

Similar answers suggesting
Local dir
Add next to your module gradle (Not the app gradle file):
repositories {
flatDir {
dirs 'libs'
}
}
Relative path:
dependencies {
implementation files('libs/mylib.jar')
}
Use compile fileTree:
compile fileTree(dir: 'libs', include: 'mylib.jar')

A flatDir repository is only required for *.aar(which is an Android specific library format, completely irrelevant to the given context). implementation and api affect the visibility, but these are also Android DSL specific). In a common Java module, it can be referenced alike this:
dependencies {
compile fileTree(include: ["*.jar"], dir: "libs")
}
And make sure to drop the *.jar into the correct one libs directory, inside the module.

I thinks you should use in dependency declaration compile name: 'mylib' in this case flatDir will search for mylib.jar.
You could try following build.gradle (it works in my project):
plugins {
id 'java'
}
apply plugin: 'java-library'
group 'dependency'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile name: 'mylib'
}

Just in case:
1 - compiler must have access to lib directory and jar
example:
javac -cp .;lib\* *.java
2 - ALSO import must be mentioned in java file
example in your java add
import static org.lwjgl.glfw.GLFW.*;

Related

Error in executing the Jar file in command Pompt (Gradle Build): NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook

I am building a Java Project using Gradle Build. The project has some external dependencies like Apache POI, Spring Core/Context, Log4j. When I run the project in my IDE , it is compiling and executing successfully without any errors.
However, when I build the Jar file using gradle build and run it in command prompt (using "java -jar file-name") I get Error -
NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook
Here is the my build.gradle file -
buildscript{
repositories{
mavenCentral()
}
dependencies{
classpath group: 'org.springframework', name: 'spring-core', version: '5.0.2.RELEASE'
classpath group: 'org.springframework', name: 'spring-context', version: '5.0.2.RELEASE'
classpath group: 'org.apache.poi', name: 'poi', version: '3.17'
classpath group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
classpath group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '3.17'
classpath group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'
classpath group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '2.6.0'
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
mainClassName = '<package>.HelloWorld'
dependencies{
compile 'org.apache.poi:poi:3.17'
compile 'org.apache.poi:poi-ooxml:3.17'
compile 'org.apache.poi:poi-ooxml-schemas:3.17'
compile 'org.springframework:spring-core:5.0.2.RELEASE'
compile 'org.springframework:spring-context:5.0.2.RELEASE'
compile 'org.apache.commons:commons-collections4:4.1'
compile 'org.apache.xmlbeans:xmlbeans:2.6.0'
}
jar {
manifest{
attributes '<package>.HelloWorld'
}
baseName = 'finder-app'
version = '0.1.0'
}
The dependency jar files are present on my local machine.
Do I need to add the jar files when I package the jar using build.gradle? If yes, then how? OR
Do I need to add CLASSPATH (to external jar directory) to my local machine environment variable?
You can try the following build.gradle, it would deliver a uber jar, which package all the dependencies (doc reference).
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3'
}
}
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
repositories {
jcenter()
}
dependencies {
compile 'com.google.guava:guava:23.0'
testCompile 'junit:junit:4.12'
}
mainClassName = "com.github.Library"
dependencies{
compile 'org.apache.poi:poi:3.17'
compile 'org.apache.poi:poi-ooxml:3.17'
compile 'org.apache.poi:poi-ooxml-schemas:3.17'
compile 'org.springframework:spring-core:5.0.2.RELEASE'
compile 'org.springframework:spring-context:5.0.2.RELEASE'
compile 'org.apache.commons:commons-collections4:4.1'
compile 'org.apache.xmlbeans:xmlbeans:2.6.0'
}
shadowJar {
baseName = 'finder-app'
version = '0.1.0'
}
Just run ./gradlew :shadowJar, and then you can run java -jar build/libs/finder-app-0.1.0-all.jar. It would work for your favor.
NOTE, you dont need so many irrelevant dependencies in your buildscript{}, those are serves for plugins usage.
To run a java application you need to provide a classpath
You have two options:
provide the classpath in the jar manifest (META-INF/manifest) then you can run your jar using
java -jar myjar.jar
provide the classpath using -cp parameter then you can run your jar using
java -cp list_of_dependencies_jar_and_main_jar package.MyMainClass

how to exclude a folder from checkstyle of Gradle on Intellij

I am new for IntelliJ and Gradle, but I have enough experience on Java and Eclipse. I generated some java classes from wsdl file. I put them under src/main/resources with a folder name - "generatedsources".
I try to prevent checkstyle for this folder and its subfolders like src/main/resources/generatedsources/* with gradle on IntelliJ.
I tried some lines such;
task checkstyle(type: Checkstyle) {
source 'src'
// include '**/*.java'
// exclude '**/gen/**'
// exclude '**/R.java'
// exclude '**/BuildConfig.java'
exclude 'src/main/resources/generatedsources/**'
}
But I'm failed again.
build.gradle;
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'checkstyle'
apply plugin: 'java'
apply plugin: 'no.nils.wsdl2java'
sourceCompatibility = 1.7
version = '1.0'
...
buildscript{
repositories{
jcenter()
mavenCentral()
}
dependencies {
classpath 'no.nils:wsdl2java:0.10'
}
}
task checkstyle(type: Checkstyle) {
source 'src'
// include '**/*.java'
// exclude '**/gen/**'
// exclude '**/R.java'
// exclude '**/BuildConfig.java'
exclude 'src/main/resources/generatedsources/**'
}
EDIT - After recommendations(but still failed!):
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'checkstyle'
apply plugin: 'java'
apply plugin: 'no.nils.wsdl2java'
sourceCompatibility = 1.7
version = '1.0'
description = """BLABLABLA_application"""
war.archiveName = "BLABLABLA.war"
configurations{
deployerJars
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.3'
compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.3'
compile group: 'org.springframework', name: 'spring-core', version:'4.0.0.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version:'4.0.0.RELEASE'
compile 'log4j:log4j:1.2.17'
compile 'com.sun.xml.ws:jaxws-rt:2.2.8'
compile 'org.jvnet.jax-ws-commons.spring:jaxws-spring:1.9'
compile group: 'org.springframework', name: 'spring-webmvc', version:'4.0.0.RELEASE'
providedCompile group: 'javax.servlet', name: 'servlet-api', version:'2.5'
testCompile group: 'junit', name: 'junit', version: '4.11'
deployerJars "org.apache.maven.wagon:wagon-http:2.2"
}
jar {
manifest {
attributes 'Implementation-Title': 'BLABLABLA', 'Implementation-Version': version
}
}
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
buildscript{
repositories{
jcenter()
mavenCentral()
}
dependencies {
classpath 'no.nils:wsdl2java:0.10'
}
}
wsdl2java{
wsdlsToGenerate = [
["$projectDir/src/main/resources/BLABLABLA.wsdl"]
]
generatedWsdlDir = file("$projectDir/src/gen/java")
wsdlDir = file("$projectDir/src/main/resources")
}
wsdl2javaExt {
cxfVersion = "2.5.1"
}
tasks.withType(Checkstyle) {
exclude '**/your/generated/package/goes/here**'
}
checkstyleMain.exclude '**/your/generated/package/goes/here**'
"exclude" in tasks.withType and "checkstyleMain" causes an error such as "cannot resolve symbol"!
When checkstyle plugin is applied custom tasks are delivered along with it (see here), so instead of adding custom task with type Checkstyle configure the shipped one. This is how it should be done:
tasks.withType(Checkstyle) {
exclude '**/your/generated/package/goes/here**'
}
You can also configure a particular task, not all:
checkstyleMain.exclude '**/your/generated/package/goes/here**'
Also this is not good practice to put generated sources under src/main/resources. Typically such files goes to e.g. src/gen/java
I followed some comments and make it work add this in file build.gradle
checkstyle {
config = rootProject.resources.text.fromFile("${project.projectDir}/checkstyle-8.34_google_checks.xml")
toolVersion = '8.34'
ignoreFailures = false
maxWarnings = 0
}
checkstyleMain
.exclude('com/examples/gen/api/*.java')
.exclude('com/examples/gen/model/*.java')
.exclude('com/examples/gen/auth/*.java')
You can only exclude a folder that is in the source set. That is something that had not been mentioned and it caused me to struggle since I am using Intellij. The generated files are in the build/ folder which is on the same level as src/. I tried excluding the build folder for a while but there was no effect. The only solution was to specify the source folder. Since the build folder is not under src (the source folder), it worked immediately.
checkstyleMain.source = "src/main/java"
I found the solution here: Specify excludes to Checkstyle task
I had lots of issues with checkStyle & pmd + QueryDSL
A final solution for me was not to exclude generated sources, but clean them after assemble task: no sources - nothing to analyze! :)
assemble {
finalizedBy cleanQuerydslSourcesDir
}
For kotlin dsl use
tasks.withType<Checkstyle>() {
exclude("**/com/generated/*.java")
}

Gradle + Java, multiproject build.gradle

This is my file hierarchy, 'Domain Module' has no code right now, basically a wrapper for DBController and Domain.
Domain Module
.gradle
.idea
build
DBController
build
src
main
java
interfaces
IDBController.java
DBController.java
res
some SQL files
test
java
some test files
build.gradle
Domain
.gradle
build
gradle
src
main
java
Server.java
build.gradle
gradlew
gradlew.bat
settings.gradle
gradle
build.gradle
gradlew
gradlew.bat
settings.gradle
This is my build.gradle in Domain Module/build.gradle
group 'Group'
version '1.0-SNAPSHOT'
apply plugin: 'java'
targetCompatibility = 1.8
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile project(':Domain')
compile project(':DBController')
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
this is build.gradle in DOmain Module/DBController/build.gradle
group 'Group'
version '1.0-SNAPSHOT'
apply plugin: 'java'
compileJava {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'org.postgresql:postgresql:9.3-1103-jdbc3'
}
}
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
dependencies {
compile('com.googlecode.json-simple:json-simple:1.1.1')
compile files('libs/json-simple-1.1.1.jar')
compile('org.postgresql:postgresql:9.3-1103-jdbc3')
}
And finally, build.gradle in Domain Module/Domain/build.gradle
group 'Group'
version '1.0-SNAPSHOT'
buildscript {
repositories {
mavenCentral()
jcenter()
}
}
apply plugin: 'java'
apply plugin: 'idea'
repositories {
mavenCentral()
jcenter()
}
sourceCompatibility = 8
targetCompatibility = 8
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
dependencies {
compile project(':DBController')
}
My main method is in Server.java, and it uses an instance of DBController. How do i assign this file in my java manifest? I've tried the simple
jar {
manifest {
attributes 'Main-Class': 'Domain.src.main.java.Server'
}
but whenever i try to execute java -jar -the generated jar in Domain Module/build/libs-
i get an error telling me it can't find the main file, and as the build gradles are now it gives me an error saying there's no reference to a main class at all.
The gist of my project is that DBController issues queries against a SQL server, and that Server.java will be a spring server. I decided to use gradle to do this so i would learn, and while i have learned alot about gradle, there is still much uncertainty.
I just figured out what was wrong.
jar {
manifest {
attributes 'Main-Class': '-insert main class here-'
}
}
This attribute assumes you're in the src/main/java dir to begin with, so if my filepath was
src/main/java/robert/util/Class.java
i would just have to say
jar {
manifest {
attributes 'Main-Class': 'robert.util.Class'
}
}
Spent so much time solving such a trivial error. My tip for anyone else is to not overlook the 'intro to gradle' sites and such. The solution was there all along.

How can I add a generated source folder to my source path in Gradle and IntelliJ?

I use thrift and it generates some source java files(interfaces) under build directory (build/generated-sources/thrift/<package name>/<class>) but under my src/main/java I have my classes which has the same package definition as in the generated java files and my classes also implements the interfaces generated by the thrift so how can I configure this in my build.gradle so it works on intelliJ as well as the build
plugins {
id "org.jruyi.thrift" version "0.3.1"
}
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: "org.jruyi.thrift"
group 'com.hello'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.5
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.apache.thrift', name: 'libthrift', version:'0.9.3'
compile 'com.datastax.cassandra:cassandra-driver-core:3.0.0'
compile 'com.datastax.cassandra:cassandra-driver-mapping:3.0.0'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
compileThrift {
thriftExecutable "/usr/local/hello/bin/thrift"
sourceDir "src/main/thrift"
createGenFolder false
}
task thrift(type: Exec) {
commandLine '/usr/local/hello/bin/thrift'
}
compileJava {
dependsOn 'compileThrift'
The gradle build should work automatically.
To make it work on Intellij, try adding the following to your build.gradle.
idea.module.sourceDirs += file("$buildDir/generated-sources/thrift")
Don't forget to refresh your gradle projects.

Is there any way of making IntelliJ IDEA recognizing Dagger 2 generated classes in a Java project?

Context
I have started a personal project in java with Gradle as the build system and I want to use Dagger 2 as a DI. The main reason of doing that is to get used to that library and be able to use it easily in bigger projects.
What have I tried
I've managed to make the Google sample runs on IntelliJ IDEA
Problem
IntelliJ IDEA keeps telling me that it cannot resolve the generated class (in this case DaggerCoffeeApp_Coffee). It's a bit annoying not to know if the written code is correct (specially when you are learning to use Dagger 2).
All java classes are the same as the Google sample. Here is my build.gradle file:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.0.1'
compile 'com.google.dagger:dagger-compiler:2.0.1'
}
Question
Is there any way to make IntelliJ IDEA recognize DaggerCoffeeApp_Coffee as a generated class (and so make it possible to go to its implementation by `ctrl + left click)?
Simplest way I found:
Add idea plugin and add Dagger2 dependency like below:
plugins {
id "net.ltgt.apt" version "0.10"
}
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.11'
apt 'com.google.dagger:dagger-compiler:2.11'
}
Turn on Annotation Processing for IntelliJ: Go to Settings and search for Annotation Processors, check Enable annotation processing like below image:
Finally I made it!
I had to add the apt and the idea plugin so right now my build.gradle file look like this:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "net.ltgt.gradle:gradle-apt-plugin:0.4"
}
}
apply plugin: "net.ltgt.apt"
apply plugin: 'java'
apply plugin: 'idea'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0.1'
}
you must manually enable the annotation processing in IntelliJ.
From: Settings --> Build, Execution, Deployment --> Compiler --> Annotation Processors --> Enable annotation processing and Obtain processors from project classpath
then rebuild the project and you will find the generated classes in the project.
Please note that I have used this solution in a (java) android project.
I'm using version 2017.3.3 of IntelliJ IDEA, version 0.14 of the net.ltgt.apt plugin and version 2.14.1 of Dagger and as well as applying the idea plugin in the build.gradle file (as in Pelocho's answer) I found I also had to tell IntelliJ where it can find the sources generated by Dagger, as follows:
apply plugin: 'idea'
idea {
module {
sourceDirs += file("$buildDir/generated/source/apt/main")
testSourceDirs += file("$buildDir/generated/source/apt/test")
}
}
This is what I had to do in order to get Idea to work with Dagger2 and gradle.
Turn on annotation processing as shown in the answers above.
Add the following to the build.gradle file in order for Idea to see the generated classes as sources.
sourceDirs += file("$projectDir/out/production/classes/generated/")
Here's the full listing of my build.gradle
plugins {
id 'java'
id 'idea'
id "net.ltgt.apt" version "0.10"
}
idea {
module {
sourceDirs += file("$projectDir/out/production/classes/generated/")
}
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.dagger:dagger:2.16'
apt 'com.google.dagger:dagger-compiler:2.16'
}
sourceCompatibility = 1.8
Also, I had to add the following gradle task (to my build.gradle file) to clear out my out directory. When I moved some files around and Dagger2 regenerated the source files, the out directory wasn't being cleared out :(. I also included this task in my run configuration, so that it gets triggered before I rebuild my project.
task clearOutFolder(type: Delete) {
delete 'out'
}
Here's the solution that worked for me:
File -> Project Structure -> (select your project under list of modules) -> Open 'Dependencies' tab
Then, click on green '+' sign, select 'JARs or directory' and select 'build/classes/main' folder.
Another solution would be to link folder with build class files using 'dependencies' block inside build.gradle:
https://stackoverflow.com/a/22769015/5761849
Using IntelliJ IDEA 2019.1 and Gradle 5.4.1, this seems to be enough:
plugins {
id 'java'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testImplementation group: 'junit', name: 'junit', version: '4.12'
implementation 'com.google.dagger:dagger:2.23.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.23.1'
}
I don't know the minimal versions for which this solution works, though.
I had a similar problem, I could not find out the cause for a long time.
Just launched and the result surprised me.
Intellij Idea 2018.3.6 -
build.gradle:
plugins {
id "java"
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.11'
apt 'com.google.dagger:dagger-compiler:2.11'
}
The following worked for me on IntelliJ 2021.3.3 (UE)
plugins {
id 'java'
id 'idea'
id("com.github.johnrengelman.shadow") version "7.1.2"
}
idea {
module {
sourceDirs += file("$projectDir/build/generated/sources/annotationProcessor/java/main")
testSourceDirs += file("$projectDir/build/generated/sources/annotationProcessor/java/test")
}
}
group 'com.codigomorsa'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
annotationProcessor 'com.google.dagger:dagger-compiler:2.44'
implementation 'com.google.code.gson:gson:2.9.1'
implementation 'com.google.dagger:dagger:2.44'
testAnnotationProcessor 'com.google.dagger:dagger-compiler:2.44'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
}
test {
useJUnitPlatform()
}

Categories

Resources