How to create a WebDriver instance to a dataprovider #Test method - webdriver

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 .

Related

Issue with catching RuntimeExceptions as NullPointerExceptions by an uncaught exception handler in Java FX applications

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);
}
}

e4 databinding converter exception not catch

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;
}
}

Jersey client throw ConcurrentModificationException when sending multiple async calls

I am trying the Asynchronous Client-side and Server-side Callbacks sample from Jersey document(https://jersey.github.io/documentation/latest/async.html#d0e10146).
I am using Grizzle client connector and server factory. The difference from the sample is I sent 10000 requests by for loop. And I set a clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 20);
Then client throws below exception:
javax.ws.rs.ProcessingException: java.util.ConcurrentModificationException
at org.glassfish.jersey.client.ClientRuntime.processFailure(ClientRuntime.java:227)
at org.glassfish.jersey.client.ClientRuntime.lambda$null$3(ClientRuntime.java:185)
at org.glassfish.jersey.client.ClientRuntime$$Lambda$103/1511834685.run(Unknown Source)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:312)
at org.glassfish.jersey.client.ClientRuntime.lambda$createRunnableForAsyncProcessing$4(ClientRuntime.java:159)
at org.glassfish.jersey.client.ClientRuntime$$Lambda$100/1987360300.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at org.glassfish.jersey.internal.util.collection.Views$1$1.next(Views.java:96)
at org.glassfish.jersey.message.internal.HeaderUtils.asHeaderString(HeaderUtils.java:230)
at org.glassfish.jersey.message.internal.HeaderUtils.lambda$asStringHeadersSingleValue$2(HeaderUtils.java:202)
at org.glassfish.jersey.message.internal.HeaderUtils$$Lambda$108/1341461635.apply(Unknown Source)
at java.util.stream.Collectors.lambda$toMap$209(Collectors.java:1321)
at java.util.stream.Collectors$$Lambda$21/936580213.accept(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.glassfish.jersey.message.internal.HeaderUtils.asStringHeadersSingleValue(HeaderUtils.java:200)
at org.glassfish.jersey.grizzly.connector.GrizzlyConnector.writeOutBoundHeaders(GrizzlyConnector.java:490)
at org.glassfish.jersey.grizzly.connector.GrizzlyConnector.apply(GrizzlyConnector.java:268)
at org.glassfish.jersey.client.ClientRuntime.lambda$null$3(ClientRuntime.java:183)
... 14 more
And I found many sockets are open by using netstat. It looks every request will open a socket. So after a little time, another exception will throw as below:
javax.ws.rs.ProcessingException: Too many open files
at org.glassfish.jersey.grizzly.connector.GrizzlyConnector$2.onThrowable(GrizzlyConnector.java:318)
at com.ning.http.client.providers.grizzly.GrizzlyResponseFuture.failed(GrizzlyResponseFuture.java:159)
at org.glassfish.grizzly.impl.SafeFutureImpl.notifyCompletionHandlers(SafeFutureImpl.java:187)
at org.glassfish.grizzly.impl.SafeFutureImpl.done(SafeFutureImpl.java:277)
at org.glassfish.grizzly.impl.SafeFutureImpl$Sync.innerSetException(SafeFutureImpl.java:382)
at org.glassfish.grizzly.impl.SafeFutureImpl.failure(SafeFutureImpl.java:122)
at com.ning.http.client.providers.grizzly.GrizzlyResponseFuture.abort(GrizzlyResponseFuture.java:72)
at com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider$1.failed(GrizzlyAsyncHttpProvider.java:138)
Invocation failed.
at org.glassfish.grizzly.utils.Futures.notifyFailure(Futures.java:129)
at org.glassfish.grizzly.connectionpool.SingleEndpointPool.notifyAsyncPollersOfFailure(SingleEndpointPool.java:1182)
null
at org.glassfish.grizzly.connectionpool.SingleEndpointPool.access$1500(SingleEndpointPool.java:102)
at org.glassfish.grizzly.connectionpool.SingleEndpointPool$ConnectCompletionHandler.onFailedToConnect(SingleEndpointPool.java:1321)
at org.glassfish.grizzly.connectionpool.SingleEndpointPool$ConnectCompletionHandler.failed(SingleEndpointPool.java:1290)
at org.glassfish.grizzly.impl.ReadyFutureImpl.addCompletionHandler(ReadyFutureImpl.java:147)
at org.glassfish.grizzly.connectionpool.SingleEndpointPool.connect(SingleEndpointPool.java:1157)
at org.glassfish.grizzly.connectionpool.SingleEndpointPool.take(SingleEndpointPool.java:788)
at org.glassfish.grizzly.connectionpool.MultiEndpointPool.take(MultiEndpointPool.java:592)
at com.ning.http.client.providers.grizzly.ConnectionManager.openAsync(ConnectionManager.java:143)
at com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider.execute(GrizzlyAsyncHttpProvider.java:174)
at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:506)
at org.glassfish.jersey.grizzly.connector.GrizzlyConnector.apply(GrizzlyConnector.java:274)
at org.glassfish.jersey.client.ClientRuntime.lambda$null$3(ClientRuntime.java:183)
at org.glassfish.jersey.client.ClientRuntime$$Lambda$103/694396298.run(Unknown Source)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:312)
at org.glassfish.jersey.client.ClientRuntime.lambda$createRunnableForAsyncProcessing$4(ClientRuntime.java:159)
at org.glassfish.jersey.client.ClientRuntime$$Lambda$100/1987360300.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I didn't change the max open file number in my system. I think even I changes the number to a high value it still will be used out when sending sufficient requests. Its not the root cause.
The questions come up to my mind are:
1, Why the ConcurrentModificationException throws?
2, How to limit the connection number opened by Grizzle and can be integrated with Jersey? It might help to get rid of above exceptions.
The client code:
ClientConfig clientConfig = new ClientConfig();
clientConfig.connectorProvider(new GrizzlyConnectorProvider());
clientConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 20);
Client client = ClientBuilder.newClient(clientConfig);
client.register(JacksonJsonProvider.class);
WebTarget target = client.target(serverURI);
AsyncInvoker asyncInvoker = target.request().async();
for (int i = 0; i < 100000; i++) {
Future<Response> responseFuture = asyncInvoker.post(
Entity.entity(json, MediaType.APPLICATION_JSON),
new InvocationCallback<Response>() {
#Override
public void completed(Response response) {
ObjectMapper mapper = new ObjectMapper();
MyResponse res = response.readEntity(MyResponse.class);
String result;
try {
result = mapper.writeValueAsString(res);
System.out.println(result);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
#Override
public void failed(Throwable throwable) {
System.out.println("Invocation failed.");
throwable.printStackTrace();
}
});
}
Sever code:
#POST
#Path("testAsyncCallback")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void handleEventReport(#Suspended final AsyncResponse asyncResponse,
JaxbBean o, #Context Request req) {
asyncResponse.register(new CompletionCallback() {
#Override
public void onComplete(Throwable throwable) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
MyResponse result = veryExpensiveOperation();
asyncResponse.resume(result);
}
private MyResponse veryExpensiveOperation() {
// ... very expensive operation
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(o);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
MyResponse response = new MyResponse();
response.setResult(1);
return response;
}
}).start();
}
Thanks in advance.

