Tuesday, 8 July 2025

POST API Automation Java using okhttp

===========

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>


≠=========

import okhttp3.*;

public class OkHttpPostExample {
    public static void main(String[] args) {
        String apiUrl = "https://api.example.com/data";
        OkHttpClient client = new OkHttpClient();

        String jsonBody = "{\"name\":\"John Doe\",\"age\":30}";

        RequestBody body = RequestBody.create(
                jsonBody, MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response Code: " + response.code());
            System.out.println("Response Body:");
            System.out.println(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Get API Java Automation using okhttp

=========

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>


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


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpExample {
    public static void main(String[] args) {
        String apiUrl = "https://api.example.com/data"; // your API endpoint
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(apiUrl)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response Code: " + response.code());
            System.out.println("Response Body:");
            System.out.println(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Wednesday, 15 May 2024

How to implement AI in selenium automation testing

Implementing AI in Selenium automation testing can enhance the testing process by adding intelligence to your tests, such as smarter element identification, dynamic test case generation, or result analysis. Here's a general approach:

1. **Identify areas for AI integration**: Determine which aspects of your testing process could benefit from AI, such as test case generation, test data management, or result analysis.

2. **Select AI techniques**: Choose AI techniques that suit your requirements. This could include machine learning for predictive analysis, natural language processing for test case generation, or computer vision for visual testing.

3. **Integrate AI libraries or services**: Incorporate AI libraries or services into your Selenium automation framework. For example, you might use TensorFlow or PyTorch for machine learning tasks, NLTK or spaCy for natural language processing, or OpenCV for computer vision tasks.

4. **Enhance element identification**: Use AI to improve element identification in your tests. Instead of relying solely on XPath or CSS selectors, consider using machine learning algorithms to dynamically identify elements based on their visual appearance or other attributes.

5. **Dynamic test case generation**: Utilize AI techniques to generate test cases dynamically based on changing requirements or user behavior. This could involve using reinforcement learning algorithms to adapt test cases over time.

6. **Result analysis and reporting**: Implement AI algorithms to analyze test results more intelligently. This could include identifying patterns or anomalies in test results, predicting potential issues, or providing insights for improving test coverage.

7. **Continuous learning and improvement**: Continuously monitor and refine your AI-powered testing approach based on feedback and new data. This could involve retraining machine learning models, updating test case generation algorithms, or fine-tuning result analysis techniques.

Remember to consider factors such as data privacy, model interpretability, and performance optimization when integrating AI into your Selenium automation testing framework.

Java Stream Filter

1) Display the string which is matched with condition by using stream.

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<String> list1=new ArrayList<>();

    public void testStream(){
        list1.add("Test");
        list1.add("Testing");
        list1.add("Selenium");

        list1.stream().filter(s->s.contains("Test")).forEach(System.out::println);

    }

}

O/p

Test
Testing 

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

2) Find duplicate number in given integer using string

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<Integer> list1=Arrays.asList(10,20,35,20,67,10)

    public void testStream(){
        Set<Integer> set1= new HashSet();
        list1.stream().filter(s->!set1.add(s)).forEach(System.out::println);

    }

}

O/p

10
20

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



Java Stream Sorted


1) Sort number in given integer using stream in ascending order

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<Integer> list1=Arrays.asList(10,20,35,20,67,10)

    public void testStream(){
        Set<Integer> set1= new HashSet();
        list1.stream().sorted().forEach(System.out::println);

    }

}

O/p

10
10
20
20
35
67

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


1) Sort number in given integer using stream in Descending order

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<Integer> list1=Arrays.asList(10,20,35,20,67,10)

    public void testStream(){
        Set<Integer> set1= new HashSet();
        list1.stream().sorted(Collections.reverseOrder()).forEach(System.out::println);

    }

}

O/p

67
35
20
20
10
10

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

public static void main(String[] args) explanation


public

is an access modifier
main() declared as globally available
JVM can invoke from outside class


static

JVM can invoke without creating the object.
we can save memory for creating the object.

void

method returns nothing.
as soon as the main method ends then java programs also terminate. So nothing returned by main



main

jvm looks for this identifier for the starting point of the program.
Main method is not a keyword.



String[] args

main method accepts one parameter as String[]
Accepts java command line argument, array of string
args - name of array. we can give any name as user defined.

Difference between Java Stream Map and Java Stream Filter



Java stream filter - Filter used to filter the data and always returns the boolean value. If its return is true then it will be added to the list.

Java Stream map - consisting result of the given function applying to the element.



collect the element from Stream




