Monday, 23 December 2024

Selenium Lesson Learnt

 1. Learn the existing framework and make guide on howto use it . Eg. Which BDD step to use to find a keyword in table and select checkbox 

2. Out of all the available test case, identify eligible test case for automation by executing each test case 2 times manually with sam test data

3. Pick the small and feasible test case for automation  first so that we can get an idea of end to end automation and show the count also to the client. 

4. Execute the failed test sripts one more time so that  they can get pass if they are failed due to env down issue. 

5. Do the mapping of test cases and test scripts properly 

6. Add test script name in the scenario outline. 

7. Add  <TestID> in example and in scenario outline . 

8. create a record of every day team efforts including activity done every hour per person. No of scripts created, executed and refactored , meetings because manager can ask any data any time from you. 

Date       Name        Activity (quantified )      Hours spent 

1/12/24 Ravinder   script created  2                7 hrs

1/12/24 Ravinder   Meetings        3                1.5 hrs


9. Keep the scenario outline length not very long . it causes issue in copying files of results due to long name . 

10. working directory should not be very long path. To avoid file copy paste issue due to long file name. 


11. Regular execution fo scripts should happen to ensure scripts are working fine and to find what kind of test data is needed. 

12. only eligible /feasible for automation test cases should be picked for automation. 

13. Implement the ode to generate one test script to generate one test result so that the test results ( individual)  can be added to each test case in jira. 

14. Autoation team should have the domain and functional knowledge before or during automation.

15. Failed test script should not generate green test results. 

16. Merge the code to master frequently . 

17. To run multiple test scripts in one go open webTestRunner.java and add tag below

tags = "EST-123" OR "EST-456" OR "EST-789", 

18. To generate glue code , write only the steps and run the test . Error will provide the glue code also. 

19. Error  --> Invalid column index(-1) allowable column range for BIFF8 is (0.255) or ( 'A' , 'IV')

Solution : 

a) Check if columns are more than 255

b) Create a new excel file 

c) open excel file inside eclipse and update here 

d) Error occurs when column does not exists 



Saturday, 21 December 2024

UFT Lesson Learnt

1. Where scripts are stored

Answer : Inside Action1 --> Script.mts

2. Where Password encoder tool is placed 

Answer : Start --> Program --> Micro Focus --> Micro Focused Unified Functional Testing --> Testing --> Tools --> Password Encoder 

3. Save the code before you run the code always because autosave feature is not available in UFT

4. Syntex of If Then Else

Answer : 

If  condition Then 

      statement 

ElseIf  condition Then

Else (optional)

End If

Tip : (1) use two tab indent for clear view of code

        (2) Each If should have one End If 

5.  Do not right click and select "execute from this line" inside a for loop

6.  .TSR is shared repository

7. To identify issue in the code / OR  run in maintenance  mode/Debug mode

8. If object spy is not able to recognize the element on the webpage do below 

    (1) Check proper add-ins are selected used in application

    (2) Ensure "Micro Focus Functional Testing Agent" is installed and enabled in browser

    (2) Restart the UFT  first 

    (3) Then Restart the application under test 

    (4) Reset the IE browser -->  Advance  -->  reset to default


9. Always Open shared OR in edit mode to add elements to it

10. Keep the naming conventions of OR objects consistent otherwise a lot of issues will occur later

Browser  - br

Page  - pg

Window -wn

Dialog - dg

Element - eml

Frame - frm

Table  - tbl 

Link - lnk

Button -btn

WebList - wl

TextBox - txt

CheckBox - chkBox

Image - img 


11. Update Run Mode : In case if Object Identification setting have been changed after adding object to the repository and if we want to reflect new settings on the existing objects instead of running manually you run in update mode mode. 

a) This works in the local repository only 

b) If  UFT is able to recognize the object, the new properties will not be updated.


12. To delete browser History --> Ctrl + Shift + Delete 

13. Use Wait(1) after each item selection from WebList to avoid sync issue

14. Create reusable function for 

  a) Navigation of all menus and Tree View

  b) fEnterData_BusinessCustomer()


15. Steps to automate 

a) Get all the test cases to automate 

b) Execute the test case manually two Times with same test data following the Jira steps to check the correctness of Jira steps and data dependency. If Jira steps are not correct ask the manual team to update the steps

c) Check the feasibility of automation of the test case . Remove from automation list if not feasible 

d) After creating the script, share the execution result with the manual team every day and get the signoff. If you receive any review comments, update the script accordingly and share the results again. 

e) First day execute first script , second day execute first and second script , third day execute first , second and third script in batch execution. This way keep executing the scripts to ensure all the previously developed scripts are working fine. 

16. Study all the scripts created by good team members and learn their reusable functions and style of coding. 

17. Meet with your automation team and show the reusable functions you created and scripts you created and discuss the issue you faced. 

18. If you are facing any issue or chanalge like technical , team issue, personal, emotional  ask for help in the team . 

19. If you see any error , try to find its root cause for eg. while running the script browser was crashing and trying to login again in Aperio application. and I was assuming it was coding error. 

