Tuesday, October 28, 2014

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.

Tuesday, September 30, 2014

Calling a Servlet Using JQuery Ajax

When developing web applications it is very common to use Ajax to call a Servlet and get a desired response.
In this lesson I will show you how to use JQuery to send an Ajax call to a Servlet.

1. First create a new web applications(In eclipse : New => Dynamic Web Project)
2. Right click on the src folder and create a new Servlet(New => Servlet). I name the servlet as MyServlet.
3. Change the servlet so that it prints some meaningful text. My servlet is as below.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via GET...!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via POST...!");
}
}

4. Right. Servlet is created. Now I need to call this servlet from JQuery.
5. Create a new JSP page in web apps folder. I name it as index.jsp.
6. Now change the contents of the page as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
   $('#btn').click(function() {
    $.ajax({
           type:"POST",
           url:"MyServlet"
       })
       .done(function (data) {
    alert(data);//data object represents the response
       });
   });
});
</script>
</head>
<body>
<input type="button" value="Call Servlet" id="btn"/>
</body>
</html>

7. That is all. Now run the application in tomcat server and click the "Call Servlet" button and you will get an alert saying "Hello from server via POST...!". The POST method has been called.
Now change the parameter 'type:"POST"' to 'type:"GET"'. Now your message will be "Hello from server via GET...!". It means the GET method has been called.

Note - 1 :- By default this ajax call is asynchronous. It means after the ajax call is executed the rest of the code continues executing without waiting for the response from the servlet. If you want to get rid of this asynchronous behavior, just add the parameter  'async:false' as below.

$.ajax({
type:"POST",
url:"MyServlet",
async:false
})

Note - 2 :- JQuery has below two shorthands to call GET and POST requests. If you want you can use them instead of above $.ajax function.

$.get('MyServlet', function(data) {
//alert(data);
});

$.post('MyServlet', function(data) {
//alert(data);
});

Tuesday, September 16, 2014

Placing two DIVs horizontally one after another in same row

In this tutorial I am going to show you how to place two DIVs near each other one after another as in below image.
Note that in this tutorial I am using inline styles so that anyone can understand easily.

If we just add two DIVs in to a HTML page those will be displayed in two rows as below.

<div style="border:solid 2px green;width:200px;height:100px;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;">
    Second DIV
</div>



Now lets see how we can place the first these DIVs side by side. It is really easy. What you need is to add the style "float:left" to both DIVs.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>



Wow! seems working. Wait...
Now add a third DIV after these two DIVs as below.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>
<div style="border:solid 3px red;width:250px;height:150px;">
    Third DIV
</div>

Output will be as below.

Oops.. something has gone wrong. You can see the third DIVs is overlapped with the first two DIVs. Actually this is the expected behavior with "float:left" style.
Any content you add after a component which is floated, will be overlapped with the floated components.
How can we overcome this issue? Just add another DIV after the first two DIVs and set the style of that DIV to "clear:both".
Any content you put after this DIV will not be overlapped.

<div style="border: solid 2px green; width: 200px; height: 100px; float: left;">
    First DIV</div>
<div style="border: solid 2px blue; width: 200px; height: 100px; float: left;">
    Second DIV</div>
<div style="clear: both;" />
<div style="border: solid 3px red; width: 250px; height: 150px;">
    Third DIV
</div>

Now you get the desired output.



Monday, September 15, 2014

JUnit Hello World example with Eclipse

This kick start guide will show you how to create and execute JUnit test cases with eclipse.

First create a new project in Eclipse. Then create a new class. I name the class as HelloWorld.java and create it inside the package com.example. I modify the HelloWorld class so that it looks like below.

package com.example;
public class HelloWorld {
  private String helloMessage;

  public HelloWorld(String message) {
    this.helloMessage = message;
  }

  public String sayHello() {
    return helloMessage;
  }
}

Right. Now what we need to do is create a JUnit test case to verify the functionality of this class.
Create another package in src folder and name it as com.tests(You may use any name).
Now right click on the newly created package and point to New ⇨ JUnit Test Case.

