How to statically weave JPA entities using EclipseLink when there is no persistence.xml as the entities are managed by Spring - spring

I've got a project that is Spring based, so the entity manager is set up progammatically, with no need for persistence.xml files to list all the entities.
I'm currently using load time weaving but am trying to get static weaving working using Eclipselink and Gradle. I want to replicate what is performed by the maven eclipselink plugin:
https://github.com/ethlo/eclipselink-maven-plugin
I have the following gradle set up (note that it's Kotlin DSL not groovy):
task<JavaExec>("performJPAWeaving") {
val compileJava: JavaCompile = tasks.getByName("compileJava") as JavaCompile
dependsOn(compileJava)
val destinationDir = compileJava.destinationDir
println("Statically weaving classes in $destinationDir")
inputs.dir(destinationDir)
outputs.dir(destinationDir)
main = "org.eclipse.persistence.tools.weaving.jpa.StaticWeave"
args = listOf("-persistenceinfo", "src/main/resources", destinationDir.getAbsolutePath(), destinationDir.getAbsolutePath())
classpath = configurations.getByName("compile")
}
When I try and run the task the weaving tasks fails as it's looking for a non-existent persistence.xml.
Is there any way you can statically weave JPA entities in a Spring based JPA project ?
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/home/blabla/trunk/my-module/src/main/resources/
Internal Exception: java.net.MalformedURLException
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionProcessingPersistenceXML(PersistenceUnitLoadingException.java:117)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:579)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:536)
... 6 more
Caused by: java.net.MalformedURLException
at java.net.URL.<init>(URL.java:627)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:620)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:148)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:806)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceXML(PersistenceUnitProcessor.java:577)
... 7 more
Caused by: java.lang.NullPointerException
at java.net.URL.<init>(URL.java:532)
... 17 more

According to org.eclipse.persistence.tools.weaving.jpa.StaticWeave documentation, it requires the persistence.xml in place to generate the static weaving sources.
Usage:
StaticWeave [options] source target
Options:
-classpath
Set the user class path, use ";" as the delimiter in Window system and
":" in Unix system.
-log
The path of log file, the standard output will be the default.
-loglevel
Specify a literal value for eclipselink log level(OFF,SEVERE,WARNING,INFO,CONFIG,FINE,FINER,FINEST). The default
value is OFF.
-persistenceinfo
The path contains META-INF/persistence.xml. This is ONLY required when the source does not include it. The classpath must contain all
the classes necessary in order to perform weaving.
I run a maven build using eclipselink maven plugin, it works without the persistence.xml as you mentioned, because it generates the persistence.xml
before invoking the StaticWeave.class when It is not located in the CLASSPATH, using this method.
private void processPersistenceXml(ClassLoader classLoader, Set<String> entityClasses)
{
final File targetFile = new File(this.persistenceInfoLocation + "/META-INF/persistence.xml");
getLog().info("persistence.xml location: " + targetFile);
final String name = project.getArtifactId();
final Document doc = targetFile.exists() ? PersistenceXmlHelper.parseXml(targetFile) : PersistenceXmlHelper.createXml(name);
checkExisting(targetFile, classLoader, doc, entityClasses);
PersistenceXmlHelper.appendClasses(doc, entityClasses);
PersistenceXmlHelper.outputXml(doc, targetFile);
}
The complete source code is here
I believe you could follow the same approach in your gradle build.

Kinda late to the party but this is definitely possible with Gradle.
There are 3 steps to do in order to make this work:
Copy the persistence.xml file into the source folder next to the classes
Do the weaving
Remove the persistence.xml file from the classes source folder to avoid duplicate persistence.xml conflicts on the classpath
Also, it's very important to hook the weaving process into the compileJava task's last step in order to not break Gradle's up-to-date check, otherwise Gradle will just recompile everything all the time which can be quite inconvenient when developing.
For a more detailed explanation, check out my article on it: EclipseLink static weaving with Gradle.