20. How to toggle value in dropdown during each test. 

Answer (1) :  

CurrentDropDownValue = Browser("").Page("").WebList("").getROProperties("value")

If CurrentDropDownValue = "Medium" Then 

    NewSelection = "Low"

Else 

     NewSelection = "Medium"

End If

 

Browser("").Page("").WebList("").Select NewSelection 

Answer (2) :  SelectByIndex

Browser("").Page("").Select fGetRandNumerWithRange(1,15)

21. For each test result generate the test result in a separate file.  Do not create one bulk execution report. because separate test results are needed to upload in JIRA with each test case. Also, up to 10MB files can be uploaded in Jira. 

22. How to pass available value from  one function to another function

Answer : 

'Save value to Global Dictionary.

objDataDict("EmpName") = "Ravi"


'To Get Value from Global dictionary

strName = objDataDict("EmpName")


Tip: in fFunctionName(objDataDict) is must 


23. How to get future date 

Answer : DateAdd function

24. How to convert Date from one format to another format

Answer : create a function for that


25. After getting function date using 

DateAdd("m","4","MMDDYYYY")

the result will come with # like #12/22/2024#

to remove # use new date = CStr(DateWithHashHere)


26. Convert String to Double 

resultValue  = CDbl (StringValue)


27.  जब संकट में हों तो आगे और पीछे का विचार न करके जब जो एक काम करना है जो सबसे ज्यादा जरुरी है सिर्फ उसी पर ध्यान दो | एक एक करके सब काम हो जायेंगे और संकट दूर हो जाएगा | 


28.  If object is getting recognized from OR but while running the code it is not then create a new test  copy the code into it and run. 

29. Before the demo or delivery of the script run it continuously two times with the same test data without changing anything


30. User click OK button until navigated to given screen

Answer : 

do { Webutils.clickOKButton( button);

       }

While (WebUtils.CheckPageDisplay(Screen)!= True)


31.  Not able to select item from dropdown. Getting error after selecting the item. 

Answer : 

obj.WebList("Gender").Select "Male"

obj.WebList("Gender").FireEvent "onchange"


32. If object is not being recognized 

Answer : 

a) Enable Smart Identification in OR

b) Visual Relation Identifier in OR 


33. How to get the numeric number out of the below string 

str =  "902848   ravinder 16/12/1957"

Answer :  FirstPart = Split( str, " ") (0)

here output will be FirstPart  = 902848


34. Replace multiple spaces with single space 

Answer : 

cleanedStr = replace (inputStr , " ", " ")

'Replace until there are no more double spaces 

Do While InStr( cleanedStr , " ") > 0 

     cleanedStr  =  Replace ( cleanedStr , " " " ")

Loop


' Split the cleaned string and get the second part 

secondPart  = Split (cleanedStr , " ") (1)


35.  Pick a test you want to work on. Start the reverse timer and try to complete the task in the estimated time. This will keep you focused on the task.  Find out how much extra time you took then estimated and why. 

36. Keep a record of all the scripts you created with 

a) Start and End date 

b) Function used /created 

c) Issue / Pending items

d) Similar test scripts using a common function which can impact if changes are done in a common function. 


37. To find a string that exists in another string 

Answer : 

If InStr ( str1, str2) > 0  Then 

    msgbox "str2 found in str1"

End If


38. What should be the approach of refactoring 

Answer: Categorize the code in modules according to functionality like Navigation, entering data, put the code into functions with required parameters. Try to use a select case statement. 


39. While Entering data in the form contactName field data gets reset and not taking new data 

Answer:  Put 5 seconds wait after entering a value in each text field. 


40. Identify steps of a Test case, and create an independent function of each step . Call them as per requirement in the main function. 


41. Learn fast, Learn to Learn Fast 

42. To test a piece of code, place the code just after the loading of library files and excel sheet. It will save time by not executing the whole flow. 


43. Before Comparing two variables always Trim (UCase (CStr (variableName)))

44. Never assume that the script will run fine without executing continuously two times 

45. How to compare two variables with values 135 and 135.00

Answer : 

Trim ( CDbl (variable1)) = Trim (CDbl(variable2))


46. Open the Object repository only from the left-side tree view. Do not open from the Top menu > Resource > OR 


47. In a function fCreateUser contains multiple screens and in each screen, we have to enter values. In another case we need the same function but with one extra checkbox checked. What are the options to avoid creating a copy of the existing function to cater to the small change? 

Answer: 

a) Use a dictionary 

objDataDict("checkbox") = CheckboxON

If CheckboxON then 

  statement 

End If 


b) use Excel Input flag 

objDataDict.Item("checkbox") = "ON"

If objDataDict.Item("checkbox") = "ON" then 

  statement 

End If 

c) Use Wrapper Class 


48.  How to find a function being used in which all test scripts 

Answer: Go to script folder  --> Command prompt 

--> FindStr  /i /s "FunctionName"  *.mts


49. How to use the same function two times in a script that takes input data from an Excel sheet. While using the function a second time it takes a different set of data. 

