com.sun.jdi.InvocationException occurred invoking method - java

I just want to create an object of class, but got this error when debugging. Can anybody tell me what the problem is? The location of this code is in some Spring(2.5) Service class.
There is a similar problem: OJB Reference Descriptor 1:0 relationship? Should I set auto-retrieve to false?
Thanks a lot~

The root cause is that when debugging the java debug interface will call the toString() of your class to show the class information in the pop up box, so if the toString method is not defined correctly, this may happen.

I also had a similar exception when debugging in Eclipse. When I moused-over an object, the pop up box displayed an com.sun.jdi.InvocationException message. The root cause for me was not the toString() method of my class, but rather the hashCode() method. It was causing a NullPointerException, which caused the com.sun.jdi.InvocationException to appear during debugging. Once I took care of the null pointer, everything worked as expected.

Well, it might be because of several things as mentioned by others before and after. In my case the problem was same but reason was something else.
In a class (A), I had several objects and one of object was another class (B) with some other objects. During the process, one of the object (String) from class B was null, and then I tried to access that object via parent class (A).
Thus, console will throw null point exception but eclipse debugger will show above mentioned error.
I hope you can do the remaining.

For me the same exception was thrown when the toString was defined as such:
#Override
public String toString() {
return "ListElem [next=" + next + ", data=" + data + "]";
}
Where ListElem is a linked list element and I created a ListElem as such:
private ListElem<Integer> cyclicLinkedList = new ListElem<>(3);
ListElem<Integer> cyclicObj = new ListElem<>(4);
...
cyclicLinkedList.setNext(new ListElem<Integer>(2)).setNext(cyclicObj)
.setNext(new ListElem<Integer>(6)).setNext(new ListElem<Integer>(2)).setNext(cyclicObj);
This effectively caused a cyclic linked list that cannot be printed. Thanks for the pointer.

I was facing the same issue because I was using Lombok #Data annotation that was creating toString and hashcode methods in class files, so I removed #Data annotation and used specific #Gettter #Setter annotation that fixed my issue.
we should use #Data only when we need all #ToString, #EqualsAndHashCode, #Getter on all fields, and #Setter on all non-final fields, and #RequiredArgsConstructor.

I had the same issue once. In my case toString() method was badly created. TO be precise a static final variable was included in the toString method when a developer form my team was assigned code cleaning task and to add toString(), hashCode() code and equals() methods to domain objects where ever possible. but in of the classes because of over looking at it, he included final static variable that caused the "com.sun.jdi.InvocationException" this exception was visible on debugging only when I hovered over the object which has the exception.

I got similar exception in Eclipse. This was due to java.lang.StackOverflowError error. I had overriden toString() method in child class, having JoinColumn, which was returning string using object of parentclass, resulting in circular dependency. Try to remove that object from toString(), and it will work.

Disabling 'Show Logical Structure' button/icon of the upper right corner of the variables window in the eclipse debugger resolved it, in my case.

so I had same problem here. Found out that my domain instance was getting detached from the hibernate session. I used isAttached() to check and attached the domain using d.attach()

This was my case
I had a entity Student which was having many-to-one relation with another entity Classes (the classes which he studied).
I wanted to save the data into another table, which was having foreign keys of both Student and Classes. At some instance of execution, I was bringing a List of Students under some conditions, and each Student will have a reference of Classes class.
Sample code :-
Iterator<Student> itr = studentId.iterator();
while (itr.hasNext())
{
Student student = (Student) itr.next();
MarksCardSiNoGen bo = new MarksCardSiNoGen();
bo.setStudentId(student);
Classes classBo = student.getClasses();
bo.setClassId(classBo);
}
Here you can see that, I'm setting both Student and Classes reference to the BO I want to save. But while debugging when I inspected student.getClasses() it was showing this exception(com.sun.jdi.InvocationException).
The problem I found was that, after fetching the Student list using HQL query, I was flushing and closing the session. When I removed that session.close(); statement the problem was solved.
The session was closed when I finally saved all the data into table(MarksCardSiNoGen).
Hope this helps.

I have received com.sun.jdi.InvocationException occurred invoking method when I lazy loaded entity field which used secondary database config (Spring Boot with 2 database configs - lazy loading with second config does not work). Temporary solution was to add FetchType.EAGER.

