Spring NoClassDefFoundError: wrong name - java

I have the following class:
package com.spring.domain;
#Document(collection = "sportactions") // for my mongodb collection
#JsonInclude(JsonInclude.Include.NON_NULL)
public class SportAction extends Action {
//code logic
}
When I compile it, it gives me the following error:
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong
name: com/spring/domain/SportAction)] with root cause
java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong
name: com/spring/domain/SportAction)
I was confused as I can see my class is called SportAction with a capital A and not a small letter a so then I attempted to refactor my class name to see if it will work with a small letter a.
I got the following error:
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Handler processing failed; nested exception is
java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong
name: com/spring/domain/Sportaction)] with root cause
java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong
name: com/spring/domain/Sportaction)
The spring application will compile perfectly but this will appear at run time when I try to use the class.
I also did several clean and then build on gradle and it still doesn't work.
Does anyone know what is wrong with the code?
The error arose in this line of my java code when I try to fetch a list of Sportaction from mongodb:
List<Sportaction> sportactions = mongoTemplate.find(query, Sportaction.class);

I don't know why this error occurred, but my build.gradle file required me to build a jar like so:
task stage(type: Copy, dependsOn: [clean, build]) {
from jar.archivePath
into project.rootDir
rename {
'app.jar'
}
}
stage.mustRunAfter(clean)
clean << {
project.file('app.jar').delete()
}
When I ran it and pushed it onto my repo, I got a very strange error where my filename was now SportAction but my class name inside my java file was:
public class Sportaction
This caused a mismatch, and I tried refactoring the name to match the filename SportAction but the same wrong name error arose. I then decided to refactor the name to something else like SportEvents and then rerun the code and then it worked.
This isn't the best solution but it will have to do for now. I suspect it has something to do with the way the jar was built but I'm not sure as the app.jar was never run. The Application.main() was the class that ran when I ran my Spring app.
I'm also confused as to why my SportAction class on bitbucket does not seem to have a commit at all - see those 3 dots next to my Action file - it doesn't have a date and neither does it have a description.

Related

Failed to load a service: io.micronaut.context.exceptions.BeanContextException: | Micronaut

I have just created a file named TransactionsRepository.java. I am not calling this class anywhere as of now
TransactionsRepository.java
package com.example.Transactions;
import io.micronaut.data.annotation.Repository;
// #Repository
public interface TransactionsRepository {
}
Whenever I run ./gradlew run, it runs perfectly, but the moment I uncomment this line, it throws an error
#Repository
ERROR
Exception in thread "main" java.lang.RuntimeException: Failed to load a service: io.micronaut.context.exceptions.BeanContextException: Unexpected error loading be
an definition [com.example.$Transactions.TransactionsRepository$Intercepted$Definition]: failed to access class com.example.Transactions.TransactionsRepository$In
tercepted from class com.example.$Transactions.TransactionsRepository$Intercepted$Definition$Reference (com.example.Transactions.TransactionsRepository$Intercepte
d and com.example.$Transactions.TransactionsRepository$Intercepted$Definition$Reference are in unnamed module of loader 'app')
I even tried doing this but still does not work
#Repository
public interface TransactionsRepository extends CrudRepository<Transaction, Long>{
}
I have also included below line in my gradle file
annotationProcessor("io.micronaut.data:micronaut-data-hibernate-jpa")
I am very new to micronaut. Its been hours I am trying this. I dont know whats wrong in this code. Please help me if I am missing something.
It's probably the package name - package sub-names should not start with uppercase letters. Change com.example.Transactions to com.example.transactions (and rename the directory from Transactions to transactions.

what causes java.lang.NoClassDefFoundError to occur randomly?