FunctionName ("ProductName")

FirstTime  use of excel data   objDataDict("Name")


use the below line before calling the function again

SecondTime  use of excel data   objDataDict("Name1") = objDataDict("Name2")


50. Regular expression to have keyboard SAVINGS in a string is   

.* SAVINGS.*


51. While entering data in a text box it is working in debug mode but not working while running the script. Adding wait is also not working. The text box is also getting highlighted. 

Answer:  Add the text box again in OR. 

52. Do not use i=i+1 in the FOR NEXT  loop if not required

53. Do not touch the code written by others. It might break the working code written by others. 

 


Sunday, 17 December 2023

Selenium 4.16.1 boiler plate code

public WebDriver driver; public ChromeOptions co;


public static void main(String[] args) {

    co = new ChromeOptions();

    driver = new ChromeDriver(co);

    driver.get("https://google.com");

    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

    driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));

    driver.findElement(By.name("q")).sendKeys("Automation Step by Step");

    driver.findElement(By.name("q")).sendKeys(Keys.ENTER);

    driver.close();

    driver.quit();

}



Quick Tips :

// to press enter key

driver.findElement(By.name("q")).sendKeys(Keys.ENTER);


// to find any keyword on the webpage

driver.getPageSource().contains("Online Courses");



Thursday, 21 September 2023

What is what - temp

Volume  -   a volume is a persistent storage location that exists outside of the container. Volumes are useful for storing data that needs to persist even if the container is stopped or removed. In a Dockerfile, the VOLUME instruction is used to specify a mount point for a volume within the container.


Bind Mount  -   a file or directory on the host machine is mounted into a container. The file or directory is referenced by its absolute path on the host machine.


Swarm / Kubernetes / Apache Mesos   - is a group of machines that are running dockers and joined into a cluster

Saturday, 26 August 2023

OOPS

Class and Object: Spaciman blank form is class and filled form by taking its photocopy   by multiple students is  object 















Inheritance: You can use your mobile and your father's mobile also but your father can not use your mobile. 



Method OverRiding:  Parent and Child class having the function with the same name. 

Parent Child relationship + Riding






Method OverLoading : 

Example 1 : You and your son are going to start dinner. You asked for spoon. knowing that you want to serve rice  from kadhai to plate son will give you a big spoon. if you are going to start eating from your plate he will give you small spoon.  



Example 2 : In the same class there are draw( a,b) , draw(a,b,c) , draw( a,b,c,d) . First funcion will draw a line, second will draw a triangle and the third will draw a rectangle.  


static block: is like a bulb inside the fridge which gets switch on automatically just before you open the fridge door. When the class is loaded static block gets executed at first 


Encapsulation:   public setter and getter methods  and private variables  in one capsule



Constructor: Whenever the doorbell rings, the door gets opened by someone. Whenever an object is created constructor gets executed









Monday, 21 August 2023

BDD - Cucumber

video -151 webservice testing 

* Always use latest dependency  and the same version of both dependencies

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>7.13.0</version>
</dependency>
<dependency>
   <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.13.0</version>
</dependency>
<dependency>
    <groupId>tech.grasshopper</groupId>
    <artifactId>extentreports-cucumber7-adapter</artifactId>
    <version>1.14.0</version>
</dependency>

* eclipse >> marketplace >> Search and install  "Cucumber Eclipse Plugin"





Saturday, 19 August 2023

SQL

SQL Data Manipulation Language (DML)

SELECT - extracts data from a database table 
UPDATE - updates data in a database table 
DELETE - deletes data from a database table 
INSERT INTO - inserts new data into a database table 


SQL Data Definition Language (DDL)
CREATE TABLE - creates a new database table 
ALTER TABLE - alters (changes) a database table 
DROP TABLE - deletes a database table 
CREATE INDEX - creates an index (search key) 
DROP INDEX - deletes an index


Syntax for a SELECT statement covering all the options:
SELECT select_list
INTO new_table
FROM table_source
WHERE search_condition
GROUP BY group_by_expression
HAVING search_condition
ORDER BY order_expression [ASC | DESC]


SQL NOTES: 
1 use <databasename>
2 select top 10   * from <tablename>
3 select top 15 <column1>, <column2> from <tablename >
4 select distinct < column1> from <tablename>
5 select * from <employee> where <city> = ' Delhi ' AND zip like  123001          ==> single quote for text , not for numric values  
6 select * from employees where city = 'London' AND extension like  '432%'
7 insert into <tablename> (column1, column3) values ( value1, value3)
8 update <tablename> set <column1> = new_value where <column2> =any value
9 delete * from <tablename> 
10 delete * from <tablename> where <column1> = any value
11 select orderID,employeeID,customerID from orders where customerName > 'g'  order by employeeID desc
12 select count (*)from employee
13 SELECT @@version
14 sp_columns @table_name=<tablename>
15 sp_pkeys @table_name=<tablename>
16 DROP TABLE <tablename>
17 delete from rakeshtest where age=45 OR age =65
18 select * from pubs.dbo.publishers
19 use pubs; select * from titles ==> two statements in one line
20 SELECT * FROM Persons WHERE (FirstName='Tove' OR FirstName='Stephen') AND LastName='Svendson'
21 select * from publishers where country IN ('Germany', 'France')
22 select * from publishers where pub_id NOT BETWEEN  1 and   1389
23 select pub_id as abcd,  city as cccc from publishers
24 create database <database_name>
25 CREATE TABLE Person
(
FirstName varchar(30),
DateOfJoin (yyyymmdd),
Address varchar,
Age int(3)
)

