Java code examples

import java.util.HashMap;

import java.util.Map;

public class PeopleAddressList { private Map<String, String> addressList; public PeopleAddressList() { addressList = new HashMap<>(); }

public void addPerson(String name, String address) { addressList.put(name, address); }

public String getAddress(String name) { return addressList.get(name); }

public void removePerson(String name) { addressList.remove(name); }

public int size() { return addressList.size(); }

public void clear() { addressList.clear(); }

public void printAddressList() { for (String name : addressList.keySet()) { System.out.println(name + ” : ” + addressList.get(name)); } }

public static void main(String[] args) { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”); list.printAddressList(); }}

//Main class as below

import java.util.HashMap;

import java.util.Map;

public class AddressSummary {

private PeopleAddressList addressList; public void setAddressList(PeopleAddressList addressList) { this.addressList = addressList; }

public String toString() { StringBuilder sb = new StringBuilder(); for (String name : addressList.keySet()) { sb.append(name + ” : ” + addressList.get(name) + “\n”); } return sb.toString(); }

public static void main(String[] args) { AddressGeneration generation = new AddressGeneration(); PeopleAddressList list = generation.getPeopleAddressList(); AddressSummary summary = new AddressSummary(); summary.setAddressList(list); System.out.println(summary); }}

public class AddressGeneration {

public PeopleAddressList getPeopleAddressList() { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”);

return list; }}

//Facade Design pattern

import java.util.HashMap;
import java.util.Map;

public class AddressSummaryFacade {

private AddressGeneration generation;
private AddressSummary summary;

public AddressSummaryFacade() {
    generation = new AddressGeneration();
    summary = new AddressSummary();
}

public String getAddressSummary() {
    summary.setAddressList(generation.getPeopleAddressList());
    return summary.toString();
}

}

public class Main {

public static void main(String[] args) {
    AddressSummaryFacade facade = new AddressSummaryFacade();
    System.out.println(facade.getAddressSummary());
}

}

tablesaw vs apachepoi