Set the name as HelloWorldTest. In "Class under test" text box browse and select the class HelloWorld which we created before. Click Next. Select the sayHello() method as below and click Finish. Note that test methods are generated only for the methods that you select here. If you want you can also select the HelloWord() also.



Now the generated test class will look like this.
package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;

public class HelloWorldTest {
  @Test
  public void testSayHello() {
    fail("Not yet implemented");
  }
}

Now we can modify above auto generated method to add out  testing logics. I modify my HelloWorldTest class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage);

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Ok, I have completed my test class now. Please take a look at testPrintMessage() method. What it does is, compares the String returned by the hello.sayHello() method with the String we set in constructor. As we know those should be the same. If those were different it means something has gone wrong.
assertEquals() method throws an error if the results were not the same.

Now right click the HelloWorldTest class and select Run As ⇨ JUnit Test. You will see that a tab like below will be opened and show the result of the test.



If we had multiple methods in our HelloWorldTest class there would be more lines in this report.If any of the methods failed those will be marked in red.
We can fail the test by modifying our class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage + "abc");

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Now run the test again and the output will look like this.



The JUnit API class org.junit.Assert consists with lot more other important methods such as
     ● assertNotEquals();
     ● assertTrue();
     ● assertFalse();
     ● assertThat();

You can find the complete list in API documentation.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html

Monday, September 8, 2014

Word Wrapping inside a table cell

You may have faced situations where you need to place long texts inside a small HTML table cell. You may need to keep the width of the cell fixed and wrap the text so that it breaks at the border of the cell. Everything will work fine as long as all the words in the text are shorter than the cell width. But what happens if you have longer words. Yes the cell will get expanded to display the word in a single line.
How to avoid this behavior and let the word break and span in two or multiple lines. You will first try something like this.

<table border="1" width="40%">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

 But this does not work. The whole part "extraodinary??????????" will display in the same line.


How to overcome this behavior? Simple, just make the layout of the table fixed by adding the style "table-layout:fixed" to the table.

<table border="1" width="40%" style="table-layout:fixed;">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

Wow... Now it works. Now the output will look like this.


Note:- To be this worked in most browsers you may need to assign a width to the table.

Wednesday, July 23, 2014

JSF 2 - Import javascript file

1. Import JS file as a local resource

★  In JSF2 you can use the <h:outputScript/> tag to import local javascript and css files in to your xhtml file. However if you are using this tag your resource file should be located in the WebContent/resources folder. Please follow the following steps.

★ Create a new folder inside your WebContent fodler and name it as 'resources'.

 Put your JS file directly in to resources folder or create a sub folder in resources folder and put the file in to it. (I will create a subfolder and name it as js and add my js file myJs.js in to it.)

 Now in your xhtml page add this line in between the <h:head></h:head> tags to import the file.
<h:outputScript name="js/myJs.js" />

2. Import an external JS file

★   You can't use the <h:outputScript/> tag to import external js files. Just use plain <script/> tag as below.
<script src="http://<your-site>/yourJs.js"/>

Wednesday, April 23, 2014

Configuring c3p0 connection provider in Hibernate

When you run your application with default Hibernate configurations you may have seen following line in your console.
>> Using Hibernate built-in connection pool (not for production use!)


What does this mean?


