Unable to getHostName with JSONObject with webdriver 2.44

518 views
Skip to first unread message

testingzeal

unread,
Jan 13, 2015, 4:00:30 PM1/13/15
to webd...@googlegroups.com
This class is NOT working post webdriver upgrade to 2.44, not sure how to fix this issue. Compilation errors on JSONObject.

It is NOT liking "JSONObject" from the below code, and i have highlighted them in red color.

Compilation error - 

Multiple markers at this line
- JSONObject cannot be resolved to a type
- The method extractObject(HttpResponse) from the type GetHostName refers to the 
missing type JSONObject
- JSONObject cannot be resolved to a type


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.remote.SessionId;

public class GetHostName {

public static String getHostName(
SessionId session) throws UnknownHostException
{
String hostDetail = null;
String hostName ="selgridin001";
int port = 4444;
String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: ";

try {
HttpHost host = new HttpHost(hostName, port);
DefaultHttpClient client = new DefaultHttpClient();
URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
System.out.println("URL is : "+sessionURL);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
JSONObject object = extractObject(response);
URL myURL = new URL(object.getString("proxyId"));
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
hostDetail = myURL.getHost();
}
} catch (Exception e) {
//logger.log(Level.SEVERE, errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
return hostDetail;
}

private static JSONObject extractObject(HttpResponse resp) throws IOException, JSONException {
BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuffer s = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
s.append(line);
}
rd.close();
JSONObject objToReturn = new JSONObject(s.toString());
return objToReturn;
}

}

Krishnan Mahadevan

unread,
Jan 13, 2015, 9:31:20 PM1/13/15
to webdriver

I believe that selenium code base stopped using JSONObject from 2.44 and switched over to using gson. Just look up samples on how to using gson libraries and modify your code accordingly.

--
You received this message because you are subscribed to the Google Groups "webdriver" group.
To unsubscribe from this group and stop receiving emails from it, send an email to webdriver+...@googlegroups.com.
To post to this group, send email to webd...@googlegroups.com.
Visit this group at http://groups.google.com/group/webdriver.
For more options, visit https://groups.google.com/d/optout.

Selenium Framework

unread,
Jan 14, 2015, 12:37:47 PM1/14/15
to webd...@googlegroups.com

testingzeal

unread,
Jan 14, 2015, 12:51:27 PM1/14/15
to webd...@googlegroups.com
Thanks

But i am stuck with this error. I added Gson.jar and added artifact to pom.xml 

  <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.3.1</version>
         </dependency>

( I see them in my Maven dependencies of the project) and also webdriver 2.44.0 .

I started the hub and node with 2.44.0 and confirmed it is 2.44.0 (Grid console confirms i am on 2.44.0)

I did a mvn clean compile and it was successful.

On test execution i see this error - (Not sure what else to do to resolve this error)

java.lang.NoClassDefFoundError: com/google/common/net/MediaType
at org.openqa.selenium.remote.http.JsonHttpCommandCodec.encode(JsonHttpCommandCodec.java:197)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:153)
at com.servicemagic.selenium.util.SiteDriverSetup.getChromeBrowser(SiteDriverSetup.java:160)

testingzeal

unread,
Jan 14, 2015, 5:16:54 PM1/14/15
to webd...@googlegroups.com
Fixed this java.lang.NoClassDefFoundError: com/google/common/net/MediaType by adding Guava libarary to my pom.xml
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Coming to converting JsonObject to Gson , here is the modified code  with Gson but i am getting this error.
Any help on this is appreciated.

public static String getHostName(
SessionId session) throws UnknownHostException
{
String hostDetail = null;
String hostName ="xxxxxxxxx";
int port = 4444;
String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: ";

try {
HttpHost host = new HttpHost(hostName, port);
DefaultHttpClient client = new DefaultHttpClient();
URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
System.out.println("URL is : "+sessionURL);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
//JSONObject object = extractObject(response);
//URL myURL = new URL(object.getString("proxyId"));
Gson gsonObject =extractObject(response);
URL myURL = new URL(gsonObject.toJson("proxyId"));
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
hostDetail = myURL.getHost();
}
} catch (Exception e) {
//logger.log(Level.SEVERE, errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
return hostDetail;
}

private static Gson extractObject(HttpResponse resp) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuffer s = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
s.append(line);
}
rd.close();
//JSONObject objToReturn = new JSONObject(s.toString());
//return objToReturn;
Gson gson = new Gson();
gson.toJson(s.toString());
System.out.println("gson to Json" +gson.toJson(s.toString()));
return gson;
}

======================

Here is the error - 

gson to Json"{\"msg\":\"slot found !\",\"success\":true,\"session\":\"d3ba5279-2d6f-4f04-bb18-eaa625aa6d9b\",\"internalKey\":\"9b1ac684-edaa-4dcb-aeac-a6c2695ba84a\",\"inactivityTime\":71,\"proxyId\":\"http://xx.xx.xx.xxx:5555\"}"
java.lang.RuntimeException: Failed to acquire remote webdriver node and port info. Root cause: 
at com.xxxxxx.selenium.util.GetHostName.getHostName(GetHostName.java:48)
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:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:73)
at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:14)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.MalformedURLException: no protocol: "proxyId"
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at com.xxxxxxxx.selenium.util.GetHostName.getHostName(GetHostName.java:41)
... 16 more

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

Selenium Framework

unread,
Jan 15, 2015, 9:23:09 PM1/15/15
to webd...@googlegroups.com
Here is your code. You can use JsonObject that is provided as part of gson library and then it is normal parsing of a Json object.

  1. Copy the below code into a class "SimpleTest.java"
  2. I assume you have all the necessary jars required
  3. The class has main method, so you can execute it directly
  4. I executed it on my localhost [after the GRID on localhost:4444] 
  5. The output i.e. the hostname is "localhost" --- you might get a different one based on where you execute this

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class SimpleTest {

public static String getHostName(SessionId session) throws UnknownHostException
{
String hostDetail = null;
String hostName ="localhost";
int port = 4444;
String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: ";

try {
HttpHost host = new HttpHost(hostName, port);
DefaultHttpClient client = new DefaultHttpClient();
URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
System.out.println("URL is : "+sessionURL);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
//JSONObject object = extractObject(response);
//URL myURL = new URL(object.getString("proxyId"));
JsonObject myjsonobject =extractObject(response);
JsonElement url = myjsonobject.get("proxyId");
System.out.println(url.getAsString());
URL myURL = new URL(url.getAsString());
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
hostDetail = myURL.getHost();
}

} catch (Exception e) {
//logger.log(Level.SEVERE, errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
return hostDetail;
}

private static JsonObject extractObject(HttpResponse resp) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuffer s = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
s.append(line);
}
rd.close();
JsonParser parser = new JsonParser();
JsonObject objToReturn = (JsonObject)parser.parse(s.toString());
System.out.println(objToReturn.toString());
System.out.println(objToReturn.get("proxyId"));
return objToReturn;
}


public static void main(String[] args) throws MalformedURLException, UnknownHostException {
// TODO Auto-generated method stub
DesiredCapabilities dc = new DesiredCapabilities();
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc.chrome());
driver.get("http://www.google.com");
System.out.println(driver.getTitle());
String hostname = getHostName(driver.getSessionId());
System.out.println("hostname" +hostname);
driver.quit();
}

}


Cheers,

testingzeal

unread,
Jan 16, 2015, 11:53:39 AM1/16/15
to webd...@googlegroups.com
Thank you so much , working like a charm.
Reply all
Reply to author
Forward
0 new messages