Rabu, 30 April 2014

JUnit4 Annotations : Test Examples and Tutorial




JUnit4 Annotations are single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations creating and running a JUnit test becomes more easy and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of  annotations used on this version and how to use them while writing tests. In this


Junit tutorial we will not only understand meaning of those annotations but also we will see examples of JUnit4 annotations. By the way this is my first post in unit testing but if you are new here than you may like post 10 tips to write better code comments and 10 Object oriented design principles for Programmer as well.






JUnit 4 Annotations : Overview



Following is a list of frequently used Annotations , which is available when you include junit4.jar in your Classpath:






@Before

@BeforeClass

@After

@AfterClass

@Test

@Ignore

@Test(timeout=500)

@Test(expected=IllegalArgumentException.class)









@Before and @After


In Junit4 there is no setup() or tearDown() method and instead of that we have @Before and @After annotations.


By using @Before you can make any method as setup() and by using @After you can make any method as teardown(). What is most important point to remember is @Before and @After annotated method will be invoked before and after each test case. So in case you have five test cases in your JUnit test file than just like setup() and tearDown() method annotated with @Before and @After will be called five times. Here is an example of using


@Before and @After Annotation :






    @Before

    public void setUp() {

        System.out.println("@Before method will execute before every JUnit4 test");

    }

 

    @After

    public void tearDown() {

        System.out.println("@After method will execute after every JUnit4 test");

    }









@BeforeClass and @AfterClass


@BeforeClass and @AfterClass JUnit4 Annotations are similar to @After and @Before with only exception that they


are called on per TestClass basis and not on per test basis. They can be used as one time setup and tearDown


method and can be used to initialize class level resources. here is an example of using @BeforeClass and @AfterClass Annotations in JUnit4, here is an example of @BeforeClass and @AfterClass Junit 4 annotation






    @BeforeClass

    public static void setUpClass() throws Exception {

        System.out.println("@BeforeClass method will be executed before JUnit test for"

                + "a Class starts");

    }



    @AfterClass

    public static void tearDownClass() throws Exception {

         System.out.println("@AfterClass method will be executed after JUnit test for"

                + "a Class Completed");

    }








@Test


@Test is a replacement of both TestCase class and convention "test" which we prefix to every test method. for example to test a method  called calculateInterest() we used to create method testCalcuatedInterest() and our class needs to be extended from org.junit.TestCase class. Now with @Test annotation that is not required any more. You just need to annotate your test method with @Test Junit4 annotation and done. no need to extend from TestCase class and no need to prefix "test" to your method, here is an example of  JUnit 4 @Test annotation






 @Test

    public void testCalculateInterest() {

        System.out.println("calculateInterest");

        fail("An Example of @Test JUnit4 annotation");

    }










@Ignore


Some time we add test method in JUnit test class but hasn't implemented that is causing your build to fail if JUnit testcase are integrated or embedded into build process. you can avoid that problem by marking your test method as @Ignore in Junit4. JUnit4 ignores method annotated with @Ignore and doesn't run during test. Here is an example of using @Ignore annotation in JUnit4 to exclude a particular Test from running:









 @Ignore("Not yet implemented")

    @Test

    public void testGetAmount() {

        System.out.println("getAmount");

        fail("@Ignore method will not run by JUnit4");

    }









@Test(timeout=500)


Now with JUnit4 writing testcases based on timeout is extremely easy. You just need to pass a parameter timeout with value in millisecond to @Test annotation. remember timeout values are specified in millisecond and your JUnit4 timeout test case will help if it doesn't complete before timeout period. This works great if you have SLA(Service Level Agreement)  and an operation need to complete before predefined timeout.






  @Test(timeout = 500)

    public void testTimeout() {

        System.out.println("@Test(timeout) can be used to enforce timeout in JUnit4 test case");

        while (1 == 1) {

         

        }

    }






This JUnit4 test will fail after 500 millisecond.





@Test(expected=IllegalArgumentException.class)


Another useful enhancement is Exception handling testcases of JUnit4. Now to test Exception is become very easy and you just need to specify Exception class inside @Test annotation to check whether a method throws a particular exception or not. here is an example which test behaviour of a method to verify whether it throws Exception or not,  when run with invalid input:






    @Test(expected=IllegalArgumentException.class)

    public void testException(int input) {

        System.out.println("@Test(expected) will check for specified exception during its run");

     

    }



