Gradle Java 9 Module not found - java

I try to develop a little example in Java 9 with Gradle. But I don't find the exact option to make a working run config. I've tried to copy the right parts from this little tutorial. But the run task does just get an error
java.lang.module.FindException: Module de.project.crawler not found
Obviously there is a mistake with the module path which I gave Gradle but I don't know how to fix this.
My working directory
project/
crawler/
| src/
| | main/
| | | java/
| | | | de.project.crawler/
| | | | | Main.java
| | module-info.java
| build.gradle
| settings.gradle
build.gradle
settings.gradle
build.gradle:
subprojects {
afterEvaluate {
compileJava {
inputs.property("moduleName", moduleName)
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
]
classpath = files()
}
}
}
}
crawler/build.gradle:
plugins {
id 'java-library'
id 'application'
}
ext.moduleName = 'de.project.crawler'
mainClassName = 'de.project.crawler/de.project.crawler.Main'
repositories {
jcenter()
}
run {
inputs.property("moduleName", moduleName)
doFirst {
jvmArgs = [
'--module-path', classpath.asPath,
'--module', mainClassName
]
classpath = files()
}
}
startScripts {
inputs.property("moduleName", moduleName)
doFirst {
classpath = files()
defaultJvmOpts = [
'--module-path', 'APP_HOME_LIBS',
'--module', mainClassName
]
}
}
crawler/src/module-java.info
module de.project.crawler {
}
crawler/src/main/java/de.project.crawler/Main.java
package de.project.crawler;
public class Main {
public static void main(String[] args) {
System.out.println("Hallo");
}
}
So, if I try this in IntelliJ everything is working. If I try this on cmd, compile with java9 and run it, everything is working. If I try 'gradle run' he states the error which I gave you in the introduction.

The module-info.java was on the wrong position. This file has to be on src/main/java in the module. This is the right structure:
project/
crawler/
| src/
| | main/
| | | java/
| | | | de.project.crawler/
| | | | | Main.java
| | | | module-info.java
| build.gradle
| settings.gradle
build.gradle
settings.gradle
Thanks Alan Bateman from the comments.

Related

gradle not finding dependencies in the build folder