We've been getting NoClassDefFoundError in our server randomly. It Occasionally throws this error, and most of the time it runs without throwing any issue. What could be the reason for such weird behavior? Below is the exception.
java.lang.NoClassDefFoundError: Could not initialize class com.github.junrar.Archive
at org.apache.tika.parser.pkg.RarParser.parse(RarParser.java:75)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:143)
at org.apache.tika.Tika.parseToString(Tika.java:527)
at org.apache.tika.Tika.parseToString(Tika.java:602)
at com.xxx.attachment.AttachmentExtractionAPI.parse(AttachmentExtractionAPI.java:108)
com.github.junrar.Archive is present in the same jar which contains other tika dependencies.
I tried looking into the source of Archive.java. Looking for some possible runtime exception in static blocks. But it doesn't have a static block itself. What could have made this to throw exception randomly and run without any problem at times?
EDIT:-
We use ant for building. Below is the part of ant.properties that controls the dependencies of tika. Junrar is available as part of the tika.
tika_jar_file=${prod_home}/tikalib/tika-app-1.24.jar
tika_jar_srcdir=${tp_pkg}/tika
tika_jar_includes=**
tika_jar_excludes=org/apache/tika/parser/** org/apache/xerces/** org/apache/html/** org/apache/wml/** org/apache/xml/** org/xml/sax/** org/apache/xmlcommons/** javax/xml/** org/w3c/dom/**
tika_update_jar_file=${prod_home}/tikalib/tika-app-1.24.jar
tika_update_jar_srcdir=${tp_pkg}/tika
tika_update_jar_includes=org/apache/tika/parser/asm/** org/apache/tika/parser/chm/** org/apache/tika/parser/code/** org/apache/tika/parser/epub/** org/apache/tika/parser/html/** org/apache/tika/parser/iwork/** org/apache/tika/parser/mail/** org/apache/tika/parser/mbox/** org/apache/tika/parser/microsoft/** org/apache/tika/parser/odf/** org/apache/tika/parser/pdf/** org/apache/tika/parser/pkg/** org/apache/tika/parser/rtf/** org/apache/tika/parser/strings/** org/apache/tika/parser/txt/** org/apache/tika/parser/utils/** org/apache/tika/parser/xml/** org/apache/tika/parser/*.* org/apache/tika/parser/image/** org/apache/tika/parser/ocr/** org/apache/tika/parser/csv/** javax/xml/bind/**
tika_update_jar_excludes=
tika_update_jar_update=true
The key to this is understanding the error message:
java.lang.NoClassDefFoundError: Could not initialize class
com.github.junrar.Archive
Note that it says that it cannot initialize the class. There are a few reasons why a class cannot be initialized. These include:
An unchecked exception was thrown (and not handled) during the initialization of this class. If this has occurred, then there should be an earlier exception and stacktrace that tells you what exception was thrown and where.
This class has static dependencies on another class that failed initialization. There should be an earlier exception and stacktrace for that failure.
Possibly there is a dependency issue, though I would have expected a different exception message in that case.
The reason of NoClassDefFoundError is that two different jar of your project depend on the same jar with different version.So you can use the ide to excludes the jar in your pom.

Java.lang.NoClassDefFoundError while using enum in a class

I am getting a weird java.lang.NoClassDefFoundError while deploying my code. No error when I compile it, but when I am deploying it using jetty, I get an error saying
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor#0'
defined in class path resource [applicationContext-dao.xml]:
Initialization of bean failed;
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in class path resource [applicationContext-dao.xml]:
Invocation of init method failed;
nested exception is
java.lang.NoClassDefFoundError: com/core/model/Webhook$Event
The class looks like below
public class Webhook extends BaseObject implements Serializable {
public enum Event {
ORDER_CREATE,
ORDER_UPDATE,
ORDER_DELETE,
TICKET_CREATE,
TICKET_UPDATE,
TICKET_DELETE,
CUSTOMER_CREATE,
CUSTOMER_UPDATE,
CUSTOMER_DELETE,
MENU_ITEM_UPDATE,
CHECK_OFFER
}
private Event triggerEvent;
public Event getTriggerEvent() {
return triggerEvent;
}
public void setTriggerEvent(Event triggerEvent) {
this.triggerEvent = triggerEvent;
}
public String getTriggerEventString() {
return triggerEvent.toString();
}
public void setTriggerEventString(String triggerEvent) {
this.triggerEvent = Event.valueOf(triggerEvent);
}
}
Any Idea whats happening? It doesn't even show what like the error is in.
java.lang.NoClassDefFoundError - 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.
When I deploy in Weblogic, I often had had NoClassDefFoundError due to Weblogic cache. May try to clean cache of jetty or rename Event enum to, for example, Event1 and try again?

NoClassDefFoundError: A (wrong name: A)

Out of a sudden in a formerly working application, I am getting a NoClassDefFoundError (wrong name) which has puzzled me. I am using an XML binding framework which tries to resolve bound classes at request time by calling ClassLoader.loadClass() with the configured class name. (Why does it behave like that is beyond me in this case.) Now I get the exception just mentioned at java.lang.ClassLoader.defineClass(). The documentation on the method says that it will throw a NoClassDefFoundError if the parameter name is not equal to the binary name of the class specified. I am aware that in that case one expects to get an exception of the form
java.lang.NoClassDefFoundError: A (wrong name: B)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:786)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:144)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:382)
....
and this is the outcome I actually see, but the weird thing is that in my case the reported A and B are exactly the same! I tried to debug the app. The line in the JDK source reads:
c = defineClass1(name, b, off, len, protectionDomain, source);
the value of source is OK. I saved the byte array b to a class file and inspected it with a decompiler and it's OK again. Of course Class.forName() reports the same error throughout, but the really funny thing is that if I set name = null in debug mode I get this beast:
java.lang.LinkageError: loader (instance of com/google/gwt/dev/shell/jetty/JettyLauncher$WebAppContextWithReload$WebAppClassLoaderExtension): attempted duplicate class definition for name: "A"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:786)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:144)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:382)
Now I feel completely clueless on this :( I appreciate your help.
The class loader in question is com.google.gwt.dev.shell.jetty.JettyLauncher.WebAppContextWithReload.WebAppClassLoaderExtension in case that matters.
Solved. Just an embarrassing capitalization issue. The names A and B in NoClassDefFoundError: A (wrong name: B) actually did differ by a capitalization.
This happens on Windows, because of its case-insensitive file system. If you look for a class named FooBar and the folder contains a file Foobar.class, the classloader opens the class file, but discovers that internally it has a different name. Hence the exception.
Check the package declaration for the class A and B. Chances are they are either without a package declaration inside some package or the package declaration is not correct.

Drools Flow Human Task example: How do I prevent 'Named query not found' exception being thrown?

I'm trying to follow the Drools Flow example code in the Human Task documentation and I have the following code:
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.drools.task.service.TaskService;
// ...
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("org.drools.task");
TaskService taskService = new TaskService(emf, null);
I have put a persistence.xml file in META-INF as specified here (which is definitely getting picked up as I get an XML parsing error if I mangle it) but the following exception is thrown:
Exception in thread "main" java.lang.IllegalArgumentException:
Named query not found: UnescalatedDeadlines
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(
AbstractEntityManagerImpl.java:108)
at org.drools.task.service.TaskService.<init>(TaskService.java:65)
at org.drools.task.service.TaskService.<init>(TaskService.java:48)
at com.sample.RuleFlowTest.main(RuleFlowTest.java:32)`
Note that the second parameter to TaskService is required but not mentioned in the documentation. It seems unlikely to me but could it be that setting it to null as I've done is causing this issue?
I prevented this exception by copying both persistence.xml and orm.xml from drools-process-task-5.0.1.jar/META-INF (the UnescalatedDeadlines named query being specified in orm.xml) into my built META-INF directory.
However, I'm now getting another exception (java.lang.NoClassDefFoundError: antlr/ANTLRException from Hibernate)...
To fix the antlr/ANTLRException problem I downloaded the latest Hibernate distribution (hibernate-distribution-3.3.2.GA-dist.zip) and added antlr-2.7.6.jar from the lib directory to the classpath.
Does it need to be this complicated?

Categories