Collect the element in Set format

 Set<String> finalString= list1.stream().filter(s -> s.contains("Test")).collect(Collectors.toSet());
        System.out.println(finalString);
--------------------------------------------

Collect the element in List format

Method 1

 List<String> finalString= list1.stream().filter(s -> s.contains("Test")).collect(Collectors.toList());
        System.out.println(finalString);

Method2

List<String> finalString= list1.stream().filter(s -> s.contains("Test")).toList();
        System.out.println(finalString);
-----------------------------------

how to check both Actual value equals to Expected Value

How to check Actual Value contains in Expected Value

public void verifyActualValuePresentInExpected(List<String> expectedValue, set<String> actualValue){

Boolean status = actualValue.stream().allMatch(expectedValue:: contains);

if(status){
Pass
} else {
Fail
List<String> extraValue = actualValue.stream().
filter(val-> ! expectedValue.contains(val)).
Collect(Collectors.toList());
System.out.println(extraValue);

List<String> missingValue = expectedValue.stream().
filter(val1-> ! actualValue.contains(val1)).
Collect(Collectors.toList());
System.out.println(missingValue);

}

How to check Expected Value contains in Actual Value

public void verifyExpectedValuePresentInActual(List<String> expectedValue, set<String> actualValue){

Boolean status = expectedValue.stream().allMatch(actualValue:: contains);

if(status){
Pass
} else {
Fail
List<String> missingValue = actualValue.stream().
filter(val-> ! expectedValue.contains(val)).
Collect(Collectors.toList());
System.out.println(missingValue);

List<String> extraValue = expectedValue.stream().
filter(val1-> ! actualValue.contains(val1)).
Collect(Collectors.toList());
System.out.println(extraValue);

}

Best practice for create selenium Automation test

Creating robust and flexible Selenium automation tests involves following best practices for test design, implementation, and maintenance. Here are some steps to achieve this:

1. **Identify clear test objectives**: Clearly define the purpose and scope of each test case to ensure that it aligns with the overall testing goals.

2. **Use descriptive and meaningful test names**: Give each test case a descriptive and meaningful name that reflects its purpose and expected behavior. This makes it easier to understand the test's intent and results.

3. **Modularize test code**: Divide your test code into small, reusable modules or functions that focus on specific actions or scenarios. This promotes code reuse, simplifies maintenance, and enhances readability.

4. **Implement robust error handling**: Anticipate and handle potential exceptions or errors gracefully in your test code. Use try-catch blocks or assertion methods to verify expected outcomes and handle unexpected conditions effectively.

5. **Parameterize test data**: Parameterize test data to make tests more flexible and adaptable to different scenarios. Use data-driven techniques to separate test logic from test data, allowing for easier maintenance and scalability.

6. **Use explicit waits**: Use explicit waits to ensure that tests wait for specific conditions to be met before proceeding. This helps avoid timing issues and makes tests more reliable, especially when dealing with dynamic web elements or network latency.

7. **Create meaningful assertions**: Write meaningful assertions that verify the expected behavior of the application under test. Use assertions to validate page content, element properties, or application state to ensure that tests accurately reflect user expectations.

8. **Implement page object model (POM)**: Organize your test code using the page object model, which encapsulates web page elements and their interactions into reusable classes. This improves code maintainability, readability, and scalability.

9. **Implement cross-browser testing**: Test your application across different web browsers and versions to ensure compatibility and consistency. Use Selenium's capabilities to automate tests on multiple browsers, and consider using cloud-based testing platforms for broader coverage.

10. **Continuous integration and testing**: Integrate Selenium tests into your continuous integration (CI) pipeline to automate test execution and ensure timely feedback on code changes. This helps catch bugs early and facilitates faster release cycles.

11. **Monitor and maintain tests**: Regularly review and update your Selenium tests to keep pace with changes in the application under test. Monitor test results for failures or regressions, and prioritize fixing flaky tests to maintain test reliability.

By following these best practices, you can create Selenium automation tests that are robust, flexible, maintainable, and provide reliable feedback on the quality of your web applications.

Wednesday, 8 November 2023

Java Stream Max

1) Find Maximum number in Array list

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<Integer> list1=Arrays.asList(10,20,35,20,67,10)

    public void testStream(){
        Int max1=list1.stream().max(Integer:: compare).get();

System.out.println(max1);

    }

}

O/p
67


≠=================================

1) Find Minimum number in Array list

import java.util.ArrayList;
import java.util.List;

public class javaStreamExamples {
    List<Integer> list1=Arrays.asList(10,20,35,20,67,10)

