I have created a custom converter to convert a String back into a Date.
public Object convert(Object fromObject){
if (fromObject != null && fromObject.toString().trim().length() == 0){
return null;
}
for (DateFormat f : formats){
try{
return f.parse(fromObject.toString());
}catch (ParseException e){
// Ignore
}
}
throw new RuntimeException(message);
}
Basically, if the string is not parsable a RuntimeException will be thrown.
I have added the converter to the update strategy in the data-dinding and it is being called.
The issue is when the exception is thrown. (For example when i start to type the date in the TextFiled). Instead of appearing the decorator field to indicated an error in the input, the exception is not catch.
The exception appears in the console log (The error in the logs is at the end of the question) as it seems that nobody is catching it.
What i am missing? The exception in the converter should be catch within the updateStrategy and display the error, shouldn't it?
!ENTRY org.eclipse.core.databinding 4 0 2017-08-18 15:16:27.816
!MESSAGE Invalid time Format
!STACK 0
java.lang.RuntimeException: Invalid time Format
at com.lsespace.earthcare.tds.gui.util.databinding.conversion.StringToJavaTimeTagConverter.convert(StringToJavaTimeTagConverter.java:21)
at org.eclipse.core.databinding.UpdateStrategy.convert(UpdateStrategy.java:715)
at org.eclipse.core.databinding.UpdateValueStrategy.convert(UpdateValueStrategy.java:1)
at org.eclipse.core.databinding.ValueBinding$3.run(ValueBinding.java:175)
at org.eclipse.core.databinding.observable.Realm$1.run(Realm.java:149)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.databinding.observable.Realm.safeRun(Realm.java:153)
at org.eclipse.core.databinding.observable.Realm.exec(Realm.java:171)
at org.eclipse.core.databinding.ValueBinding.doUpdate(ValueBinding.java:158)
at org.eclipse.core.databinding.ValueBinding.access$4(ValueBinding.java:147)
at org.eclipse.core.databinding.ValueBinding$1.handleValueChange(ValueBinding.java:46)
at org.eclipse.core.databinding.observable.value.ValueChangeEvent.dispatch(ValueChangeEvent.java:70)
at org.eclipse.core.databinding.observable.ChangeManager.fireEvent(ChangeManager.java:117)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue.fireValueChange(DecoratingObservableValue.java:61)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue.handleValueChange(DecoratingObservableValue.java:103)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue$1.handleValueChange(DecoratingObservableValue.java:76)
at org.eclipse.core.databinding.observable.value.ValueChangeEvent.dispatch(ValueChangeEvent.java:70)
at org.eclipse.core.databinding.observable.ChangeManager.fireEvent(ChangeManager.java:117)
at org.eclipse.core.databinding.observable.value.AbstractObservableValue.fireValueChange(AbstractObservableValue.java:82)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue.notifyIfChanged(SimplePropertyObservableValue.java:126)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue.access$3(SimplePropertyObservableValue.java:118)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue$1$1.run(SimplePropertyObservableValue.java:70)
at org.eclipse.core.databinding.observable.Realm$1.run(Realm.java:149)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.databinding.observable.Realm.safeRun(Realm.java:153)
at org.eclipse.core.databinding.observable.Realm.exec(Realm.java:171)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue$1.handleEvent(SimplePropertyObservableValue.java:66)
at org.eclipse.core.databinding.property.NativePropertyListener.fireChange(NativePropertyListener.java:69)
at org.eclipse.jface.internal.databinding.swt.WidgetListener.handleEvent(WidgetListener.java:56)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1084)
at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:3117)
at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:4939)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4794)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5115)
at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method)
at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:2446)
at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:262)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4889)
at org.eclipse.swt.widgets.Text.windowProc(Text.java:2704)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5102)
at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method)
at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3814)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
at org.eclipse.jface.window.Window.open(Window.java:794)
at com.lsespace.earthcare.tds.gui.jface.actions.EditConfigAction.run(EditConfigAction.java:39)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
at org.eclipse.jface.action.ActionContributionItem.lambda$5(ActionContributionItem.java:436)
at org.eclipse.jface.action.ActionContributionItem$$Lambda$57/765702264.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4228)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3816)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:161)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
at org.eclipse.equinox.launcher.Main.main(Main.java:1492)
This is the implementation of the UpdateStrategy that I use so exceptions in the converter are treated like validation exceptions.
/**
* This implementation of UpdateValueStrategy does not catch the exceptions thrown by the converter,
* thus letting the normal mechanism of ValueBinding deal with the exception as it will do with a
* validation exception.
*
*/
public class AlternativeUpdateValueStrategy extends UpdateValueStrategy {
public AlternativeUpdateValueStrategy() {
this(UpdateValueStrategy.POLICY_UPDATE);
}
public AlternativeUpdateValueStrategy(int updateStrategy) {
super(updateStrategy);
}
#Override
public Object convert(Object value) {
if (converter != null) {
return converter.convert(value);
}
return value;
}
}
Related
I read this post JavaFx 8 global exception handling and tried to handle uncaught exceptions in my application. It works fine as described in the post. But when I added a statement which caused a NullPointerException the UncaughtExceptionHandler did not catch this exception. Why ? Is there another thread handling this exception? Or do I have to set the DefaultUncaughtExceptionHandler? I read JavaDocs:
Uncaught exception handling is controlled first by the thread, then by the thread's ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread's thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler's uncaughtException method will be invoked.
I have no idea how to get the solution which handles all uncaught exceptions. Can you help? Thanks for your support!!
This is the code:
package TestSimpleDialog;
public class Main extends Application {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private MyHandler myHandler = new MyHandler();
#Override
public void init() {
// Thread.currentThread is the FX-Launcher thread:
Thread.currentThread().setUncaughtExceptionHandler(myHandler);
System.out.println(Thread.currentThread().getUncaughtExceptionHandler());
try {
logger.addHandler(new FileHandler("java.myLOG"));
}
catch (IOException e) {
throw new IllegalStateException("IOException when adding File Handler");
}
}
#Override
public void start(Stage primaryStage) {
logger.info("Test Application started");
// Thread.currentThread() is the FX-Application thread:
Thread.currentThread().setUncaughtExceptionHandler(myHandler);
// If this thread has not had an uncaught exception handler explicitly set then this thread's ThreadGroup object
// is returned, unless this thread has terminated, in which case null is returned.
System.out.println(Thread.currentThread().getUncaughtExceptionHandler());
// try {
// URI uriTest = new URI(null);
// } catch (URISyntaxException e) {
// throw new IllegalStateException("URISyntaxException by testing");
// }
StackPane root = new StackPane();
Button button = new Button("Throw exception");
button.setOnAction(event -> {
throw new RuntimeException("** T E S T **") ;
});
root.getChildren().add(button);
Scene scene = new Scene(root, 150, 60);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
class MyHandler implements Thread.UncaughtExceptionHandler{
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
System.out.println("MyHandler caught exception: "+throwable.getMessage());
logger.log(Level.SEVERE, "**TEST** threw an uncaught exception", throwable);
}
}
}
When I push the button, I have got this output on the console:
TestSimpleDialog.Main$MyHandler#49285759
Aug. 08, 2020 5:55:33 NACHM. TestSimpleDialog.Main start
INFORMATION: Test Application started
TestSimpleDialog.Main$MyHandler#49285759
MyHandler caught exception: ** T E S T **
Aug. 08, 2020 5:55:51 NACHM. TestSimpleDialog.Main$MyHandler uncaughtException
SCHWERWIEGEND: **TEST** threw an uncaught exception
java.lang.RuntimeException: ** T E S T **
at TestSimpleDialog.Main.lambda$start$0(Main.java:47)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher............
But when I activated this statement to get a NullPointerException
try {
URI uriTest = new URI(null);
} catch (URISyntaxException e) {
throw new IllegalStateException("URISyntaxException by testing");
}
I could see on the console that the exception was not caught because of missing the statement "MyHandler caught exception: " the class MyHandler prints on Sysout. Furthermore nothing is written on the logging file.
TestSimpleDialog.Main$MyHandler#22b2aa29
TestSimpleDialog.Main$MyHandler#22b2aa29
Aug. 08, 2020 6:16:51 NACHM. TestSimpleDialog.Main start
INFORMATION: Test Application started
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException
at java.base/java.net.URI$Parser.parse(URI.java:3104)
at java.base/java.net.URI.<init>(URI.java:600)
at TestSimpleDialog.Main.start(Main.java:41)
at javafx.graphics/com.sun.javafx.application.............
Don't have an answer to how - just a tentative explanation to the why (looks like the first thought in my comments wasn't far off ;)
At its base is the fact that the Application is instantiated via reflection: whatever exceptions happen in init/start bubble up as errors in instantiation, namely as InvocationTargetException. And these are indeed handled by LauncherImpl.launchApplicationWithArgs by .. ex.printStackTrace
public static void launchApplicationWithArgs(final ModuleAccess mainModule,
final String mainClassName,
final String preloaderClassName, String[] args) {
// invoke, handle exception, line 472
...
} catch (InvocationTargetException ex) {
ex.printStackTrace();
abort(null, "Exception running application %1$s", tempAppClass.getName());
return;
}
Don't see any way to intercept that (which might be a bug .. or not).
Edit
To achieve logging (beyond printing to the error output) of errors coalesced into InvocationTargetException, an option might be to wrap the workload of the init/start method into a try .. catch ... block and manually invoke the handler, something like
#Override
public void init() throws Exception {
try {
// do stuff that might be throwing
throw new ArithmeticException("am I caught?");
} catch (Exception ex) {
// invoke the handler and re-throw
myHandler.uncaughtException(Thread.currentThread(), ex);
throw(ex);
}
}
I have 2 storage enabled cache nodes that i am trying to use for pre-loading of cache. About 1 million accounts are to be loaded by these 2 storage enabled nodes. Both key and value are String objects which I am trying to write to cache. I am using InvocationService.execute() method to invoke the pre-loading tasks asynchronously:
for (Map.Entry<Member, LoaderInvocable> entry : mappedWork.entrySet()) {
Member member = entry.getKey();
LoaderInvocable task = entry.getValue();
invocationService.execute(task, Collections.singleton(member), null);
}
LoaderInvocable is a class that is implementing Invocable and Serializable interfaces and its run() method has been overridden to performs the actual work of reading from database and writing to the cache.
InvocationService is defined as below in the coherence config file:
<invocation-scheme>
<scheme-name>
InvocationScheme</scheme-name>
<service-name>
LoaderInvocationService</service-name>
<autostart system-property="tangosol.coherence.invocation.autostart">true</autostart>
</invocation-scheme>
Below is the exception that i am getting:
2016-02-22 17:16:24,612 [pool-1-thread-1] ERROR (support.context.SessionExecutable) Caught exception from SessionExecutable.execute()
(Wrapped) java.io.NotSerializableException: com.oracle.common.collections.ConcurrentLinkedQueue
at com.tangosol.util.Base.ensureRuntimeException(Base.java:289)
at com.tangosol.util.Base.ensureRuntimeException(Base.java:270)
at com.tangosol.coherence.component.util.daemon.queueProcessor.packetProcessor.PacketPublisher.packetizeMessage(PacketPublisher.CDB:28)
at com.tangosol.coherence.component.util.daemon.queueProcessor.packetProcessor.PacketPublisher$InQueue.add(PacketPublisher.CDB:8)
at com.tangosol.coherence.component.util.daemon.queueProcessor.packetProcessor.PacketPublisher.post(PacketPublisher.CDB:1)
at com.tangosol.coherence.component.net.Message.dispatch(Message.CDB:77)
at com.tangosol.coherence.component.net.Message.post(Message.CDB:1)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.Grid.post(Grid.CDB:2)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.Grid.send(Grid.CDB:1)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.InvocationService.execute(InvocationService.CDB:33)
at com.tangosol.coherence.component.util.safeService.SafeInvocationService.execute(SafeInvocationService.CDB:1)
.
.
.
.
.
.
Caused by: java.io.NotSerializableException: com.oracle.common.collections.ConcurrentLinkedQueue
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at java.util.Hashtable.writeObject(Hashtable.java:988)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:438)
at com.tangosol.coherence.Component.writeObject(Component.CDB:1)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:438)
at com.tangosol.coherence.Component.writeObject(Component.CDB:1)
It seems that half of the accounts have been cached successfully. Can it be node specific issue? Both of the storage enabled cache nodes are on the same server using the same cluster configuration. From the logs it is clear that both nodes successfully joined the cluster.
Thanks Praveen. I have implemented the PortableObject interface and not facing the NotSerializableException anymore. But now i am facing a new problem. The second node is not invoking the task and leaving the cluster without any exception in the logs.
I used the InvocationObserver which suggests that memberLeft() the cluster. Can it be something wrong with my implementation of readExternal() and writeExternal() methods for serialization? Below is the implementation:
#Override
public void readExternal(PofReader paramPofReader) throws IOException {
// TODO Auto-generated method stub
cacheName = paramPofReader.readString(0);
firstRow = paramPofReader.readLong(1);
lastRow = paramPofReader.readLong(2);
}
#Override
public void writeExternal(PofWriter paramPofWriter) throws IOException {
// TODO Auto-generated method stub
paramPofWriter.writeString(0, cacheName);
paramPofWriter.writeLong(1, firstRow);
paramPofWriter.writeLong(2, lastRow);
}
i am running a browser instance inside a #Test(dataprovider .. method. But i am unable to pass the driver instance to the Test method,
Here is my code, in the last statement i am getting a null point exception.
My question is, How do i pass the instance of driver into the test method
#Test (dataProviderClass=GetData.class)
public class createUserPageTest {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
private MailCode openMail;
#BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = “http://demo.mysite.com”;
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + “/pageLink/Home.action”);
}
#Test(dataProvider=”RegisterUserStage1″)
public void NewUsrStage1(String name,String email,String password)
{
CreateUserPage createuser = PageFactory.initElements(driver, CreateUserPage.class);
createuser.CreateUserStage1(driver,name,email,password);
try {
openMail.testValidateEmail(driver);
——-
——-
The error message displayed is
java.lang.NullPointerException
at demoname.org.createUserPageTest.NewUsrStage1(createUserPageTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:128)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1203)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
at org.testng.TestNG.run(TestNG.java:1036)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
My DataProvider name is as follows
#DataProvider(name="RegisterUserStage1")
public static Object[][] getTestData() throws Exception
{
Object retObject[][]=getTableArray("src\\resource\\TestData.xls", 0, "NewUserStage1");
return retObject;
}
There where multiple issues with code.
As AJ rightly pointed out objects where initialized .
My users are reporting that when they download a JSON file using WiFi, the app works like charm, but when they attempt to download the same file using their data connection: GPRS, 3G, 3.5G etc... the app force closes. It doesn't happen with all types of smartphones, e.g, with my LG Optimus Black it doesn't happen.
To retrieve this file I use an AsyncTask.
private class GetData extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://url.com);
HttpResponse response = httpclient.execute(httpget);
strPlayers = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (IOException e) { e.printStackTrace(); }
finally { httpclient.getConnectionManager().shutdown(); }
return null;
}
protected void onPostExecute(Void result) {
Players players = new Gson().fromJson(strPlayers, Players.class);
quantity_darkmatter.setText(String.valueOf(players.userName));
}
}
Here's the StackTrace()
java.lang.RuntimeException: Unable to start activity ComponentInfo{carl.fri.fer.omegan/carl.fri.fer.omegan.Research}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at carl.fri.fer.omegan.Research.onStart(Research.java:613)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3791)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1632)
... 11 more
What can be the problem?
For non-WIFI the connection might take considerably more time, so it might be an issue of connection timeout, when that happens strPlayers will be blank and as there is no errorhandling in onPostExecute this might give Gson.fromJson hickups and make it throw an exception... try testing that strPlayers!=null before trying to parse it or putting it in a try-catch block to see if it throws an exception of some sort.
Is there any output of the e.printStackTrace() in the doInBackground function?
I had been using jmock with seam all these days, but its not sufficient to mock final/static/enums. So I tried working with JMockit. However everytime I run, I get NPE. Can't even debug, below is sample code
public class TestJmockit extends SeamTest {
#Mocked Dependency dependencyInCodeToTest;
CodeToTest bean = new CodeToTest();
#Test
public void testSaveSectionChangesJMockit() throws Exception {
new AbstractSeamTest.ComponentTest() {
#Override
protected void testComponents() throws Exception {
new NonStrictExpectations()
{
{
dependencyInCodeToTest.getLabel(); result = "Normal";
}
};
bean.execute();
}
}.run();
}
}
Actual Code..
package com.abc.action.account.information;
import com.abc.vo.account.ExternalAccountStatus;
import com.abc.vo.account.information.ExternalAccountStatusClosedInfo;
import com.abc.vo.account.information.ExternalAccountStatusInfo;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.jboss.seam.mock.AbstractSeamTest;
import org.jboss.seam.mock.SeamTest;
import org.junit.Test;
public class ConsumerAccountInformationActionTestJmockit extends SeamTest {
#Mocked ExternalAccountStatus mockExternalAccountStatus;
#Mocked ExternalAccountStatusInfo mockExternalAccountStatusInfo;
// ConsumerAccountInformationAction bean = new ConsumerAccountInformationAction();
#Test
public void testSaveSectionChangesJMockit() throws Exception {
new AbstractSeamTest.ComponentTest() {
#Override
protected void testComponents() throws Exception {
new NonStrictExpectations()
{
{
mockExternalAccountStatus.getLabel(); result = "Normal";
mockExternalAccountStatusInfo.getClosedInfo(); result = new ExternalAccountStatusClosedInfo();
}
};
// bean.saveSectionChanges();
}
}.run();
}
}
If I put a breakpoint at class declaratiom (Public Class Consumer..), stepping over to next line causes NPE. If I take out the commented lines in the code, it fails at the first uncommented line.
I am using Java 1.6 and IntelliJ IDE. Wonder if it has to do with IDE configuration.
With TestNG I dont even get the stack trace, with JUnit I see the below..
java.lang.NullPointerException
at org.jboss.seam.servlet.ServletApplicationMap.get(ServletApplicationMap.java:54)
at org.jboss.seam.contexts.BasicContext.get(BasicContext.java:49)
at org.jboss.seam.contexts.BasicContext.get(BasicContext.java:44)
at org.jboss.seam.core.Init.instance(Init.java:117)
at org.jboss.seam.contexts.BusinessProcessContext.<init>(BusinessProcessContext.java:47)
at org.jboss.seam.contexts.TestLifecycle.beginTest(TestLifecycle.java:35)
at org.jboss.seam.mock.AbstractSeamTest$ComponentTest.run(AbstractSeamTest.java:159)
at com.billmelater.csa.action.account.information.ConsumerAccountInformationActionTestJmockit.testSaveSectionChangesJMockit(ConsumerAccountInformationActionTestJmockit.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 255
General Objection: mocking is there to isolate you from external code,
especially from those coming from your server wendor ( like AbstractSeamtest ) - so
you do not have to initialize them or have server runing or whatever.
Treat mocked test as saved debug session. In your case you like to assure (I'm guessing), that method
bean.saveSectionChanges();
interacts correctly with seam infrastructure, or other collaborators. This is easily achieved by something like:
public static testProperInteraction(#Mocked final Collaborator collaborator) {
new Expectations() {
{
collaborator.doThis(with some parameters);
returns(something you like);
}
};
Bean bean = new Bean(collaborator);
assertSomething(bean.saveSessionChanges());
// nothing else shall be called
new FullVerifications() {
{
}
};
}