Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, March 12, 2019

Run failed test cases in Java


Create a class that fails test case


 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 public class TestFailClass {  
      @Test(retryAnalyzer=MyRetry.class)  
      public void failMethod(){  
           System.out.println("FAILED CLASS");  
           Assert.assertTrue(false);  
      }  
 }  

Create a class that re-runs the failed test cases

 package testNG;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.testng.TestNG;  
 public class RunFailed {  
      public static void main(String[] args) {  
           TestNG testRunner = new TestNG();  
           List<String> failedXmls = new ArrayList<String>();  
           //Enter the full path for the 'test-faailed.xml' file  
           failedXmls.add("C:/Users/Mutturaj.h/workspace/hulagabal/test-output/testng-failed.xml");  
           testRunner.setTestSuites(failedXmls);  
           testRunner.run();  
      }  
 }  

Retry failed test cases TestNG in Java


Create test cases which fails

 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 public class TestFailClass {  
      @Test(retryAnalyzer=MyRetry.class)  
      public void failMethod(){  
           Assert.fail("Test failed");  
      }  
 }  

Create a retry class which implements IRetryAnalyzer interface like below which tries for 3 times

 package testNG;  
 import org.testng.IRetryAnalyzer;  
 import org.testng.ITestResult;  
 public class MyRetry implements IRetryAnalyzer {  
      private int retryCount = 0;  
      private static final int maxRetryCount = 3;  
      public boolean retry(ITestResult result) {  
           if (retryCount < maxRetryCount) {  
                retryCount++;  
                return true;  
           }  
           return false;  
      }  
 }  

Friday, March 8, 2019

Select an Item from the drop-down in selenium webdriver

 package learning;  
 import java.util.concurrent.TimeUnit;  
 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 Dropdown {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://html.com/attributes/select-size/?utm_source=network%20recirc&utm_medium=Bibblio");  
           //Select dropdown by Select class  
           Select select = new Select(driver.findElement(By.xpath("//select")));  
           //select required item from the above dropdown  
           select.selectByValue("Lesser");  
      }  
 }  

Handling Alert in selenium

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class AlertPopup {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:\\Users\\Mutturaj\\Downloads\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.manage().window().maximize();  
           driver.manage().deleteAllCookies();  
           driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);  
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
           driver.get("https://mail.rediff.com/cgi-bin/login.cgi");  
           driver.findElement(By.name("proceed")).click();  
           Alert alert = driver.switchTo().alert();  
           System.out.println(alert.getText());  
           alert.accept();  

           // other importent methods  
           /*  
            * alert.getText() alert.dismiss(); alert.sendKeys("text");  
            */  
      }  
 }  

Monday, February 18, 2019

Retrieve data from excel , data provider and TestNG

 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
 import org.apache.poi.ss.usermodel.Row;  
 import org.apache.poi.ss.usermodel.Sheet;  
 import org.apache.poi.ss.usermodel.Workbook;  
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
 import org.testng.annotations.DataProvider;  
 public class PoiEx {  
      static Object[][] names = null;  
      static String filePath = "C:\\Users\\Mutturaj\\Desktop";  
      public static Object[][] readExcel(String filePath, String filename, String sheetName) throws IOException {  
           File file = new File(filePath + "\\" + filename);  
           FileInputStream fileInputStream = new FileInputStream(file);  
           Workbook workbook = null;  
           String fileextensionname = filename.substring(filename.indexOf("."));  
           if (fileextensionname.equals(".xlsx")) {  
                workbook = new XSSFWorkbook(fileInputStream);  
           } else if (fileextensionname.equals(".xls")) {  
                workbook = new HSSFWorkbook(fileInputStream);  
           }  
           // Get sheet by name  
           Sheet sheet = workbook.getSheet(sheetName);  
           // Count rows in the sheet  
           int rowCount = sheet.getLastRowNum();  
           int colCount = 2;  
           names = new Object[rowCount + 1][colCount];  
           for (int i = 0; i < rowCount + 1; i++) {  
                Row row = sheet.getRow(i);  
                int lastCellNumber = row.getLastCellNum();  
                for (int j = 0; j < lastCellNumber; j++) {  
                     names[i][j] = (row.getCell(j).getStringCellValue());  
                }  
           }  
           return names;  
      }  
      @DataProvider(name = "array")  
      public Object[][] nana() throws IOException {  
           Object[][] array = PoiEx.readExcel(filePath, "muttu.xlsx", "muttu");  
           return array;  
      }  
      
 }  



 import org.testng.annotations.AfterMethod;  
 import org.testng.annotations.AfterTest;  
 import org.testng.annotations.BeforeMethod;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.Test;  
 public class NGTest1 {  
      @BeforeTest()  
      public void loadFile() {  
           System.out.println("File open....");  
      }  
      @BeforeMethod  
      public void openBrowser() {  
           System.out.println("Browser opened************");  
      }  
      @AfterMethod  
      public void closeBrowser() {  
           System.out.println("**************Close browser");  
      }  
      @Test(priority = 1, dataProvider = "array", dataProviderClass = PoiEx.class)  
      public void add(String first, String second) {  
           System.out.println(first);  
           System.out.println(second);  
      }  
      @Test(priority = 2)  
      public void substract() {  
           System.out.println("Substraction");  
      }  
      @Test(priority = 3)  
      public void Multiply() {  
           System.out.println("Multiply");  
      }  
      @Test(priority = 4)  
      public void Divide() {  
           System.out.println("Divide");  
      }  
      @AfterTest  
      public void closeFile() {  
           System.out.println("File closed.....");  
      }  
 }  

Monday, February 11, 2019

