Handling HTTP 404 using Selenium WebDriver with Java - java

Clicking on a hyperlink is throwing me the below error.
Please suggest me how to handle this is below exception.

Use below code to check for the response code of the URL:
public static boolean getResponseCode(String chkurl) {
boolean validResponse = false;
try {
//Get response code of URL
HttpResponse urlresp = new DefaultHttpClient().execute(new HttpGet(chkurl));
int resp_Code = urlresp.getStatusLine().getStatusCode();
System.out.println("Response Code Is : "+resp_Code +" for "+chkurl);
if ((resp_Code == 404) || (resp_Code == 505)) {
validResponse = false;
} else {
validResponse = true;
}
} catch (Exception e) {
}
return validResponse;
}

I'm afraid there is no way to check do HTTP status code directly using Webdriver. You can use a HTTP client directly, but if the problem is a 500 code, or a 403, it can become unwieldy. We cover a more powerful technique using Mob Browser Proxy with WedDriver in our book:
http://selenium-webdriver-in-practice.github.io

Related

Rest service call is not triggering the handler

I am writing an application in vert.x and Java.
I have a class in which I have registered the end points for basic rest services:
private void setRoutes(Router router){
router.route("/*").handler(StaticHandler.create());
router.get("/service").handler(req -> {
getServices();//Call to Database and populate the services
List<JsonObject> jsonServices = services
.entrySet()
.stream()
.map(service ->
new JsonObject()
.put("name", service.getKey())
.put("status", service.getValue()))
.collect(Collectors.toList());
req.response().setStatusCode(200)
.putHeader("content-type", "application/json")
.end(new JsonArray(jsonServices).encode());
});
router.post("/service").handler(req -> {
JsonObject jsonBody = req.getBodyAsJson();
addService(jsonBody);//Persist the service
//services.put(jsonBody.getString("url"), "UNKNOWN");
req.response()
.putHeader("content-type", "text/plain")
.end("OK");
});
I am making a HTTP Get call to the GET /service end point as shown below and I am trying to get the response status code. But every-time the thread just gets stuck at the conn.getResponseCode() and then nothing happens.
Also my router.get("/service").handler is never called and in debug mode I can see that ResponseCode has a value of -1. From postman when I hit this url I am able to get proper results and also from the browser I can get proper results. Why is status code 200 not being returned. Also it does not go the catch or the finally blocks.
private void checkService(String key,DBConnector connector) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://localhost:8080/service");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(50);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//Update the status of the URL to OK
connector.query("UPDATE service set status = 'OK' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to OK");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to OK");
}
});
}
else {
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to fail");
}
});
}
}
catch (Exception e) {
e.printStackTrace();
//Code to set the status to FAIL
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to fail");
}
});
}
finally {
System.out.println("INSIDE FINALLY");
}
System.out.println(" Done");
}
Try setting the static handler after your routes:
router.get("/service").handler(req -> {...});
router.post("/service").handler(req -> {...});
router.route("/*").handler(StaticHandler.create());
Vertx routers match routes in the order they were attached in. In your current state all requests matching /* which would include /service are matched and passed to the static handler.
https://vertx.io/docs/vertx-web/java/#_route_order
By default routes are matched in the order they are added to the
router.
When a request arrives the router will step through each route and
check if it matches, if it matches then the handler for that route
will be called.
If the handler subsequently calls next the handler for the next
matching route (if any) will be called. And so on.

Reading content from google client http response multiple times in a batch request

Following the Google Drive REST API documentation, I'm implementing an exponential backoff strategy for recoverable API errors. I'd like to retry my request if the error code is 500 or 403 (and maybe 429), but I noticed that not all 403 errors are recoverable, so I'd like to retry only for those with a reason in a selected list. The error reason is not provided as a separate information in the response, but it's contained in the content inputstream, which I parsed and processed:
private boolean isRateLimitExceeded(com.google.api.client.http.HttpResponse response) {
int statusCode = response.getStatusCode();
if (statusCode == 403) {
response.getRequest().setParser(Utils.getDefaultJsonFactory().createJsonObjectParser());
GoogleJsonErrorContainer jsonResponse = response.parseAs(GoogleJsonErrorContainer.class);
List<ErrorInfo> errors = jsonResponse.getError().getErrors();
if (errors != null && !errors.isEmpty()) {
List<String> recoverableErrors = Arrays.asList("limitExceeded", "concurrentLimitExceeded", "rateLimitExceeded", "userRateLimitExceeded", "servingLimitExceeded");
for (ErrorInfo errorInfo : errors) {
if (!recoverableErrors.contains(errorInfo.getReason())) {
return false;
}
}
return true;
}
}
return false;
}
This works fine, but consumes the content. During the execution of the batch request, the google client tries to read and parse the content again, finds nothing left, and throws an exception. I tried marking and resetting the response.getContent() inputstream, but Google's HttpResponse doesn't support marking. Is there any other way I can make the content available again, or reading it without consuming it?
If it matters, I'm using a GoogleNetHttpTransport.
I believe this is the proper way to do that:
private static final String USER_RATE_LIMIT_EXCEEDED_REASON = "userRateLimitExceeded";
private static final String RATE_LIMIT_EXCEEDED_REASON = "rateLimitExceeded";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private boolean isRateLimitExceeded(HttpResponse response) {
return response.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN
&& isRateLimitExceeded(GoogleJsonResponseException.from(JSON_FACTORY, response));
}
private boolean isRateLimitExceeded(GoogleJsonResponseException ex) {
if (ex.getDetails() == null || CollectionUtils.isEmpty(ex.getDetails().getErrors())) {
return false;
}
String reason = ex.getDetails().getErrors().get(0).getReason();
return RATE_LIMIT_EXCEEDED_REASON.equals(reason) || USER_RATE_LIMIT_EXCEEDED_REASON.equals(reason);
}
See also: https://www.programcreek.com/java-api-examples/?code=cchabanois/mesfavoris/mesfavoris-master/bundles/mesfavoris.gdrive/src/mesfavoris/gdrive/connection/GDriveBackOffHttpRequestInitializer.java

server availability checker in Android

I am trying to check internet connection of device first, if Internet is available...I need to check server is online or not. I have searched lot of in stackflow for it but there no where latest solution is available like below
1
2
but none of it is working properly as people comments and my trial. I am checking internet status of device with below code
public static boolean isInternetAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isActiveNetworkConnected = false;
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
isActiveNetworkConnected = true;
} else {
isActiveNetworkConnected = false;
}
}
} else {
isActiveNetworkConnected = false;
}
return isActiveNetworkConnected;
}
Let me know anyone have proper solution which can check server available or not with this code.
After checking the internet connectivity, you can simply make a test API hit to check server status. Send the request to server if server respond ok, start next work or in-other case handle server not responding message for user.
Here is a sample using okhttp
public boolean isServerUp(){
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("your server url here")
.build();
client.newCall(request).enqueue(new Callback() {
#Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
return false;
}
#Override public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return true;
}
});
}
return false;
}
For checking the current status of the server after network checked, need to check if the response is not null

Test Java RESTful calls to Web API .Net

I have a weird question. I am working on a Java project for work, where we need to make HTTP GET/POST calls to our WEB API. I wanted to make a WebAPI testing project in C#; run it locally (localhost on some random port) and make sure I am sending the right stuff. That way I could control what was sent back(success, errors, JSON, XML, and different variables like that).
Here is some key stuff I have so far:
Client-Java code:
public String sendAPIRequest( HttpRequestMethod method, String apiURI, String payload) throws IOException
{
// Method is GET, POST....
// apiURL specific API navigating to.
// pauload is the html body.
if(payload == null)
{
payload = "";
}
// Establish a connection.
String strURL = String.format("%s%s", this.BaseURL, apiURI);
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Accept-Charset", this.CHARSET);
conn.setRequestMethod(method.toString());
conn.setRequestProperty("Content-Type", "text/json;charset=" + this.CHARSET);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// write the payload out, if it exists.
//if(payload != null)
{
try(OutputStream output = conn.getOutputStream())
{
output.write(payload.getBytes(CHARSET));
}
}
// read the response.
StringBuilder response = new StringBuilder();
InputStream input = conn.getInputStream();
try(Scanner inputScanner = new Scanner(input))
{
while(inputScanner.hasNextLine())
{
response.append((inputScanner));
}
}
return response.toString();
}
public String CheckForApplicableLicenses(String dCode, String key)
{
String result;
try
{
String APICall = String.format("/license/find_matching?d_code=%s&key=%s", dCode, key);
String Response = API.sendAPIRequest(HttpRequestMethod.GET, APICall);
// TODO Parse the String Response JSON/XMl.
result = Response;
}
catch(Exception ex)
{
// TODO: incorporate some sort of logging and error handling.
result = ex.toString();
}
return result;
}
Server-C#.Net code (tested with fiddler, and in the browser):
[Route("api/[controller]")]
public class LicenseController : Controller
{
[HttpGet]
[Route("find_matching")]
public IEnumerable<string> find_matching(string d_code = "", string key = "")
{
return new string[] { d_code, key };
}
}
Results so far:
I've gotten 404 errors, and I have been able to connect. Most of the time the Java client blows up when I get to the creating the InputStream. I've never been able to trip the breakpoint in the C# server.
Questions:
1) Is what I am doing even feasible? I'm really just trying to test the Java Client, without calling the API, before I am ready. Maybe it has something to do with not running the service on the default HTTP port of 80?
2) Is there a better way of testing this? I don't want to make call to our actual service until we are done.
Thanks in advance for an assistance.

calling some online service from GWT

I have this JavaScript code which is connecting with the service and sending back the result.
Now the requirement is to call the same service from Pure Java.
Below is the javascript code for calling the service.
If some one can guide me to convert this Javascript to Java in my GWT Application
Thanks
function verifyValidationSyntax(textToValidate)
{
var url = "https://validation-grammar.example.com/validation_grammar_service/rest/validation_step_validation";
var client = new XMLHttpRequest();
client.open("POST", url, false);
client.setRequestHeader("Content-Type", "text/plain");
client.send(textToValidate);
if (client.responseText==='true') {
return "true";
} else {
return "false";
}
}
I wont convert your code, But here is the sweetest example from docs
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
You may miss this in docs
To use the HTTP types in your application, you'll need to first inherit the GWT HTTP module by adding the following tag to your module XML file:
<inherits name="com.google.gwt.http.HTTP" />

Categories

Resources