26 select empname, count (empname) from employee group by empname having count(empname)>1
27 select * into <newtable_name> from <oldtable_name>
28 select column1, column3  into #temp2 from <tablename>
29    sp_helptext <vw_view_Name> 
30 select avg(fieldname) from tablename    ==> Returns the arithmetic average of the fields.
31 select count(*) from tablename    where fieldname=condition ;  ==> Returns the number of records that match the condition. select max(fieldname) from tablename ==> Returns the largest value of fieldname. 
32 select min(fieldname) from tablename  ==>  Returns the smallest value of fieldname.
33 select sum(fieldname) from tablename  ==> Returns the summation value of fieldname.
34 select convert(newdatatype, fieldname) from tablename   ==> converts one datatype into another.



--SQL TOOLs:
--Find a column in database
SELECT so.id, so.name as [Table Name], sc.name as [Column Name]
FROM sysObjects so inner join sysColumns sc
ON so.id=sc.id
WHERE sc.name like '%Column_Name_to_search%'
---------------------------------------------------------------------------
--view database schema
SELECT  SO.NAME as [Table Name], SC.NAME as [Column Name], ST.NAME as [Data Type], ST.PREC as [Data Length], ST.SCALE
FROM  SYSOBJECTS SO INNER JOIN SYSCOLUMNS SC ON SO.ID = SC.ID
INNER JOIN SYSTYPES ST ON SC.XTYPE = ST.XTYPE
WHERE SO.XTYPE IN ('U')
---------------------------------------------------------------------------
--view all table name  of database
select name as [Table Name] from sysobjects where xtype='u'
---------------------------------------------------------------------------
Two files in SQL are required to copy the table structure and data - databasename.mdf, databasename.ldf
---------------------------------------------------------------------------
Querying the SQL Server System Catalog FAQ
http://msdn2.microsoft.com/en-us/library/ms345522.aspx#_FAQ31

---------------------------------------------------------------------------
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMN 
WHERE COLUMN_NAME like 'TaxId";
---------------------------------------------------------------------------
SELECT COLUMN_NAME, DATA_TYPE,  CHaRACTER_MAXIMUM_LENGHT 
FROM INFORMATION.COLUMNS 
WHERE TABLE_NAME ="Nick_account_NAME" ;

---------------------------------------- Joins  -----------------------------------



SELECT <table1>.<column1> , <table1>.<column2> , <table2>.<column1>, <table2>.<column2> 
FROM  <table1> INNER JOIN / LEFT OUTER JOIN / RIGHT OUTER JOIN / FULL OUTER JOIN <table2>
ON <table1>.<Common_column1> =<table2>.<Common_column1> 

---------------------------------------------------------------------------

Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
List all employees, and their orders - if any.
SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
List all orders, and who has ordered - if any.
SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
Who ordered a printer?
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'

---------------------------------------------------------------------------

---Two inner joins
SELECT table1.column1, table2.column2, table3.column3
FFROM table1 inner join table2 
ON table1.column1=table2.column2 inner join table3.column3 
ON table2.column2=table3.column3
---where condition is optional if required 
WHERE table1.column1=X and table3.column3=Y
GROUP BY  table1.column1
---------------------------------------------------------------------------

A CROSS JOIN produces a cartesian product between the two tables, returning all possible combinations of all rows. It has no ON clause because you're just joining everything to everything.

A FULL OUTER JOIN is a combination of a LEFT OUTER and RIGHT OUTER JOIN. It returns all rows in both tables that match the query's WHERE clause, and in cases where the ON condition cannot be satisfied for those rows it puts NULL values for the unpopulated fields.
---------------------------------------------------------------------------


---------------------------------------------------------------------------


---------------------------------------------------------------------------
Steps to see the schema of a table :
query analyzer-->select SQL server name on the network --> select sql server authontication --->login name and password-->ok--> select database ( if required )--> type command in right side white panel -->sp_help tblCNTCountry --> press F5

---------------------------------------------------------------------------

Copy table structure:
enterprise manager-->source database (medical web site )-->table--> tblAdminCountry -->right click-->all task--> generate SQL script -->  ok -->save (1.sql)
Paste table structure
SQL query analizer--->select SQL server name on the network --> select sql server authontication --->login name and password-->ok--> open-->browse-->select (1.sql)-->select destination database  --->Press F5
table structure is copied
---------------------------------------------------------------------------