    public void testStream(){
        Int min1=list1.stream().max(Comparator.reverseOrder()).get();

System.out.println(min1);

    }

}

O/p
67


≠=================================


Wednesday, 13 May 2020

Lambda Expression in JAVA



-> The Lambda expression is used to provide the implementation of an interface which has functional interface.

->  It saves a lot of code.

-> In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.

-> Java lambda expression is treated as a function, so compiler does not create .class file.



Functional Interface

-> Lambda expression provides implementation of functional interface.

-> An interface which has only one abstract method is called functional interface.

-> Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.


Syntax

(argument-list) -> {body}


Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.



Example :  Addition of two numbers using lamda expression

@FunctionalInterface
interface Calc{

   int add(int n1,int n2);

}




public class Calculation{
 
 
    public static void main(String[] args) { 

     
       Calc addition=(n1,n2)->{

          return n1+n2;
       };
   
 
       System.out.println("Addition "+addition.add(10,20)); 


       
 }


}


Output

Addition 30

Comparator Interface in java


-> Comparator used to sorting the object element by using multiple sorting sequence.

-> We can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

-> The comparator interface provide two methods like compare(Object obj1,Object obj2) and equals(Object obj).



1) compare(Object obj1,Object obj2) function

Its compares first object(obj1) and second object(obj2) and return int value

Syntax : public int compare(Object obj1,Object obj2)


positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.



2) equals(Object obj1) function

Its used to compare current object with specified object

Syntax : public boolean equals(Object obj1)




Example : Sorting by name and Emp id by using comparator

import java.util.*; 
import java.io.*;

// User - Defined Class

class Employee { 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 
} 
}


class sortByAge implements Comparator{
                         
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

if(s1.empage==s2.empage) 
return 0; 
else if(s1.empage>s2.empage) 
return 1; 
else 
return -1; 
} 
   
}
 

class sortByName implements Comperator{
   
public int compare(Object o1,Object o2){ 
Employee s1=(Employee)o1; 
Employee s2=(Employee)o2; 

return s1.empname.compareTo(s2.empname);
   
}   
}


// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
 
System.out.println("Sorting By Age"); 
Collections.sort(al, new sortByAge()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
}


System.out.println("Sorting By Name");
Collections.sort(al, new sortByName()); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
} 

} 
} 


Output

Sorting By Age

4 Surya 21
1 Ajith 23
6 Vijay 27


Sorting By Name

1 Ajith 23
4 Surya 21
6 Vijay 27

Comparable interface in java



-> Comparable is an interface of comparing the objects with other objects os the same type. This is also called "natural ordering"

-> by using compare interface, we can sort the elements based on single data member only.

-> It provides single method name as compareTo(object) and provides single sorting sequence only.

-> The interface found in java.lang.package


compareTo(Object obj) method

The method used to compare the current object with specified object. Please find the below return values

positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.



Example 1: Sort by Integer Value (Ascending Order) by using Comparable

import java.util.*; 

// User - Defined Class

class Employee implements Comparable<Employee>{ 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 
} 
 
public int compareTo(Employee st){ 
if(empage==st.empage) 
return 0; 
else if(empage>st.empage) 
return 1; 
else 
return -1; 
} 
}



// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
Collections.sort(al); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
} 
} 
} 




Output

4 Surya 21
1 Ajith 23
6 Vijay 27


********************************************************


Example 2: Sort by Integer Value (Decending Order) by using Comparable


import java.util.*; 

// User - Defined Class

class Employee implements Comparable<Employee>{ 
int empid; 
String empname; 
int empage; 
Employee(int empid,String empname,int empage){ 
this.empid=empid; 
this.empname=empname; 
this.empage=empage; 
} 
 
public int compareTo(Employee st){ 
if(empage==st.empage) 
return 0; 
else if(empage<st.empage) 
return 1; 
else 
return -1; 
} 
}



// Main Class



public class TestSort1{ 
public static void main(String args[]){ 
ArrayList<Employee> al=new ArrayList<Employee>(); 
al.add(new Employee(1,"Ajith",23)); 
al.add(new Employee(6,"Vijay",27)); 
al.add(new Employee(4,"Surya",21)); 
 
Collections.sort(al); 
for(Employee st:al){ 
System.out.println(st.empid+" "+st.empname+" "+st.empage); 
} 
} 
} 




Output


6 Vijay 27
1 Ajith 23
4 Surya 21


Monday, 30 March 2020

Difference between Web driver, Remote Web Driver and Chrome Driver