java.lang.NullPointerException when i run my unit test - mockito

i have a spring mvc application and using mockito for my unit test.I keep getting null pointer exception when i run my unit test. :(
Please find below the method that my unit test will be based on:
#Controller
public class LogInController {
#Autowired
private MessageSource messageSource;
#RequestMapping(method = RequestMethod.POST, value = "/login")
public ModelAndView validateViewLogin(#ModelAttribute Person person,
BindingResult result, HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
String userName = person.getFirstName();
String password = person.getPassword();
boolean isUserValid = false;
if (userName != null && password != null) {
isUserValid = userManagerService.validateUserLogin(userName,password);
}
if (!isUserValid) {
mav.addObject("failLog",messageSource.getMessage("login.user.fail", new String[] {" ", "" }, request.getLocale()));
mav.addObject("isUserValid", false);
mav.setViewName("login");
return mav;
}
mav.addObject("isUserValid", isUserValid);
mav.setViewName("home");
return mav;
}
Please find below my unit test:
#Test
public void validateViewLogin_NotValidLogin_returnsLoginPage() {
MockHttpServletRequest request = new MockHttpServletRequest();
Person person = new Person();
person.setFirstName("John");
person.setPassword("123");
isUserValid = false;
LogInController controller = new LogInController();
// Inject mock user service into controller
UserManagerService mockUserService = mock(UserManagerService.class);
controller.setUserManagerService(mockUserService);
// Configure mock user service to accept the person
when(mockUserService.validateUserLogin("John", "123")).thenReturn(
isUserValid);
// Attempt the validation
ModelAndView mav = controller
.validateViewLogin(person, result, request);
// Check the result
assertEquals("login", mav.getViewName());
}
Please find below stack trace error message when i run the unit test above:
java.lang.NullPointerException
at com.gemstone.presentation.LogInController.validateViewLogin(LogInController.java:99)
at com.gemstone.presentation.LogInControllerTest.validateViewLogin_NotValidLogin_returnsLoginPage(LogInControllerTest.java:79)
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.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.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Basically line 99 which is shown below is returning null according to the stack trace:
mav.addObject(
"failLog",
messageSource.getMessage("login.user.fail", new String[] {
" ", "" }, request.getLocale()));
Any ideas why i am getting the null pointer on this line please?However when i run my application it works fine and failLog message is displayed on my page.
thanks in advance.
My guess is that your messageSource is null. You are mocking your request, but not your messageSource, and where you are newing the login controller it's not being injected by Spring.
While running it would get injected by Spring automatically.
Edit to clarify:
First you need to be able to set it some how for testing. You can either add a setter or a constructor to get to it, such as:
#Controller
public class LogInController {
#Autowired
private MessageSource messageSource;
public void setMessageSource(MessageSource ms){
this.messageSource = ms;
}
// ......
}
Then your test would need to change as well:
#Test
public void validateViewLogin_NotValidLogin_returnsLoginPage() {
MockHttpServletRequest request = new MockHttpServletRequest();
Person person = new Person();
person.setFirstName("John");
person.setPassword("123");
isUserValid = false;
LogInController controller = new LogInController();
// Inject mock user service into controller
UserManagerService mockUserService = mock(UserManagerService.class);
/** ADDED **/
MessageSource ms = mock(MessageSource.class);
controller.setUserManagerService(mockUserService);
/** ADDED **/
controller.setMessageSource(ms);
// Configure mock user service to accept the person
when(mockUserService.validateUserLogin("John", "123")).thenReturn(
isUserValid);
/** ADDED **/
when(ms.getMessage("login.user.fail", new String[] {" ", "" }).thenReturn("message");
// Attempt the validation
ModelAndView mav = controller
.validateViewLogin(person, result, request);
// Check the result
assertEquals("login", mav.getViewName());
}
Just free handing this, so make sure I don't have any typos! Essentially you try the MessageSource as you did your UserManagerService, it's just an interface after all and can be mocked exactly the same way.

Jmockit TestNG/JUnit NullPointerException with Seam

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() {
{
}
};
}

Resources