Following is an extract from Hibernate 3.3 documentation:
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. 
(Reference: http://docs.jboss.org/hibernate/orm/3.3/reference/.../...)

The same can be found in different words in other Hibernate documentations too. In 4.1:
Hibernate's internal connection pooling algorithm is rudimentary, and is provided for development and testing purposes. Use a third-party pool for best performance and stability.
(Reference:http://docs.jboss.org/hibernate/orm/4.1/devguide/../../..)

So according to the documentation Hibernate does not recommend using its built-in connection provider. The same documentation recommends the c3p0 connection provider to use.

These are the quick steps to add c3p0 as your connection provider


Adding required jars
When you are using c3p0, you need to add these two jars to your project.
c3p0-x.x.x.x.jar
mchange-commons-java-x.x.x.x.jar

However when you have configured c3p0, Hibernate uses its C3P0ConnectionProvider for connection pooling .
So it additionally needs following jar which contains the above class.
hibernate-c3p0-x.x.x.Final.jar

If you are using Oracle as your database you may need to add following library also.
c3p0-oracle-thin-extras-x.x.x.x.jar
However if you are not using CLOB or BLOB data types, you may not need to add them.

Now we have added all the required libraries.

But how do we tell Hibernate to use c3p0 connection provider instead of its inbuilt connection provider?

Hibernate documentation says:
To use a third-party pool, replace the hibernate.connection.pool_size property with settings specific to your connection pool of choice. This disables Hibernate's internal connection pool.

According to this line Hibernate will automatically disables its  internal connection pool if you properly configured the c3p0 (or any third-party pool).

Adding c3p0 properties to hibernate.cfg.xml
Open hibernate.cfg.xml file and add following lines. You can change values according to your requirements.
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.max_size">200</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.validationQuery">SELECT 1</property>

Now start your application and you will now not see the line "Using Hibernate built-in connection pool (not for production use!)" in your console. Instead you will see a line like this.
>> Instantiating explicit connection provider:org.hibernate.service.jdbc.connections.
   internal.C3P0ConnectionProvider

You have successfully configured c3p0 connection provider.

According to Hibernate documentation above four parameters are the most important. However there are more other parameters that you can use.
All of them can be found in c3p0 official website.
http://www.mchange.com/projects/c3p0/#hibernate-specific

Usage of above main parameters are listed below.
hibernate.c3p0.min_size - Minimum number of JDBC connections in the pool. (Hibernate default: 1)
hibernate.c3p0.max_size - Max number of JDBC connections in the pool. (Hibernate default: 100)
hibernate.c3p0.max_statements - The size of c3p0's global PreparedStatement cache. (Hibernate default: 0. no caching)
hibernate.c3p0.timeout - Seconds a Connection can remain pooled but unused before being discarded. (Hibernate default:0 never expires)

Wednesday, April 9, 2014

ORA-01882: timezone region not found error with Oracle Sql Developer

In order to solve this issue add your time zone to the sqldeveloper.conf file as below. You can find this file inside the <sqldeveloper-home>\sqldeveloper\bin folder.

AddVMOption -Duser.timezone=<Your Time Zone>

Example:-

    AddVMOption -Duser.timezone="+02:00"

or 

    AddVMOption -Duser.timezone=GMT

Quartz - Quick guide

Quartz is an easy to use open source job scheduling library.
In this tutorial I am going to show you how to use this great tool to
  1. Schedule a job to run at a given time
  2. Repetitively run a job at given intervals

In this tutorial I'm using quartz-2.2.1.jar because currently it is the laterst stable version. You can download the library from http://quartz-scheduler.org/downloads.

Create a new Java project and add the quarts library to it. Since this version of Quartz depends on slf4j-1.6.6, you should add the slf4j-api-1.6.6.jar to your project as well. You can find this jar inside the zip file you downloaded from Quartz download page.
First I am going to write the method which should be run at the scheduled time. In order to do this we need to create a class which implements the org.quartz.Job interface. Then we should override the execute() method and include our logic there.

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;

public class PrintJob implements Job {
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("Job Started at " + new Date());
  }
}

Below is the class which schedule the above job at a future time.
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class PrintSchedule {
  public static void main(String[] args) throws SchedulerException {
    JobBuilder jobBuilder = JobBuilder.newJob(PrintJob.class);
    JobDetail job = jobBuilder.withIdentity("myJobName", "myGroup1").build();
    Date sheduleTime = getSheduleTime();
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName",
                  "myGroup1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }

  private static Date getSheduleTime() {
    //job will run after 5 seconds from current time
    return new Date(new Date().getTime() + 5000);
  }
}

Now run the PrintSchedule class and wait for 5 seconds. You will see a line similar to this printed on console.
Job Started at Wed Apr 09 17:30:42 IST 2014

Now we see how to shedule a job to run at certain intervals. Its very simple. Assume that you need to print the above line in every five seconds. Then just replace the below line in above code with
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName",
                  "myGroup1").startAt(sheduleTime).build();
with
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTriggerName", "myGroup1").withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

That is all. Now run the PrintSchedule class again and you will see the the above line printed on console in every five seconds.

Tuesday, January 28, 2014

Run Android Application On Device Startup

In this example I am going to show how to make your application runs on device startup. All the steps are very easy.

 Create a new Android project using Android Development Tools. Let MainActivity to be
   created by IDE.
 Add following permission in to your Manifest file.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Create a BroadcastReceiver class which is going to be informed when device rebooted.
package com.example.startuprunner;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class StartupReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent mainIntent = new Intent(context, MainActivity.class);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mainIntent);
        }
    }