I admit, I do not completely understand what you mean by weaving. My answer might help if you need to create dynamically PersistenceUnits which provide JPA-Entitymanagers, and if these units should be able to create a Db-Schema (for example in H2) and manage Entities based dynamically on the classes you provide at runtime.
The code-example I am mentioning later, does not work with JPA in Spring but in Weld. I think the answer to your question is related to how EntityManagers are created and what classes the PersistenceUnit, which creates the EntityManager, does manage. There is no difference between those two. Instead of using the EntityManagerFactory as CDI-Producer you might Autowire it or register it using an old fashioned application-context. Therefore I think the answer to your question lies in the following official sources:
PersistenceProviderResolverHolder and
PersistenceProvider#createEntityManagerFactory(getPersistenceUnitName(), properties)
properties is the replacement for the persistence.xml, where a SEPersistenceUnitInfo-Object can be registered in.
To start look at: PersistenceProviderResolverHolder
Later: PersistenceProvider
or you can try to understand how my code (see below) is doing that. But I have to admit, I am not very proud of this part of that software, sorry.
Those classes and objects are used by me to create a module that enables the simulation of a server deployed JPA-WAR-File.
To do that, it scans some classes and identifies Entities.
Later in the Testcode a so called PersistenceFactory creates EntityManager and Datasources. If eclipselink is used this factory weaves those classes together. You need no persistence.xml. The working there might be help to answer your question.
If you look at:
ioc-unit-ejb:TestPersistencefactory
search for the creation of SEPersistenceUnitInfo. That Interface got fed by a list of classes which it returns as
#Override
public List<String> getManagedClassNames() {
return TestPersistenceFactory.this.getManagedClassNames();
}
This object is used to create a Persistencefactory with the help of a PersistenceProvider. This can be discovered as soon as eclipselink is available in the classpath.
The code is not easy to be understood because it allows both Hibernate or Eclipselink to be used for JPA, that depends on the availability of the jars in the classpath.

Related

spring-integration: SplitterFactoryBean may only be referenced once

