Class.forName() is not working with a particular class - java

I am trying to load with java reflection a bunch of classes. Everything seems working fine (I am handling the exception if the class is not found).
However there is a particular class that is raising another exception that is not thrown by call to the Class.forname() but by an internal method and so I cannot even catch it.
Here is my code:
try {
URL url = Class.forName(qualifiednameOfTheClass);
} catch (ClassNotFoundException ex) {
// ok class not found can be handled
} catch (Exception e){
// catch every other exception just to try to get the strange exception
}
So with this code everything is working, I am using it on lots of classes and it's working (sometimes it finds it sometimes it doesn't).
However there is one case that is not working properly and I cannot understand why. If qualifiednameOfTheClass = sun.security.krb5.SCDynamicStoreConfig my code is raising an exception:
Exception in thread "mythread-1" java.lang.UnsatisfiedLinkError: no
osx in java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886) at
java.lang.Runtime.loadLibrary0(Runtime.java:849) at
java.lang.System.loadLibrary(System.java:1088) at
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67)
at
sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47)
at java.security.AccessController.doPrivileged(Native Method) at
sun.security.krb5.SCDynamicStoreConfig.(SCDynamicStoreConfig.java:39)
at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:190) at
com.myclass.getJARFromClassForName(JavaId.java:510)
at com.myclass.getJARUrl(Id.java:550) at
com.myclass.collectInformation(Graph.java:366)
at
com.myclass.createNode(Graph.java:166)
at com.myclass.Graph.(Graph.java:143) at
com.myclass2.run(myclass2.java:246)
at java.lang.Thread.run(Thread.java:745)
So as you can see in the error we have this strange exception that cannot be caught even with a generic catch like in my code and I cannot understand why it has been raised and what actually is this osx library (I am on linux)
EDIT: The only thing that I found is this link http://www.straub.as/java/pocketapi/index7.html but is in german and so I read it with google translate and I don't know if I got it right but is saying that the classes listed there cannot be reproduced with Class.forname() itself.
Is it true? Is there a reason why this cannot be loaded with reflection or am I doing something wrong?

"Cannot be caught" because it's an Error, not an Exception. I'd recommend reviewing the object hierarchy in the JDK for Throwable.
Try changing that to Throwable and you'll have better luck catching. I don't know why the error is happening.
This looks like a JNI class that's using native code. I don't know what you're doing, but this looks like a bad idea to me.

This is not how this class expects to be loaded and loading this internal class directly doesn't appear to work. You need to load the class using the standard encryption API so that this class can be loaded as expected, or possibly not loaded at all (it could be code which will only work on OSX)

As you can see in the link you have provided, there are some classes where this method fails.
When calling this method on these objects, Java needs first to load additional stuff, as this is platform specific stuff which is not shipped by default. In your case, it is Kerberos, a security API.
As you can see in its Documentation, it searches for some files in specific paths (java.library.path). As it can not find it there, it throws an error.
Note that the error UnsatisfiedLinkError does not refer to finding the class name for sun.security.krb5.SCDynamicStoreConfig itself. It refers to not finding the native library in the paths provided by java.library.path.
This path itself points, for example on Windows, to C:Windows/system32/.
However, you may catch this error with catch(Error e), note that an Error is not an Exception (Throwable hierarchy).
Be aware that catching an Error in general is no good idead as you can not be sure if the JVM can recover from it.

Related

Exception: Unmarshalling unknown type code occurred at run time