Finally register the receiver in Manifest file.
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity android:name="com.example.startuprunner.MainActivity"
              android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
 
    <receiver android:enabled="true" android:exported="true" android:label="StartupR"
             android:name="com.example.startuprunner.StartupReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>
</application>

Monday, September 16, 2013

Simple Custom Validator in JSF2

JSF has several built in validators such as <f:validateRegex/>, <f:validateRegex/> etc. But sometimes you may need to create your own validator. This tutorial will teach you to create your own validator with your own logic.
  Assume that you have a text box in your web page. You need to force the user to enter a text starts with letter 'A'. Following example shows how to do it.

This is the JSF page.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<body>
  <h:form>
    <h:inputText id="txt1">
<f:validator validatorId="myValidator"/>
    </h:inputText>
    <h:message for="txt1" style="color:red" />
    <br/>
    <h:commandButton value="Click Me" />
  </h:form>
</body>
</html>

Note that in above page we have added a <h:message/> to display the error message. This is not a must.

Following is out validator class. Validator class should implement the javax.faces.validator.Validator and its validate() method. We should write our logic so that this method throws javax.faces.validator.ValidatorException if the validation failed.

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("myValidator")
public class MyValidator implements Validator {
  @Override
  public void validate(FacesContext ctx, UIComponent comp, Object val)
      throws ValidatorException {
    if(!val.toString().startsWith("A")) {
      FacesMessage msg = new FacesMessage("Please enter a value starts with 'A'");
      throw new ValidatorException(msg);
    }
  }
}

Now run the project and go to the page. Enter a text which doesn't start with 'A' and click the button. A message should be displayed as below.


Thursday, September 5, 2013

How to Read and Write to a Property File In Java -Simple example

In java.util package there is a class called Properties which easily allow you to do read and write operations with Property files. The get() method reads from the file and the store() method writes to the file. If the property is already available in the file, the value will be overridden. Using this class is very simple.

First of all you have to initialize the Properties object by loading a ".properties" file.

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;

  public PropertyTest() {
    initProperties();
  }

  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Note the properties.load() method in above code. That method loads the existing properties to properties Object.

Now your properties object is ready to use. You can save or load data now.
Below code add a property called "testProperty" to the file.
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }


Note that we have used the properties.store() method to save the value.

In below method you can see how to retrieve data from file.
  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }

Note that if the property does not exist in the file it returns null.
That is all.

The following is a full working code.
package testing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;
 
  public PropertyTest() {
    initProperties();
  }
 
  public static void main(String[] args) {
    initProperties();
    addProperty();
    readProperty();
  }
 
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }

  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }
 
 
  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Primefaces Pie Chart Example

It is very easy to create charts with Primefaces. In following example you will see how to add a pie chart to your application within minutes.
☞Remember you should have Primefaces jar added in to your project before continue.
    You can download the latest version of Primefaces from below link.
    http://www.primefaces.org/downloads.html

We use <p:pieChart/> component to add the chart to out xhtml page. So our page will look like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head></h:head>
<body>
    <p:pieChart title="Sales" value="#{chartBean.pieModel}" legendPosition="w"
        id="salesChart" style="width:350px;height:300px" />
</body>
</html>