JUnit 4 annotations tutorials and examples





These were list of frequently used JUnit 4 annotations and there meanings. In the course we have also learn how to use @Before , @After in place of setup() and teardown(). Code review and Unit testing is one of the best development practices to follow and we must try our best to incorporate that in our daily coding and development cycle.





























Source:http://javarevisited.blogspot.com/2012/06/junit4-annotations-test-examples-and.html

All about Maximo domains and lookups

A useful set of articles and tutorials from IBM about domain, crossover domain, lookup, value list.

Adding a valuelist (ALN Domain) in Maximo
Adding Lookup Functionality to a Field in Maximo
Setting Up Crossover Functionality in Maximo
Filtering an out of the box lookup in Maximo
Troubleshooting Crossover Domains
Setting Up A Conditional Domain
Associating Lookups in Maximo using the MAXLOOKUPMAP Table
Conditional Lookup Functionality
Displaying Additional Information Through a Relationship in Maximo
Limiting Lookups using WHERECLAUSE
The Hidden Feature of Crossover Domain

Source:http://maximodev.blogspot.com/2012/06/maximo-domain-lookup-lists.html

Maximo Everyplace on Motorola ET1 tablet

Maximo Everyplace is a great addon to enable mobile capabilities in IBM products based on Maximo/TPAE without dealing with complex setup and configuration required by the more advanced Maximo Mobile solutions. The great advantage of Maximo Everyplace over Maximo Mobile is its simplicity.
Basically speaking, with Maximo Everyplace you can build small-screen-friendly TPAE applications that are tailored to fulfill specific user scenarios. The process of creating a custom application is well described in the product documentation and is easy if you are familiar with the Application Designer.

The current supported platform for Maximo Everyplace are iOS (Apple), Android and Blackberry. I found iOS and Blackberry very limited because they have proprietary hardware platforms. On the other hand, many hardware manufacturers are starting to produce industrial rugged devices based on the Android platform.
When I was asked for some advice by one of my customers I performed a market research based on the following requirements.
  • Well known manaufacturer to provide excellent and durable support.
  • 7 inches screen. I think that 3.5 or 4 screens are to small to effectly use Everyplace in a real working environment. Tablets with 10-inches screen seems to big to be handled with one hand.
  • Good CPU running at at least 1GHz to deliver a smooth browsing user experience.
  • Built in barcode scanner with dedicated button to activate the scan.

7-inch Android rugged tablets are not yet very common (June 2012). In particular I have found two interesting devices that seems to fit my requirements. Motorola ET1 and Panasonic Toughpad A1Since the Panasonic is not yet available I ended up with choosing Motorola ET1 tablet. Even if Motorola seems to fit all my needs I want to be sure it works well with Maximo Everyplace so I have asked Motorola to send me a device to perform a hands on test.
After few days of testing I have to say that I really like the Motorola's tablet. Here are my favorite characteristics.

Stylish and robust hardware

Looking at ET1 you wan't believe that you are looking at a MIL STD 810G certified 'rugged' device.



Dedicated buttons for barcode scanning

The ET1 is equipped with two buttons on the back that can trigger barcode scanning through the rear camera. Considering that it is not a laser scanner, I found it quite fast and powerful. It takes around 1 second to start the camera and recognize a wide variety of barcode types.


Soft-buttons on the front

There are three customizable buttons on the lower left corner of the screen. I have assigned one of these to type a TAB character so i can quickly move across Maximo field without having to play too much with the touchscreen.



Hand strap
The optional hand strap accessory allows you to steadily hold the ET1 with the left hand while leaving your right hand free to type and swype on the display or hold and move items and tools in your storeroom.



Source:http://maximodev.blogspot.com/2012/06/best-device-tablet-everyplace-motorola.html

How to close Java program or Swing Application with Example




