Wednesday, 11 September 2013

Adding An Image to Word programatically using Java

Purpose: Adding An Image to Word programatically using Java

Following Code will allow to add an Image to a Word file using Java from local or web based source.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
public class AddImageToWord
{
    public static void main(String[] args) throws Exception
    {
     String img = "";
      IDocument doc = new Document2004();
      doc.addEle(Paragraph.with("Image from Web URL:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      img = Image.from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png").setHeight("100").setWidth("300").create().getContent();
      doc.addEle(img);
      doc.addEle(new BreakLine(2)); //Add two break lines
      doc.addEle(Paragraph.with("Image from Hard Disk:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      String wh = Image.from_FULL_LOCAL_PATHL("D://Screen.png").getOriginalWidthHeight();
      String[] temp = wh.split("#");
      System.out.println(temp[0]);
      System.out.println(temp[1]);
      img = Image.from_FULL_LOCAL_PATHL("D://Screen.png").setHeight("300").setWidth("500").create().getContent();
      doc.addEle(img);
     
      File fileObj = new File("D://Java2word_allInOne.doc");
      PrintWriter writer = null;
      try {
          writer = new PrintWriter(fileObj);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      String myWord = doc.getContent();
      writer.println(myWord);
      writer.close();
    }
}


 

Tuesday, 10 September 2013

How to add text to a word file using Java

Purpose: How to add text to a word file using Java


Following code will help you to Add text to a Word file programatically.

import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileOutputStream;
public class AddToWord
{
    public static void main(String[] args) throws IOException, InvalidFormatException
    {
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Sample Text to add a word file programatically");
        run.setFontSize(33);
        FileOutputStream out = new FileOutputStream("Success.doc");
        document.write(out);
        out.close();
    }
}

Generating previous day's Date using Java

Purpose: Generating previous day's Date using Java


Some times we may need to use date in different situations in different applications dynamically. That is very simple and we can use the methods of Date/Calender class. But some times we may need to capture previous day's date.

Following code will be useful to capture previous day's date.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class PreviousDate {
 public static void main(String[] args)
 {
//     Selecting Previous Date --- Start
    
     DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
     Date date = new Date();
     Calendar cal = new GregorianCalendar();
     cal.setTime(date);
     cal.add(Calendar.DAY_OF_YEAR,-1);
     Date oneDayBefore= cal.getTime();
     System.out.println();
     System.out.println("Previous Day's Date in dd/mm/yyyy format: "+dateFormat.format(oneDayBefore).toString());
//     Selecting Previous Date --- End
 }
}
 

Monday, 9 September 2013

Capturing an Element Screenshot using Selenium Webdriver

Purpose: Capturing an Element Screenshot using Selenium Webdriver

Following Code will help to capture a particular element form a Webpage.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class CaptureElement {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }

 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Required Element Screen shot
  driver.get("http://www.google.com");
  WebElement ele = driver.findElement(By.id("hplogo"));  
  try
  {
  File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  BufferedImage  fullImg = ImageIO.read(screenshot);
  //Get the location of element on the page
  Point point = ele.getLocation();
  //Get width and height of the element
  int eleWidth = ele.getSize().getWidth();
  int eleHeight = ele.getSize().getHeight();
  //Crop the entire page screenshot to get only element screenshot
  BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
  ImageIO.write(eleScreenshot, "png", screenshot);
  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshot, new File("GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Capturing Entire Page Screenshot using Selenium Webdriver

Purpose: Capturing Entire Page Screenshot using Selenium Webdriver

Following code will help to take the screenshot entire page of any webpage.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TakeScreenshot {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
  driver = new FirefoxDriver();
 }
 @Test
 public void gomezTest() throws InterruptedException, IOException {
  // Capturing Screen shot
  driver.get("http://www.google.com");
  //Get entire page screenshot
  try
  {
   File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

  //Copy the element screenshot to disk
  FileUtils.copyFile(screenshotFile, new File("\\GoogleLogo_screenshot.png"));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 @AfterClass
 public void tear() {
  driver.close();
 }
}
 

Saturday, 18 May 2013

Automation Testing for Android Mobile Web Applications & Steps to setup environment

Purpose: Automation Testing for Android Mobile Web Applications & Steps to setup environment
Introduction:

Android WebDriver allows to run automated end-to-end tests that ensure your site works correctly when viewed from the Android browser. Android WebDriver supports all core WebDriver APIs, and in addition to that it supports mobile spacific and HTML5 APIs. Android WebDriver models many user interactions such as finger taps, flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5 features such as local storage, session storage and application cache.

The current apk will only work with Gingerbread (2.3.x), Honeycomb (3.x), Ice Cream Sandwich (4.0.x) and later.
  • Note that there is an emulator bug on Gingerbread that might cause WebDriver to crash.

Install the Android SDK:

Download the Android SDK, and unpack it to ~/android_sdk/. NOTE: The location of the Android SDK must exist in ../android_sdk, relative to the directory containing the Selenium repository.

Android WebDriver test can run on emulators or real devices for phone and tablets.

Setup Emulator

To create an emulator, you can use the graphical interface provided by the Android SDK, or the command line. Below are instructions for using the command line.

First, let's create an Android Virtual Device (AVD):

$cd ~/android_sdk/tools/
$./android create avd -n my_android -t 12 -c 100M


-n: specifies the name of the AVD.
-t: specifies the platform target. For an exhaustive list of targets, run:

./android list targets

Make sure the target level you selected corresponds to a supported SDK platform.
-c: specifies the SD card storage space.
When prompted "Do you wish to create a custom hardware profile [no]" enter "no".

Now, start the emulator. This can take a while, but take a look at the FAQ below for tips on how to improve performance of the emulator.

$./emulator -avd my_android &

Setup the Device

Simply connect your Android device through USB to your machine.

Using the Remote Server

This approach has a client and a server component. The client consists of your typical Junit tests that you can run from your favorite IDE or through the command line. The server is an Android application that contains an HTTP server. When you run the tests, each WebDriver command will make a RESTful HTTP request to the server using JSON according to a well defined protocol. The remote server will delegate the request to Android WebDriver, and will then return a response.

Install the WebDriver APK

Every device or emulator has a serial ID. Run this command to get the serial ID of the device or emulator you want to use:

$~/android_sdk/platform-tools/adb devices

Download the Android server from http://code.google.com/p/selenium/downloads/list. To install the application do:

$./adb -s <serialId> -e install -r  android-server.apk

Make sure you are allowing installation of application not coming from Android Market. Go to Settings -> Applications, and check "Unknown Sources".
Start the Android WebDriver application through the UI of the device or by running this command:

$./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity

Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. In a terminal type:

$./adb -s <serialId> forward tcp:8080 tcp:8080

This will make the android server available at http://localhost:8080/wd/hub from the host machine. You're now ready to run the tests. Let's take a look at some code.

Run the Tests

import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.android.AndroidDriver;
public class OneTest extends TestCase {
  public void testGoogle() throws Exception {
    WebDriver driver = new AndroidDriver();
   
    // And now use this to visit Google
    driver.get("http://www.google.com");
   
    // Find the text input element by its name
    WebElement element = driver.findElement(By.name("q"));
   
    // Enter something to search for
    element.sendKeys("Cheese!");
   
    // Now submit the form. WebDriver will find the form for us from the element
    element.submit();
   
    // Check the title of the page
    System.out.println("Page title is: " + driver.getTitle());
    driver.quit();
  }
}

To compile and run this example you will need the selenium-java-X.zip (client side piece of selenium). Download the selenium-java-X.zip from our download page, unzip and include all jars in your IDE project. For Eclipse, right click on project -> Build Path -> Configure Build Path -> Libraries -> Add External Jars

Hope this will be useful for steup and test your application under Android.

Tuesday, 23 April 2013

Selecting any date from JQuery Date Picker using Selenium Web Driver

Purpose: Selecting any date from JQuery Date Picker using Selenium Web Driver

Automating JQuery Date Picker is not as easy as selecting Date Month Year select options. Following Selenium Web Driver code will help and provide basic logic to automate different JQuery Date Pickers.

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class JQueryDatePicket {
 WebDriver driver;
 WebElement dateWidget;
 List<WebElement> rows;
 List<WebElement> columns;
 List<String> list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
 // Expected Date, Month and Year
 int expMonth;
 int expYear;
 String expDate = null;
 // Calendar Month and Year
 String calMonth = null;
 String calYear = null;
 boolean dateNotFound;

 @BeforeTest
 public void start(){
 driver = new FirefoxDriver();
 }

 @Test
 public void testJQueryDatePicket() throws InterruptedException{

  driver.get("http://jqueryui.com/datepicker/");
  driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox of Date so that datepicker will appear
  driver.findElement(By.id("datepicker")).click();
  dateNotFound = true;
  expMonth= 3;
  expYear = 2015;
  expDate = "12";
  while(dateNotFound)
  {
  
   calMonth = driver.findElement(By.className("ui-datepicker-month")).getText();
   calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
   if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear)))
   {
    selectDate(expDate);
    dateNotFound = false;
   }
   else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
   }
   else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click();
   }
  }
  Thread.sleep(3000);
 }
 public void selectDate(String date)
 {
 dateWidget = driver.findElement(By.id("ui-datepicker-div"));
 rows=dateWidget.findElements(By.tagName("tr"));
 columns=dateWidget.findElements(By.tagName("td"));

 for (WebElement cell: columns){
  //Selects Date
  if (cell.getText().equals(date)){
   cell.findElement(By.linkText(date)).click();
   break;
  }
 }
 }

 @AfterTest
 public void tearDown()
 {
  driver.quit();
 }
}