Filter unwanted INFO-Messages from Logger - java

I'm using java.util.logging to log in my Java application. I'm also using javax.xml.ws.Endpoint to publish a SOAP-interface.
Over the time I added more and more exceptions which all turn up at startup with a log-entry like this:
Jan 24, 2011 12:29:27 PM com.sun.xml.internal.ws.model.RuntimeModeler getExceptionBeanClass
INFO: Dynamically creating exception bean Class de.wi08e.myhome.frontend.jaxws.NotLoggedInBean
I tried following filter to block them, but I'm not sure which class to get with getLogger:
/* Filter ExceptionBeanClass logs */
Logger loggerInfo = Logger.getLogger("javax.xml.ws.Endpoint");
loggerInfo.setFilter(new Filter() {
#Override
public boolean isLoggable(LogRecord l) {
System.out.println(l.getMessage());
if (l.getMessage().startsWith("Dynamically creating exception bean Class"))
return false;
return true;
}
});
Does anyone know how to find out which class creates this log-entries? Is there another way to filter out this nerving messages?
EDIT: I also tried Logger.getLogger("com.sun.xml.internal.ws.model.RuntimeModeler"), but it's still not working...

You should be able to just run the java program with the following flag: -Djava.util.logging.config.file=<mylogging.properties> where mylogging.properties is a file with the following contents instead of doing it in code.
javax.enterprise.resource.webservices.jaxws.server.level = WARN
From http://www.docjar.com/html/api/com/sun/xml/internal/ws/model/RuntimeModeler.java.html
186 private static final Logger logger =
187 Logger.getLogger(
188 com.sun.xml.internal.ws.util.Constants.LoggingDomain + ".server");
and from Constants
public static final java.lang.String LoggingDomain = "javax.enterprise.resource.webservices.jaxws";

Edit: Clement P answered this question right long before me; all thumbs-up should go to him!
I keep my answer here because it uses a slightly other way.
I've now solved it myself. In short, this is the solution:
Logger.getLogger("javax.enterprise.resource.webservices.jaxws.server").setLevel(Level.WARNING);
If anyone's interested, this is how I found it:
The method getExceptionBeanClass in com.sun.xml.internal.ws.model.RuntimeModeler is responsible for the messages. It uses a static Logger instanciated with the function
Logger.getLogger(com.sun.xml.ws.util.Constants.LoggingDomain + ".server");
Google-ing for com.sun.xml.ws.util.Constants leads here where you can copy-and-past the LoggingDomain constant.
But keep in mind: This solution won't work on every JRE, because it depends on Sun's 'private' namespace and implementation.

The log entry seems to indicate that it's the com.sun.xml.internal.ws.model.RuntimeModeler class which generates this log message. You should be able to filter it out by raisong the level for this logger.

Alternatively, you could just create the missing class.
Actually, that's the standard procedure that I follow when creating webservices.
If you create this class (i.e. de.wi08e.myhome.frontend.jaxws.NotLoggedInBean),
then it will just use the existing class, without trying to create it at runtime.
Actually, you don't even have to create these classes yourself. You can generate them using the wsgen tool. The wsgen.exe is part of the java jdk. So, you can just run this from the commandline.
wsgen.exe -verbose -keep -cp . de.wi08e.myhome.frontend.WebService -d source
Next move the created files to the correct project source folder.

Related

java.lang.NoSuchMethodError related with a class constructor

I have the following class signature:
public BlockstemRequester(RateLimiter throttler,
String url, List<String> payloadsToBeRequested, List<String> objRef) {
.
.
.
}
And I'm using that constructor at this following code:
threads.add(new BlockstemRequester(RateLimiter.create(1.0),
String.format("url...", apiKey),
chunks.get(index),
chunksObjRef.get(index)))
where:
RateLimiter is from import com.google.common.util.concurrent.RateLimiter
chunks is defined as val chunks:util.List[util.List[String]] = new util.Vector[util.List[String]]
chunksObjRef is defined as val chunksObjRef:util.List[util.List[String]] = new util.Vector[util.List[String]]
But, unfortunately I'm getting an error telling me that class constructor was not found or defined:
java.lang.NoSuchMethodError: BlockstemRequester.<init>(Lcom/google/common/util/concurrent/RateLimiter;Ljava/lang/String;Ljava/util/List;Ljava/util/List;)
Basically, I'm using this class defined in Scala at my java code project, and I did defined the scala class to use List from java to avoid any problem of incompatible types between the languages.
At runtime I'm getting this following types according to my debug process:
chunks is a Vector[Collections$SynchronizedRandomAccessList]
chunksObjRef is a Vector[Collections$SynchronizedRandomAccessList]
I appreciate any kind of help towards this problem. Thank you!
As per Java docs:
Thrown if an application tries to call a specified method of a class
(either static or instance), and that class no longer has a definition
of that method. Normally, this error is caught by the compiler; this
error can only occur at run time if the definition of a class has
incompatibly changed.
From you question it is not clear if you are getting this at compile time or run time but looks like you are having issue at run time. So, use a Java decompiler and check the .class of this class whether this method is present or not.
Most probable root cause of this issue is that library used at compile time have such a method but library used at runtime doesn't have it, and hence NoSuchMethodError.
Use decompiler and check .class file of the class.
Just solved the problem. So this was the scenario: I have a project X and using a library Y. So both X and Y have different definition of the class BlockstemRequester, both with different constructor signatures. I had to change that class name of my project and refactor my code. So, at runtime the constructor pointed out it was that one from my project X and not from that one defined in the library Y
I appreciate any advise if there is any way to approach this problem better than just renaming/refactoring my local classes
I think that the problem is with your 'typed' list.
If you change the signature to
public BlockstemRequester(RateLimiter throttler,
String url, List payloadsToBeRequested, List objRef)
Or
public BlockstemRequester(RateLimiter throttler,
String url, List<?> payloadsToBeRequested, List<?> objRef)
This will work.

