Monday, 17 August 2015

Create HTML, Error and Execution logs using log4j -Create more than 2 log files (Core JAVA)

It will create 3 files:

1. HtmlLogReport.html
2. Logfile.log
3. ErrorLog.log

Implement the logger as per your requirement.

Below is the code for log4j.property

# Define the root logger with appender file
log4j.rootLogger = INFO, FILE, rfile
 

# Define the file appender-Logfile.log
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.logfile.File=./TestLogs/Logfile.log

# Define the layout for file appender-Logfile.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.File=./TestLogs/Logfile.log
log4j.appender.FILE.layout.ConversionPattern=%d [%25F:%t:%L] - %m%n

# Define the layout for RollingFileAppender-HtmlLogReport.html
log4j.appender.rfile=org.apache.log4j.RollingFileAppender
log4j.appender.rfile.File=./TestLogs/HtmlLogReport.html
log4j.appender.rfile.MaxFileSize=1000MB
log4j.appender.rfile.Append=true
log4j.appender.rfile.layout=org.apache.log4j.HTMLLayout
log4j.appender.rfile.layout.Title=HTML Log Report
log4j.appender.rfile.layout.LocationInfo=true
# For Second Log File i.e ErrorLog.log
log4j.appender.errorLog=org.apache.log4j.FileAppender
log4j.appender.errorLog.File=./TestLogs/ErrorLog.log
log4j.appender.errorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.errorLog.layout.ConversionPattern=%d [%25F:%t:%L] - %m%n
log4j.logger.errorLog=TRACE,errorLog

JAVA program to implement above log4j.properties


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import reusable.Base;

public class google {
 static Logger log = Logger.getLogger(google.class);
 static Logger elog = Logger.getLogger("errorLog");
 WebDriver driver;
  
  @Test
  public void google1() {
    PropertyConfigurator.configure("src/main/resources/utilities/log4j.properties");
    log.info("Starting first test case");
    driver = Base.getDriver();
    driver.get("http://www.google.com/");
    elog.error("Test Case Fail");      
  }
}

Wednesday, 12 August 2015

Sending Email using gmail with Attachment and Text (Core JAVA)

If you want to use this function with testNG then use as below under AfterSuite annotation of TestNG:


//After complete execution send pdf report by email
    
    @AfterSuite
 
    public void tearDown(){
 
        sendPDFReportByGMail("FROM@gmail.com", "PASSWORD", "TO@zellax.com", "PDF Report", "");

 
        }

package reporting;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class PDEmail{
 
 public static void main(String[] args){
  sendPDFReportByGMail("FROM@gmail.com", "PASSWORD", "TO@zellax.com", "PDF Report", "");
 }
 
 public static void sendPDFReportByGMail(String from, String pass, String to, String subject, String body) {
   
  Properties props = System.getProperties();
   
  String host = "smtp.gmail.com";
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.user", from);
  props.put("mail.smtp.password", pass);
  props.put("mail.smtp.port", "587");
  props.put("mail.smtp.auth", "true");
  
  Session session = Session.getDefaultInstance(props);
  
  MimeMessage message = new MimeMessage(session);
  try {
      //Set from address
   
   message.setFrom(new InternetAddress(from));
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
   //Set subject
   message.setSubject(subject);
   message.setText(body);
   
   BodyPart objMessageBodyPart = new MimeBodyPart();
   objMessageBodyPart.setText("Dear Customer,\n\nPlease Find the attached Automation Report File!\n\nThanks and Regards\nZellax Solutions");
   
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(objMessageBodyPart);
   objMessageBodyPart = new MimeBodyPart();
   
   //Set path to the pdf report file
   
   String filename = System.getProperty("user.dir")+"\\Default test.pdf";
   
   //Create data source to attach the file in mail
   
   DataSource source = new FileDataSource(filename);
   objMessageBodyPart.setDataHandler(new DataHandler(source));
   objMessageBodyPart.setFileName("Automation Testing Report");
   multipart.addBodyPart(objMessageBodyPart);
   message.setContent(multipart);
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, pass);
   transport.sendMessage(message, message.getAllRecipients());
   transport.close();
   }
   
  catch (AddressException ae) {
   ae.printStackTrace();   
  }
   
  catch (MessagingException me) {
   me.printStackTrace();   
  } 
}
}
 