Webdriver

Web driver is interface.
Global for all browsers
The interface provide common methods signature for all browser.
Ex : findElement(), get(),switchTo()

Remote Webdriver

Remote Webdriver is concrete class  implements Webdriver.
The implementation of webdriver method is available  in Remote Webdriver Class.
The Class provide additional  method  which is not available in webdriver. Provide method to run selenium test in remote machine.
ex : getSessionID()


Chrome driver

Chrome Driver is class extends Remote Webdriver.
Only specific to Chrome browser.
The class have implementation for only chrome browser. 

Difference between String, String Builder and String Buffer

Immutable : Cannot change value
Mutable : Can change the Value


String :

 String is Immutable.
 If we update any existing String then it will create String object. It won't override existing value.

Ex : 
String S1="Testing"
print (S1)

String concat(String s1){
S1 = S1+"Java"
}

O/P

S1: Testing


String Builder

String Builder is mutable.
we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuilder S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1: Testing Java


String Buffer

Both String Buffer and String builder same. Except one concept.
String Buffer is thread safe. we can refer the String buffer object via multi thread.

String Buffer is mutable. we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuffer S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1 : Testing Java





When to use

String : if String object value contant entire program.
String Builder : If String object value need to change at any time.
String Buffer : If String object value need to change at any time. It can be access same value via multithread.

Saturday, 4 March 2017

How to implement Log in Selenium (Using Log4j)



-> During the Automation Execution users need some information about the Execution steps in console.

-> We need information which helps the users to understand the testcase or any failure during the testcase execution.

-> With the help of Log4j its possible to enable logging in selenium testcase.


Follow the below steps to implement logs


1) Log4j Download


Download Log4j by using this link -> https://logging.apache.org/log4j/1.2/download.html

2) Create Log4j.properties file

-> Log4j.properties file for display log message only in console

# Root logger option
log4j.rootLogger=INFO,stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


->Log4j.propertiesfiles for display log message only in file

# Root logger option
log4j.rootLogger=INFO,file

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./Log/log_${current.date}.log
log4j.appender.fileout.Append=false
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.Append=false
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


->Log4j.propertiesfiles for display log message in both console and File

# Root logger option
log4j.rootLogger=INFO,stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./Log/log_${current.date}.html
log4j.appender.fileout.Append=false
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.Append=false
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


-> Load properties file in Main()


Initial Environment variable (Current.date) which is used in Log4j.properties file and load Log4j.properties file.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh_mm_ss");
        System.setProperty("current.date", dateFormat.format(new Date()));
       
           PropertyConfigurator.configure("C:/Selenium/log4j.properties");
          


-> create log for required class files



public class Login {
   
    final static Logger logger = Logger.getLogger(Login.class);

public static boolean LoginGmail(){

logger.info("Information Message");
logger.debug("Warning Message");
logger.error("Error Message");
}

}


-> Best practise for use logger

logger.info = Instead of Sysout we can use looger.info
logger.debug = use inside of conditional Statments and looping statments.
logger.error =  use inside catch block.


-> LoGGER Level

See the link for logger level ->  http://arunrajvdm.blogspot.in/2016/12/log4j-how-to-disable-all-log-details.html


Tuesday, 6 December 2016

How to launch safari browser in selenium webdriver



Please follow belows steps for launching safari browser in selenium webdriver


We need to install safari driver extension in safari browser. please follow the below steps for launch safari browser.

1) Go to http://docs.seleniumhq.org/download/

2) Scroll down -> Go to the section "SafariDriver" and download "SafariDriver.safariextz"

3) Double click on "SafariDriver.safariextz" (previously downloaded)

4) Safari would open with a pop up containing "Install" button -> Click Install button

5) Now go to Preferences of Safari and you would see WebDriver (in my case WebDriver 2.48.0) is installed (Enable WebDriver checkbox is checked))

6) It's now time to instantiate SafariDriver and get the desired URL by using Java code:

WebDriver driver = new SafariDriver();
driver.get("https://www.google.com");




Error :

If we are not install SafariDriver.safariextz extension in safari browser, we will get the below error in safari browser during the automation

"Unable to establish a connection with the SafariDriver Extension"


Solution : Follow the above steps to get install "SafariDriver.safariextz" extension in safari browser.



Exception :


If we are not install SafariDriver.safariextz extension in safari browser, we will get the below exception in console during the automation

Driver instantiation Exception Remote Client is not accessible



Solution : Follow the above steps to get install "SafariDriver.safariextz" extension in safari browser.