Our JSF managed bean is this. Look that our getPieModel method returns a PieChartModel object. In our xhtml page the "value" attribute of <p:pieChart/> component is bound to this method.

import javax.faces.bean.ManagedBean;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "chartBean")
public class ChartBean {
    public PieChartModel getPieModel() {
PieChartModel pieModel = new PieChartModel();
        pieModel.set("Item 1", 10);
        pieModel.set("Item 2", 12.5);
        pieModel.set("Item 3", 30);
        pieModel.set("Item 4", 18);
        return pieModel;
    }
}

Now run the application and go to the page. You will get an output like below.

Wednesday, September 4, 2013

Add a JFreeChart Pie Chart to a JSF Page

JFreeChart is an open-source java library which can be used to create interactive charts of various types. It is widely used in java swing applications. It has the capability to export the generated chart as an image. We can use this ability to use this to display the chart as an image in a JSF page.

☞ JFreeChart is distributed under the LGPL license and so you can use it in your own project without
    publishing your source code.

In this example you will learn to add a JFreeChart chart to your JSF page. You need RichFaces added to your JSF project.

☯ Go to the download page of JFreeChart website to download JFreeChart libraries.

☯ Extract the zip file and open the lib folder. You will see several libraries inside the folder. Just 
    add jcommon-1.0.18.jar and jfreechart-1.0.15.jar to your project.

☯ Now you are ready to use JFreeChart with your project.

☯ Create your JSF managed bean as below.
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

@ManagedBean(name = "chartDemo")
public class ChartDemo {
  public void drawChart(OutputStream out, Object data) throws IOException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Item1", 10);
    dataset.setValue("Item2", 15);
    dataset.setValue("Item3", 8);
    dataset.setValue("Item4", 12.5);
    dataset.setValue("Item5", 30);
    JFreeChart chart = ChartFactory.createPieChart("Sales", dataset, true, true, Locale.ENGLISH);
    BufferedImage bufferedImage = chart.createBufferedImage(300, 300);
    ImageIO.write(bufferedImage, "gif", out);
  }
}

☯ We are going to use the Richfaces <a4j:mediaOutput> tag to show the output. So your xhtml
     page will looks like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich">

<h:head></h:head>
<body>
    <rich:panel>
        <a4j:mediaOutput style="width:200px;height:200px;" element="img"
  cacheable="false" session="true" createContent="#{chartDemo.drawChart}"
     mimeType="image/gif" />
    </rich:panel>
</body>
</html>

That is all. Run the project and you will see an output like below.


















Note:-
This note is not relative to JFreeChart. But if you are using eclipse and if you got an error like below when you try to run your project it means your JFreeChart libraries are not added to your war file.
java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset from [Module "deployment.RF1.war:main" from Service Module Loader]

To include these files in final deployment do following.
Right click the project ⇨ Properties ⇨ Deployment Assembly ⇨ Add ⇨ Java build path entries
Now select the  jcommon-1.0.18.jar and jfreechart-1.0.15.jar and click Finish. Then click Ok  to close the properties window. Now your deployment will work.

Wednesday, August 14, 2013

Example of Using Basic Authentication In a Java Web Project

Adding basic authentication mechanism to your web project is very easy. You don't need to design a login form or a login page. You just need to define the protected resources and authorized roles for those records.
This  example will show you how to do this. I am using eclipse IDE in this example.

Create a new Dynamic Web project in Eclipse. I name the project as BasicAuthTest.








































Right click on the WebContent folder and create a new JSP page. I name it as home.jsp.
Change the content of the page as below.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Hello User!</h1>
  </body>
</html>

Now open the web.xml file. You can find it in WEB-INF folder.

















Clear the default content between <webapp> </webapp> tags. Now the file will look like this.


Now add following block between the <webapp> </webapp> tags.
<security-constraint>
  <web-resource-collection>
    <web-resource-name>jsp pages</web-resource-name>
    <url-pattern>*.jsp</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>

  <auth-constraint>
    <role-name>manager</role-name>
  </auth-constraint>
</security-constraint>