I have a Spring project (not using Spring Boot, if that's relevant) that I'm trying to connect to a local database using the Postgres JDBC driver. (The local database is actually Yugabyte, but that should be fully compatible with the Postgres driver.)
When starting the application, I get this error message:
java.lang.IllegalArgumentException: An AbstractMessageProducingMessageHandler may only be referenced once (org.springframework.integration.config.SplitterFactoryBean#0) - use scope="prototype"
at org.springframework.util.Assert.isTrue(Assert.java:118)
at org.springframework.integration.config.AbstractStandardMessageHandlerFactoryBean.checkReuse(AbstractStandardMessageHandlerFactoryBean.java:168)
at org.springframework.integration.config.AbstractStandardMessageHandlerFactoryBean.createHandler(AbstractStandardMessageHandlerFactoryBean.java:137)
at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.createHandlerInternal(AbstractSimpleMessageHandlerFactoryBean.java:186)
at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.getObject(AbstractSimpleMessageHandlerFactoryBean.java:174)
at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.getObject(AbstractSimpleMessageHandlerFactoryBean.java:59)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:171)
... 52 more
I can't place this error at all. There is one similar question on Stack Overflow, but there the asker seems to actually know what they're doing and how this is related to spring integration. I, however, am not aware at all that I'm trying to 'reuse' anything. The referenced question also doesn't seem to be related to database configuration.
My setup/configuration is a bit involved, so I'll try to quote the parts that seem relevant.
I have a dao layer project that has the following gradle dependencies (among others):
implementation("org.springframework:spring-context:5.2.2.RELEASE")
implementation("org.springframework:spring-jdbc:5.2.2.RELEASE")
implementation("org.jooq:jooq-kotlin:3.14.11")
runtimeOnly("org.postgresql:postgresql:42.2.19.jre7")
In the same project, I have some configuration (in Kotlin):
#Configuration
open class Config {
#Bean
open fun jdbcTemplate(dataSource: DataSource): JdbcTemplate = JdbcTemplate(dataSource)
#Bean
open fun dslContext(): DSLContext = DefaultDSLContext(SQLDialect.POSTGRES)
#Configuration
#Profile("!unittest")
open inner class NonTestConfig {
#Bean
open fun dataSource(): DataSource {
return DriverManagerDataSource().apply {
// Hardcoded properties to be replaced by values from property file
setDriverClassName("org.postgresql.Driver")
url = "jdbc:postgresql://localhost:5433/demo"
username = "yugabyte"
password = "yugabyte"
}
}
}
}
(Notes: the DSLContext bean is used for JOOQL, included for completeness' sake. The inner class config is there because there is also a separate unit testing config for an embedded database - that one works fine!)
Now, the above project is used in my top-level project that contains the actual application. It's a maven runtime dependency there. I import the config class in this project's XML configuration, using this method:
<context:annotation-config />
<bean class="my.package.Config" />
Then trying to start the application produces the error message.
I figured out what the problem was, but I still don't know how it relates to a <splitter>.
The problem was that the Config class, apart from the database stuff, also included a bean to encrypt data. It turned out that this bean was also defined in another library used by the top-level project. Fixing this duplicate bean problem made the error go away.
I discovered this in a roundabout way: I included the dao project and its configuration in a different top-level project that uses Spring Boot. This led to a clear error message about the encryptor bean having two definitions.
If anyone can explain why the error message is so cryptic in the non-Boot case, that would be a nice complementary answer.

Classloader Issues with Envers in OSGi

I've successfully started Hibernate in an OSGi context, and now I want to add Envers.
The documentation claims that's possible. I don't believe it anymore. There is no documentation of any kind for this subject and nobody seems to have actually done it. Moreover even with a Blueprint implementation I had to hack the classloader to make Hibernate even find Envers:
osgiClassLoader = new org.hibernate.osgi.OsgiClassLoader();
osgiClassLoader.addBundle(requestingBundle);
osgiClassLoader.addBundle(FrameworkUtil.getBundle(SessionFactory.class));
osgiClassLoader.addBundle(FrameworkUtil.getBundle(HibernateEntityManagerFactory.class));
osgiClassLoader.addBundle(FrameworkUtil.getBundle(EnversService.class));
Thread.currentThread().setContextClassLoader(osgiClassLoader);
(I feel like I should be asking: "Is Envers in OSGi even possible?" So if you have a definite answer for that question, please let me know. I've been spending way too much time on these issues.)
However the actual problem has nothing to do with Hibernate / Envers and all with OSGi. Both want to access the entities and enums used. With reflection nonetheless. Of course they can't. And of course I can't add Import-Packages.
The relevant stack trace looks something like this:
Caused by: java.lang.ClassNotFoundException: org.acme.project.MyEnum cannot be found by org.hibernate.core_5.1.0.Final
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:461)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:161)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:151)
at org.hibernate.type.EnumType.setParameterValues(EnumType.java:105)
... 62 more
Normally with OSGi-agnostic frameworks I'd just add something like this to the MANIFEST.MF:
// to org.hibernate.core
Eclipse-BuddyPolicy: registered
// to org.acme.project
Eclipse-RegisterBuddy: org.hibernate.core
However I can't add anything to Hibernate's manifest. I tried contributing the line via fragment, but that did not work either.
I even tried adding the entire Hibernate dependencies as JAR into a plug-in to add the above. It won't work.
How to resolve these classloader issues?
If your #Audited class references an Enum, org.hibernate.core needs to import the classes package. The best way to do this is to register a fragment bundle.
Also, it is wise to make sure your start level for hibernate bundles is lower than the start levels for entity bundles.
Here is a snippet from a sample Gradle script to create a fragment bundle. Make sure your change the org.hibernate.core bundle version to the one you are using, and also update the 'your.package' to the one that contains your Enum.
/*
When using Envers, entities that reference Enum classes must be imported (Import-Package) by the org.hibernate.core bundle.
*/
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:3.2.0'
}
}
apply plugin: 'biz.aQute.bnd.builder'
jar {
manifest {
attributes(
'Fragment-Host': 'org.hibernate.core;' + 'bundle-version=' + '5.2.9.Final',
'Import-Package': 'your.package'
)
}
}
Late to the party, but throwing this here in case anyone else needs it:
Hibernate bootstrapping looks fairly different in OSGi than it does in SE/EE land. We have numerous tickets in JIRA tracking enhancements, especially to make things more dynamic and to reduce the brittleness of startup ordering (Steven is absolutely correct that hibernate-core, hibernate-envers, etc. must currently be started first prior to your bundle).
I'd highly advise against the bundle fragment approaches, but I'll comment why on Steven's answer.
Our hibernate-demos project has a few OSGi quickstarts, all of which include Envers setup. This one is probably more of what you're looking for: https://github.com/hibernate/hibernate-demos/tree/master/hibernate-orm/osgi/unmanaged-native

