Tuesday, December 4, 2012

Write the data in Excel file

To Import the data and Write it in excel file. this is could be the one of teh way  





package dDT1;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Iterator{

public static void main (String[] args){
// Name of excel file that we are going to create
String fileName ="C:\\TEMP\\testdata.xls";
writeDataToExcelFile(fileName);
}
// This method write data to excel file
private static void writeDataToExcelFile(String fileName)
{
String[][] excelData = prepareDataToWriteInExcel();
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet =workBook.createSheet();
HSSFRow row =null;
HSSFCell cell = null;

for(int rowNum=0;rowNum < excelData[0].length;rowNum++)
{
row= sheet.createRow(rowNum);
for (int cellNum = 0;cellNum < 4;cellNum++)
{
cell= row.createCell(cellNum);
cell.setCellValue(excelData[rowNum][cellNum]);
}
}
try{
FileOutputStream out =new FileOutputStream(fileName);
workBook.write(out);
out.close();
}
catch(Exception e){
e.printStackTrace();
}
// return excelData;
}
// created some demo date for excel sheet
public static String [][] prepareDataToWriteInExcel(){
String [][] excelData = new String[4][4];
        excelData[0][0]="First Name";
        excelData [0][1]="Last Name";
        excelData[0][2]="EmpNo";
        excelData[0][3]="Sal";
       
        excelData[1][0]="Sachin";
        excelData[1][1]="Gainewar";
        excelData[1][2]="003";
        excelData[1][3]="1500000";
       
        excelData[2][0]="Pravin ";
        excelData[2][1]="Balpande";
        excelData[2][2]="004";
        excelData[2][3]="1800000";
       
        excelData[3][0]="Nilesh";
        excelData[3][1]="Thakare";
        excelData[3][2]="005";
        excelData[3][3]="2100000;
       
        return excelData;
}
}

Tuesday, September 11, 2012

Identification canonical tag is correct tag

Below program identify the canonical tag and open it the canonical url in new window and verified it is correct url



int result =0;
String url = selenium.getLocation();
if (selenium.isElementPresent("//link[@rel='canonical' and @href='" + (url) + "']"))
{
//System.out.println("Canonical tag present : " + selenium.getText("//link[@rel='canonical']"));
System.out.println("Canonical tag present : " + url);
selenium.openWindow(url, "url");
selenium.selectWindow(url);
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.getHtmlSource().matches("^[\\s\\S]*404[\\s\\S]*$"))
System.out.println("Canonical tag is wrongly , gives 404 error for url"+url);
break; }
catch (Exception e) {
System.out.println("Canonical tag is correctly put");
};
Thread.sleep(1000);






Tuesday, September 4, 2012

Retrieving Canonical tag on page with selenium

Retrieving Canonical tag on page with selenium :-

HTML Source :- 
<link rel="canonical" href="base url" />



int result =0;
String url = selenium.getLocation();
if (selenium.isElementPresent("//link[@rel='canonical' and @href='" + (url) + "']"))
{
//System.out.println(url+"Canonical tag present : " + selenium.getText("//link[@rel='canonical']"));
System.out.println("Canonical tag present : " + url);
selenium.open(url);
}
else 
{
System.out.println("Canonical tag not present : " +url);
result++;
}





Monday, August 27, 2012

Handling Multiple window or Pop-Up window using Selenium RC

Handling Multiple window or Pop-Up window using Selenium RC :

// select new window
selenium.selectWindow("Google Window"); 
//Do whatever you want to do on new window
selenium.click("link=submit");
//Close the newly opened window
Selenium.close(); 
//To choose the original window back.
selenium.selectWindow(null); 


Friday, August 3, 2012

Creating Junit test Suites in Ecplice

Retrieving all Hyperlinks on Page with Selenium

You can retrieve the all the hyperlinks on page by this way


// Initialized  the counter and get the hyperlinks (started with //a) count