As you can understand in the above code we have introduced a security-constraint block. Within it we define a web-resource-collection. web-resource-collection is a collection of resources that we need to protect. First we give a name for the collection. Then we define a url pattern. It means all the resources which match this url pattern are protected. Note that the url pattern we have used is *.jsp. It means all the requests ends with .jsp require this authentication.

Similarly you can define a url pattern of a servlet within the url-pattern tags as below.
<url-pattern>/LoginServlet</url-pattern>
Then all the requests with this pattern(i.e. http://localhost:8080/BasicAuthTest/LoginServlet) also requires authentication.

The http-method specifies which HTTP methods should be refined by this security constraint. In above code we have only the GET defined as the http method. It means this constraint applies only to GET requests. You can have multiple http-method nodes within the <web-resource-collection> </web-resource-collection> block . If you didn't specify any http-methods this constraint is applied to all the HTTP methods.

Then within <auth-constraint> </auth-constraint> tags we define the role where users in which can access this resources. You can have multiple <role-name> tags within this <auth-constraint> </auth-constraint> tags. Here we have specified manager as the role where users belongs to which role can access these restricted resources. We should also have to define this role as a security role in web.xml. See below code.


Add following block after the <security-constraint> </security-constraint> block.

<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>allPages</realm-name>
</login-config>
<security-role>
  <role-name>manager</role-name>
</security-role>

In above code within the <login-config> </login-config> block we define the auth-method (authentication method) as BASIC. This is because in this example we are going to use Basic Authentication.

Possible values for auth-method are:
✔ BASIC
✔ DIGEST
✔ CLIENT-CERT
✔ FORM

There is another node inside the <login-config> </login-config> tags. It is <realm-name>allPages</realm-name>. What does this do?
The tag realm-name is used to separate a certain authenticated area which can be accessed using same credentials. This realm value is included in the header of the server response and when the browser reads this it opens a dialog box asking the username and password for this realm.
Keep in mind that realm-name is used in Basic Authentication only.


Ok. That is it. Now right click on the project name BasicAuthTest ⇨ Run AsRun On Server
Select Tomcat server and click Finish.




















Now your application will be deployed in Tomcat server. After the server started, enter following url in the address bar of your web browser.
http://localhost:8080/BasicAuthTest/home.jsp (Assuming your Tomcat runs on port 8080)


✎ Note:-
I recommend to use FireFox because in chrome it is difficult to clear the cached credentials of Basic Authentication. In FireFox cached Basic Authentication Credentials are cleared after you restart the FireFox. If you still want to test this with chrome you may need to read this stackoverflow post.

Wow! You will see a dialog box asking for a username and a password to access the page.
















Enter arbitrary credentials and try. You will again and again receive the popup.

Configuring Tomcat users and Roles
In order to login you need to have a user with the role manager configured in tomcat-users.xml file.

In Project Explorer open the Servers folder and you will see your Tomcat instances. Expand the relevant tomcat folder and double click the tomcat-users.xml file.



















✎ Note:-
    In your Tomcat installation directory you can find another tomcat-user.xml file. However in the case you start the Tomcat through Eclipse, there is no effect of changing this default tomcat-user.xml file. When Tomcat is started through Eclipse it doesn't read configurations from this file. Instead it reads the tomcat-user.xml file I have shown in above screen.

Add following lines inside the <tomcat-users> </tomcat-users> tags. In first line we are creating a role named as "manager". In second line we are creating a user with username "admin" and password "admin" and assigns the role "manager" to that user.

<role rolename="manager"/>
<user password="admin" username="admin" roles="manager"/>

Save the tomcat-users.xml file and restart the Tomcat server. Restart FireFox and retry the url
http://localhost:8080/BasicAuthTest/home.jsp (Assuming your Tomcat runs on port 8080).
Enter the username and password as "admin" and "admin".
Now you should be able to login.

✎ Note:-
After you successfully logged in, you can again and again access your protected resources without being asked for the credentials. If you want to see the login box again just restart FireFox. For chrome users please take a visit to this stackoverflow post.