Loading a class and checking for method presence without resolving the class

I am trying to load a class from a folder to check for the implementation of a specific method. The class has some imports that are not present in the folder or its subfolders. Loading the class with Class clazz = Class.forName(className, false, classLoader); works fine, but when I call clazz.getDeclaredMethod("methodName") then I get a NoClassDefFoundError because some imports cannot be resolved.
Is there a possibility to examine a class at runtime (I do not intend to call methods or instantiate it) without loading dependencies?
If not, how else can I check a class for a specific method implementation when I have a classes-folder as a starting point?
Interesting question.
I don't think you want to roll your own byte code parser, so try Apache BCEL or Spring ASM. Both allow you to read/write class files without having to load them.
You might be able to do that with a library such as Apache Commons BCEL.
The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).
you could try executing `javap ' from your program and parsing the output. For example:
javap Driver
Compiled from "Driver.java"
public class Driver {
public Driver();
public static void main(java.lang.String[]);
}

Scala trouble accessing Java methods

So, I have something written in Java, and I want to extend it in Scala... The issue I'm running into is that Scala isn't seeing methods I need.
Here is how it's set up:
Player extends Mob, and Mob extends Entity.
I need to access a method in Player that isn't defined in Mob or Entity, but Scala doesn't think it exists even though Java does.
It can see methods defined by Mob and Entity just fine. Also, all the methods I'm talking about are non-static.
So, am I doing something wrong, or is this a limitation imposed by Scala?
Edit --
Here is the relevant code:
package test
import rsca.gs.model.Player
object Test {
def handle(p:Player): Unit = {
p.getActionSender().sendTeleBubble(0, 0, false);
}
}
Player class:
package rsca.gs.model;
// imports
public final class Player extends Mob {
// Implemented methods (not going to post them, as there are quite a few)
// Relevant code
private MiscPacketBuilder actionSender;
public MiscPacketBuilder getActionSender() {
return actionSender;
}
}
Error:
value getActionSender is not a member of rsca.gs.model.Player
I never encountered such problems, and you probably checked your configuration and everything else twice, so I would guess this is some Eclipse related build issue. You should try to build from the command line in order to see whether Scala or Eclipse is the problem.
Is it possible for you to run a test against the class just to see if you got the right one?
p.getClass.getMethods
... and if possible (may run into NPE) in order to find the source:
p.getClass.getProtectionDomain.getCodeSource.getLocation.getPath
When compiling the Scala class, do something like this:
scalac *.scala *.java
This way, Scala will look a the Java code to see what is available. If, however, the Java code is already compiled and provided as a jar file, just add it to the classpath used when compiling the Scala code.

Why do I get a NullPointerException when initializing Spring

I've got a problem running a batch job on my server, whereas it runs fine from Eclipse on my development workstation.
I've got my Spring environment set up using Roo, made an entity, and make a batch that does some work, and test it well on my develompent box. I initialize my context and do the work, but when I run my batch on the server, the context isn't initialized properly. Here's the code:
public class TestBatch {
private static ApplicationContext context;
#SuppressWarnings("unchecked")
public static void main(final String[] args) {
context = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");
try {
#SuppressWarnings("unused")
TestBatch app = new TestBatch();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void TestBatch() { /** Do Something using the context **/ }
}
And here's the log and exception:
2010-02-16 11:54:16,072 [main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6037fb1e: startup date [Tue Feb 16 11:54:16 CET 2010]; root of context hierarchy
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:194)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:458)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:388)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at tld.mydomain.myproject.batch.TestBatch.main(TestBatch.java:51)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:103)
... 7 more
Any idea or hints as to what's going on? My classpath is set to $PROJECTHOME/target/classes, and all my dependencies are in $PROJECTHOME/target/lib, and I execute using "export CLASSPATH=$PROJECTHOME/target/classes; java -Djava.endorsed.dirs=$PROJECTHOME/target/lib tld.mydomain.myproject.batch.TestBatch"
Is there anything in my setup that looks very wrong? When I run this from Eclipse, no problems, but when I deploy it on the server where I want to run it and run it as described above, I get this problem. Because it runs from Eclipse, I believe my config files are all right, but how can I debug what's causing this? Perhaps I have some config errors or a mismatch between the server and the development workstation after all? Or is this a really weird way of saying file not found, and if so, how do I make sure it finds the correct file??
I'm really looking forward to hearing your suggestions as to how to tackle this problem.
Cheers
Nik
The cause of problem is -Djava.endorsed.dirs=$PROJECTHOME/target/lib
org.springframework.beans.factory.support.DefaultListableBeanFactory contains the following code:
static {
ClassLoader cl = DefaultListableBeanFactory.class.getClassLoader();
try {
javaxInjectProviderClass = cl.loadClass("javax.inject.Provider"); //Line 103
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - Provider interface simply not supported then.
}
}
It causes a NullPointerException, because getClassLoader() returns null when class is loaded via -Djava.endorsed.dirs. From javadoc:
Some implementations may use null to represent the bootstrap class loader.
So, use -classpath (with explicit specification of all jars) instead of -Djava.endorsed.dirs
Exception in thread "main" java.lang.ExceptionInInitializerError is occurs while adding User Library. I faced same problem in Hibernate and Spring as well. So i removed User Library say "Spring" then i add jars manually it work perfectly.
In Eclipse:
If you are using the spring jars as user library(Say SpringLib), see if the user library for spring is added(or checked) as System Library(added to the boot class path). If yes, remove the check mark.`
Just add the jars to referenced libraries and not to user library. It worked for me!