int count = selenium.getXpathCount("//a").intValue();
// run the loop till  total hyper link counter
for(int i=1;i<=count;i++)
{
//Iterate the received links through getText
String links = selenium.getText("xpath=(//a)["+i+"]" );
System.out.println("link : "+links);
}

Thursday, August 2, 2012

Folder Lock


if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Locker goto MDLOCKER
:CONFIRM
echo Are you sure u want to Lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Locker "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo Enter password to Unlock folder
set/p "pass=>"
if NOT %pass%==type your password here goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Locker
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Locker
echo Locker created successfully
goto End
:End



Note:-New folder named 'Locker' would be formed at the same location. keep all artifacts in the lock folder

Sending Email in Selenium RC

This is function help you to send the Email to multiple stockholders with Test Report as an attachment.:


package zipQuoteNavigation;
//File Name SendFileEmail.java

import java.text.SimpleDateFormat;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import org.fest.swing.testng.listener.*;


public class SendFileEmail
{
public static void main(String [] args){
// Recipient's email ID needs to be mentioned.
String to = "utakalkar@king.com,argupta@king.com,mdeshmukh@king.com,sgainewar@king.com" ;
//String to = "sgainewar@king.com";
  // Sender's email ID needs to be mentioned
  String from = "sgainewar@king.com";

  // Assuming you are sending email from localhost  , enter the host (check in outlook)
  String host = "host";

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);

  // Get the default Session object.
  Session session = Session.getDefaultInstance(properties);

  try{
  System.out.println("---------------- Email Process Started.... " + System.currentTimeMillis());

// Below code in try catch method executed the batch file created in location D:\temp
  //Runtime rn =Runtime.getRuntime();
try {
//Process p1 = rn.exec("cmd /c start D:\\temp\\a.bat");

}
catch(Exception e){};

     // Create a default MimeMessage object.
     MimeMessage message = new MimeMessage(session);

     // Set From: header field of the header.
     message.setFrom(new InternetAddress(from));

     // Set To: header field of the header.
     message.addRecipients(Message.RecipientType.TO,
                              to);

     // Set Subject: header field
     message.setSubject("Whistleblower Report on Zip code navigation !");

     // Create the message part
     BodyPart messageBodyPart = new MimeBodyPart();

     // Fill the message
     messageBodyPart.setText("To find the more details on the test result find attachment ");
   
     // Create a multipar message
     Multipart multipart = new MimeMultipart();

     // Set text message part
     //multipart.addBodyPart(messageBodyPart);

     // Part two is attachment
     messageBodyPart = new MimeBodyPart();
   
     String filename = "C:\\Documents and Settings\\sgainewar\\workspace\\HQF\\test-output\\emailable-report.html";
     DataSource source = new FileDataSource(filename);
     messageBodyPart.setDataHandler(new DataHandler(source));
     messageBodyPart.setFileName(filename);
     multipart.addBodyPart(messageBodyPart);
     // Send the complete message parts
     message.setContent(multipart );

     // Send message
     Transport.send(message);
     System.out.println("Sent message successfully....");
  }catch (MessagingException mex) {
     mex.printStackTrace();
   
  }
}
}  

Friday, July 13, 2012