--To search all columns of all tables in Pubs database for the keyword: "Computer"
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @DataType nvarchar(128)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
IF ISNUMERIC(@SearchStr) = 1
BEGIN
DECLARE @SearchStr3 DECIMAL(26, 8)
SET @SearchStr3 = CAST(@SearchStr AS DECIMAL(26, 8))
END
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @DataType = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND
TABLE_NAME = PARSENAME(@TableName, 1) AND
DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int','decimal','numeric','tinyint','bigint','float') AND
QUOTENAME(COLUMN_NAME) > @ColumnName
)
SET @DataType =
(
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND
TABLE_NAME = PARSENAME(@TableName, 1) AND
QUOTENAME(COLUMN_NAME) = @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
IF (@DataType = 'char' OR  @DataType = 'varchar' OR @DataType = 'nchar' OR @DataType = 'nvarchar')
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
IF ISNUMERIC(@SearchStr) = 1 AND (@DataType ='int'  OR @DataType = 'decimal' OR @DataType = 'numeric' OR @DataType = 'tinyint' OR @DataType = 'bigint' OR @DataType = 'float')
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' = ' + @SearchStr3
)
END
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
 END

Run this SP in below manner in query analyzer
SearchAllTables  Computer
---------------------------------------------------------------------------


Create Trigger :
CREATE TRIGGER raviTrigger
ON emp_table_name
for insert
As
begin
insert into emp (Id, Name, age) values ( 4,444,30) 
end
---------------------------------------------------------------------------


---------------------------------------------------------------------------


---------------------------------------------------------------------------


---------------------------------------------------------------------------

---------------------------------------------------------------------------

---------------------------------------------------------------------------

---------------------------------------------------------------------------

Wednesday, 9 August 2023

JDBC Connection for mysql

package jdbc;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;


public class JDBCConnection2

{

public static void main(String[] args) throws SQLException, ClassNotFoundException

{

// Maven dependency "mysql-connector-java" can also be used instead of below line

// Load the MySQL JDBC driver

Class.forName("com.sql.cj.jdbc.Driver");


// Connect to the MySQL database

String url = "jdbc:mysql://localhost:3306/mydatabase";

String username = "root";

String password = "root";

Connection connection = DriverManager.getConnection(url, username, password);


// Create a statement

Statement statement = connection.createStatement();


// Execute a query

ResultSet resultSet = statement.executeQuery("SELECT * FROM users");


// Process the results

while (resultSet.next())

{

System.out.println(resultSet.getString("username"));

}


// Close the connection

connection.close();

}

}

Monday, 7 August 2023

Selenium grid on local and AWS Docker

video reference: https://www.youtube.com/watch?v=_lBaedX4UAE

Mukesh otwani playlist : https://www.youtube.com/playlist?list=PL6flErFppaj1quyeiIF8Rz7nlBPOZTk6d 


docker install on windows  - on ubuntu :

Turn Windows Feature on and off: select 

1. virtual machine plateform

2. Windows subsystem for linux 

3. Restart the system


download and install  : WSL2 Linux kernel update package for x64 machines

Powershell > wsl -l -o

Powershell > wsl --install -d  Ubuntu-22.04

Powershell > sudo apt update

Powershell > sudo apt install docker.io

Powershell > docker   --version

Powershell > docker-compose   --version


$ sudo apt-get remove docker docker-engine docker.io    ==> remove existing docker installed if any 

$ sudo apt-get update             ==> update Linux

$ sudo apt install docker.io    ==> docker installation command 

$ sudo snap install docker      ==> other decker dependencies also needed 

$ docker --version                  ==> check the installed docker version

$ sudo docker run hello-world   ==> install hello-world docker image

$ sudo docker images ==> Show docker images list in local 

$ sudo docker ps -a         ==> to show both the stopped and running docker containers

$ sudo docker ps         ==> process status

$ sudo docker pull selenium/hub   -d                 ==> download the docker image

$ sudo docker pull selenium/node-chrome-debug     ==> download the latest docker image 

$ sudo docker pull selenium/node-firefox-debug    ==> download the latest docker image 

$ sudo docker images             ==> show docker images list in local 


****** run docker images on Windows Subsystem for Linux  - STANDALONE SETUP:  ******

reference Link : https://github.com/SeleniumHQ/docker-selenium#quick-start

Note: Only one Standalone container can run on port 4444 at the same time.

docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome :4.12.1-20230920

docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-firefox:4.12.1-20230920

docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-edge:4.12.1-20230920


Execute below code from local eclipse : works fine 

ChromeOptions co = new ChromeOptions();

WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/"),co);


$sudo docker stop <Container_ID>

$sudo docker rm   <Container_ID>

  

**************************Docker Compose Commands **************************

 sudo apt-get install docker-compose-plugin     ==> install docker-compose

$ docker-compose  --version

$  mkdir DockerComposeFile   ==> create folder

$  nano docker-compose.yml   ==> create docker-compose file 

$ docker-compose config      ==> check error in docker-compose.yml file

$  docker-compose up -d      ==>  run docmer.compose.yml file 

