simple Restful call results in InvocationTargetException - httpclient

I'm using Seam with RestEasy. RestEasy provides httpClient type functionality, among other things.
An action of mine that is called when a page loads (that is, it is called from the xxx.page.xml). The code looks like:
try {
ClientRequest request = new ClientRequest(url);
ClientResponse response = null;
response = request.get();
} catch (Exception e) {
e.printStackTrace();
}
the e.printStackTrace() is never reached, but while trying the request.get(), the code generates the following exception:
Exception during request processing:
Caused by javax.el.ELException with message: "java.lang.reflect.InvocationTargetException"
org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:339)
org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348)
org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
org.jboss.seam.core.Expressions$2.invoke(Expressions.java:175)
org.jboss.seam.navigation.Page.preRender(Page.java:311)
org.jboss.seam.navigation.Pages.preRender(Pages.java:350)
org.jboss.seam.jsf.SeamPhaseListener.preRenderPage(SeamPhaseListener.java:561)
org.jboss.seam.jsf.SeamPhaseListener.beforeRenderResponse(SeamPhaseListener.java:472)
org.jboss.seam.jsf.SeamPhaseListener.beforeServletPhase(SeamPhaseListener.java:148)
org.jboss.seam.jsf.SeamPhaseListener.beforePhase(SeamPhaseListener.java:118)
com.sun.faces.lifecycle.Phase.handleBeforePhase(Phase.java:214)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:96)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
Why would a Reflection API call even be involved????

Related

Caused by: java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use