executing .bat with java code




 try{
       Runtime rn =Runtime.getRuntime();
        try {
            Process p1 = rn.exec("cmd /c start D:\\temp\\a.bat");
           
        }
        catch(Exception e){};

Thursday, July 12, 2012

Retrieve the H1 tag Title :



package autoInsurance;


import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class H1tag {

public Selenium selenium;
public SeleniumServer seleniumserver;

@BeforeClass
public void setUp() throws Exception{

selenium =new DefaultSelenium("localhost",4444,"*chrome", "http://www.loan.com");
selenium.start();

}
@Test
public void TestH1tag() throws Exception{
selenium.open("http://www.loan.com");
selenium.windowMaximize();

// To retirve the H1 tag title selenium.gettext(xpath)
System.out.println("FirstChild of h1 with descendent child "+selenium.getText("css=h1"));
}
@AfterClass
public void tearDown() throws Exception{

selenium.stop();
}
}






To verify the Text from Source code in selenium : 


package zipQuoteNavigation;

import com.thoughtworks.selenium.*;

import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;

import static org.testng.Assert.*;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import zipQuoteNavigation.SendFileEmail;

public class Compuquotes {
public Selenium selenium;
public SeleniumServer seleniumserver;
SendFileEmail e = new SendFileEmail();

@BeforeClass
public void setUp() throws Exception
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://www.loan.com");
selenium.start();
}

@Test
public void test() throws Exception{


BufferedReader in=null;
InputStreamReader inputStream =null;
try{
inputStream = new InputStreamReader (new FileInputStream("C:\\Documents and Settings\\sgainewar\\workspace\\HQF\\src\\zipQuoteNavigation\\urls.csv"));
in =new BufferedReader(inputStream);
String line = null;
String url ="";
while ((line = in.readLine())!=null)
{
String[] data = line.split(",");
if(data.length >= 1){
url = data[0];
System.out.println("url : "+ url );
selenium.deleteCookie("", "");
Thread.sleep(500);
selenium.open(url);
Thread.sleep(4000);
selenium.waitForPageToLoad("30000");
selenium.click("id=zipCode");
selenium.type("id=zipCode", "94154");
selenium.click("id=fs-index-submit");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.getHtmlSource().matches("^[\\s\\S]*in_frame[\\s\\S]*$")) break; } catch (Exception e) {}
Thread.sleep(1000);


}
}
}
}
catch (Exception e){
e.printStackTrace();
}
finally{
try{
if(in!=null){
in.close();
}
if(inputStream !=null){
inputStream.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}

}
@AfterClass
public void tearDown() throws Exception{
selenium.stop();
Thread.sleep(2000);
e.main(null);
}
}



Thursday, April 19, 2012

datadriven test in selenium

package mortgageLender;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import com.thoughtworks.selenium.*;

