Wednesday, October 29, 2014

HTML5 FileReader Example

As you know in javascript it is not allowed to access files from users local machine. If it was allowed by any browser it would be a huge security hole.
But now in HTML5 it is allowed to read files from users machine if the user himself selects the file. You can do this using HTML5s FileReader API.
Below is a quick example which illustrates this functionality. In this example the content of the selected file is read by the FileReader and displayed in below textarea.

<html>
  <head>
    <title>Page Title</title>
    <script>
      function readSingleFile(e) {
       var file = e.target.files[0];
       var reader = new FileReader();
       reader.onload = function(e) {
        var content = reader.result;
        document.getElementById('txt1').innerHTML = content;
       };
       reader.readAsText(file);
      }
    </script>
  <head>
  <body>
    <form action="b.html" method="get">
      <input type="file" id="file1" name="file1" onchange="readSingleFile(event)"/>
      <br/>
      <br/>
      <textarea style="width:400;height:500px;" id="txt1"/></textarea>
    </form>
  </body>
</html>

Tuesday, October 28, 2014

Selenium HtmlUnitDriver Example

All of you may have used Seleniums FirefoxDriver or ChromeDriver for web application automation. When using them you know a browser window is opened visibly. If you do not need to visually examine the process and just need to check a final result you can use the HtmlUnitDriver instead. This consumes less memory and it is super fast when comparing with above browser drivers.
In a previous tutorial I showed you how to use FirefoxDriver to automation google search. Now I am going to show you how to do a google search invisibly using HtmlUnitDriver and get the search result page title and search result count.
If you do a google search using a browser, you know it displays the result count at the top of the result page. If you inspect the source of this page you will see that the id of the div in which this text is displayed is "resultStats". We are going to use this id to get the total time.

1. Create a new java project and name it as SeleniumLearn
2. Download the Selenium library from Selenium Download Page and add to the project
3. Add a new Java class and name it as SeleniumExample
4. Modify the class as below.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class SeleniumExample  {
    public static void main(String[] args) {

        WebDriver driver = new HtmlUnitDriver();
        driver.get("http://www.google.com");
        //The name of the google search text box is "q". 
        //You can find this by looking at the html source of the google search page.
        //Webdriver can find the search text box by that name as below
        WebElement searchBox = driver.findElement(By.name("q"));

        //Enter the search text
        searchBox.sendKeys("fast cars");
        //Below command will submit the form to which the searchBox belongs
        searchBox.submit();
        //We can get the title of the result page as below
        System.out.println("Page title : " + driver.getTitle());
        //We can get the result count as below
        WebElement resultCount = driver.findElement(By.id("resultStats"));
        System.out.println("Result Count : " + resultCount.getText());
        
        //Close the driver
        driver.quit();
    }
}

5. Now run this file and you will see the page title and the search result count printed on the console.

Selenium automation quick start - Automate Google Search

In this quick tutorial I'll show you how to use Selenium Firefox Driver to Automate Google Search
When running this simple application we hope to get below output without user interaction.

1. Firefox will be opened automatically
2. The text "fast cars" will be inserted in to search box automatically
3. Search form will be submitted
4. Search result page will be displayed

Ok lets start.
1. Create a new java project and name it as SeleniumLearn
2. Download the Selenium library from Selenium Download Page and add to the project
3. Add a new Java class and name it as SeleniumExample
4. Modify the class as below.

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

public class SeleniumExample  {
    public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.google.com");

        //The name of the google search text box is "q". 
        //You can find this by looking at the html source of the google search page.
        //Webdriver can find the search text box by that name as below
        WebElement searchBox = driver.findElement(By.name("q"));

        //Enter the search text
        searchBox.sendKeys("fast cars");
        //Below command will submit the form to which the searchBox belongs
        searchBox.submit();
    }
}

5. Now run this file and you will see the desired output.

Wednesday, October 15, 2014

Log4j in 1 minute - Log4j Quick Start Guide

In this tutorial I am showing you the minimum steps you need to use log4j in your project.

Note:-
In this example I am using RollingFileAppender as the appender. RollingFileAppender lets you to write logs in to a log file. The default maximum size of the file is 10MB. You can change this value in log4j.properties file.

1. Create a new java project.
2. Download log4j-2.x.xx.jar from http://logging.apache.org/log4j/2.x/download.html and add it to your project(Im using log4j-1.2.12.jar).
3. Create a new property file in your source folder(src) and name it as log4j.properties. Then add below content to it.

log4j.rootLogger = debug, myFileAppender
log4j.appender.myFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.myFileAppender.File=D://log.log
log4j.appender.myFileAppender.layout=org.apache.log4j.PatternLayout

4. Now you can use various logging methods in your classes as below.
import org.apache.log4j.Logger;

public class Log4jExample{

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

  public static void main(String[] args) {
     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
     log.warn("Hello this is an warn message");
     log.error("Hello this is an error message");
     log.fatal("Hello this is an fatalmessage");
    }
}

One minute tutorial is over. Now you know how to use log4j.
Happy logging with log4j...!!




Below I will include some extra information.

If you want to change the maximum size of the log file you can do it as below.
log4j.appender.myFileAppender.MaxFileSize=200KB

If you want to bakup the old log files after max file size reached, use MaxBackupIndex property as below. The MaxBackupIndex is the nuber of bakup files you need to keep.
log4j.appender.myFileAppender.MaxBackupIndex=3

If you want to print the log messages in console too, you need to configure a ConsoleAppender too. Then your complete property file would looks like below. Newly added content has been marked with different color.

log4j.rootLogger = debug, myFileAppender, myConsole
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.myFileAppender.MaxFileSize=2GB
log4j.appender.myFileAppender.MaxBackupIndex=3
log4j.appender.myFileAppender.File=D://log.log
log4j.appender.myFileAppender.layout=org.apache.log4j.PatternLayout

Even though you have set the log level of the rootLogger to debug you can set the log level of an appender to a higher level. For an exemple you can set the log level of the appender myFileAppender to Error level like this.
log4j.appender.myFileAppender.Threshold=ERROR

There are lot more properties that you can use to customize the output. Just google and you could find them.

NOTE:In above example we used log4js RootLogger with multiple appenders. If you want you can define your own loggers like this.

log4j.logger.myLogger = info, myFileAppender2

In this case myFileAppender2 prints only the logs which come through myLogger logger. The appenders bound to root logger prints all the logs come through root logger and myLogger.