I am getting this error
Thread [TimerDemo(185)id=307040256] (Suspended (exception ClassCastException))
UiApplication.getUiApplication() line: 462
TimerDemoTask$1.run() line: 18
BackGroundProcess(Application).dispatchInvokeLater(Runnable, Object, int) line: 1456
BackGroundProcess(Application).doProcessNextMessage(Message) line: 2088
BackGroundProcess(Application).processNextMessage(Message) line: 1530
BackGroundProcess(Application).enterEventDispatcher() line: 1371
TimerDemo.main(String[]) line: 15
when I am trying to call a popUpScreen() using,
UiApplication.getUiApplication()).pushGlobalScreen(new PanicPopUP(), 0, 0)//Defined in TimerDemoTask class.
BackGroundProcess class which extends Application calls TimerDemoTask class which invokes popUpScreen() as above. I tried to cast Application and UiApplication in this way
((UiApplication)Application.getApplication()).pushGlobalScreen(new TimerDemoPopupScreen(),0,0);
but still getting the same exception.Any idea how to impelement this.
Try like this in your Timertask demo class..
i think you are not getting the eventlock
synchronized (getEventLock()) {
//with this UiEngine pushGlobal dialogs
//whenever with the app in background
UiEngine ui = Ui.getUiEngine();
ui.pushGlobalScreen(new TimerDemo(), 1, UiEngine.GLOBAL_QUEUE);
}
like this and see if it solved your issue ....
Related
BaseTest.java:
private static ReportService reportService; // Calling report service interface
#BeforeSuite:
reportService = new ExtentReportService(getConfig()); // New instance of ExtentReportService.
#BeforeMethod:
reportService.startTest(testname); // Starting the test and passing the name and description of the test.
#AfterMethod:
reportService.endTest(); // Ending the test
#AfterSuite:
reportService.close(); // Closing the test
**ExtentReportService.java:** // Contains different extent API methods. (These are designed to be generic.)
protected static ExtentReports extent; // static instance of ExtentReports
protected static ExtentTest test; //static instance of ExtentTTest
#Override // StartTest method
startTest(Method method) {
testMetaData = getTestMetaData(method);
test=extent.startTest(testMetaData.getId(),testMetaData.getSummary());
}
#Override //End test method
endTest() {
extent.endTest(test);
extent.flush();
}
The above is my selenium code.
When I am executing my suite file with parallel="methods" and thread count="3", I am getting the following error: "com.relevantcodes.extentreports.ExtentTestInterruptedException: Close was called before test could end safely using EndTest.".
While debugging, I found that even before all endTest() in AfterMehtod were executed, AfterSuite was being called.
I tried different variations such that the code works, such as, removing static, calling endTest() in the test itself rather than after method, removing close() call from AfterSuite and many other variations. But still getting the same error.
I tried all the possible solutions given on the internet, but to no use.
Attaching a hierarchy file for the ExtentReport used in my project
I also the following solution given in StackOverflow:
Extent report :com.relevantcodes.extentreports.ExtentTestInterruptedException: Close was called before test could end safely using EndTest
Unsynchronized output
XMF file for parallel test.
ExtentReports Intialized in ExtentManager class using Singleton().
public class ExtentManager {
private static ExtentReports extent;
public static ExtentReports getInstance() {
if(extent == null) {
extent = new ExtentReports(System.getProperty("user.dir")+"\target\surefire-reports\html\extent.html", true, DisplayOrder.OLDEST_FIRST);
extent.loadConfig(new File(System.getProperty("user.dir")+"src\test\resources\extentconfig\ReportsConfig.xml"));
}
return extent;
}
}
Declared in TestBase class as global.
public ExtentReports repo= ExtentManager.getInstance();
public static ExtentTest test
Call startTest in public void onTestStart(ITestResult result)
test = repo.startTest(result.getName().toUpperCase());
Call endTest in CustomListener Class both in a)public void onTestFailure(ITestResult result); b)public void onTestSuccess(ITestResult result).
repo.endTest(test)
Call close() OR flush() in #AfterSuite in TestBase class but NOT both!
//repo.close();
repo.flush();
Note: I have ExtentReports ver-2.41.2, and TestNg ver-7.1.0.
After the above steps, error 'Getting closed before endTest call in Selenium using Extent Reports' got resolved.
Extent report generates each test successfully in the report.
Try it out!
I found that I am forced to throw exception in a background thread:
#Background
void bootstrap() throws IOException {
mProgressBar.setVisibility(View.VISIBLE);
restClient.setBearerAuth(Auth.token);
UserID userIdJsonn = restClient.getUserId();
Auth.user_id= userIdJsonn.getUser_id();
PhoenixPlug.getInstance().ini();
mProgressBar.setVisibility(View.GONE);
}
Of course, I've got this error:
Error:(619, 5) error: org.androidannotations.annotations.Background annotated methods should not declare throwing any exception
So, what's the recommended way to handle such a case?
If you are using a background annotation, you have to catch the exception locally.
I am using JNA in my project and my Java JNA Callbacks throw exception in some cases. I want to know from C/C++ code an exception was thrown by last calbback method call. In JNI, one can do it using env->ExceptionCheck() but could not find any equivalent in JNA.
Is there any possibility to achieve this?
The native code calling your callback certainly has no expectation that a Java exception will be raised. There is no guarantee that a JNA callback will be invoked from a containing JVM context. Even if it were, you'd have to establish an out of band channel to pass the exception from the callback to the JVM further up the stack, since you have no guarantees about the calling C code.
Assuming you have Java code -> C code -> callback, I'd recommend you catch all your callback's exceptions, then put them somewhere for the calling Java code to examine after the call.
You could make this happen under the covers with an InvocationMapper, which basically lets you capture and/or modify the results of an interface-mapped call, but it's probably easier just to be explicit about it and wrap the whole thing in a utility function.
For example:
public interface MyLibrary extends Library {
MyLibrary INSTANCE = (MyLibrary)Native.loadLibrary();
interface MyCallback extends Callback {
void invoke();
}
void myFunction(MyCallback callback);
}
Then you provide a utility wrapper:
public void myFunction(final MyCallback callback) {
final List<Exception> exceptions = new List<Exception>();
MyLibrary.INSTANCE.myFunction(new MyCallback() {
public void invoke() {
try {
callback.invoke();
} catch(Exception e) {
exceptions.add(e);
}
}
});
if (exceptions.size() > 0) {
// ...
}
}
If I call the following RoboVM method with any non-null argument:
public static void runOnUiThread(final Runnable runnable) {
System.out.println("Inside runOnUiThread():");
System.out.println(" Null-check: "+(runnable==null));
NSOperation operation = new NSOperation() {
#Override
public void main() {
System.out.println("Inside main():");
System.out.println(" Null-check: "+(runnable==null));
runnable.run(); // NullPointerException here?!? How???
System.out.println(" main() completed");
}
};
NSOperationQueue.getMainQueue().addOperation(operation);
}
it outputs:
Inside runOnUiThread():
Null-check: false
Inside main():
Null-check: true
java.lang.NullPointerException
at RoboVMTools$1.main(RoboVMTools.java)
at org.robovm.apple.foundation.NSOperation.$cb$main(NSOperation.java)
at org.robovm.apple.uikit.UIApplication.main(Native Method)
at org.robovm.apple.uikit.UIApplication.main(UIApplication.java)
at Main.main(Main.java)
What on earth is going on??? And more importantly, how can I work around it?
I tried adding operation.addStrongRef(runnable); right before NSOperationQueue.... No difference.
I also tried moving the anonymous inner class into its own class that has a private final field to store the runnable which is passed into its constructor. Same result.
Am I just missing something totally obvious???
You are right about the GC. Your NSOperation instance is garbage collected before the operation is invoked from the Objective-C side. When NSOperationQueue calls into the Java side a new instance of your NSOperation anonymous class will be created which doesn't have a reference to the Runnable instance but rather null and the result is a NullPointerException getting thrown.
The way you resolved it using addStrongRef() is correct though only the mainQueue.addStrongRef(operation) and the corresponding removeStrongRef() calls should be sufficient:
public static void runOnUiThread(final Runnable runnable) {
final NSOperationQueue mainQueue = NSOperationQueue.getMainQueue();
NSOperation operation = new NSOperation() {
#Override
public void main() {
runnable.run();
mainQueue.removeStrongRef(this);
}
};
mainQueue.addStrongRef(operation);
mainQueue.addOperation(operation);
}
This will prevent the Java operation instance (and any Java objects reachable from it like the Runnable) from being GCed until the Objective-C NSOperationQueue instance is deallocated. As the Objective-C side queue is a singleton it won't get deallocated during the lifetime of the app.
The RoboVM NSOperationQueue Java class provides a version of the addOperation() method that takes a Runnable. When using this method RoboVM will take care of retaining the Runnable instance while it's needed by the Objective-C side for you. The same is true for any method that takes a #Block annotated parameter of type Runnable or any of the org.robovm.objc.block.VoidBlock* or org.robovm.objc.block.Block* interfaces.
Using this addOperation() method your code simply becomes:
public static void runOnUiThread(Runnable runnable) {
NSOperationQueue.getMainQueue().addOperation(runnable);
}
PS. The GC used by RoboVM has nothing to do with the Apple garbage collector so Apple's docs won't help you understand problems like this.
Well... This fixes it:
public static void runOnUiThread(final Runnable runnable) {
final NSOperationQueue mainQueue = NSOperationQueue.getMainQueue();
NSOperation operation = new NSOperation() {
#Override
public void main() {
runnable.run();
mainQueue.removeStrongRef(runnable);
mainQueue.removeStrongRef(this );
}
};
mainQueue.addStrongRef(runnable );
mainQueue.addStrongRef(operation);
mainQueue.addOperation(operation);
}
But don't ask my why this is necessary. The Apple docs say "In garbage-collected applications, the queue strongly references the operation object." So, operation.addStrongRef(runnable); as I tried earlier should have been sufficient as the operation object should be referenced by the queue anyways. But I guess the world doesn't always work the way I interpret the documentation.
This line in TopLevelTransaction (neo4j-kernel-2.1.2) throws a NullPointerException every time I call next() on an iterator obtained via GraphRepository#findAll():
protected void markAsRollbackOnly()
{
try
{
transactionManager.getTransaction().setRollbackOnly(); // NPE here
}
catch ( Exception e )
{
throw new TransactionFailureException(
"Failed to mark transaction as rollback only.", e );
}
}
I found some threads about similar crashes with slightly different stack traces. The accepted solution on this question is to use "proxy" transaction management, but that seems like a band-aid solution. This question also mentions "proxy" transaction management and suggests that there might be something wrong with the #Transactional annotation when using AspectJ.
Is this legitimately a bug, or have I just set up my project incorrectly? My code is essentially the same as in my standalone hello world, with a slightly more complex main class:
#Component
public class Test2 {
#Autowired
FooRepository repo;
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext("test2");
Test2 test2 = context.getBean(Test2.class);
test2.doStuff();
}
public void doStuff() {
createFoo();
printFoos();
}
#Transactional
public Foo createFoo() {
Foo foo = new Foo();
foo.setName("Derp" + System.currentTimeMillis());
repo.save(foo);
System.out.println("saved " + foo.toString());
return foo;
}
#Transactional
public void printFoos() {
Iterable<Foo> foos = repo.findAll();
System.out.println("findAll() returned instance of " + foos.getClass().getName());
Iterator<Foo> iter = foos.iterator();
System.out.println("iterator is instance of " + iter.getClass().getName());
if(iter.hasNext()) {
iter.next(); // CRASHES HERE
}
}
}
I can post my POM if needed.
I didn't find a bug. Two or three things are required to make this work, depending on whether you want to use proxy or AspectJ transaction management.
First, transaction management must be enabled. Since I'm using annotation-based configuration, I did this by annotating my #Configuration class with #EnableTransactionManagement. Contrary to the docs, the default mode now seems to be AdviceMode.ASPECTJ, not AdviceMode.PROXY.
Next, you need to ensure that the Iterator is used within a transaction. In my example, if I use AdviceMode.PROXY the entire bean containing the #Autowired repository has to be annotated #Transactional. If I use AdviceMode.ASPECTJ I can annotate just the method. This is because the call to the method using the iterator is a self-call from within the bean, and proxy transaction management cannot intercept and manage internal calls.
Finally, if you're using AdviceMode.ASPECTJ you must set up weaving as discussed here.