Current date and time in java

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeFormatter {

public static void main(String[] args) {
//I used SimpleDateFormat class for date and time format
SimpleDateFormat formatter = new SimpleDateFormat(“dd/MM/yyyy HH:mm:ss”);
//Here formatter is the reference object to class SimpleDateFormat
//I am using Date class to fetch the current date and time from server.
Date date = new Date();
//Here date is the reference object to class Date
System.out.println(formatter.format(date));
}
}

JavaScriptExecuter

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import net.slideshare.test.SlideShareTestCase;

public class Helper {
public static WebDriver launchBrowser(String browserName) {
WebDriver driver = null;
if (browserName.equalsIgnoreCase(“ie”)) {
driver = new InternetExplorerDriver();
} else if (browserName.equalsIgnoreCase(“chrome”)) {
Capabilities cap = DesiredCapabilities.chrome();
driver = new ChromeDriver(cap);
} else if (browserName.equalsIgnoreCase(“ff”)) {
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}

public static String linkValidation(String hyperLinkUrl) {
String result = “”;
try {
URL url = new URL(hyperLinkUrl);

HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.setConnectTimeout(5000);
openConnection.connect();

if (HttpURLConnection.HTTP_OK == openConnection.getResponseCode()) {
result = hyperLinkUrl + ” : ” + openConnection.getResponseCode();
} else {
result = hyperLinkUrl + ” : ” + openConnection.getResponseMessage();
}
} catch (Exception e) {
result = “Exception caught: ” + e.getMessage();
}
return result;
}

static public void synchronization(WebElement element) {
WebDriverWait wait = SlideShareTestCase.wait;
for (int i = 0; i < 5; i++) {
try {
wait.until(ExpectedConditions.not(ExpectedConditions.stalenessOf(element)));
wait.until(ExpectedConditions.visibilityOf(element));
return;
} catch (Exception e) {
}
}
}

public static void captureScreenShort(WebDriver driver, String fileName) {
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File("./screenshot/" + fileName + new Date() + ".png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
// System.out.println("Screenshot is taken.");
}

public static void highlightElement(WebDriver driver, WebElement element) {

JavascriptExecutor js = ((JavascriptExecutor) driver);

js.executeScript("arguments[0]" + ".setAttribute('style','background-color: yellow; border: 2px solid red;')",
element);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
js.executeScript("arguments[0]" + ".setAttribute('style','border: 2px solid white;')", element);

}
}

Dynamic Dropdown selection

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class SpiceJet
{
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.chrome.driver”,”path”);
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get(“http://spicejet.com/&#8221;);
Thread.sleep(1000);
driver.findElement(By.id(“ctl00_mainContent_ddl_originStation1_CTXT”)) .click(); driver.findElement(By.cssSelector(“a[value=’GOI’]”)).click();
driver.findElement(By.xpath(“(//a[@value=’HYD’])[2]”)).click();
Select sel=new Select(driver.findElement(By.cssSelector(“#ctl00_mainContent_DropDownListCurrency”)));
sel.selectByValue(“USD”);
Thread.sleep(1000);
driver.findElement(By.cssSelector(“[name=’ctl00$mainContent$chk_friendsandfamily’]”)).click();
System.out.println(driver.findElement(By.cssSelector(“[name=’ctl00$mainContent$chk_friendsandfamily’]”)).isSelected());
driver.close();

}
}

Sibling xpath

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class XpathSiblingsParent
{
public static void main(String[] args) throws InterruptedException {
System.setProperty(“webdriver.chrome.driver”,”path”);
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get(“http://www.qaclickacademy.com/interview.php&#8221;);
driver.findElement(By.xpath(“//li[@id=’tablist1-tab1′]/following-sibling::li[3]”)).click();
Thread.sleep(1000);
driver.findElement(By.xpath(“//*[text()=’ Selenium ‘]”)).click();
driver.close();
}
}

Finding Broken Links

import java.net.URL;import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;
public class “class Name”
{
public static void main(String[] args) 
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http://www.google.co.in/&#8221;); List links=driver.findElements(By.tagName(“a”));
System.out.println(“Total links are “+links.size());
for(int i=0;i<links.size();i++)
{
WebElement ele= links.get(i);
String url=ele.getAttribute("href");
verifyLinkActive(url);
}
}
public static void verifyLinkActive(String linkUrl)
{       
try        
{           
URL url = new URL(linkUrl);                    
 HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();       httpURLConnect.setConnectTimeout(3000);                      httpURLConnect.connect();                      if(httpURLConnect.getResponseCode()==200)           {               System.out.println(linkUrl+" – "+httpURLConnect.getResponseMessage());                     if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)           {               
System.out.println(linkUrl+" – "+httpURLConnect.getResponseMessage() + " – "+ HttpURLConnection.HTTP_NOT_FOUND);         
  }       
}
catch (Exception e)
{                  
   
}
}

Getting Text of an element using contains in xpath

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class “Class Name”
{
public static void main(String[] args) throws InterruptedException
{
System.setProperty(“webdriver.chrome.driver”,”path”);
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.MILLISECONDS);
driver.get(“https://login.salesforce.com/&#8221;);
driver.findElement(By.cssSelector(“input[class=’input r4 wide mb16 mt8 username’]”)).sendKeys(“aaa”);
driver.findElement(By.cssSelector(“input[class=’input r4 wide mb16 mt8 password’]”)).sendKeys(“test”);
driver.findElement(By.cssSelector(“input[value=’Log In’]”)).click(); Thread.sleep(5000); String ele=driver.findElement(By.xpath(“//div[contains(text(),’Please check your username and password.’)]”)).getText();
System.out.println(ele); driver.close();
}
}

Java

Java:

Java is a programming language and a platform-independent language. Java is a high level, robust, secure and object-oriented programming language.

Types of Java Applications:

There are mainly 4 types of applications that can be created using java programming:

1) Standalone Application

It is also known as a desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications etc. It has the advantage of the high-level security, load balancing, and clustering. In java, EJB is used for creating enterprise applications.

4) Mobile Application

An application that is created for mobile devices. Currently, Android and Java ME are used for creating mobile applications.

Java Platforms:

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. and includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of Java SE platform and includes topics like Servlet, JSP, Web Services, EJB, JPA etc.

3) Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

4) JavaFx

It is used to develop rich internet applications. It uses light-weight user interface API.

Getting the drop down values in TestNG

package package_name;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
import org.openqa.selenium.support.ui.Select;

public class Class_name {
WebDriver driver;

@BeforeTest
public void setup() throws InterruptedException{
System.setProperty(“webdriver.chrome.driver”,”driver path/chromedriver.exe”);
driver = new ChromeDriver();
System.out.println(“Performing the action”);
driver.manage().window().maximize();
driver.get(“Site URL”);
driver.findElement(By.id(“login_email”)).sendKeys(“Username/Mail”);
driver.findElement(By.id(“login_password”)).sendKeys(“Password”);
driver.findElement(By.className(“login button”)).click();
Thread.sleep(1000);
Select dropdown = new Select(driver.findElement(By.className(“search_data[section_id]”)));
dropdown.selectByVisibleText(“video”);
Thread.sleep(10000);
}
@Test
public void preview() throws InterruptedException {
driver.findElement(By.id(“login_search”)).click();
Thread.sleep(6000);
}
@AfterTest
public void teardown() throws InterruptedException {
System.out.println(“Closing the driver”);
Thread.sleep(1000);
driver.close();
}
}

Drag and drop using TestNG framework

package package_name;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;

public class class_name {
WebDriver driver;
@BeforeTest
public void setup() throws InterruptedException{
System.setProperty(“webdriver.chrome.driver”, path of driver”/chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(“url”);
Thread.sleep(1000);
}
@Test
public void dragdrop() throws InterruptedException{
driver.findElement(By.id(“login_email”)).sendKeys(“Mail ID/Username”);
driver.findElement(By.id(“login_password”)).sendKeys(“Password”);
driver.findElement(By.xpath(“Submit button”)).click();
Thread.sleep(1000);
driver.findElement(By.xpath(“//img[@alt=’image alt tag’]”)).click();
WebElement dragElement=driver.findElement(By.xpath(“drag element”));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
WebElement dropElement=driver.findElement(By.xpath(“drop element”));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(dragElement)
.moveToElement(dropElement)
.release(dropElement)
.build();
dragAndDrop.perform();
System.out.println(“Drag and drop successful”);
}
@Test
public void preview() throws InterruptedException {
driver.findElement(By.xpath(“opening preview”)).click();
Thread.sleep(6000);
System.out.println(“Preview sucessfull”);
driver.findElement(By.xpath(“Closing preview”)).click();
}
@AfterTest
public void teardown() throws InterruptedException{
System.out.println(“Closing the driver”);
Thread.sleep(2000);
driver.close();
}
}

Getting the count from Search result

package package_name;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class class_name {
//The first letter of class name must be in Upper case
WebDriver driver;
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,” path of driver/chromedriver.exe”);
//Starting the driver
ChromeDriver driver = new ChromeDriver();
// Expanding the browser
driver.manage().window().maximize();
// Getting the URL
driver.get(“https://www.bing.com/ “);
// Enter search keyword
driver.findElement(By.id(“sb_form_q”)).sendKeys(“Dhoni”);
// Clicking on enter button
driver.findElement(By.xpath(“.//*[@id=’sb_form_go’]”)).click();
//Getting and storing the text in a variable
String aaa= driver.findElement(By.xpath(“.//*[@id=’b_tween’]/span[1]”)).getText();
//Displaying result
System.out.println(aaa);
//Closing the driver
driver.close();
}
}