Friday, 7 August 2015

Common Functions Used for Selenium Framework



package testing.MavenTestNG;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class CommonFunctions { 

 static Logger log = Logger.getLogger(CommonFunctions.class.getName());

 static char specialCharacters[] = { '!', '@', '#', '$', '%', '^', '&', '*',
  '(', ')', '?', '/', '"', '|', '{', '[', '<', '>', ';', '`', ',',
  '_', '-' };

 /**
  * Retrieve popup text message.
  * 
  * @param WebDriver
  *            driver
  * @return
  */
 public static String getPopupMessage(final WebDriver driver) {
  String message = null;
  try {
   Alert alert = driver.switchTo().alert();

   message = alert.getText();
   alert.accept();
  } catch (Exception e) {
   // Sometimes the text exist, but not the accept button.
   // this means the popup wasn't displayed and therefore
   // really never existed.
   //
   message = null;
  }
  System.out.println("message"+message);
  return message;
 }

 public static String cancelPopupMessageBox(final WebDriver driver) {
  String message = null;
  try {
   Alert alert = driver.switchTo().alert();

   message = alert.getText();
   alert.dismiss();
  } catch (Exception e) {
   // Sometimes the text exist, but not the accept button.
   // this means the popup wasn't displayed and therefore
   // really never existed.
   //
   message = null;
  }

  return message;
 }

 private static SecureRandom random = new SecureRandom();

 /**
  * Generate random string of special characters of length x
  * 
  * @return
  */
 public String getRandomSpecialString(int length) {
  int len = specialCharacters.length;
  String str = "";
  Random randomGenerator = new Random();
  int index;

  for (int i = 0; i < length; i++) {
   index = randomGenerator.nextInt(len - 1);
   str = str + specialCharacters[index];
  }
  return str;
 }

 /**
  * Generate random string of length x
  * 
  * @return
  */
 public static String getRandomString(int length) {
  String result = new BigInteger(Long.SIZE * length, random).toString(32);
  return result.substring(0, length);
 }

 /**
  * Generate random string of length x
  * 
  * @return
  */
 public static void populateField(WebDriver driver, By locator, String value) {
  WebElement field = driver.findElement(locator);
  field.clear();
  field.sendKeys(value);

 }

 /**
  * Check hover message text
  * 
  * @param driver
  * @param by
  * 
  * @return string
  */
 public static String checkHoverMessage(WebDriver driver, By locator){
  String tooltip = driver.findElement(locator).getAttribute("title");
  return tooltip;
 }

 /**
  * Select radio button
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectRadioButton(WebDriver driver, By locator, String value){
  List<WebElement> select = driver.findElements(locator);

  for (WebElement radio : select){
   if (radio.getAttribute("value").equalsIgnoreCase(value)){
    radio.click();               

   }}}

 /**
  * Select multiple check boxes
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectCheckboxes(WebDriver driver, By locator, String value){

  List<WebElement> abc = driver.findElements(locator);
  List<String> list = new ArrayList<String>(Arrays.asList(value.split(",")));

  for (String check : list){
   for (WebElement chk : abc){         
    if(chk.getAttribute("value").equalsIgnoreCase(check)){          
     chk.click();                   
    }                               
   }
  }
 }


 /**
  * Select drop down
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectDropdown(WebDriver driver, By locator, String value){
  new Select (driver.findElement(locator)).selectByVisibleText(value); }


 /**
  * Select auto-suggest search drop down
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void selectSearchDropdown(WebDriver driver, By locator, String value){
  driver.findElement(locator).click();
  driver.findElement(locator).sendKeys(value);
  driver.findElement(locator).sendKeys(Keys.TAB);  
 }


 /**
  * Upload file
  * 
  * @param driver
  * @param by
  * @param value
  * 
  */
 public static void uploadFile(WebDriver driver, By locator, String value){
  driver.findElement(locator).sendKeys(value);    
 }


 /**
  * Takes controls on new tab
  * 
  * @param driver
  * 
  */
 public static void handleNewTab(WebDriver driver)
 {
  Set<String> allWindowHandles = driver.getWindowHandles();
  String window0 = (String) allWindowHandles.toArray()[1];
  driver.switchTo().window(window0);
 }


 /**
  * Helper method: looks through a list of WebElements, to find the first WebElement with matching text
  * 
  * @param elements
  * @param text
  * 
  * @return WebElement or null
  */
 public static WebElement findElementByText(List<WebElement> elements, String text) {
  WebElement result = null;
  for (WebElement element : elements) {
   element.getText().trim();
   if (text.equalsIgnoreCase(element.getText().trim())) {
    result = element;
    break;
   }
  }
  return result;
 }


 /**
  * Compact way to verify if an element is on the page
  * 
  * @param driver
  * @param by
  * @return
  */
 public static boolean isElementPresent(final WebDriver driver, By by) {


  try {
   driver.findElement(by);

   return true;
  } catch (NoSuchElementException e) {
   return false;
  }
 }


 /**
  * Downloads a file from the defined url, and saves it into the
  * OutputDatafolder, using the filename defined
  * 
  * @param href
  * @param fileName
  */
 public static void downloadFile(String href, String fileName) throws Exception{

  PropertyConfigurator.configure("config/log4j.properties");

  URL url = null;
  URLConnection con = null;
  int i;

  url = new URL(href);

  con = url.openConnection();
  File file = new File(".//OutputData//" + fileName);
  BufferedInputStream bis = new BufferedInputStream(con.getInputStream());

  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
  while ((i = bis.read()) != -1) {
   bos.write(i);
  }
  bos.flush();
  bis.close();

 }


 /**
  * Writes content to the excel sheet
  * 
  * @param text
  * @param fileName
  */
 public static void writeExcel(String text,String fileName) throws Exception 
 { 
  FileOutputStream file = new FileOutputStream(".//OutputData//" + fileName+".csv",true);
  WritableWorkbook book = Workbook.createWorkbook(file); 
  WritableSheet sheet = book.createSheet("output", 0);
  Label l = new Label(0, 0, text);
  sheet.addCell(l);
  book.write(); 
  book.close(); 
 }

}