Access Levels in Java



Modifier
Class
Package
Subclass
World
public
 Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
*no modifier is: Package private

Saturday, February 9, 2019

String Manipulations


 public class Str {  
  public static void main(String[] args) {  
  String s = "Mutturaj Hulagabal";  
  System.out.println(s.charAt(4));  
  System.out.println(s.length());  
  String trim = s.trim();  
  System.out.println(trim.length());  
  System.out.println(s.concat("Atharga"));  
  System.out.println(s.contains("Muttu"));  
  System.out.println(s.indexOf("H"));  
  System.out.println(s.compareTo("Naveen Patil"));  
  System.out.println(s.toUpperCase() + " " + s.toLowerCase());  
  System.out.println(s.compareTo("Mutturaj Hulagabal"));  
  System.out.println(s.compareToIgnoreCase("mutturaj hulagabal"));  
  System.out.println(s.isEmpty());  
  // Sub String  
  System.out.println(s.substring(9));  
  System.out.println(s.substring(0, 8));  
  // Object  
  System.out.println(s.equals("Mutturaj Hulagabal"));  
  }  
 }  


Sunday, March 25, 2018

[Android App Development] Re-load app after permission granted

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] 
permissions, @NonNull int[] grantResults) {
    Intent permiIntent=new Intent(this,MainActivity.class);
    finish();
    startActivity(permiIntent);
}


Tuesday, November 7, 2017

String class in Java

package MyPackage;

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.exec.util.StringUtils;



public class StringOperations
{

public static void main(String[] args) {
String mystring="Muttturaj Hulagabal";

char text=mystring.charAt(1);

System.out.println(text);

int count=mystring.length();

System.out.println(count);

String afterTrim=mystring.trim();
System.out.println("Lenght after Trim"+afterTrim.length());

String anotherString="Muttturaj Hulagabal";
System.out.println("0 means true here"+mystring.compareTo(anotherString));

System.out.println("In Bytes here: "+mystring.getBytes());


String suffix="bal";
System.out.println(mystring.endsWith(suffix));

//Substring is important here, it gets Sub string starting from 10th Index
System.out.println("Substring of my string: "+mystring.substring(10));

//Substring is importent here, it gets Sub string starting from 10th Index and ending from 19th Index
System.out.println(mystring.substring(10, 19));


System.out.println(mystring.subSequence(0, 18));

//Add other string to your string
String duplic=mystring.concat(anotherString);
System.out.println(duplic);

//And here we can use campare string with string variable by using == by using intern() Method
if(mystring==new String("Muttturaj Hulagabal").intern())
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}

//Converting number to string is importent here

int i = 10;
double d=10.00;


//toString() Method is used to convert to String
String s1=Integer.toString(i);
String s2=Double.toString(d);

System.out.println(s1);
System.out.println(s2);

System.out.println(mystring.toLowerCase());

System.out.println(mystring.toUpperCase());

//valueOf() Method is here which will convert defferent types value into String.
int value=10;

String s10=String.valueOf(value);

System.out.println(s10);

//split() is an importent method here in the String class

String string="12345-67890";
String[] parts=string.split("-");
String part1=parts[0];
String part2=parts[1];

System.out.println(part1);
System.out.println(part2);

//org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
String split[]=StringUtils.split(string, "-");

String split1=split[0];
System.out.println(split1);

String split2=split[1];
System.out.println(split2);

//Lets split by "-"

String stringtopart="12-123-1234-12345-123456";

String[] parttomany=stringtopart.split("-");
System.out.println(parttomany.length);

for(int k=0;k {
System.out.println(parttomany[k]);
}


//Lets split by using Array list Java 8

ArrayList stringlist = (ArrayList) Pattern.compile("-").splitAsStream("12-123-1234-12345").collect(Collectors.toList());
System.out.println(stringlist);
for(int l=0;l System.out.println(stringlist.get(l));


}

}


Monday, November 6, 2017

Writing to PDf file by using PDFBox Java

package MyPackage;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class PDFWrite
{

public static void main(String[] args) throws Exception
       {

PDDocument doc=new PDDocument();

PDPage page=new PDPage();
doc.addPage(page);

int numberOfPages=doc.getNumberOfPages();
System.out.println(numberOfPages);

float version=doc.getVersion();

System.out.println(version);

PDDocumentInformation info=new PDDocumentInformation();

String title="Mutturaj Hulagabal";

info.setTitle(title);

System.out.println(info.getTitle());

String author = "Mutturaj Hulagabal";

info.setAuthor(author);

System.out.println(info.getAuthor());

PDPageContentStream stream=new PDPageContentStream(doc, page);

stream.beginText();

stream.setFont(PDType1Font.TIMES_BOLD, 20);

stream.newLineAtOffset(25,750);

stream.showText("Mutturaj Hulagabal");

stream.endText();

stream.close();

doc.save(filepath);

doc.close();

}

}

Sunday, November 5, 2017

Write to Excel(.XLSX) using Java Apachi POI

package MyPackage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteX {

public void writeX() throws Exception
{

File f=new File("C:/Users/Mutturaj.h/Desktop/Me.xlsx");

FileInputStream fis=new FileInputStream(f);

XSSFWorkbook wb=new XSSFWorkbook(fis);

XSSFSheet sheet=wb.getSheet("Muttu2");

XSSFRow row=sheet.createRow(6);

XSSFCell cell=row.createCell(6);

cell.setCellValue("Muttu");

FileOutputStream fos=new FileOutputStream(f);

wb.write(fos);

public static void main(String[] args) throws Exception
{

WriteX x=new WriteX();
x.writeX();

}

}