I am trying to build a gradle project.
here is my project structure :
|── build
| |──src-gen
|
├── buildSrc
│ ├─gradle.build (2)
|
├── modules
│ ├── tobris-open-suite
│ ├── tobris-accounting
│ | └── gralde.build
├ ├──tobris-admin
| └── gralde.build
|
├── tobris-erp
└── gralde.build (1)
here is my tobris-erp gradle.build (1)
import com.tobris.gradle.tasks.GenerateAosChangelog
import com.tobris.gradle.tasks.CheckEOLCharsInCsv
buildscript {
ext.repos = {
flatDir {
dirs 'libs'
}
mavenCentral() {
content {
excludeGroup 'com.tobris'
}
}
maven {
url 'https://plugins.gradle.org/m2/'
content {
excludeGroup 'com.tobris'
}
}
maven { url 'https://repository.tobris.com/nexus/public/' }
}
ext.openPlatformVersion = '5.4.13'
ext.appVersion = '6.2.2'
repositories repos
dependencies {
classpath "com.google.guava:guava:28.1-jre"
classpath "com.opencsv:opencsv:3.9"
classpath "gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0"
classpath "org.yaml:snakeyaml:1.25"
classpath "org.hibernate:hibernate-core:5.6.5.Final"
classpath "org.hibernate:hibernate-hikaricp:5.6.5.Final"
classpath "org.hibernate:hibernate-validator:5.4.1.Final"
classpath "org.hibernate:hibernate-jcache:5.6.5.Final"
classpath 'javax.persistence:javax.persistence-api:2.2'
classpath 'javax.persistence:javax.persistence-api:2.2'
classpath "com.tobris:tobris-common:${openPlatformVersion}"
classpath "com.tobris:tobris-core:${openPlatformVersion}"
classpath "com.tobris:tobris-gradle:${openPlatformVersion}"
classpath "com.tobris:tobris-test:${openPlatformVersion}"
classpath "com.tobris:tobris-tomcat:${openPlatformVersion}"
classpath "com.tobris:tobris-web:${openPlatformVersion}"
}
}
allprojects { repositories repos }
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: "com.tobris.app"
apply from: './gradle/style.gradle'
allprojects {
configurations {
runtimeClasspath.exclude group: "org.eclipse.birt.runtime.3_7_1", module: "org.apache.commons.codec"
}
apply plugin: 'idea'
apply plugin: 'eclipse'
group = "com.tobris"
version = "${appVersion}"
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
subprojects {
group = "com.tobris.apps"
}
tobris {
title "Tobris ERP"
description "Tobris Entreprise Application"
}
dependencies {
gradle.appModules.each { dir ->
implementation project(":modules:$dir.name")
}
}
task("dataImport", type: JavaExec) {
main = "com.tobris.apps.erp.Main"
classpath = sourceSets.main.runtimeClasspath
if (System.getProperty("exec.args") != null) {
args System.getProperty("exec.args").split()
}
}
task archiveReports(type: Zip) {
file("modules").traverse(type: groovy.io.FileType.DIRECTORIES, maxDepth: 1) { dir ->
if (new File(dir, "build.gradle").exists() && new File(dir, "/src/main/resources/reports").exists()) {
new File(dir, "/src/main/resources/reports/").listFiles().each { report ->
from report.getPath()
}
}
}
classifier 'reports'
includeEmptyDirs = false
destinationDirectory = file("$buildDir/libs")
}
task generateChangeLog(type: GenerateAosChangelog) {
group "Tobris application"
description "Generate change logs from unreleased entries."
files = fileTree(projectDir) {
include '**/changelogs/**/*.yml'
include '**/changelogs/**/*.yaml'
}
}
task checkCsvEOL(type: CheckEOLCharsInCsv) {
group "Tobris application"
description "Generate change logs from unreleased entries."
files = fileTree(projectDir) {
exclude '**/build'
exclude '**/bin'
exclude '**/out'
include '**/*.csv'
}
}
build.finalizedBy archiveReports
and here is my buildSrc gradle.build (2) :
def repos = {
jcenter()
mavenCentral()
mavenLocal()
maven { url 'https://plugins.gradle.org/m2/' }
maven { url 'https://repository.tobris.com/nexus/repository/maven-public/' }
}
ext.repos = repos
repositories repos
buildscript.repositories repos
dependencies {
implementation 'org.yaml:snakeyaml:1.25'
implementation "org.hibernate:hibernate-core:5.6.5.Final"
implementation "org.hibernate:hibernate-hikaricp:5.6.5.Final"
implementation "org.hibernate:hibernate-validator:5.4.1.Final"
implementation "org.hibernate:hibernate-jcache:5.6.5.Final"
implementation 'javax.persistence:javax.persistence-api:2.2'
}
I am generating database entities from XML files using hibernate.
the generated classes are under the src-gen folder under the build.
the issue is when I build the project the classes under src-gen show this error /tobris-erp/build/src-gen/java/com/tobris/dms/db/DMSFile.java:9: error: package javax.persistence does not exist while the I put all the dependencies in all the gradle.build and eclipse is not showing error. I am sure that the jars are in the classpath.
Where should I put the dependencies ? any clue?
it is because of duplicate declaration of dependencies section in the gradle.build (1) :
dependencies {
gradle.appModules.each { dir ->
implementation project(":modules:$dir.name")
}
}

How to load EC private key from a Java string?

I have an EC private key stored in Java String. I am using the following code to read the string and convert it into PrivateKey object which I need to generate a SHA256withECDSA signature.
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
public static PrivateKey getPrivateKey() {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Reader rdr = new StringReader("-----BEGIN EC PRIVATE KEY-----\n" +
"<line1>\n" +
"<line2>\n" +
"<line3>\n" +
"-----END EC PRIVATE KEY-----\n");
Object parsed = new PEMParser(rdr).readObject();
KeyPair pair = new JcaPEMKeyConverter().getKeyPair((org.bouncycastle.openssl.PEMKeyPair) parsed);
return pair.getPrivate();
} catch (IOException e) {
logger.error("IOException generating private key {} ", e);
}
return null;
}
I am able to generate a PrivateKey successfully using a unit test in IntelliJ. However, when I deploy my war on Tomcat, this code throws following exception :
class "org.bouncycastle.asn1.pkcs.RSAPublicKey"'s signer information does not match signer information of other classes in the same package
Maven dependency tree output:
mvn dependency:tree | grep -i "bouncycastle"
[INFO] | | | +- org.bouncycastle:bcmail-jdk15on:jar:1.49:compile
[INFO] | | | +- org.bouncycastle:bcprov-jdk15on:jar:1.49:compile
[INFO] | | | +- org.bouncycastle:bcpkix-jdk15on:jar:1.49:compile
[INFO] | | | | +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile
[INFO] | | | | +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile
I added one of the versions to pom exclusions. Still facing the same issue:
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15</artifactId>
</exclusion>
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15</artifactId>
</exclusion>
Any pointer is appreciated.
Thank you.
Finally excluding unwanted version from war packaging resolved the issue. Added 'packagingExcludes' in my pom.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>
WEB-INF/lib/bcmail-jdk15-1.45.jar,
WEB-INF/lib/bcprov-jdk15-1.45.jar
</packagingExcludes>
</configuration>
</plugin>
Ref : https://maven.apache.org/plugins/maven-war-plugin/examples/including-excluding-files-from-war.html

