Monday, April 23, 2012

Ajax with Dojo

It is very safe to use Dojo like java script frameworks for Ajax operations since they ensure browser compatibility. We don't have to change the code based on different browsers. dojo will handle those stuff for us. Any way , If we are using such java script frameworks for Ajax operations  we must carefully choose a proper framework with wide range of browser support.

In this example I have used a very simple Servlet and a simple HTML page to demonstrate the client server model.

Friday, April 20, 2012

Browser Automation With Selenium

Selenium is a browser automation framework. it is available in many flavors such as Java , .net , python . I am interested in Java implementation of Selenium.  Selenium can be successfully used in regression automation. It provides all the necessary functionalists required to automate the browser. Such as navigating, verifying, drag and drop,  clicking , selecting..etc.

Selenium can be downloaded from here
Getting started guide


Following program will demonstrate some of the basic functionalists of the selenium.
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;



public class SeleniumBasics {

  /**
   * @param args
   * @throws IOException 
   */
  public static void main(String[] args) throws IOException {
    //get configured webdriver
    WebDriver driver=getWebdriver();
    
    //goto google.lk
    driver.get("http://www.google.lk");
    WebElement searchBox=driver.findElement(By.xpath("//input[@type='text' and @name='q']"));
    //enter some text in the search textbox
    searchBox.sendKeys("Namo Buddhaya!!!");
    
    //cick on search button
    WebElement searchButton=driver.findElement(By.xpath("//button[@aria-label='Google Search' and @name='btnG']"));
    searchButton.click();
    
    //waiting until results div is loading successfully or 5sec is over
    long endTime=System.currentTimeMillis()+5000;
    while(System.currentTimeMillis()<endTime){
      WebElement resultsDiv=driver.findElement(By.xpath("//div[@id='ires']"));
      if(resultsDiv.isDisplayed()){
        break;
      }
    }
    
    //list down the search results
    List<WebElement> searchResults=driver.findElements(By.xpath("//a[@class='l']"));
    for(WebElement w : searchResults){
      System.out.println(w.getText());
    }

    //saving a screenshot
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
    
    System.out.println("-==DONE==-");
  }
  
  //creates the default driver
  public static WebDriver getWebdriver() {
    WebDriver driver = null;
    try {
      File firebug = new File("C:\\FFPlugins\\firebug-1.7.3.xpi");
      File xpathChecker = new File("C:\\FFPlugins\\xpath_checker-0.4.4-fx.xpi");
      FirefoxProfile profile = new FirefoxProfile();
      profile.setAcceptUntrustedCertificates(true);
      profile.setAssumeUntrustedCertificateIssuer(true);
      profile.addExtension(firebug);  //installing pligins
      profile.addExtension(xpathChecker);
      profile.setPreference("extensions.firebug.currentVersion", "1.7.3");
      profile.setPreference("extensions.xpath_checker.currentVersion", "0.4.4");
      driver=new FirefoxDriver(profile);
    } catch(IOException e) {
      e.printStackTrace();
    }
    return driver;
  }
}

Tuesday, April 3, 2012

Log4j In Action

Logging is very important for the maintenance of  a deployed application. Just assume a situation that we deploy our application on the client systems and work on another project. After some time client reports a failure of our system. What will happen if we haven't maintained a log file! We may be in a big trouble in such situations. It may be very hard to track where the bug occurred. Because we haven't any IDE's , debuggers on deployed machine.

So it is always recommended to use a logging mechanism for large applications. Logging may be a overhead if we don't use it carefully. We can use logging inside exception handling blocks.

Log4j is a simple and solid logging framework. Lets see how we can use Log4j in our projects. There are 5 main logging levels.
  • INFORMATION
  • DEBUG
  • WARN
  • ERROR
  • FATAL
Log4j can be configured in 3 ways.
  • Basic configuration
  • Property file configuration
  • XML configuration.
Most popular way is using property file configuration. We will see how to use basic config. and property file config.

Example using Basic configuration.
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class Log4jSimpleConfigDemo {
  static final Logger logger = Logger.getLogger(Log4jSimpleConfigDemo.class);

  public static void main(String args[]) {
    BasicConfigurator.configure();

    logger.info("This is an INFORMATION level message");
    logger.debug("This is a DEBUG level message");
    logger.warn("This is a WARN level message");
    logger.error("This is an ERROR level message");
    logger.fatal("This is a fatal level message");

  }
}