$  docker-compose down       ==>  bring everything down run by docker compose

$  docker-compose   --help      ==>  get help 

$  docker-compose up -d   --scale mysql=4       ==>  created 4 instances of sql (any service) 



***************************  Hub - Node in docker ******************************

$ docker network create grid

$ docker run -d -p 4442-4444:4442-4444 --net grid --name selenium-hub selenium/hub:4.12.1-20230920

$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub \

    --shm-size="2g" \

    -e SE_EVENT_BUS_PUBLISH_PORT=4442 \

    -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 \

    selenium/node-chrome:4.12.1-20230920

$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub \

    --shm-size="2g" \

    -e SE_EVENT_BUS_PUBLISH_PORT=4442 \

    -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 \

    selenium/node-edge:4.12.1-20230920

$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub \

    --shm-size="2g" \

    -e SE_EVENT_BUS_PUBLISH_PORT=4442 \

    -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 \

    selenium/node-firefox:4.12.1-20230920


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



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

$ sudo docker run -d -p 4567:4444 --name selenium-hub selenium/hub

check if hub is running :  http://localhost:4546  ==> hub should be running

$ sudo docker run -d -p <hostPort>:<containerPort> --link selenium-hub:hub selenium/node-chrome-debug

$ sudo docker run -d -p  --link selenium-hub:hub selenium/node-chrome-debug

$ sudo docker run -d -p  --link selenium-hub:hub selenium/node-firefox-debug

$ sudo docker run -d -p 4444:4444 --name selenium-hub selenium/hub

$ sudo docker run -d -p <hostPort>:<containerPort> --link selenium-hub:hub selenium/node-chrome-debug

$ sudo docker run -d    --link selenium-hub:hub selenium/node-firefox-debug

***************************SETUP  DOCKER ON FRESH  AWS   ********************

* windows machine on cloud is same as our windows laptop

* AWS  contains remote machines >> remote machine  contains docker  >> docker contains Containers of chrome, firefox and edge browsers  


CREATE AWS ACCOUNT:

https://signin.aws.amazon.com/  >> root user email / pass>> personal >> credit card info >> account created

Search VPC ( virtual privat cloud ) >>  your vpc  >>  on Top right side ACTION >> create default VPC >> 

Top left SERVICES >> EC2 >> EC2 DashBoard  >>  top right Launch Instance >>  Select "Free Tier eligible" AmazonLinux 2 AMI (HVM) image >> select "Free tier eligible " >> Configure instance details (keep as it is)

 >> next : Add Storage >> next : add Tags >>  next: Configure security group >>  Review and Launch >> Launch >> create a new key pair >> select RSA radio button  >> enter any keypair name "myLinuxMachine" >>  download keypair  >> Launch Instance  >>  view Instance >>   wait  for Instance state "Running" >>  click "Instance ID" Link >>  copy public IPv4 >> Security >> Security Group >>  launch wizard link  >> Edit Inbound Rule >>  Add Rule Custome TCP  >> Port Range 4444 >> Source = anywhere >>  save rules >> Instance from left navigation >> Instance Id link  >> Connect  >> 

for linux { SSH clinet} >> open location of downloaded keypair in cmd >> c:\downloads >  ssh -i "myLinuxMachine" ec2-user@99.111.22.33 , here 99.111.22.33 is your public ipv4  >> YES >> you are connected to amazon linux machine . 


$sudo su    ==> login as root user

# yum update -y   ==> package manager to install everything 


# yum install java-1.8.0-openjdk -y    ==> Install java 

# yum remove java  -y  ==> to remove java 


# yu install maven  ==> install maven 

# mvn --version ==> check installed maven version


# yum install docker ==> to install docker

# docker --version

# systemct1 start docker  ==> start docker

# systemct1 enable docker  ==> enable docker

# systemct1 restart docker  ==> restart docker

# docker ps  ==> tells how many docker containers are running "Process Status"

# docker stop <containerid> ==> stops the particular container

# docker rm <Container id>  ==> removes the particular docker container, However, image will still be there to create a container from that image

# docker images ==> shows the docker images available 

# docker run -d -p 4444:4444 -p 7900:7900 --shm-size="2g" selenium/standalone-firefox:4.11.0-20230801      ==> run a docker container with firefox  from image, if not available downloads image also


# docker run -d -p 4444:4444              --shm-size="2g" selenium/standalone-firefox:4.11.0-20230801

# docker run -d -p 4444:4444   --shm-size="2g" selenium/standalone-chrome:4.11.0-20230801

# docker run -d -p 4444:4444   --shm-size="2g" selenium/standalone-edge:4.11.0-20230801


open browser >> yourpublic ipv4 : 4444   in this case  99.111.22.33:4444 



Play with docker without installing it : https://labs.play-with-docker.com/

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

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

Raghav docker playlist : https://www.youtube.com/watch?v=wi-MGFhrad0&list=PLhW3qG5bs-L99pQsZ74f-LC-tOEsBp2rK&index=1