Create logs in html format using log4j (Core JAVA)

There are two steps to create HTML log file:
1. Create log4j.properties
2. Create Log4jHtmlLayout.java (this is just java file specifies the usage of log4j)

If you want only customize logger then change "log4j.rootLogger = All, FILE, rfile" to "log4j.rootLogger = INFO, FILE, rfile"

log4j.properties


# Define the root logger with appender file
log4j.rootLogger = All, FILE, rfile
 

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.logfile.File=./TestLogs/Logfile.log

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.File=./TestLogs/Logfile.log
log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Define the layout for RollingFileAppender
log4j.appender.rfile=org.apache.log4j.RollingFileAppender
log4j.appender.rfile.File=./TestLogs/applog.html
log4j.appender.rfile.MaxFileSize=1000MB
log4j.appender.rfile.Append=true
log4j.appender.rfile.layout=org.apache.log4j.HTMLLayout


Log4jHtmlLayout.java


package testing.MavenTestNG;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jHtmlLayout {

 static Logger log = Logger.getLogger(Log4jHtmlLayout.class);
 
 public static void main(String[] args) {
  
  PropertyConfigurator.configure("config/log4j.properties");
  log.debug("Sample debug message");
        log.info("Sample info message");
        log.error("Sample error message");
     }

}

Below is the example HTML log file (applog.html-as specified in log4j.properties)



Friday, 31 July 2015

Input text to text field with and without sendkeys

Input text to text field:

1. sendkeys()
2. javascript