Output
1 [main] INFO Log4jSimpleConfigDemo  - This is an INFORMATION level message
2 [main] DEBUG Log4jSimpleConfigDemo  - This is a DEBUG level message
3 [main] WARN Log4jSimpleConfigDemo  - This is a WARN level message
3 [main] ERROR Log4jSimpleConfigDemo  - This is an ERROR level message
3 [main] FATAL Log4jSimpleConfigDemo  - This is a fatal level message

Eample using property file.
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jPropertyFileConfigDemo {
  static final Logger logger = Logger.getLogger(Log4jPropertyFileConfigDemo.class);

  public static void main(String[] args) {
    PropertyConfigurator.configure("log4j.properties");

    logger.info("This is an INFORMATION level message");
    logger.debug("This is a DEBUG level message");
    logger.warn("This is a WARN level message");
    logger.error("This is an ERROR level message");
    logger.fatal("This is a fatal level message");

  }

}

Property file (log4j.properties)
log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Logging into the console is not always appropriate. Lets see how we can can logging into a file.
This configuration makes no changes to the source code but for the property file.

Property file (log4j.property)
log4j.rootLogger=DEBUG, CA, FA
 
#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=mylog.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
 
# Set the logger level of File Appender to WARN
log4j.appender.FA.Threshold = WARN




Monday, April 2, 2012

Dependancy Injection (Spring Note 1)

Just assume a situation where we have to develop a module that must generate different types of reports such as PDF reports, Excel reports. One of a worst design for such scenario is design classes for each report separately without any form of polymorphism. Such a design may may result in increasing coupling of the program.
example :
ExcelReport excelReport=new ExcelReport();
PDFReport pdfReport=new PDFReport();

excelReport.initialize();
excelReport.createReport();
excelReport.saveReport();

pdfReport.initialize();
pdfReport.createReport();
pdfReport.saveReport();

We can use polymorphism to reduce the coupling of the design.


Report excelReport=new ExcelReport();
Report pdfReport=new PDFReport();

excelReport.initialize();
excelReport.createReport();
excelReport.saveReport();

pdfReport.initialize();
pdfReport.createReport();
pdfReport.saveReport();

But still the caller have to know about the type of the objects. still there is no much advantage of using above design to reduce coupling.

There is another solution to reduce coupling dramatically. Which is called "Dependency Injection" . What we do here is, using a helper class to separate dependencies.

Report.java
package model;

public interface Report {
 public void initialize();
 public void createReport();
 public void saveReport();
}

ExcelReport.java
package model;

public class ExcelReport implements Report {
 @Override
 public void initialize() {
  System.out.println("-= Initializing Excel Report =-");
 }

 @Override
 public void createReport() {
  System.out.println("-= Creating Excel Report =-");
 }

 @Override
 public void saveReport() {
  System.out.println("-= Saving Excel Report =-");
 }
}

PDFReport.java
package model;

public class PDFReport implements Report{
 @Override
 public void initialize() {
  System.out.println("-= Initializing PDF Report =-");
 }

 @Override
 public void createReport() {
  System.out.println("-= Creating PDF Report =-");
 }

 @Override
 public void saveReport() {
  System.out.println("-= Saving PDF Report =-");
 }

}

ReportGenerator.java
package model;

public class ReportGenerator {
 Report reoprt;
 
 public ReportGenerator(Report report){
  this.reoprt=report;
 }
 
 public void generateReport(){
  this.reoprt.createReport();
  this.reoprt.saveReport();
 }
 
 public void setReport(Report report){
  this.reoprt=report;
 }
}

DependancyInjectionDemo.java
import model.ExcelReport;
import model.PDFReport;
import model.Report;
import model.ReportGenerator;

public class DependancyInjectionDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // without dependancy injection
  System.out
    .println("========Generating Reports Using Without Fependancy Injection========");
  Report excelReport = new ExcelReport();
  Report pdfReport = new PDFReport();

  excelReport.initialize();
  excelReport.createReport();
  excelReport.saveReport();

  pdfReport.initialize();
  pdfReport.createReport();
  pdfReport.saveReport();

  System.out
    .println("========Generating Reports Using Fependancy Injection========");
  // using dependancy injection
  ReportGenerator rpeortGen = new ReportGenerator(excelReport); // dependancy
                  // injection
                  // via
                  // constructor
  rpeortGen.generateReport();

  rpeortGen.setReport(pdfReport); // dependancy injection via mutator
  rpeortGen.generateReport();
 }
}

The above process can be simplified by using Spring.



 
© Copyright 2035 kani.stack.notez
Theme by Yusuf Fikri