public class DebtConsolidation extends SeleneseTestCase{
private static final String[] data = null;
public DefaultSelenium selenium;

private void verifytrue(boolean textPresent) {
// TODO Auto-generated method stub

}

@BeforeClass
public void setUp()throws Exception{

selenium = new DefaultSelenium ("localhost", 4444, "*chrome", "http://www.google.com/");
selenium.start();
}
@Test(description="Debt Consolidation")

public void Test() throws Exception{
// Select the field "Debt Consolidation"
// Intialization of the user input ;
BufferedReader in=null;
InputStreamReader inputStream =null;
try{
// define the path of date in excel
inputStream = new InputStreamReader (new FileInputStream("C:\\Documents and Settings\\sgainewar\\workspace\\google\\src\\mortgageLender\\Pages.csv"));
in =new BufferedReader(inputStream);
String line = null;
String url ="";
String category ="";
// define the loop that loop should executed till last row
while ((line = in.readLine())!=null){
// Declare to column is separated with coma  
String[] data = line.split(",");
if(data.length >= 1){
// Declare first row -first column
url = data[0];
category = data[1];
System.out.println("url : "+ url );
System.out.println("Category selected :"+ category);

Thread.sleep(500);
// define data should taken from url column
selenium.open(url);
Thread.sleep(3000);
selenium.click("id=service_debtConsolidation_label");
Thread.sleep(50);
selenium.click("xpath=//form[@id='lenders-form']/div/fieldset/div[2]/button");
//selenium.click("id=PropertyType");
selenium.waitForPageToLoad("30000");
Thread.sleep(3000);
selenium.type("id=property_zipcode", "94154");
Thread.sleep(200);
selenium.mouseOver("xpath=//form[@id='3stepform']/div/div/div/div[2]/button");
selenium.clickAt("xpath=//form[@id='3stepform']/div/div/div/div[2]/button","5,5");
Thread.sleep(400);
try{
Assert.assertEquals("Rate Your Credit:", selenium.getText("xpath=//form[@id='3stepform']/div/div/div[2]/h2/strong"));
System.out.println("Rate Your Credit: is present");
}
catch(Exception e){
System.out.println("Rate Your Credit: is NOT present");
}
selenium.select("id=credit_rating", "label=Good (620-719)");
selenium.mouseOver("xpath=//form[@id='3stepform']/div/div/div[2]/div[3]/button");
selenium.click("css=#slide_page2 > div.clearfix > button.next");

//selenium.clickAt("xpath=//form[@id='3stepform']/div/div/div[2]/div[3]/button", "5,5");
//selenium.mouseOver("xpath=//form[@id='3stepform']/div/div/div[2]/div[3]/button");
Thread.sleep(100);


verifyTrue(selenium.isTextPresent("How would you like to consolidate your debt?"));

selenium.click("id=debtcon1");
selenium.click("id=debtcon");
selenium.click("css=#slide_page3 > div.clearfix > button.next");
try{
Assert.assertEquals("Property Value:", selenium.getText("xpath=//form[@id='3stepform']/div/div/div[3]/h2/strong"));
}
catch(Exception e){
System.out.println("Property Value: is not present");
}
selenium.click("css=#slide_page3 > div.clearfix > button.next");
Thread.sleep(1000);
try{

verifyTrue(selenium.isTextPresent("Total Mortgage Balance:"));
assertTrue(selenium.isTextPresent("Include 1st & 2nd mortgages plus any equity loans or credit lines."));
assertTrue(selenium.isTextPresent("OK to estimate"));

}
catch(Exception e){
System.out.println("Total Mortgage Balance:,OK to estimate is NOT present");
}
selenium.click("css=#slide_page4 > div.clearfix > button.next");
try{
assertTrue(selenium.isTextPresent("Additional Cash Needed:"));
assertTrue(selenium.isTextPresent("Get extra cash for any expense or pay-off credit cards or loans."));
}
catch(Exception e){
System.out.println("Additional Cash Needed: is NOT present");
}
selenium.click("css=#slide_page5 > div.clearfix > button.next");
try{
assertTrue(selenium.isTextPresent("Is your existing mortgage an FHA Loan?"));
}
catch(Exception e){
System.out.println("Is your existing mortgage an FHA Loan? is NOT present");
}

selenium.click("css=#slide_page7 > div.clearfix > button.next");
try{
assertTrue(selenium.isTextPresent("Have you ever had a bankruptcy?"));
}
catch(Exception e){
System.out.println("Have you ever had a bankruptcy? is NOT present");
}

selenium.click("css=#slide_page6 > div.clearfix > button.next");
try{
assertTrue(selenium.isTextPresent("Are you a veteran or active military?"));
}
catch (Exception e){
System.out.println("Are you a veteran or active military? is NOT present");
}
selenium.click("id=military_eligibility");
selenium.click("xpath=(//input[@id='military_eligibility'])[2]");
selenium.click("css=#slide_page7 > div.clearfix > button.next");
selenium.type("id=first_name", "test");
selenium.type("id=last_name", "test");
selenium.type("id=address", "tewst");
selenium.click("link=change");
selenium.type("id=email_address", "test@qs.com");
selenium.type("id=phone_number_1", "321");
selenium.type("id=phone_number_2", "321");
selenium.type("id=phone_number_3", "2133");
selenium.click("id=get_lenders");
verifytrue(selenium.isTextPresent("What is the property zip code?"));

}
}
}
catch (Exception e){
e.printStackTrace();
}
finally{
try{
if(in!=null){
in.close();
}
if(inputStream !=null){
inputStream.close();
}
}
catch(Exception e){
e.printStackTrace();
}

}
}
/*@AfterClass
public void Teardown()throws Exception {
selenium.stop();

}*/


}