dockerFile --> developers requirements  ( like recipe with all ingredients  and steps to make a dish)

docker images --> application + requirements + dependencies  . these images can be pulled in any env to create docker container   

Docker container --> This is run time instance of docker images 

Docker Hub  --> online repository where docker images are stored. 

virtualization --> virtual box  ( resource allocation is fized and does not change as per application needs containerization --> docker  ( lightweight alternatives to vm)

Docker has client-server architecture 

Deamon (server) received the command from the docker client through  cli or REST APIs

Docker client and deamon can be present on the same host machine or differtent hosts 

Docker Engine  = client ( CLI) + Server ( Docker Deamon +Container1+ container2 + container3) 

Play with docker without installing it : https://labs.play-with-docker.com/

docker manual : http://docs.docker.oeynet.com/engine/installation/

docker installation commands on ubuntu:   http://docs.docker.com/engine/install/ubuntu/

$ sudo apt-get update

$ sudo apt-get install \

    apt-transport-https \

    ca-certificates \

    curl \

    gnupg-agent \

    software-properties-common

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

$ sudo apt-key fingerprint 0EBFCD88

$ sudo add-apt-repository \

   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \

   $(lsb_release -cs) \

   stable"

 $ sudo apt-get update

 $ sudo apt-get install docker-ce docker-ce-cli containerd.io

$ sudo docker -v

$ sudo docker run hello-world

$ sudo docker images

$ sudo docker ps -a

$ sudo docker run hello-world


Containers : are running instances fo  Docker images.  a container image is a lightweight , standalone , executable package  of a piece of software that includes everything needed to run it .  code, runtime, system  tools, system lybraries, settings. 

It uses less resources, booting of containers is very fast , can start , stop kill remove containers easily and quickly , OS resources can be shared within docker,  Containers run on the same machinee sharing the same os kernel . this makes it faster 

what are images : Docker images are templates used to create docker containers . Container is a running instance of image. 

Where images are stored : Docker hub , locally , remote

Dockers can build images automatically by reading the instructions from a dockerfile. 

A single image can be used to create multiple containers 

Docker Compose : tool for defining and runnig multi-container docker applications

use yaml files to comfigure application services

can start all services with a single command 

docker volumes: By default all files created inside a container are stored on ta writeble container layer 

the data does not persist when that container is no longer running 

A containers writable layer is tightly coupled to the host  machine where the container is running. you can not easliy move the data somewhere else 

docker has two optons for containers to store files in the host machine so that the files are persisteed even after the containers stops. 

volumes are stored na part of host flesystems which is managed by docker 

Non docker processes should not modify this part of the filesystem 

Bind mount may be stored anywhere on the host system 

Non docker processes on the docker host or an docker container can modify then at any time 

Bind mounts the file or directory is referenced by its full path on the host machine. 

volumes are the best way to persist data in Docker 

volumes are managed by Docker and are solated from the core functionality of the host machine. 

A given volume can be mounted into multiple containers simultaniously . 

When no running container is useing a volume  the volume is still available to docker and s not removed automatcally. yo can remove unused volumes using docker volume prune . 

When you mount a volume it may be name dor anonymus. 

Anonymus volumes are not given an explicit name when they  are first mounteed into a container.

Volumes also support the use of volume dreivers which allows you to store your data on remote hosts or cloud providers among other possblties. 

docker commands help :   https://get.docker.com/

installation steps for Amazon EC2 : https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html

Basic :

sudo docker version 

sudo docker -v

sudo docker --version

sudo docker info

sudo docker --help 

sudo docker login

sudo export PS1="\u$"   this is to shorten the command line name 


Images :

sudo docker images --help          to get help

sudo docker images                    to view the images

sudo docker images -a                to view the images

sudo docker images -q                to get the images id

sudo docker pull ubuntu          //   to pull images from Docker Hub site // sudo docker run ubuntu   is better command 

sudo docker pull image

sudo docker images -f "dangling=false"  show images which are NOT associated with container

sudo docker images -f "dangling=false" -q shows only imagesID  NOT associated with container

sudo docker images -f "dangling=true"  show images associated with container

 

sudo docker rmi --help

sudo docker run image

sudo docker rmi  image

sudo docker rmi  -f image

sudo docker rmi  imageIDxxx   to remove docker image


Containers:

sudo docker ps --help

sudo docker run ubuntu

sudo docker ps -a shows the list of container running from the image

sudo docker run ubuntu    if image is not available locally , it will be downloaded and run

sudo docker run -it ubuntu bash  start the shell 

sudo docker start    containerID/Name      to start containers, you can not attach stopped container, start it first

sudo docker attach containerID/Name      to attach  containers

sudo docker kill containerID/Name

sudo docker stop  containerID/Name       to stop containers

sudo docker run -it ubuntu    go inside ubuntu

sudo docker inspect ubuntu

sudo docker rm containerID                     to remove the container

sudo docker history imageName

sudo docker pause MyUbuntuName

sudo docker unpause MyUbuntuName

sudo docker top MyUbuntuName     to see the top process of that containers

sudo docker stats MyUbuntuName

sudo docker container create           to create container in stopped state

sudo exit     move back to our system 


System :

docker system df     to check disk usage of docker

docker system prune --help   CAUTION : use with very carefully


jenkns:

sudo docker pull jenkins      //   to pull images from Docker Hub site 

sudo docker run -p 8080:8080 -p 50000:50000 jenkins      //   to jenkins on docker container

sudo docker run --name  myjenkins1 -v myvolume1:/var/jenkins_home -p 8080:8080 -p 50000:50000 jenkins      //   to jenkins on docker container

sudo docker run --name myjenkins1 -p 8080:8080 -p 50000:50000  -v /users/ravinder/desktop/jenkins_home :/var/jenkins_home jenkins        

sudo docker volume create 

sudo docker volume ls              // to see the docker volumes list

sudo docker volume inspect myjenkins1   // to get the mountpoint


creating docker file :

mkdir dockerfiles

cd dockerfiles


cat > dockerfile

vi dockerfile    

FROM

RUN

CMD // enter the file contant in it

https://github.com/wsargent/docker-cheat-sheet#dockerfile


sudo docker build -t myimage1:1.0 .         // enter dot if you in the same directory where the docker file is present

sudo docker run imageID


Dockerfile : A text file ith instructions to build image automation of docker mage creation

step1 : create a fle named Dockerfile

step2 : Add instructions in Dockerfile

step3 : Build dockerfile to create image

step4 : Run image to create container 


Docker Compose : tool  for defining and running multi container docker applications

sudo docker-compose -v   // to check the version of dockercompose

sudo docker-compose version

sudo docker-compose --version


sudo curl -L https://github.com/docker/compose/releases/download/1.25.4/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose


sudo chmod +x /usr/local/bin/docker-compose 


// to install composes

$pip install -u docker-compose    // method 2  - to install composes 


Create Services: 

mkdir DockerComposeFile

cd DockerComposeFile

touch docker-compose.yml

vi docker-compose.yml // edit the file and enter below details in the file 

version: '3'

services: 


 web:

     image: nginx

     ports:

     - 9090:80/tcp

 database: 


  image: redis  // copy the above code in file as it is with line space and spaces


docker-compose config   // to check the validity of  below file 


sudo docker-compose  up  // can start all services with a single command

sudo docker-compose  up  -d // to run the yml file in detached mode


localhost:9090   // to check if nginx is running or not 


sudo docker-compose  --help // to get help

sudo docker-compose -up -d -- scale database =4    // creates 4 db instances . can scale up selected services when required

sudo docker-compose down   // to stop all services with a single command 


docker Volumes: mechanism for persisting data generated by and used by docker containers

sudo docker volume --help

sudo docker volume create myvolume1  // create volume

sudo docker volume ls  // list of volumes


sudo docker volume  inspect myvolume1 

sudo docker volume 



pending practical : sharing the same volume by two containers

Bind mount : to store data at physical location instead of volume

sudo docker run --name  myjenkins3 -v  /users/ravinder/desktop/jenkins_home:/var/jenkins_home -p 9191:8080 -p 40000:50000 jenkins     


Docker Swarm : is a group of machines that are running dockers and joined into a cluster

sudo docker-machine --help   // help 

sudo docker-machine create --driver virtualbox manager1     // to create manager1

sudo docker-machine create --driver virtualbox worker1       // to create worker1

sudo docker-machine create --driver virtualbox worker2       // to create worker2

sudo docker-machine ls                                                          // to see the created manager and worker

Sudo Brew cask install virtualbox    // to 

sudo apt install linuxbrew-wrapper    // install brue if not already installed 

sudo docker-machine ls  

sudo docker-machine ip machine1   // shows ip address of machine


sudo docker-machine ssh manager1     // connect to manager1 account

sudo docker-machine ssh worker1       // connect to worker1   account

sudo docker-machine ssh worker2       // connect to worker2    account


sudo docker-machine ip manager1       // get the ip address of manager

sudo docker swarm init -- advertise-addr  ipAddressOfManager1        // initilize docker swarm and assigns manager1  as manager role


sudo docker node ls     // tells manager1 is now assigned as manager role. this command will not work on worker node


sudo docker swarm    // shows all the commands

sudo docker swarm join-token worker1     // for manager to join the worker1


sudo docker swarm join-token manager1  // for worker1 to join the manager1


sudo docker info      // get details from manager1 account


   // create replica


sudo docker service ls   // check the status 


sudo docker service  ps web1  // 


sudo docker service scale web1=4  // scale service up and down


docker node inspect self


sudo docker node update --availability drain worker1Error: No such node: worker1 // shut down node


sudo docker swarm leave


Pending items: practical of all above commands and docker swarm 


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

DOCKER ON WINDOWS PRO :

download "Docker desktop" and install 

c:\ docker  ==> check if docker is installed or not

c:\ docker version ==> check the docker version


download VNC viewer from https://www.realvnc.com/en/connect/download/viewer/