Spring 4 with maven build application is not deployed in tomcat 8 compiled using java 8 upgradation.Unable to resolve [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

NullPointerException com.liferay.portal.spring.util.SpringFactoryImpl.setBeanDefinitions

I'm using springFramework and I try to setBeanDefinitions, the problem is that this methode need a Map beanDefinition as a param... could U tell me plz how I could instantiate this param?
NullPointerException at com.liferay.portal.spring.util.SpringFactoryImpl.setBeanDefinitions(SpringFactoryImpl.java:56)
additional information:
I try to deploy a liferay project without using liferay configuration files (only springFramework libraries), I created my own sessionFactory, my own dataSource ... etc!!
when I run the program, I'm able to create dataBase Schema basing on portlet-hbm.xml information... well now I try to instantiate beans for portal-spring.xml.. (which are xxxxpersistance.java)! those latters told me that they use 'com.liferay.portal.kernel.dao.orm.SessionFactory' as a required type and it can not convert property value of type 'org.hibernate.impl.SessionFactoryImpl'!! so I tried to use the liferay libraries only for those beans and I try to instanciate them manually... but I wasn't able to setBeanDefinitions cause I need a Map beanDefinition as a param... I don't know if there is a way to get them using sessionFactory or not!!
Thanks again
You only mention junit in the tags to your question. I'd recommend to write unit tests without relying on the whole Liferay infrastructure. That will tremendously lower your required setup efforts and simplify your life a lot.

Testing Hibernate Mappings

I'm using Hibernate to map objects to a legacy schema which contains some ginormous tables via annotations (as XML files are so 2003). Since these classes are so large, yes I occasionally make an occasional typo, which Hibernate doesn't bother to tell me about until I try to run it.
Here's what I've tried:
One: Setting hbm2ddl.auto to "validate":
This causes the String values of the class to validate against varchar(255). Since many of the column types in the database are CHAR(n), this blows up. I would have to add the columnDefinition="CHAR(n)" to several hundred mappings.
Two: Using Unitils.
Importing these via Maven causes imports of dependency libraries which blow up other sections of code. Example: I'm using Hibernate 4.1, but Unitils imported Hibernate 3.2.5 and blew up a UserType.
So, is there another way to do this? I looked at the Unitils code to see if I could simply yank the sections I needed (I do that with apache-commons fairly often when I just need a single method), but that's not a simple task.
Hibernate is configured via a Spring application context.
Any ideas out there?
I would write tests against an in-memory database (HSQLDB, H2) using the Spring testing framework. You'll quickly see any mapping errors when you attempt to run queries against the tables.
The test class would look something like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=MyTestConfig.class)
#TransactionConfiguration(transactionManager="txMgr", defaultRollback=true)
public class MyTest {
#Autowired
private SessionFactory sessionFactory;
// class body...
}
I would configure Hibernate to auto-deploy the tables as part of the tests.

Resources