Class.getDeclaredMethods throwing NoClassDefFoundError for class method with no arguments and void return type

I want to get the names of all the public methods (void return type and no arguments) of a class1 which is dependent on some other class2.
I am loading class through UrlClassLoader. Now when i am calling getDeclaredMethods, it is throwing NoClassDefFoundError caused by ClassNotFoundException.
I am having 3 mvn modules as
SampleClassLoader: Using it to get the methods of class of Module1.
Module1: Its class using the reference to classes of Module2. And has a dependency of Module2 in its pom.xml also.
Module2
The whole module structure looks like:
Project Structure
ClassLoadingTest
|----- Module1
| |--- pom.xml
| |--- src/main/java/
| | |--- com.classloadingtest.module1
| | |
| | |--- Module1Class1.java
| | |--- Module1Class2.java
|
|----- Module2
| |--- pom.xml
| |--- src/main/java/
| | |--- com.classloadingtest.module2
| | |
| | |--- Module2Class.java
|
|----- SampleClassLoader
| |--- pom.xml
| |--- src/main/java/
| | |--- com.classloadingtest.sampleClassLoader
| | |
| | |--- SampleClassLoader.java
Module1Class1.java
public class Module1Class1 {
public void claas1Fun() {
Module2Class module2ClassObj = new Module2Class();
module2ClassObj.module2Fun();
}
}
Module1Class2.java
public class Module1Class2 {
public void class2Fun(){
try {
Module2Class module2ClassObj = new Module2Class();
module2ClassObj.module2Fun();
} catch(Exception e ){
}
}
}
Module2Class.java
public class Module2Class {
public void module2Fun(){
}
}
SampleClassLoader.java
public class SampleClassLoader {
public static void main(String[] args) {
try {
URL mainSourceClassPathURL = new URL("file:" + System.getProperty("user.dir") + "/ClassLoadingTest/Module1/target/classes/");
URL[] urls = { mainSourceClassPathURL};
ClassLoader classLoader = URLClassLoader.newInstance(urls);
Class<?> testCaseClass = classLoader.loadClass("com.classloadingtest.module1.Module1Class1");
Method method[] = testCaseClass.getDeclaredMethods();
for (int i = 0 ; i < method.length ; i++) {
System.out.println(method[i].getName());
}
} catch (Exception e){
e.printStackTrace();
}
}
}
Now, When Running the SampleClassLoader for class Module1Class1 prints
claas1Fun
But when running for class Module1Class2 it is giving NoClassDefFoundError as:
Exception in thread "main" java.lang.NoClassDefFoundError: com/classloadingtest/module2/Module2Class
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at com.classloadingtest.sampleClassLoader.SampleClassLoader.main(SampleClassLoader.java:26)
Caused by: java.lang.ClassNotFoundException: com.classloadingtest.module2.Module2Class
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 4 more
I am having two questions here that is:
When using try catch, why it is giving error?
If the class1 is already loaded at classLoader.loadClass then why getDeclaredMethods method need to load dependent classes?
Concerning the try-catch issue, the point is that java.lang.NoClassDefFoundError is not an Exception, is an Error which is a more severe kind of Throwable.
Errors are, generally speaking, unrecoverable (Like OutOfMemoryError or StackOverflowError, ...), so they are seldom catched.
If you want to catch NoClassDefFoundError you should add catch(NoClassDefFoundError e) to your try