I am working on Android app and we are working as a team. I am facing a serious issue. And that is when ever I try to get the data from intent it gives me following exception
Parcel android.os.Parcel#355932a: Unmarshalling unknown type code
4784211 at offset 712
I know on SO there are a lot of helping material related to this issue, but my case is different and quiet mind boggling .....
Here is a quick code to see how I am getting my object
try {
if (data.hasExtra("KEY_MY_MODEL")) {
MyCustomModel newSelectedModel = data.getParcelableExtra("KEY_MY_MODEL");
//DO SOME THING WITH OBJECT
}
} catch (Exception e) {
e.printStackTrace();
}
Case1:
I am getting exception on first line if (data.hasExtra("KEY_MY_MODEL")) {
and this is quiet funny because when I inspect the intent object (data) while debugging and if I look into intent object using debugging I can see all my custom object.
The keys of getting object are same, if in any case the key is wrong I think the code inside the if condition must not get run. as it will return false.
But instead of returning false it is giving the above mentioned exception.
Case2: As I told you we are working in team, the same set of code is running perfectly on other system, but when I run app from my system and install app on device, it is giving the exception I mentioned above.
This is very much frustrating. I think there is something wrong with proguard, as I read on S.O but its still not helpful. Any Idea why this is happening? This looks like a big bug.
Note: I am using A.S 3.5 and on other system A.S 3.5 is in use, even we have same set of sdk, configurations and other things are quiet
identical on both sides...
It seems to be a ProGuard issue
Just add this line in proguard.rules.pro/txt
-keepclassmembers class * implements android.os.Parcelable {
static ** CREATOR;
}

Exception Handling in JS using Graal

I work on a Java application that makes fairly heavy use of Javascript to form the business logic/glue. It runs using Graal. This all works fine, but we struggle with effective error handling.
This is essentially how the JS is executed:
try {
Context context = Context.newBuilder("js").allowAllAccess(true).build()
Source s = Source.newBuilder("js", src, "script").build();
context.eval(s);
} catch (Exception e) {
LOGGER.error("Exception occurred in JavaScript:...", e);
}
So when errors happen we log them somewhere so we can do some postmortem, etc. It's possible to get the JS stack trace in these logs out of the PolyglotException that Graal throws, which is great. However, things are more complicated when some JS code has called back into Java-land, and a Java exception has been thrown:
var x = callJavaFunction("invalid parameter"); // Throws a NoSuchElementException, for example
The PolyglotException has an asHostException() method that returns the original Java-land exception, and my code that executes the JS files is smart enough to understand this and produce a useful error log. The problem arises when the JS code has tried to catch this itself, for whatever reason:
try {
var x = callJavaFunction("invalid parameter"); // NoSuchElementException
} catch (e) {
doSomeCleanup();
throw e;
}
Now we have lost the original Exception, and even worse, the JS-stack trace now just shows us the catch block, instead of where the cause was. isHostException() returns false, because this is just a JS error now. I cannot find a way to get at the original cause, which makes diagnosing errors quite difficult, especially when they have come out of a production system. The original Java exception message ends up in the JS-error object, which is helpful, but we don't have the stack trace, which is not.
What approaches can I take to try and address this?
One thought I had: Can I hook into the GraalVM and get a callback whenever a host-exception is thrown? At least that way I could have a log saying "the following Java Exceptions were thrown during execution" which I could attach to the error report. So far I've not been able to find a way to achieve this.

Exception breakpoint occurred at EventDispatchThread.java

we are getting this error at the end of running application. I search in google buti don't know what cause this error and what this means. What to do and how to solve it?
i even don't know what raise this exception...
Exception breakpoint occurred at line 145 of EventDispatchThread.java.
java.lang.NullPointerException:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at oracle.jbo.uicli.jui.JUTableBinding$JUTableModel$2.run(JUTableBinding.java:1209)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Don't know what kind of searches you have performed on Google. I would suggest looking up each error (or rather each class where error occurs). Starting from the beginning as subsequent errors may be a due to error propagation. Two searches for EventDispatchThread and JUTableBinding.java may provide some insight at what went wrong.
http://www.docjar.org/docs/api/java/awt/EventDispatchThread.html
It seems that this class deals with AWT components ("takes events off the EventQueue and dispatches them to the appropriate AWT components")
For the JUTableBinding.java there are quite a few pages that say about NullPointerException
https://forums.oracle.com/forums/thread.jspa?threadID=515213
https://forums.oracle.com/forums/thread.jspa?threadID=2343921
https://kr.forums.oracle.com/forums/thread.jspa?threadID=503593
Some of them say that the problem may be with jdk version (seems 1.6 and above throw errors). I would assume that may be the case. Try to recompile using earlier versions of jdk and check whether error is still there. If it is not this then we will investigate further.
"I've looked into the code and found out that JUTableBinding.JUTableModel calls
mScrollUnit = control.getScrollableUnitIncrement(null,
SwingConstants.VERTICAL, 0);
(Line 947)
This was okay in Java 5, since JTable's getScrollableUnitIncrement just returned the row height."
"I changed the line to:
mScrollUnit = control.getScrollableUnitIncrement(
control.getVisibleRect(), SwingConstants.VERTICAL, 0);
and everything works fine on Java 6..."
Hope it helps.

IllegalStateException: Can't overwrite cause in Guava map.put

I create a map using
new MapMaker().softValues().maximumSize(cacheSize).makeMap();
This seemed to work fine, however, I sometimes get the following exception after accessing right after deploying on the server and putting new elements into the map:
java.lang.IllegalStateException: Can't overwrite cause
at java.lang.Throwable.initCause(Throwable.java:320)
at org.jboss.mx.loading.RepositoryClassLoader.findClass(RepositoryClassLoader.java:624)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at org.jboss.mx.loading.RepositoryClassLoader.loadClassImpl(RepositoryClassLoader.java:474)
at org.jboss.mx.loading.RepositoryClassLoader.loadClass(RepositoryClassLoader.java:415)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at com.google.common.collect.CustomConcurrentHashMap$2.iterator(CustomConcurrentHashMap.java:828)
at java.util.AbstractCollection.remove(AbstractCollection.java:241)
at com.google.common.collect.CustomConcurrentHashMap$Segment.removeFromChain(CustomConcurrentHashMap.java:2599)
at com.google.common.collect.CustomConcurrentHashMap$Segment.processPendingCleanup(CustomConcurrentHashMap.java:2772)
at com.google.common.collect.CustomConcurrentHashMap$Segment.runLockedCleanup(CustomConcurrentHashMap.java:2860)
at com.google.common.collect.CustomConcurrentHashMap$Segment.preWriteCleanup(CustomConcurrentHashMap.java:2806)
at com.google.common.collect.CustomConcurrentHashMap$Segment.put(CustomConcurrentHashMap.java:2374)
at com.google.common.collect.CustomConcurrentHashMap.put(CustomConcurrentHashMap.java:3346)
at my.app.cache.CacheImplGoogleGuava.put(CacheImplGoogleGuava.java:36)
...
What could be the reason?
--- Updated:
JBoss version is 5.
Setting a breakpoint in Throwable.initCause revealed ClassNotFoundException with message:
Invalid use of destroyed classloader for com.google.common.collect.Iterators, UCL destroyed at:
and with Stacktrace
ClassNotFoundException(Throwable).initCause(Throwable):320
UnifiedClassLoader3(RepositoryClassLoader).findClass(String):628
...
UnifiedClassLoader3(ClassLoader).loadClass(String):248
CustomConcurrentHashMap$2.iterator():828
CustomConcurrentHashMap$2(AbstractCollection<E>).remove(Object):241
CustomConcurrentHashMap$Segment.enqueueCleanup(...):2738
CustomConcurrentHashMap$Segment.unsetValue(...):2662
CustomConcurrentHashMap<K, V>.reclaimValue(...)
CustomConcurrentHashMap$SoftValueReference<K, V>.finalizeReferent():1637
...
Method.invoke:574
Finalizer.claenUp:154
Finalizer.run:127
From the stacktrace, it seems as if an object in the map was finalized where in finalizeReferent the class com.google.common.collect.Iterators cannot be loaded.
Your problem seems to be unrelated to MapMaker or Guava in general.
You only see an exception that happens while handling another exception (unfortunately).
Throwable.initCause() throws an exception when it's called while there was already a cause specified for the current Throwable (either via the method or the constructor`.
The RepositoryClassLoader.findClass() method seems to be handling some exception that it expects not to have a cause, but in fact it already has a cause set, which triggers this exception.
Unfortunately the exception you see here hides the actual exception (which would probably be much more important for solving the problem).
Try to put a breakpoit at Throwable.initCause() at line 320 or at RepositoryClassLoader.findClass() (at line 624) and reproduce the problem to (hopefully) see the "real" exception in the local variables view of your IDE.
This seems to be a known JBoss bug that might have already been resolved in new versions of the platform. Here is at least one similar bug:
JBREM-552: cannot init cause of ClassCastException
You might try upgrading your version of JBoss (though this particular bug implies the fix was in 2006) or filing another bug if your version is up to date. It could be the fix was sloppy and only fixed the one case that the author of that bug reported, and not similar cases.

Servlet Compiling error

I developed simple servlet using Apache Tomcat 6.
Firstly I write simple Hello World print servlet. Then set CLASSPATH for servlet-api.jar and compile and copy webapps/login/WEB-INF/classes/test/HelloServlet.class. That's working fine.
After I write simple JDBC connection in the servlet. I downloaded MySQL J-Connector and set CLASSPATH like this:
C:\Program Files\apache-tomcat-6.0.32\lib\servlet-api.jar;C:\Program Files\apache-tomcat-6.0.32\lib\mysql-connector-java-5.1.16-bin.jar
then try to compile; it then shows the following message:
"Unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown"
How should I solve that?
Keep your Class.forName() under try catch block & classpath should ends with (.;) check it once.
java.lang.ClassNotFoundException is a checked exception. That means that you are required to deal with it, either by putting the call that may throw this exception inside a try { ... } catch (ClassNotFoundException e) { ... } block or by adding a throws clause to the method declaration of the method in which you make the call to the method that may throw this exception.
Read more about dealing with checked exceptions in The Catch or Specify Requirement in Oracle's Java Tutorials.

Categories