import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import tech.tablesaw.api.Table;import org.openjdk.jmh.annotations.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;@BenchmarkMode(Mode.Throughput)@Warmup(iterations = 3, time = 1)@Measurement(iterations = 5, time = 1)@State(Scope.Benchmark)public class ExcelReadBenchmark { private File excelFile; private Table tablesawTable; @Setup public void setup() { // Initialize your Excel file and Tablesaw table here excelFile = new File(“your-excel-file.xlsx”); // Replace with your Excel file path tablesawTable = Table.read().csv(“your-csv-file.csv”); // Replace with your CSV file path } @Benchmark public void readAndPrintWithTablesaw() { // Perform reading and printing using Tablesaw String column1 = tablesawTable.column(“Column1”).toString(); // Print or process column1 here } @Benchmark public void readAndPrintWithApachePOI() throws IOException { // Perform reading and printing using Apache POI FileInputStream inputStream = new FileInputStream(excelFile); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet for (Row row : sheet) { Cell cell = row.getCell(0); // Access the first cell (column 1) if (cell != null) { String cellValue = cell.toString(); // Print or process cellValue here } } workbook.close(); inputStream.close(); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); }}

read from 100 to 200

import tech.tablesaw.api.*;
import tech.tablesaw.io.csv.CsvReadOptions;

public class ReadCSVWithTablesaw {

public static void main(String[] args) {
    // Define the path to your CSV file
    String csvFilePath = "path/to/your/file.csv"; // Replace with your CSV file path

    // Define the range of rows you want to read (100 to 200)
    int startRow = 100;
    int endRow = 200;

    try {
        // Define read options
        CsvReadOptions options = CsvReadOptions.builder(csvFilePath)
                .header(true) // Assuming the CSV file has a header row
                .build();

        // Read the CSV file into a Table
        Table table = Table.read().csv(options);

        // Extract the desired rows (100 to 200) from column 1
        Column<String> column1 = table.column(1).subList(startRow, endRow + 1).asStringColumn();

        // Print or process the values in column1
        for (String value : column1) {
            System.out.println(value);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

How to setup kubernetes on windows WSL

How do I setup Kubernetes and run kubectl commands from windows machine

WSL(Windows subsystems linux) can be leveraged when you want to run kubectl commands from windows machine. Steps as below,

  1. Enable WSL with Kalilinux
  2. Install Windows Docker
  3. Create docker hub account and link account to Windows docker
  4. In Windows docker, go to settings
  5. Then enable Kubernetes
  6. Setup Persistent volume claim (pvc) by creating a yaml configuration for this.
  7. Run kubectl apply to yaml file
  8. When creating pods, or does kubectl deployment, make sure volume mounting done based on pvc
  9. Verify pod status by accessing commandline to docker containet directories

Selenide

Selenide is a wrapper jar to Selenium automation projects.

How to get Selenide jars – reference selenide.org

How does I disable webdriver manager api calls to github to avoid driver.exe pulls?

system property -Dselenide.driverManagerEnabled=false can avoid pulling driver exes and you could define driver binary path in selenium project configurations itself

Angular 12.1 new features

Angular 12.1 new features:

Improved CLI performanceng build defaults to prod, that avoids accident production deployment from development builds

New @use syntax points to new Saas API in Angular 12.1. Automatically happens when you do ng update on Angular 12.1

Angular components supports in line Saas in styles field in @component decorator

Strict mode can be enabled via CLI to catch errors early in development cycle

Webpack 5 module is Production ready

Unused methods will be removed to improve performance by DomAdaptor

Custom router outlet implementations are allowed

min max validators for forms are added

TypeScript 4.2 support has been added and dropped support for TypeScript 4.0 and 4.1

Deprecating support for IE11

Above some of the features, please go through official Angular docs for detailed info.

What is a proxy server?

What is a proxy server?

Proxy server is a server that acts like a middle-man between your computer and internet.

Why Proxy servers are used?

Main prupose is security by hiding your machine ip from internet.

Also tracking employee activity on various aite they access

What is VPN and why VPN is used?

Virtual private Network is used for data protection and building secure connection between your computer and internet.

VPN creates a virtual tunnel between your computer and internet or external server where you request info from.

Selenium tutorials

Selenium # Selenium Implicit and Explicit wait

//Implicit Wait
driver.manage()
.timeouts().implicitlyWait(10,
TimeUnit.SECONDS)
// Explicit wait
WebDriverWait wait = new
WebDriverWait(driver,
20);
wait.until(Expected
Conditions.textTo
BePresent
InElementLocated

Selenium # Selenium Keyboard and Mouse events
keyDown(); keyUp(); sendKeys();doubleClick();

Code Example:
Actions builder = new Actions(driver);
Action actions = builder
.moveToElement(“logintextbox”)
.click()
.keyDown(“logintextbox”, Keys.SHIFT)
.sendKeys(“logintextbox”, “hello”)
.keyUp(“logintextbox”, Keys.SHIFT)
.doubleClick(“logintextbox”)
.contextClick()
.build();
actions.perform() ;

What is Cucumber BDD for Selnium tests

Cucumber BDD (Behaviourdriven development):Cucumber is a testing toolused for Software testingwith behaviour drivendevelopment approach.Cucucmber BDD comes with feature file, whereacceptance, functional,regression tests are written in plain english called Gherkin language…Sample feature file inGherkin language is like below:

Feature: my app login test

Scenario: positve test on login

Given user enters correct credentials

Then user should be able to login

Scenario: login negative test

Given user enters wrong password

Then login is not allowed

in the above feature file,each line below to

Scenario, i. e Given, Then steps are mapped with java methods to perform selenium Automation tests

What is TestRunner in Cucumber:

TestRunner is a programused in Cucumber toaccess Feature fileTestRunner drives theselenium automationfeatures executionFeature file is somethingthat has user requirementscenarios written in Englishwhich gives more readabilityand understandability ofthe requirement which iscalled Gherkin language#shorts

Unit testing mocks, stubs

Mocks replaces external Interface. Mocks are not to check thereturn value but to verify function level call happened,called correctly etc.Stubs are replacement ofreturn value and is to test behavior of code.Stubs generates the pre defined output fakes to replace actual implemention like to replaceweb server with local httpserver or replace db serverwith fake in memory db to generate db response

TestNG Parameterization:

Approach 1: feed input parameters via TestNGand receive using@Parameters annotation at the target method

Approach 2: use Dataprovider when complex parameters like data from database, xls,property file, arraylist etc

What is Single slash ‘/’in Xpath in selenium:

Single slash ‘/’ is usedwhen absolute Xpathis considered for Elementidentification for SeleniumWebDriver

What is Double slash ‘//’in Xpath in selenium:

Double slash ‘//’ is usedwhen relative Xpathis considered for Element identification for SeleniumWebDriverRelative Xpath ‘//’is better Element identification strategy


What is Polymorphism:
Polymorphism is one
of the OOPs concepts
where many forms or
characteristics shown
by single  java  method

Different types of
Polymorphism are,

1. compile time/static
Polymorphism
2. Runtime/Dynamic
Polymorphism

1. Compile time/static
Polymorphism is
achieved by Method
overloading
2. Runtime/Dynamic
Polymorphism is
achieved by Method
overriding

Method overloading
is feature where
many methods having
same name but different
argument types
Method overriding is
a feature where child
class method override the
parent class method


#Interface:

Interface is like
class having variables
and methods but methods
are abstract by default.

abstract methods mean
no body/implementation

Any class can
implement Interface and
achieve abstraction and
multiple inheritance

#encapsulation#java#selenium#OOPS is binding of data or variableswith code/methodsas a sigle unit from classthis helps hiding datafrom other classes whendata is declared as private.and keeping methods/codeas public, other class canget data.

#shorts#Abstractclass#cpncreatclassAbstract class:a class declaredusing abstract keywordand has abstract methodsAbstract methodsdoes not haveimplementationor bodyConcreat class:Concreat class extendsAbstract class and implements the methodsfrom Super Abstract classConcreta class does notuse Abstract keywordSelenium classes:Selenium classesextends Concreatclass and instantiateConcreat class touse the implementedmethods from Concreat class


#selenium
#captcha
Selenium: Handling Captcha using Sikuli

Purpose of Captcha
is to avoid Automation.

However some level
of Captcha automation
can be done using Sikuli

Sikuli can capture
image captcha having
numbers or letters
as contents and store
as string values
to continue Automation

Sikuli is a library
that works based
on image recognition

Sikuli can read text from
image and that can be
used for some level of
captcha Automation

#shorts
#dybamicobjects
#selenium

Selenium:
Handling
dynamic
elements

Dynamic Objects
are those it’s id or
other properties
are changing
during page load
or other
user actions

How to handle
dynamic objects:

1. use XPath axes
methods :
use child, parent, sibling
elements to write Xpath

2. use dynamic Xpath
having “contains,
or starts with
or  ends with  etc

#shorts
What is SelectorsHub?

It is a Browser extension
helps to auto suggest
XPath or CSS Selector

How to setup SelectorsHub

1. download and install from
www.selectorshub.com
for browser type
chrome, opera, edge, firefox

2. after adding extention to
browser, it will appear
as browser toolbar item

3. after restarting
browser  inspect any
WebElement,
SelectorHub will be
displayed on Elements
tab on right

4. start typing XPath or
CSS Selector, you
would notice SelectorsHub
auto suggesting
Xpath or CSS Selector

Ref : www.selectorshub.com

#shortsSwitch to Frame:driver.switchTo().frame(“frame name/frame index”);Switch backfrom Frame:driver.switchTo().defaultContent();note: commandsare single line

#shorts
#selenium
#locators
Different
Selenium Locators :

By.id()
By.name()
By.tagName()
By.className()
By.xpath
By.cssSelector()
By.linkText()
By.partialLinkText()

#shorts
#selenium
#Exceptions
Different
WebDriver Exceptions :

   1.WebDriver
Exception
2.Timeout
Exception
         3. NoAlertPresent
Exception
        4. Nosuchwindow
Exception
         5. NoSuchElement
Exception

#shorts
#selenium
#css
#xpath
#seleniumlocator

XPath:
1. XPath(XML Path)
is used to find element
in HTML DOM
2. XPath is the locator
type used in Selenium
3. High success rate
in finding elemet
4. Xpath is slower in IE

CSS(Cascading Style
Sheet )
1. CSS Selector, a
selenium locator type,
used to find
elements using style
language
2. Faster in all
Browsers but may not
work on certain browser
elements

#shorts
1. W3C standard protocol
is used by Selenium 4
WebDriver to
communicate
to Browser, which makes
communication
standardised
and no API encoding
/decoding required

2. Logging and tracing are
improved for better
monitoring
3. Better documentation on
selenium features
4. enabled two url
opening on two browser
tabs

5. Relative Locators
like. toRightOf(),
above(), near()
6.Opera and
PhantomJs support
are removed

7. Optimized
SeleniumGrid
by fixing open issues

#shorts
for chrome:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

for Firefox:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new FirefoxDriver(caps);
// Pass the capabilities
as an argument to driver object

DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

#shorts// to retrieve the current URL of the webpagegetCurrentUrl() // to retrieve the current page source of the webpagegetPageSource() //to retrieve the text of the specified web elementgetText() //to retrieve the value specified in the attributegetAttribute() //to retrieve the current title of the webpagegetTitle()getCurrentUrl() getPageSource() getText()getAttribute() getTitle()

Driver will switch to specific
frame using
Name or ID or index
:::
driver.switchTo.frame
(“frameName value”)

or
driver.switchTo
.frame(“ID value”)

or
driver.switchTo.frame(0)

Fluent Wait in Selenium is used for defining the maximum time for the webdriver to wait for a condition, and also the frequency with which we want to check the condition before throwing Exception

Handle multiple Browser windows and tabs
getWindowHandle()

//to retrieve the handle of the current page

getWindowHandles() vs getWindowHandle()

driver.close(); // closes the current browser window
driver.quit(); //This method Closes all browser windows opened by the WebDriver

DevOps tool chain and important tools and frameworks

  1. Source code management:
    GitHub, BitBucket, GitLab
  2. Programming Languages:
    Java, Python,JavaScript,
    Typescript
  3. Build management tools:
    Gradle, Maven, Ant
  4. Configuration management:
    Ansible, Chef, Puppet,
    Salt Stack
  5. Container:
    Docker, LXC, RKT
  6. Container orchastrators:
    Kubernetes, Docker swarm,
    Openshift, NoMad
  7. Infrastructure Provisioning:
    Terraform, Azure template,
    AWS cloud formation,
    Google Deployment Manager
  8. Monitoring :
    DataDog, Grafana, Zabbix,
    Prometheus, Checkmk,
    New Relic
  9. Logging:
    Splunk, ELK, Graylog
  10. Clouds:
    Azure, AWS, GCP, OpenStack ,
    IBM Bluemix, Alicloud
  11. CI/CD:
    Jenkins, Travis CI, Circle CI
    TeamCity, AWS CodePipeline,
    Google Cloudbuild, Gitlab CI
    Bitbucket pipeline, Github action
  12. Web Server:
    Apache, Nginx, IIS,
    Jetty, Tomcat
  13. Caching Server:
    MemCache, Redis
  14. NoSQL Database:
    MongoDB, Cassandra,
    Google datastore,
    AWS Dynamo db
  15. SQL Database:
    Oracle, MySQL, MsSQL
    PstgreSQL

Kubernetes concepts, cluster, nodes, docker container, image, Dockerfile

Kubernetes concepts to remember:

1. Kubernetes Cluster: combination of large number of node machines

2. node machines:where Kubernetes software is installed and docker containers are hosted

3. docker container:each node machines contain large number of docker containers

4. docker image:Docker instructions are build and stored as image

5.Dockerfile:Docker instructions are written in markup language and stored in Dockerfile

Docker more info:

  1. Docker image can be run in terminal interactive mode while container started.
  2. While running in the terminal interactive mode, any program runtime, or filesystem can be added to the live container.
  3. A commit on container can create another fresh image.
    4.Fresh image from container can be tagged for easy use.
  4. Now the fresh image will have ubundu and the additional file system, runtime(like Java runtime) associated.

Git basic concepts to remeber

Git basic concepts
to remeber:

  1. working directory:
    this is local folder where
    coding is done using IDE
  2. staging area:
    git add command move
    code from working directory (1)
    to staging area
  3. local repository:
    git commit command will move
    code to local repo with a commit id
  4. remote repository :
    During git push code will get moved to remote repo that will be git/bitbucket

git fetch will move remote
repo commits to local repo

git merge moves code from local
repo to working directory

What is JUnit and what are the mostly used Annotations

JUnit is a unit testing library.

@Test – is an Annotation to mark test method in a class to act like test.

@TestFactory – Annotation for creating test method on run time, done by creating ranodmized tests or tests from external data

@DisplayName – to make reports readable with repoet name

@Disabled – to skip junit tests

@BeforeAll/@BeforeEach – lofe cycle mthods meant to run before tests

@AfterAll/@AfterEach – method to do clean up/tear down, meant execute after tests

#shorts#JUnit#Annotations