There could be two reasons an element doesn't exist:
Bad xpath (//*[#id'forgotQuote])
Correct xpath but no element (//*[contains(text(),'This text is not in the page')])
Would you get com.sun.jdi.InvocationException in either case when you are running Debug and you hover your mouse over a reference to the WeBElement (this with Selenium and Java)???
We use the following, but can't distinguish if it returns false due to bad xpath or non-existent element (valid xpath syntax):
public static boolean isElementDisplayed(WebElement element) {
boolean isDisplayed = false;
try {
isDisplayed = element.isDisplayed();
} catch (NoSuchElementException e) {
;// No Worries
}
return isDisplayed;
}

Removing hashCode() and equals() solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.

In my case it was due to the object reference getting stale.
I was automating my application using selenium webdriver, so i type something into a text box and then it navigates to another page, so while i come back on the previous page , that object gets stale.
So this was causing the exception, I handled it by again initialising the elements -
PageFactory.initElements(driver, Test.class;

I also faced the same problem. In my case I was hitting a java.util.UnknownFormatConversionException. I figured this out only after putting a printStackTrace call. I resolved it by changing my code as shown below.
from:
StringBuilder sb = new StringBuilder();
sb.append("***** Test Details *****\n");
String.format("[Test: %1]", sb.toString());
to:
String.format("[Test: %s]", sb.toString());

I faced the same problem once. In my case it was because of overridden equals method. One values was coming null.

Related

Unit test: running programmatically a code that runs only at a real application instance

I am developing a plugin for PhpStorm, and in some point, it try to getContainingClass() from visited method. This method should return null when the class name is absent.
Just to make easier to explain, my visitPhpMethod() is like that:
final PhpClass methodClass = method.getContainingClass();
if (methodClass == null) {
return null;
}
My problem is justly to make the code-coverage of return null programmatically (from unit test) to proof that it is not a dead code. From a real instance of PhpStorm running my plugin I can reach this code when I just remove the class name like that:
Original code, that not access the return null:
class ThisIsMyClass { function x(){} }
Modified code without the class name, that access return null:
class { function x(){} }
But when I run the modified code from unit test, it give that:
class<error descr="Expected: class name"> </error>{ function x(){} }
And with that, my visitPhpMethod() is not triggered (while in real PhpStorm application it does). In this way, is impossible to coverage this part of code (but I like to do).
My best attempt: instead I relying on testHighlight() for that, I inputted with the functional code (that have the class name), then programatically I removed the class name (then the "expected class name" error don't happen anymore). Finally I run the visitPhpMethod() programmatically.
Unfortunatelly, the getContainingClass() instead of return null (that is what I expect to do), it just returns a PhpClass instance that don't have a name (and it should not works to me).
The code from this attempt could be seen here.
I tried to post the same problem on Intellij Community too, but without luck.
Okay, I found my issue.
On reality, the problem is not on getContaingClass(). It really doesn't returns null when called from visitPhpMethod(). I found my problem on another method that try to getNameIdentifier() from the containing class, in this case, it is really absent and I just try to return it from a #NotNull method.

xp:checkbox breaks programme

On an XPage I have placed a checkbox group:
<xp:checkBoxGroup
value="#{employeeBean.employee.concern}"
disabled="#{employeeBean.employee.editable eq false}">
<xp:selectItem itemLabel="yes"></xp:selectItem>
<xp:selectItem itemLabel="no"></xp:selectItem>
<xp:selectItem itemLabel="maybe"></xp:selectItem>
</xp:checkBoxGroup>
I have binded the value of the control to field in my Proposal class via a managed bean.
The field concern is of type string and has its out of the box getters and setters.
The problem is whenever I include the data-binding and change values the complete XPage SSJS fails. I do not get an error in the console (server, web client).
Does this have something to do with the type of value the checkbox returns or should I change the type of field in my class?
One thing that springs to mind is the employee object. If this is not set (i.e. there is an instance of the object) then it will fail with a null pointer exception.
In your case it is quite valid the concern field is of type String - obviously you will need a getConcern() and setConcern(String value) method.
Now the real problem is that you cannot see what the server thinks is wrong!
The best way to get to that is to look at the stack traces in the logs. And by far the easiest way to do that is to install the "XPages Log File Reader" application from OpenNTF.org
But my guess is that you haven't created an employee object prior to calling the getEmployee() method to return it ;-)
/John

Append type level validation error message to specific field

I've got a simple class which get's validated using the boolean isValid() method, which works and of course the error message is at class/type level.
Here's my simple class:
public class NewPasswordDTO {
#NotNull
public String password;
#NotNull
public String confirmation;
#AssertTrue(message="Passwords must match.")
protected boolean isValid() {
return password.equals(confirmation);
}
}
But what I really want is something like that:
public class NewPasswordDTO {
#NotNull
#Equals("confirmation", message="...")
public String password;
#NotNull
public String confirmation;
}
So the error message would be set at field level and not at class/type level.
Is this possible somehow? Maybe using a custom Validator for that class?
Thanks in advance!
SOLUTION:
Thanks to Gunnar! I've just came up with a nice, universal solution :-). I simply used (means copy & paste) the code from Hibernates #ScriptAssert and ScriptAssertValidator and modified it slightly:
#ScriptAssert:
Add new String field(). (this is where the error message gets appended)
ScriptAssertValidator:
Inside the initialize method, make sure to also save the fieldName and message properties, because we need to access them in the next step
Add this snippet at the bottom of isValid method:
context.buildConstraintViolationWithTemplate(errorMessage)
.addPropertyNode(fieldName).addConstraintViolation();
Also add context.disableDefaultConstraintViolation(); somewhere inside the isValid method to not generate the default error message which else would get appended at class level.
And that's it. Now I can use it like that:
#FieldScriptAssert(lang="javascript", script="_this.password.equals(_this.confirmation)", field="password", message="...")
public class NewPasswordDTO { ... }
You either could use the #ScriptAssert constraint on the class (note that a constraint should always be side-effect free, so it's not a good idea to alter the state of the validated bean; instead you should just check whether the two fieldss match) or you implement a custom class-level constraint.
The latter also allows to point to a custom property path for the constraint violation, which it allows to mark the "confirmation" property as erroneous instead of the complete class.
Simple answer : It is not (unless you implement it) :http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html shows all annotation constraints.
Of course you could inject your string as a resource in your class by #producer and so on (which recently is discussed to be removed in jdk8), but you could not use this value for your assert. In reply to the comment:
This was asuming that the nature is a constant string which you would like to use as a string resource.And then of course it is possible to write your own class based on java.lang.string with a #Producer which is then #Inject - able. Though it is certainly not the way I personally would deal with constant strings.
If you’re using the Spring Framework, then as an alternative to the #ScriptAssert using a JSR 223 scripting, you can use the #SpELAssert that uses the Spring Expression Language (SpEL). The advantage is that it doesn’t need any JSR 223 compliant scripting engine which may not be available on some environments. See this answer for more information.

java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to org.openqa.selenium.internal.WrapsDriver

I have following pointcut and the given advice in AspectJ
#Pointcut("(call(* org.openqa.selenium.WebElement.sendKeys(..)))")
public void onWebElementAction() {
}
#After("onWebElementAction() && target(webelement)")
public void afterWebElementAction(JoinPoint joinPoint, WebElement webelement) {
System.out.println(webelement.getAttribute("name")); //1
WebDriver driver = ((WrapsDriver) webelement).getWrappedDriver(); //2
//DO SOMETHING HERE
}
While the line 1 is executed without any error. It is on line 2 I get error
java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to org.openqa.selenium.internal.WrapsDriver
The casting works in other places without issues.
Can someone please help?
While the answer flagged as correct does point out the issue, it doesn't explain the issue nor suggests a solution which does actually exist. Let me begin with giving a bit more of detail around the underlying issue here which is the way the WebElement could have been instantiated.
On one hand, when a WebElement gets instantiated as the result of a call to WebDriver#findElement, the actual RemoteWebElement object gets constructed at that very moment, however, when a WebElement gets instantiated via PageFactory#initElements, the actual concrete class object (RemoteWebElement) doesn't get created at that point but instead a proxy does.
Here is where the main issue relies. The proxy object does NOT implement the WrapsDriver interface and that is why the cast exception is thrown, which is perfectly fine. However, if you are curious enough to see how the actual proxy creation is done (at least by the default decorator), you will see that the object instantiated as the proxy does instead implement the WrapsElement interface which does offer the method getWrappedElement so, with it, you can extract the underlying WebElement and then with this, extract the underlying WebDriver, just as you are trying.
Now, the key here is that any WebElement instantiated via WebDriver#findElement does not implement WrapsElement because it is the actual element and not a proxy so, before you attempt using WrapsElement#getWrappedElement, you first need to check if the passed WebElement is actually a proxy or not.
You can achieve this with reflection, i.e.
if(WrapsElement.class.isAssignableFrom(element.getClass()))
webDriver = ((WrapsDriver)((WrapsElement)element).getWrappedElement()).getWrappedDriver();
else
webDriver = ((WrapsDriver)element).getWrappedDriver();
tl;dr
The WebElement instance you are using was instantiated via PageFactory#initElements and you first need to extract the underlying WebElement with WrapsElement#getWrappedElement and then the WebDriver from it.
This is a wild guess since I don't see a case where it actually worked. From the exception it seems that the WebElement that is being passed to afterWebElementAction is initialized via PageFactory. My guess is that if you pass WebElement derived from driver.findElement(), to afterWebElementAction, you wouldn't get casting exception. This is how it must be working for you in other cases most likely.

how to handle entity manager can not find an object instance case?

I have sceneario in which I have to check if an onject instance exist in entity manager. It works fine when the instance eexists but throws null pointer exception when it doesn't. When it doesn't I have to do another thing. so how can catch this state? I already tried try catch, but it doesn't work.
Sorry when I was asking this question I was on the way and trying to type in a different device that I am used to. My code is:
AJPAController aJPAController;
AClass aClass = aJPAController.find((Integer.parseInt(request.getParameter("id")));
try{
if(aJpaController.contains(aClass)){
response.sendRedirect("gosomewhere.com");
}
}
catch (java.lang.NullPointerException R){
response.sendRedirect("gosomewhereelse.com");
}
I might have a logical mistake in trying first find and then contains method, but I couldn't find a better solution.
Thanks in advance.
You can check if an entity is managed (within the persistence context) with help of the contains method of your EntityManager

Categories

Resources