In order to close Java program we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java program to swing GUI application. In general all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn't wait for daemon thread so as soon as last user thread finished, Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit(). This cause JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non zero value denote abnormal execute and its the result returned by java command to caller. In this java tutorial we will see example of closing both Java program and Java Swing application. This is also a good swing interview questions which you can ask to any GUI developer and my second article in swing after writing invokeAndWait vs invokeLater










Example of Closing Java program using System.exit()



Here is a code example of closing Java program by calling System.exit() method. Remember non zero argument to exit() method like exit(1) denotes abnormal termination of Java application.






import java.util.logging.Level;

import java.util.logging.Logger;



/**

 *Java program which terminates itself by using System.exit() method , non zero call to exit() method denotes abnormal termination.

 */


public class JavaCloseExample {

 

    public static void main(String args[]) throws InterruptedException {

   

       Thread t = new Thread(){

            @Override

           public void run(){

               while(true){

                   System.out.println("User thread is running");

                    try {

                        Thread.sleep(100);

                    } catch (InterruptedException ex) {

                        Logger.getLogger(JavaCloseExample.class.getName()).log(Level.SEVERE, null, ex);

                    }

               }

           }

       };

     

       t.start();

       Thread.sleep(200);

       System.out.println("terminating or closing java program");

       System.exit(1); //non zero value to exit says abnormal termination of JVM

    }

}



Output:

User thread is running

User thread is running

terminating or closing java program

Java Result: 1  //1 is what we passed to exit() method






This Java program first creates a Thread  in main method and start it  which prints “User thread is running” and than main thread sleep for 200 Milli second, till than other user thread is running and printing but once main thread woken up it terminates the program by calling exit() method of java.lang.System class.





How to close Java swing application from program



close or terminate Java program with exampleSwing application mostly uses JFrame as top level container which provides two option to close swing GUI application from code. First option which is default is EXIT_ON_CLOSE which terminates Java swing GUI program when you click close button on JFrame window. Another option is DISPOSE_ON_CLOSE which terminates JVM if last displayable window is disposed off. Difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that if you have a non daemon thread running it will not be closed in case of DISPOSE_ON_CLOSE, while EXIT_ON_CLOSE terminate JVM even if user thread is running. run the below example by un comment DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on close button. here is a complete code example of closing Swing application in Java.






import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JFrame;



/**

 * Java swing program which terminates itself by calling  EXIT_ON_CLOSE and DISPOSE_ON_CLOSE

 */


public class CloseSwingExample {



    public static void main(String args[]) throws InterruptedException {



        JFrame frame = new JFrame("Sample");

        //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); won't terminate JVM if user thread running

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(200, 200);

        frame.setVisible(true);



        Thread t = new Thread() {



            @Override

            public void run() {

                while (true) {

                    System.out.println("User thread is running");

                    try {

                        Thread.sleep(100);

                    } catch (InterruptedException ex) {

                        Logger.getLogger(CloseSwingExample.class.getName()).log(Level.SEVERE, null, ex);

                    }

                }

            }

        };



        t.start();



    }

}









Important points about terminating or closing Java program



Few points worth noting regarding close or termination of Java application from program itself:


1) System.exit() actually calls Runtime.getRuntime().exit() method.


2) Non zero argument to exit() denotes abnormal termination of Java program.


3) Shutdown hooks are executed before Java program actually terminates.


4) There are two options to close Java Swing application one is EXIT_ON_CLOSE and other is DISPOSE_ON_CLOSE.


5) DISPOSE_ON_CLOSE doesn't terminate JVM if any user thread is running.


6) You can also implement window listener to implement your closing mechanism by using System.exit() in Swing application.





That's all on how to close or terminate Java program. we have also seen example of closing Swing application in Java and difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE.





Other Java programming tutorial you may find useful:































Source:http://javarevisited.blogspot.com/2012/06/how-to-close-java-program-or-swing.html

Selasa, 29 April 2014

JDBC Database connection pool in Spring Framework – How to Setup Example