Memory leak in my GWT application

I have a web application created with GWT that has a memory leak.
honestly, I can't produce this memory leak but when we deploy the application in the client environment with many users we face a memory leak problem.
I received this file maybe it can help me, it has the objects in the memory when the memory leak produced.
2'777'369'064 (62.72%) [32] 8 class */planning/canvas/shared/serializable/ActionCycleSZ 0x68759f768
|- 2'777'365'536 (62.72%) [256] 35 org/apache/catalina/loader/WebappClassLoader 0x688ce9df8
| |- 2'775'589'272 (62.68%) [48] 1 java/util/HashMap 0x688ceabe0
| | |- 2'775'589'224 (62.68%) [32'784] 3'533 array of java/util/HashMap$Entry 0x689af74c0
| | |- 2'763'509'944 (62.41%) [24] 2 java/util/HashMap$Entry 0x68a0b1f98
| | | |- 2'763'509'744 (62.41%) [40] 1 org/apache/catalina/loader/ResourceEntry 0x68a0b1fb0
| | | | |- 2'763'509'704 (62.41%) [32] 41 class
*/gwt/server/servlet/TaProjectsSessionManager 0x68653c8e8
| | | | |- 2'763'047'360 (62.4%) [32] 6 class */selfservice/SelfConfigurator 0x6875922a0
| | | | | |- 2'763'047'328 (62.4%) [16] 2 */gwt/server/servlet/TaProjectsSessionManager$1 0x689aee328
| | | | | | |- 2'154'573'968 (48.66%) [160] 30 */impl/HRSessionImpl 0x689ee49f8
| | | | | | | |- 2'138'350'824 (48.29%) [32] 3 java/util/Collections$SynchronizedMap 0x689ee4c70
| | | | | | | | |- 2'138'350'760 (48.29%) [64] 3 org/apache/commons/collections/map/LRUMap 0x689ee5218
| | | | | | | | | |- 2'134'913'368 (48.21%) [32] 2 org/apache/commons/collections/map/AbstractLinkedMap$LinkEntry 0x68a3573d0
| | | | | | | | | |- 3'437'328 (0.08%) [2'064] 121 array of org/apache/commons/collections/map/AbstractHashedMap$HashEntry 0x68a356bc8
| | | | | | | | | |- 16 (0%) [16] 1 org/apache/commons/collections/map/AbstractHashedMap$KeySet 0x69d443088
| | | | | | | | |- 32 (0%) [16] 2 java/util/Collections$SynchronizedSet 0x69d443098
| | | | | | | | |- 2'138'350'824 (48.29%) [32] 3 java/util/Collections$SynchronizedMap 0x689ee4c70
| | | | | | | |- 16'078'096 (0.36%) [104] 19 */impl/Dictionary 0x689ee4ad8
I conclude that the class ActionCycleSZ maybe produce the memory leak
this is ActionCycleSZ
public class ActionCycleSZ extends ActionDTO implements IsSerializable {
private CycleSZ bean;
public ActionCycleSZ() {
}
public ActionCycleSZ(Type actionType, CycleSZ bean ) {
super(actionType);
this.bean = bean;
}
public CycleSZ getBean(){
return bean;
}
public void setBean(CycleSZ bean){
this.bean = bean;
}
}
public class CycleSZ implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String cycleLabel;
Date startDate;
Date endDate;
String startDateDTO;
String endDateDTO;
Integer numlign;
String accumulatedHours;
List<SiteSZ> listOfSites = new LinkedList<SiteSZ>();
//getter and setter
}
public class SiteSZ implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
int week;
String siteLabel;
Date startDate;
Date endDate;
String startHour;
String endHour;
String site;
String time;
String particularSlotTime;
Integer numlign;
DaySZ dayAttribute;
String accumulatedWeekHours;
Map<Util.WeekDays,DaySZ> mapAttributes = new LinkedHashMap<Util.WeekDays,DaySZ>();
boolean workedDay; //Flag for Exceptional Canevas Entry
boolean reposHebdo;
String contratId; //contratId for Exceptional Canevas Entry
ActionCycleSZ Contains the cycle and the action (create,delete,update)
this object will appear when the user create or update or delete this object
eventBus.addHandler(CycleSaveEvent.TYPE, new CycleSaveHandler() {
#Override
public void onCycleSaved(CycleSaveEvent event) {
final List<ActionCycleSZ> listCycleAction = new LinkedList<ActionCycleSZ>();
boolean newInsertion = getDetailsOfNewCycle(listCycleAction); //this methode can detect is there any new cycle and it will add actioncycleSZ
if (editedValuechange) {
getDeletedCycle(listCycleAction);
}
if (!newInsertion) getDetailsOfOldCycle(listCycleAction); getNotWorkedCycle(listOfNWSites,listCycleAction);
updateCycle(listCycleAction);
when the method updateCycle() called the listCycleAction will have all the cycles so the method will call an RPC service to save the cycles
This is updateCycle
public void updateCycle(final List<ActionCycleSZ> listCycleAction) {
//Call to service
new RpcCall2<String>() {
#Override
public void onFailure(Throwable caught) {
deletedListOfCycleSZ.clear();
view.setChantierGridUpdated(false);
}
#Override
public void onSuccess(final String message) {
isNewCycle=false;
SC.say(TAMessages.getMessage("ta.canvas.cycle.saved"), new BooleanCallback() {
#Override
public void execute(Boolean value) {
/* popup to make the user know that the cycle is saved */
}}}
#Override
protected void callService(AsyncCallback<AsyncCallback<String> callback) {
canvasServices.updateListActionCreatedCycle(listOfEmployees, listCycleAction, true, callback);
}
}.call();
I don't see anything that can make a memory leak so I install JProfiler to understand more my problem, I notice that the garbage collector for this object doesn't work whatever I call
canvasServices.updateListActionCreatedCycle(listOfEmployees,listCycleAction,true, callback);
even if the method is empty, On the other hand, the object will disappear in the memory if I don't give the object in the RPC call
what is the cause of the memory leak? am I on the right path?
I want to indicate that I am using GWT 2.5. can it be that GWT makes the memory leak ?

Gradle compile project manifest empty

I have a probleme with my build.gradle, it's compile fine but when i try to execute the .jar the console give me this: "no manifest manifest attribute..."
it's my bluid.gradle:
apply plugin: 'java'
group = "com.xxx.xxx.xxx"
archivesBaseName = "xxx"
version = "0.1"
task pack(type: Jar, dependsOn: 'jar') {
inputs.files jar.archivePath;
jar {
baseName = 'xxxx'
version = '0.1'
}
manifest {
attributes(
"Manifest-Version" : "1.0",
"Main-Class" : "com.xxx.xxx.xxx.xxx"
)
}
doLast {
manifest.writeTo("${buildDir}/MANIFEST.MF")
project.ant {
taskdef name: "jarjar", classname: "com.tonicsystems.jarjar.JarJarTask", classpath: configurations.tools.asPath
jarjar(jarfile: archivePath, manifest: "${buildDir}/MANIFEST.MF") {
fileset(dir : "${buildDir}/classes")
fileset(dir : "${buildDir}/resources/main")
configurations.runtime.files.each { jarjarFile ->
zipfileset(src: jarjarFile) {
// WARNING: MUST keep META-INF/DgmInfo, META-INF/services, ... which are needed by Groovy
}
}
rule pattern: "*", result: "#0"
}
}
}
configurations {
tools
}
dependencies {
tools files("${rootDir}/tools/jarjar-1.4.jar")
compile files("${rootDir}/lib/bluecove-2.1.0.jar")
compile files("${rootDir}/lib/bluecove-gpl-2.1.0.jar")
}
}
I don't write the whole code, I don't really know to code a gradle script,
someone help ? :)
I understand that this part:
"Main-Class" : "com.xxx.xxx.xxx.xxx"
in reality is pointing to a valid Java class that has a main method inside, and the class is on your class path?
If yes, unzip your output jar, find META-INF folder and check what is inside MANIFEST.MF and tell us.

Categories