NoClassDefFoundError on JFace FontRegistry

When I launch an SWT application (via an Eclipse launch profile), I receive the following stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/jface/resource/FontRegistry
at org.eclipse.jface.resource.JFaceResources.getFontRegistry(JFaceResources.java:338)
at org.eclipse.jface.window.Window.close(Window.java:313)
at org.eclipse.jface.dialogs.Dialog.close(Dialog.java:971)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.close(ProgressMonitorDialog.java:348)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.finishedRun(ProgressMonitorDialog.java:582)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:498)
at com.blah.si.workflow.SWTApplication.main(SWTApplication.java:135)
Now, the things that make this odd:
When I change the project build path and replace jface.jar with the source project (same version - 3.3.1), the error goes away.
Other applications I have that use the same jar, and a copy of the same launch profile and project, all works fine.
This is NOT a ClassNotFoundException. The class is on the classpath. If I attach source to the jar, I can debug into the getFontRegistry method. The method will execute successfully several times before eventually throwing a NoClassDefFoundError on line 338. Line 337 is a "if variable == null" statement checking to see if a static variable has been initialized. Line 338 is initializing it if it is not already initialized. The first time through, the null check fails, and the initialization is performed. On subsequent passes through the method, the null check passes, and thus the already-initialized static value is returned. On the final pass (the one that fails,) the null check fails again (even though the static variable has already been initialized) and when it tries to re-initialize the static variable, the NoClassDefFoundError is thrown. Here is the relevant source (starting with line 336, note that fontRegistry is a private static variable that is set in no other place):
.
public static FontRegistry getFontRegistry() {
if (fontRegistry == null) {
fontRegistry = new FontRegistry(
"org.eclipse.jface.resource.jfacefonts");
}
return fontRegistry;
}
.
I have already gotten a fresh copy of the jar (to ensure it isn't corrupted,) deleted my .classpath and .project files and started a fresh project, and recreated the launch profile. No change.
Because of the peculiarities in #3 above, I'm suspecting some kind of wierd classloader behavior - it seems as if that final pass through the method is in another classloader?
Ideas?
Update: The answer provided by Pourquoi Litytestdata prompted me to pay attention to what happens in the try block just above line 458 of ProgressMonitorDialog. Indeed, that code was throwing an exception, which was being gobbled by the finally block. The root cause was ANOTHER missing class (the missing class was not JFontRegistry or any of its directly related classes, but another that was spider-web dependencied in an edge case.) I'm upvoting all answers pointing me to pay attention to the classpath, and accepting Pourquoi's, because it was the breakthrough. Thanks to all.
It sounds like you are missing a JAR file that holds a dependency, as mentioned in this blog entry from July 2006, written by Sanjiv JIVAN:
Difference between ClassNotFoundException and NoClassDefFoundError
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader.
This typically means that the class is missing from the CLASSPATH.
It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent ClassLoader and hence the class from the child ClassLoader is not visible.
This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such ClassLoader issues).
People often tend to confuse java.lang.NoClassDefFoundError with java.lang.ClassNotFoundException. However there's an important distinction.
For example an exception (an error really since java.lang.NoClassDefFoundError is a subclass of java.lang.Error) like
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH.
In fact, its quite the opposite.
It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition.
This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader.
So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members.
If you don't have access the the source, then simply decompile it using JAD.
On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.
private static SomeClass foo = new SomeClass();
Tip : To find out which jar a class belongs to, you can use the web site jarFinder. This allows you to specify a class name using wildcards and it searches for the class in its database of jars.
jarhoo allows you to do the same thing but its no longer free to use.
If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan. You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.
I think the stacktrace presented above is concealing the real problem here. Below is the code in the method run within
org.eclipse.jface.dialogs.ProgressMonitorDialog (with a comment added by me):
public void run(boolean fork, boolean cancelable,
IRunnableWithProgress runnable) throws InvocationTargetException,
InterruptedException {
setCancelable(cancelable);
try {
aboutToRun();
// Let the progress monitor know if they need to update in UI Thread
progressMonitor.forked = fork;
ModalContext.run(runnable, fork, getProgressMonitor(), getShell()
.getDisplay());
} finally {
finishedRun(); // this is line 498
}
}
The second-from-bottom line in Jared's stacktrace is line 498 of this class, which is the call to finishedRun() within the finally block. I suspect that the real cause is an exception being thrown in the try block. Since the code in the finally block also throws an exception, the original exception is lost.
To get a better handle on if it is a class loader issue go through the code where it works and add:
try
{
final Class clazz;
final ClassLoader loader;
clazz = Class.forName("org/eclipse/jface/resource/FontRegistry");
loader = clazz.getClassLoader();
System.out.println("The classloader at step 1 is: " + loader);
}
catch(final Throwable ex)
{
ex.printStackTrace();
}
And then do the same thing where you are getting the NoClassDefFoundError and see if the class loaders are different.
Then you will be able to ensure that it is the ClassLoader that is different. Can you report back with what happens with this? Depending on what the result is I might have more ideas.
To add to the excellent TofuBeer's answer, since NoClassDefFoundError indicates that:
class org.eclipse.jface.resource.FontRegistry was found by the ClassLoader,
but can not been loaded without triggering an error, like having static blocks or members which use a Class that's not found by the ClassLoader.
Let's look at org.eclipse.jface.resource.FontRegistry source code:
It does not have any static variable initialization (nor does its superclasses).
Let's look at org.eclipse.jface.resource.JFaceResources source code
The getFontRegistry() function in which the Error is triggered is using the static variable fontRegistry:
/**
* The JFace font registry; <code>null</code> until lazily initialized or
* explicitly set.
*/
private static FontRegistry fontRegistry = null;
Thus, it begs raises the question: why a static initialized variable would suddenly be considered null again ?
Because somehow FontRegistry or JFaceResources get unloaded by the gc ?!
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
So it doesn't matter whether instances of the class exist at any time, the field will exist as long as the Class itself has been loaded.
If this were a eclipse Plugin, this could have been related to this FAQ entry
Here is a typical scenario for a new user:
You are writing a plug-in that extends plug-in XYZ.
To get it to compile, you add a reference to the JAR file for plug-in XYZ to your project’s build path either from the Java Build Path property page or by editing the .classpath file.
When you launch a runtime workbench, the following surprising error is reported: java.lang.NoClassDefFoundError: XYZ.SomeClass.
Do not start looking in the Plug-ins and Fragments tab in the launch configuration for the runtime workbench.
That tab influences only which plug-ins are used for your runtime workbench and whether they are loaded from the workspace or from the Eclipse install directory.
Instead, start looking in the plug-in manifest.
Edit the plugin.xml file and ensure that XYZ is mentioned as a required plug-in.
Then, save the plugin.xml file.
This will update the project’s build path automatically.
Never manually edit the .classpath file when you are writing a plug-in.
The plug-in Manifest Editor simply overwrites any changes you make to it. Not very civilized, but that is the way it works.
If you try to load the class FontRegistry on your own (like TofoBeer described), you will find out that classes of the following JAR are dependent classes if using FontRegistry.
org.eclipse.core.commands_xxxxx.jar
You must add this JAR to your build path.

Categories

Resources