public void startAppiumServer() throws MyException {
try {
if (appiumService == null) {
appiumService = AppiumDriverLocalService.buildService(new AppiumServiceBuilder().usingAnyFreePort()
.withArgument(() -> "--allow-insecure", "chromedriver_autodownload"));
appiumService.start();
}
} catch (Exception e) {
throw new MyException("Error while starting appium server: " + e.toString());
}
}
PSS Automation
The desire to create this blog to share my knowledge to others.
Friday, November 20, 2026
Start Appium Server
Tuesday, October 6, 2026
Network Log Capture
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v154.network.Network;
import org.openqa.selenium.devtools.v154.network.model.RequestId;
public class NetworkLogCapture {
public static Logger APP_LOGS = LogManager.getLogger(NetworkLogCapture.class.getName());
private DevTools devTools;
private final List<String> failedRequests = new ArrayList<>();
public void enableNetworkLogging(ChromeDriver driver) {
devTools = driver.getDevTools();
devTools.createSession();
// Store URL per requestId for correlation
Map<String, String> requestUrlMap = new ConcurrentHashMap<>();
// Enable Network domain
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(),
Optional.empty()));
// Log all requests
devTools.addListener(Network.requestWillBeSent(), request -> {
String url = request.getRequest().getUrl();
requestUrlMap.put(request.getRequestId().toString(), url);
APP_LOGS.info("\n=== REQUEST ===");
APP_LOGS.info("URL : " + url);
APP_LOGS.info("Method : " + request.getRequest().getMethod());
APP_LOGS.info("Headers : " + request.getRequest().getHeaders());
// Request body (only for POST/PUT)
request.getRequest().getPostDataEntries().ifPresent(b -> APP_LOGS.info("REQUEST BODY : " + b));
// Fetch post data via CDP if not inline
try {
RequestId requestId = request.getRequestId();
String postData = devTools.send(Network.getRequestPostData(requestId)).getPostData();
APP_LOGS.info("[REQUEST BODY - CDP] " + postData);
} catch (Exception e) {
APP_LOGS.info("[REQUEST BODY] Not available: " + e.getMessage());
}
});
// Log all responses
devTools.addListener(Network.responseReceived(), response -> {
int status = response.getResponse().getStatus();
String url = response.getResponse().getUrl();
// Flag non-2xx responses (blocked, failed, etc.)
if (status >= 400 || status == 0) {
failedRequests.add(status + " | " + url);
APP_LOGS.info("\n=== RESPONSE HEADERS ===");
APP_LOGS.info("Status : " + status);
APP_LOGS.info("URL : " + url);
APP_LOGS.info("Headers : " + response.getResponse().getHeaders());
}
});
// Log load failures (blocked by firewall/CSP)
devTools.addListener(Network.loadingFinished(), finished -> {
String url = requestUrlMap.getOrDefault(finished.getRequestId().toString(), "");
try {
Network.GetResponseBodyResponse body = devTools.send(Network.getResponseBody(finished.getRequestId()));
APP_LOGS.info("\n=== RESPONSE BODY (" + url + ") ===");
APP_LOGS.info(body.getBase64Encoded() ? new String(java.util.Base64.getDecoder().decode(body.getBody()))
: body.getBody());
} catch (Exception e) {
APP_LOGS.info("[RESPONSE BODY] Skipped: " + e.getMessage());
}
});
// Log load failures (blocked by firewall/CSP)
devTools.addListener(Network.loadingFailed(), failed -> {
APP_LOGS.error("[FAILED] " + failed.getErrorText() + " | blocked=" + failed.getBlockedReason()
+ " | url type=" + failed.getType());
});
}
public void printFailedRequests() {
APP_LOGS.info("=== FAILED/BLOCKED REQUESTS ===");
failedRequests.forEach(msg -> APP_LOGS.error(msg));
}
}
Friday, April 10, 2026
Appium Automating Mobile Gestures
Android gesture: There is a couple of basic gestures, like swipe, fling or pinch, which are commonly used in Android applications
public void swipeUp() {
Dimension size = driver.manage().window().getSize();
int startX = size.getWidth() / 2;
int startY = (int) (size.getHeight() * 0.8);
int endY = (int) (size.getHeight() * 0.2);
performSwipe(startX, startY, startX, endY);
}
public void swipeDown() {
Dimension size = driver.manage().window().getSize();
int startX = size.getWidth() / 2;
int startY = (int) (size.getHeight() * 0.2);
int endY = (int) (size.getHeight() * 0.8);
performSwipe(startX, startY, startX, endY);
}
public void swipeLeft() {
Dimension size = driver.manage().window().getSize();
int startX = (int) (size.getWidth() * 0.8);
int endX = (int) (size.getWidth() * 0.2);
int y = size.getHeight() / 2;
performSwipe(startX, y, endX, y);
}
public void swipeRight() {
Dimension size = driver.manage().window().getSize();
int startX = (int) (size.getWidth() * 0.2);
int endX = (int) (size.getWidth() * 0.8);
int y = size.getHeight() / 2;
performSwipe(startX, y, endX, y);
}
public void longPress(WebElement element) {
Point center = getCenter(element);
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence longPressSeq = new Sequence(finger, 0);
longPressSeq.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), center.getX(), center.getY()));
longPressSeq.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
longPressSeq.addAction(new Pause(finger, Duration.ofSeconds(2)));
longPressSeq.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(longPressSeq));
}
public void doubleTap(WebElement element) {
Point center = getCenter(element);
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence doubleTapSeq = new Sequence(finger, 0);
doubleTapSeq.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), center.getX(), center.getY()));
doubleTapSeq.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
doubleTapSeq.addAction(new Pause(finger, Duration.ofMillis(50)));
doubleTapSeq.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
doubleTapSeq.addAction(new Pause(finger, Duration.ofMillis(100)));
doubleTapSeq.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
doubleTapSeq.addAction(new Pause(finger, Duration.ofMillis(50)));
doubleTapSeq.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(doubleTapSeq));
}
private void performSwipe(int startX, int startY, int endX, int endY) {
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence swipe = new Sequence(finger, 0);
swipe.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), startX, startY));
swipe.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
swipe.addAction(finger.createPointerMove(Duration.ofMillis(600), PointerInput.Origin.viewport(), endX, endY));
swipe.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(swipe));
}
private Point getCenter(WebElement element) {
Point loc = element.getLocation();
Dimension size = element.getSize();
return new Point(loc.getX() + size.getWidth() / 2, loc.getY() + size.getHeight() / 2);
}
How to capture browser network logs
Create a Chrome devtool object
protected static DevTools devTools;
Call below function in the setup method.
/**
* To capture browser network logs
*/
public void getBrowserNetworkLogs() {
if (getBrowserName().equalsIgnoreCase("CHROME")) {
// Create a session with DevTools
devTools = ((ChromeDriver) driver).getDevTools();
devTools.createSession();
devTools.send(Network.clearBrowserCache());
devTools.send(Network.setCacheDisabled(true));
// Enable network tracking
devTools.send(Network.enable(java.util.Optional.empty(), java.util.Optional.empty(),
java.util.Optional.empty(), java.util.Optional.empty(), java.util.Optional.empty()));
// final RequestId[] requestIds = new RequestId[1];
// Capturing request information of a network call
/*
* devTools.addListener(Network.requestWillBeSent(), request -> {
* APP_LOGS.error("Request: " + request.getRequest().getUrl()); });
*/
// Capturing response information of a network call
devTools.addListener(Network.responseReceived(), response -> {
RequestId requestId = response.getRequestId();
if (response.getResponse().getStatus() != 200) {
String responseUrl = response.getResponse().getUrl();
if (responseUrl.contains("chubb") && !responseUrl.contains("favicon.ico")
&& !responseUrl.contains("chubb-publico")) {
int responsStatus = response.getResponse().getStatus();
// String responseType = response.getType().toJson();
String statusText = response.getResponse().getStatusText();
String responseHeaders = response.getResponse().getRequestHeaders() != null
? response.getResponse().getRequestHeaders().toString()
: "N/A";
String responseBody = devTools.send(Network.getResponseBody(requestId)).getBody();
String requestPostData = devTools.send(Network.getRequestPostData(requestId)).toString();
APP_LOGS.error("Response Url: " + responseUrl);
APP_LOGS.error("Response Status Code: " + responsStatus);
APP_LOGS.error("Response Text: " + statusText);
APP_LOGS.error("Response Headers: " + responseHeaders);
APP_LOGS.error("Response Body: " + responseBody);
APP_LOGS.error("Request Post Data: " + requestPostData);
}
}
});
} else {
APP_LOGS.info("Browser network log not captured for: " + getBrowserName());
}
}
Close the dvetools connection in the tearDown methid.
if (devTools != null) {
devTools.send(Network.disable());
}
Tuesday, April 1, 2025
Check the date format of value
public boolean isValidDateFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException e) {
e.printStackTrace();
}
return date != null;
}
Monday, March 24, 2025
JSON Using Jackson API
Maven Dependency:
<!-- jackson-databind jar -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.3</version>
</dependency>
Class ObjectMapper:
// Create an object to ObjectMapper ObjectMapper objectMapper = new ObjectMapper();
Create a JSON Object or Object Node:
It is similar to map put method. put method is overloaded to accept different types of data
// Creating Node that maps to JSON Object structures in JSON content ObjectNode bookingDetails = objectMapper.createObjectNode();
// String as field value
bookingDetails.put("firstname", "Jim");
bookingDetails.put("lastname", "Brown");
// integer as field value
bookingDetails.put("totalprice", 111);
// boolean as field value
bookingDetails.put("depositpaid", true);
bookingDetails.put("additionalneeds", "Breakfast");Note: Duplicate field name. Will override the value.
bookingDetails.put("additionalneeds", "Lunch");// To print created json object as string.
String createdPlainJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);Output :–
Created plain JSON Object is :
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch"
}Create a nested JSON Object or Object Node:
// Since requirement is to create a nested JSON Object
ObjectNode bookingDateDetails = objectMapper.createObjectNode();
bookingDateDetails.put("checkin", "2021-07-01");
bookingDateDetails.put("checkout", "2021-07-01");We use set(String fieldName, JsonNode fieldValue) or replace(String fieldName, JsonNode fieldValue)
bookingDetails.set("bookingdates", bookingDateDetails);// To get the created json object as string. Use writerWithDefaultPrettyPrinter() for proper formatting
String createdNestedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("Created nested JSON Object is : \n"+ createdNestedJsonObject); Output:
Created nested JSON Object is :
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
}
} Retrieve a field value from JSON Object or ObjectNode:
We can retrieve field value by passing field name. Since it is string, use asText().
String firstName = bookingDetails.get("firstname").asText();
System.out.println("First name is : "+firstName);
// We can use asText() as well but return type will be string
boolean depositpaid = bookingDetails.get("depositpaid").asBoolean();
System.out.println("deposit paid is : "+depositpaid);
// To retrieve value of nested ObjectNode
bookingDetails.get("bookingdates").get("checkin").asText();
System.out.println("Checkin date is : "+depositpaid);Output:
First name is : Jim deposit paid is : true Checkin date is : 2021-07-01
Retrieve all field names from JSON Object or Object Node:
To retrieve all field names from a ObjectNode, we need to use fieldNames() methods which returns an Iterator<String>.
// To get all field names
System.out.println("Count of fields in ObjectNode : "+ bookingDetails.size());
Iterator allFieldNames = bookingDetails.fieldNames();
System.out.println("Fields are : ");
while(allFieldNames.hasNext())
{
System.out.println(allFieldNames.next());
}Output:
Count of fields in ObjectNode : 6 Fields are : firstname lastname totalprice depositpaid additionalneeds bookingdates
Retrieve all field values from from JSON Object or ObjectNode:
To retrieve all field values from an ObjectNode, use elements() method which returns an Iterator of JsonNode.
// To get all field values
Iterator allFieldValues = bookingDetails.elements();
System.out.println("Fields values are : ");
while(allFieldValues.hasNext())
{
System.out.println(allFieldValues.next());
}Output:
Fields values are :
"Jim"
"Brown"
111
true
"Lunch"
{"checkin":"2021-07-01","checkout":"2021-07-01"}Retrieve all key-value pair from JSON Object or ObjectNod:
We can use fields() method to get all fields (with both names and values) of a JSON Object. It returns an Iterator<Entry<String,JsonNode>>.
// To get all key-value pair
Iterator> allFieldsAndValues = bookingDetails.fields();
System.out.println("All fields and their values are : ");
while(allFieldsAndValues.hasNext())
{
Entry node = allFieldsAndValues.next();
System.out.println("Key is : "+node.getKey()+" and its value is : "+node.getValue());
}Output:
All fields and their values are :
Key is : firstname and its value is : "Jim"
Key is : lastname and its value is : "Brown"
Key is : totalprice and its value is : 111
Key is : depositpaid and its value is : true
Key is : additionalneeds and its value is : "Lunch"
Key is : bookingdates and its value is : {"checkin":"2021-07-01","checkout":"2021-07-01"}Remove a field from JSON Object or ObjectNode:
Use remove(String fieldName) method to remove a field from ObjectNode. It will return value of the field, if such field existed; null if not.
// To remove a field
String removedFieldValue = bookingDetails.remove("firstname").asText();
System.out.println("Value of Removed field is " + removedFieldValue);
String removedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("After removing field , JSON Object is : \n"+ removedJsonObject);Output:
Value of Removed field is Jim
After removing field , JSON Object is :
{
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
}
}Update a field from JSON Object or ObjectNode:
We need to use put() method to update a field value if fieldValue is not another ObjectNode. If fieldValue is an ObjectNode use set() or replace() method.
// To replace a field value, use put() method for non ObjectNode type and replace() or set() for ObjectNode
bookingDetails.put("firstname", "Amod");
bookingDetails.put("firstname", "Aaditya");
String updatedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("After updating field , JSON Object is : \n"+ updatedJsonObject);Output:
After updating field , JSON Object is :
{
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
},
"firstname" : "Aaditya"
}JSON Array:
create JSON Array we use createArrayNode() method of ObjectMapper class. createArrayNode() will return reference of ArrayNode class.
- Create an empty JSON Array.
- Create first JSON Object
- Create second JSON Object
- Add created JSON Objects to JSON Array
// Create an array Node
ArrayNode arrayNode = objectMapper.createArrayNode();//add our elements directly to array
arrayNode.add("Apple").add("Banana").add("Cherry");// Update an array Node
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(arrayNode);
arrayNode.set(1, "Blueberry");This test demonstrates reading a JSON array into an ArrayNode and updating the value at index one from “Banana” to “Blueberry“.
Finally, we use the set() method to directly replace the value with a String, and Jackson automatically handles the conversion to a TextNode internally.
// Create an array ArrayNode parentArray = objectMapper.createArrayNode();
Add created JSON Objects to JSON Array:
Class ArrayNode provides a method add() which can add one JSON Object to array at a time.
parentArray.add(firstBookingDetails); parentArray.add(secondBookingDetails);
To add multiple Object Nodes to array at a time we can use addAll() method which accepts a Collection<? extends JsonNode> . We can create a List (because List extends Collection)of all JSON Objects and add.
parentArray.addAll(Arrays.asList(firstBookingDetails,secondBookingDetails));
String jsonArrayAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray); System.out.println(jsonArrayAsString);
Note:- If you try to add duplicate Object Nodes, it will be added to array.
Retrieving JSON Object from JSON array using index:
// To get json array element using index JsonNode firstElement = parentArray.get(0); System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(firstElement));
Get size of JSON Array:
size() method can be used to get size of JSON Array.
int sizeOfArray = parentArray.size();
System.out.println("Size of array is "+sizeOfArray);Iterate JSON Array:
iterator() method can be used to iterate through a JSON Array.
// To iterate JSON Array
Iterator iteraor = parentArray.iterator();
System.out.println("Prining Json Node using iterator : ");
while(iteraor.hasNext())
{
JsonNode currentJsonNode = iteraor.next();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(currentJsonNode));
}
Remove a JSON Object from JSON Array:
We can remove a JSON object from JSON Array using its index.
// To remove an element from array
parentArray.remove(0);
System.out.println("After removing first element from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
Empty JSON Array:
// To empty JSON Array
parentArray.removeAll();
System.out.println("After removing all elements from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
Friday, August 26, 2022
Parallel testing with DataProviders in TestNG
Create a class for the DataProvider method.
DataProvider Class:
import org.testng.annotations.DataProvider;
public class DataProviderDemo {
@DataProvider(name = "testData", parallel=true)
public Object[][] dataProvFunc() {
return new Object[][] {
{"","","Username cannot be empty"},
{"","Test","Username cannot be empty"},
{"$%1234","2345%$","Invalid credentials"}
};
}
}
An extra parameter “parallel” is required to initiate parallel execution in TestNG using the data provider.
A new ThreadLocal is instantiated for each test class since it’s in the BeforeClass annotation.
private static final ThreadLocal<WebDriver> WEB_DRIVER_THREAD_LOCAL = new ThreadLocal<WebDriver>();
Below is the complete test code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DataProviderParallelTests {
public WebDriver driver;
private static final ThreadLocal<WebDriver> WEBDRIVER_THREADLOCAL = new ThreadLocal<WebDriver>();
@BeforeMethod
public void setUp(){
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Vibha\\Software\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
WEBDRIVER_THREADLOCAL.set(driver);
System.out.println("Before method Thread Id:" + Thread.currentThread().getId());
}
@Test(dataProvider = "testData", dataProviderClass = DataProviderDemo.class)
public void invalidLoginTest(String username, String password, String errorMessage) throws InterruptedException {
driver = WEBDRIVER_THREADLOCAL.get();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/");
Thread.sleep(2000);
driver.findElement(By.name("txtUsername")).sendKeys(username);
System.out.println("Username :" + username);
Thread.sleep(2000);
driver.findElement(By.name("txtPassword")).sendKeys(password);
System.out.println("password :" + password);
Thread.sleep(2000);
String expectedError = driver.findElement(By.id("spanMessage")).getText();
System.out.println("Error Message :" + expectedError);
Assert.assertTrue(expectedError.contains(errorMessage));
}
@AfterMethod
public void tear_down() {
WebDriver driver = WEBDRIVER_THREADLOCAL.get();
System.out.println("After method Thread Id:" + Thread.currentThread().getId());
if (driver != null) {
driver.quit();
}
}
}
testng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" thread-count="2" data-provider-thread-count="2">
<test name="Test">
<classes>
<class name="DataProvider.DataProviderParallelTests"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
In this file, data-provider-thread-count is set to 2, then two browsers will be opened, and the first two tests will run from the list.