I am getting the below error when trying to download file in liferay
05:03:35,867 ERROR [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'][PortletRequestDispatcherImpl:115] org.springframework.web.util.NestedServletException: View rendering failed; nested exception is java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
org.springframework.web.util.NestedServletException: View rendering failed; nested exception is java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
at org.springframework.web.servlet.ViewRendererServlet.processRequest(ViewRendererServlet.java:96)
at org.springframework.web.servlet.ViewRendererServlet.doGet(ViewRendererServlet.java:67)
Caused by: java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
at com.liferay.portlet.MimeResponseImpl.getWriter(MimeResponseImpl.java:90)
at com.liferay.portlet.PortletServletResponse.getWriter(PortletServletResponse.java:207)
at com.netcracker.portal.framework.spring.templates.view.SoyDataView.renderMergedOutputModel(SoyDataView.java:93)
and below is the code, i tried searching online but none of them have worked
String defaultFileName = "hello.pdf";
resourceResponse.setContentType("application/octet-stream");
resourceResponse.addProperty(GenericServiceTransport.CONTENT_DISPOSITION, "attachment; filename= hello.pdf" );
resourceResponse.flushBuffer();
try {
out = resourceResponse.getPortletOutputStream();
out.write(backendFile.getContent());
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return;
As first item I'd try to remove the flushBuffer call. You probably get the exception in the line following it, and flushing the buffer surely will use the output stream.
If that doesn't help, please add mute code, e.g. the complete method including its signature

Mongo db authentication failure in java code does not go to catch block

I am trying to write code where mongo DB authentication is tested.
However when authentication fails the code does not reach to the catch block.
Here is the code :
MongoClient client = null;
try {
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
MongoCredential.createScramSha1Credential(
"abc",
"test",
"abc#123".toCharArray()
)
);
client = new MongoClient(host,credentials, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
} catch (Exception e) {
client = new MongoClient(host, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
// e.printStackTrace();
}
client.getDatabase("admin").runCommand(new Document("ping",1));
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='abc', source='test', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Unknown Source)
This code never falls through into the catch block and runs the line just after the catch block.
Can you tell me how to handle this situation.

Logback no ExceptionInInitializerError in file only on console

I'm using logback 1.7.5 with play framework 2.2.4, during working I'm getting such error:
Exception in thread "Thread-5" java.lang.ExceptionInInitializerError
at controllers.db.SyncDBManager.createDeviceCollectionsIfNotExists(SyncDBManager.scala)
at server.impl.logic.controller.DeviceInitializer.checkAuthenticationResponse(DeviceInitializer.java:226)
at server.impl.logic.controller.DeviceInitializer.processReceivedFrames(DeviceInitializer.java:117)
at server.impl.logic.controller.DeviceController.onReceivedPackets(DeviceController.java:77)
at server.impl.logic.io.DeviceReader.run(DeviceReader.java:130)
Caused by: java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:313)
at scala.None$.get(Option.scala:311)
at controllers.base.MongoSyncHelper$class.$init$(MongoSyncHelper.scala:16)
at controllers.db.SyncDBManager$.<init>(SyncDBManager.scala:32)
at controllers.db.SyncDBManager$.<clinit>(SyncDBManager.scala)
... 5 more
But only on console, how can I catch such exception and write it to file?
Seems like an ordinary stack trace in a console printed with the sysout. Depending on your design if you want to log an exception with the Play logger you should do it in a catch block with one of logger's methods by passing an exception as one of parameters. For example:
try {
// code
} catch {
case e: Exception => play.api.Logger.error("An error occurred", e)
}
The logger level is up to you. If you don't have a catch block and want to log an unexpected exception that occurs in any place of an application you should log it in the Global object by overriding onError method.
override def onError(request: RequestHeader, e: Throwable): Future[SimpleResult] = {
play.api.Logger.error("An error occurred", e)
super.onError(request, e)
}
Remember that onError method is called only in the production mode.

Solution to NullPointerException in my TestNG test case

I am trying to login Facebook by using multiple sets of login cridential from external excel sheet using TestNG but in between the code what i have written throws:
FAILED: f
java.lang.NullPointerException
at DataDriven.loginRetesting.f(loginRetesting.java:31)
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 org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
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:127)
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:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
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)
Code:
#Test
public void f() throws Exception{
FileInputStream fi=new FileInputStream("E:\\workspace99\\SeleniumAutomations\\testdata\\LoginData.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
for (int i = 1; i < 8; i++) {
driver.findElement(By.id("email")).sendKeys(s.getCell(0,i).getContents());
driver.findElement(By.id("pass")).sendKeys(s.getCell(1,i).getContents());
driver.findElement(By.id("u_0_1")).click();
Thread.sleep(1000);
if (selenium.isElementPresent("id=userNavigationLabel")) {
//driver.findElement(By.cssSelector("span.gb_V.gbii")).click();
driver.findElement(By.id("userNavigationLabel")).click();
driver.findElement(By.cssSelector("input.uiLinkButtonInput")).click();
Thread.sleep(1000);
}
else{
System.out.println("invalid cridential");
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("pass")).clear();
}
}
}
I am not able to find out where the problem is? so how to solve it.
For one thing, don't use "throws Exception" in the method declaration. Instead, have a try block inside the method with a "not null assertion".
Keep in mind that you never want to throw typical exceptions in a test method because it will drop you out of the test lifecycle too early and skip your #After phases. An exception thrown in a #Before annotated method will probably cause a SkipAssertion.
So, what you want to do instead is fail assertions. So, if you have a exception condition that occurs sometimes, swallow the exception (don't throw it) and use an assertion to handle it.
For example:
try {
} catch ( NullPointerException e ) {
Assert.assertTrue( "There was an error in blah.", false );
}
Null pointer means, exepected value of variable is null.
Please check the file exists at the specified path "E:\workspace99\SeleniumAutomations\testdata\LoginData.xls" and you get the value correctly from the file.
The stack trace says the issue is line 31 in your code but your snippet does not allow us to work out where line 31 is .
you are calling "selenium.isElementPresent". Could "selenium" be nil?

smack api giving error to login gtalk

I used all the api's related to smack so that i could login and use the gtalk in my and app. All the api's (smack 3.22, asmack, qsmack) give me same error. Error is coppied from logcat and pasted below. Please help me i am almost frustated now :(
XMPPConnection xmppConnection;
String host = "talk.google.com";
int port = 6222;
String service = "gmail.com";
String username = "test1";
String password = "password";
try {
xmppConnection = new XMPPConnection(new ConnectionConfiguration(host,
port, service));
xmppConnection.connect();
xmppConnection.login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
No response from the server.:
at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:74)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:404)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at com.android.xmppproject.XmppManager.performLogin(XmppManager.java:56)
at com.android.xmppproject.XMPPProjectActivity.onCreate(XMPPProjectActivity.java:29)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
I think you have provided incorrect GTalk port.
Please try port = 5222