package automation.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class test1 {

 
 public static void main(String[] args) {
  WebDriver drv=new FirefoxDriver();
  drv.navigate().to("http://www.google.com/");
  
  try{
   
   // WITH SENDKEYS
   //drv.findElement(By.id("lst-ib")).sendKeys("big data");
   
   // WITHOUT SENDKEYS 
   JavascriptExecutor jse = (JavascriptExecutor)drv;
       //jse.executeScript("document.getElementById('lst-ib').value='big data';");
    //   OR
       jse.executeScript("document.getElementById('lst-ib').setAttribute('value', 'big data');");
    drv.findElement(By.id("lst-ib")).submit();
  }
  catch(Exception e){
   e.printStackTrace();
  }
  

 }

}

Tuesday, 14 July 2015

Convert PDF to text file (Core JAVA)

If you are using maven then add dependency for itextpdf from below link or add itextpdf jars to your project:
Maven Dependency itextpdf

Download sample pdf from below link and and save it in your d drive as examplePDF.pdf:
Download Sample PDF (examplePDF.pdf)

Save exampleText.txt in your d drive.

If you want in other format like word document, just change the file name for OUTPUT i.e. "exampleText.doc"


package automation.prac;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
//iText imports
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
 
public class pdfToText {
 
  public void partPdf(String pdf, String txt) throws IOException {
         PdfReader reader = new PdfReader(pdf);
         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
         TextExtractionStrategy strategy;
         for (int i = 1; i <= reader.getNumberOfPages(); i++) {
             strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
             out.println(strategy.getResultantText());
         }
         out.flush();
         out.close();
         reader.close();
     }
 
 private static String INPUTFILE = "d:\\examplePDF.pdf";
    private static String OUTPUTFILE = "d:\\exampleText.txt";
 
    public static void main(String[] args) throws DocumentException, IOException {
     
     System.out.println("Program Starts");
     new pdfToText().partPdf(INPUTFILE, OUTPUTFILE);
     System.out.println("Program Ends");
        
    }
 
}

Verify Content in PDF-Page wise (Core JAVA)


If you are using maven then add dependency for itextpdf from below link or add itextpdf jars to your project:
Maven Dependency itextpdf

Download sample pdf from below link and and save it in your d drive as examplePDF.pdf
Download Sample PDF (examplePDF.pdf)

Output is :
Page Number: 1 Fail
Page Number: 2 Pass
Page Number: 3 Fail
Page Number: 4 Fail



package automation.prac;

import java.io.IOException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

public class getContentPdf {
 
 private static String INPUTFILE = "d:\\examplePDF.pdf";
 
 public void parsePdf(String pdf) throws IOException {
  
        PdfReader reader = new PdfReader(pdf);
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        TextExtractionStrategy strategy;
        
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            if(strategy.getResultantText().contains("Gurdial Singh")){
             System.out.print("Page Number: "+i);
             System.out.println(" Pass");
            }
            else{
             System.out.print("Page Number: "+i);
             System.out.println(" Fail");
            }
        }
      }

 public static void main(String[] args) throws IOException {
  
  new getContentPdf().parsePdf(INPUTFILE);
 }

}

Monday, 13 July 2015

Program to determine Prime Numbers from 1 to 100 (Core JAVA)

Save File as primeNumber.java



package myFirstProject;

public class primeNumber {

 public static void main(String[] args) {
  
   int a1 =0;
   int number =0;
   //Empty String for printing Prime Numbers
   String  primeNumbers = "";

        for (a1 = 1; a1 <= 100; a1++)         
        {        
           int counter=0;    
           for(number =a1; number>=1; number--)
           {
              if(a1%number==0)
              {
               counter = counter + 1;
              }
           }
            if (counter ==2)
            {
         //Appended the Prime number to the String
         primeNumbers = primeNumbers + a1 + " ";
            } 
        } 
         System.out.println("Prime Numbers from 1 to 100 are :");
         System.out.println(primeNumbers);
 }
}