Setting up JDBC Database Connection Pool in Spring framework is easy for any Java application, just matter of changing few configuration in spring configuration file.If you are writing core java application and not running on any web or application server like Tomcat or  Weblogic,  Managing Database connection pool using Apache Commons DBCP and Commons Pool along-with Spring framework is nice choice but if you have luxury of having web server and managed J2EE Container, consider using Connection pool managed by J2EE server those are better option in terms of maintenance, flexibility and also help to prevent java.lang.OutofMemroyError:PermGen Space in tomcat by avoiding loading of JDBC driver in web-app class-loader, Also keeping JDBC connection pool information in Server makes it easy to change or include settings for JDBC over SSL. In this article we will see how to setup Database connection pool in spring framework using Apache commons DBCP and commons pool.jar





This article is in continuation of my tutorials on spring framework and database like LDAP Authentication in J2EE with Spring Security and  manage session using Spring security  If you haven’t read those article than you may find them useful.






Spring Example JDBC Database Connection Pool





Spring framework provides convenient JdbcTemplate class for performing all Database related operation. if you are not using Hibernate than using Spring's JdbcTemplate is good option. JdbcTemplate requires a DataSource which is javax.sql.DataSource implementation and you can get this directly using spring bean configuration or by using JNDI if you are using J2EE web server or application server for managing Connection Pool. See How to setup JDBC connection Pool in tomcat and Spring for JNDI based connection pooling for more details. In order to setup Data source you will require following configuration in your applicationContext.xml (spring configuration) file:


  



//Datasource connection settings in Spring

id="springDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >

    name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_TEST" />

    name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

    name="username" value="root" />

    name="password" value="root" />

    name="removeAbandoned" value="true"/>

    name="initialSize" value="20" />

    name="maxActive" value="30" />





//Dao class configuration in spring

  id="EmployeeDatabaseBean" class="com.test.EmployeeDAOImpl">

    name="dataSource" ref="springDataSource"/>

 






 


Below configuration of DBCP connection pool will create 20 database connection as initialSize is 20 and goes up to 30 Database connection if required as maxActive is 30. you can customize your database connection pool by using different properties provided by Apache DBCP library. Above example is creating connection pool with Oracle 11g database and we are using oracle.jdbc.driver.OracleDriver comes along with ojdbc6.jar or ojdbc6_g.jar ,  to learn more about how to connect Oracle database from Java program see the link.




Java Code for using Connection pool in Spring



Database connection pool Spring example codeBelow is complete code example of DAO class which uses Spring JdbcTemplate to execute SELECT query against database using database connection from Connection pool. If you are not initializing Database connection pool on start-up than it may take a while when you execute your first query because it needs to create certain number of SQL connection and then it execute query but once connection pool is created subsequent queries will execute faster.






//Code for DAO Class using Spring JdbcTemplate

package com.test

import javax.sql.DataSource;

import org.log4j.Logger;

import org.log4j.LoggerFactory;

import org.springframework.jdbc.core.JdbcTemplate;



/**

 * Java Program example to use DBCP connection pool with Spring framework

 * @author Javin Paul

 */


public class EmployeeDAOImpl implements EmployeeDAO {



    private Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);

    private JdbcTemplate jdbcTemplate;



    public void setDataSource(DataSource dataSource) {

        this.jdbcTemplate = new JdbcTemplate(dataSource);

    }



    @Override

    public boolean isEmployeeExists(String emp_id) {

        try {

            logger.debug("Checking Employee in EMP table using Spring Jdbc Template");

            int number = this.jdbcTemplate.queryForInt("select count(*) from EMP where emp_id=?", emp_id);

            if (number > 0) {

                return true;

            }

        } catch (Exception exception) {

            exception.printStackTrace();

        }

        return false;

    }

}









Dependency:


1. you need to include oracle driver jar like ojdbc_6.jar in you classpath.


2. Apache DBCP and commons pool jar in application classpath.





That's all on how to configure JDBC Database connection pool in Spring framework. As I said its pretty easy using Apache DBCP library. Just matter of few configuration in spring applicationContext.xml and you are ready. If you want to configure JDBC Connection pool on tomcat (JNDI connection pool) and want to use in spring than see here.





Other Java JDBC tutorials you may like






























Source:http://javarevisited.blogspot.com/2012/06/jdbc-database-connection-pool-in-spring.html

Adding HTML5 attributes to standard JSF components



For OmniFaces I've recently looked for the least intrusive way (i.e. no custom component/tag/renderer boilerplate necessary) to add HTML5 specific

, ,