Archive | February, 2008

Java Remoting – Benchmark

Recently, I am looking into Java remoting. I need to find the fastest protocol in remoting spectrum in order to ship a large number of objects across the net. Here I found a great article that experimented several popular remoting protocols and did a comparison. The protocols covered include:

  1. RMI - Java remoting standard, each method needs to throw a checked RemoteException and need to generate stubs and skeletons.
  2. Hessian 1 and 2 – Lightweight binary protocol from Caucho, HTTP-based, Custom binary serialization mechanism. Support for several platforms PHP / Python / C++ / C# / Objective C / Ruby / Java.
  3. HttpInvoke - Spring Java-to-Java remoting, HTTP-based, Java serialization just like RMI, easy to set up.
  4. Burlap – XML-based lightweight protocol from Caucho, HTTP-based, Custom XML based serialization mechanism, Do not know support different than for Java
  5. Apache XML-RPC

From the result, binary protocols are much faster than xml ones. HttpInvoke from Spring is great but you need to use Spring client. Hessian is good but it has known issues regarding the serialization of Hibernate objects in combination with lazily-initialized collections. The issue looks like being taken care of in Hessian 2. It is worth to take a look. If you want to ship xml across, burlap could be a good option.

Leave a comment Continue Reading →

Postgresql – Power of Array Type

Create 2 tables
Item(id) and Item_log(item_id, price)

Populate it
insert into item(id) values(1);
insert into item(id) values(2);
insert into item(id) values(3);
insert into item(id) values(4);

insert into item_log(item_id, price) values(1, 100);
insert into item_log(item_id, price) values(1, 100);
insert into item_log(item_id, price) values(1, 100);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(1, 200);
insert into item_log(item_id, price) values(2, 200);
insert into item_log(item_id, price) values(2, 200);

Run SQL
SELECT COUNT(il.price), i.id AS item_id, il.price
FROM item i, item_log il
WHERE i.id = il.item_id GROUP BY il.price, i.id;

Result
count | item_id | price
——-+———+——-
3 | 1 | 100
6 | 1 | 200
2 | 2 | 200

Run SQL
SELECT COUNT(il.price), i.id AS item_id, il.price, array_accum(il.id) AS item_id_array
FROM item i, item_log il
WHERE i.id = il.item_id
GROUP BY il.price, i.id;

Result
count | item_id | price | item_id_array
——-+———+——-+—————
3 | 1 | 100 | {1,2,3}
6 | 1 | 200 | {4,5,6,7,8,9}
2 | 2 | 200 | {10,11}

Leave a comment Continue Reading →

Unit test your layered architecture

Unit test is to test the logic of a class with its dependencies mocked. To do that, here are the best practices I used when I test classes in different layers of my project.

Use TestNG

TestNG is a replacement for JUnit. It “fixes” many of the issues with JUnit, and we will use it as our primary testing framework.

Get it work with Eclipse:

  1. Select menu Help->Software Updates->Find and Install.
  2. Select Search for New Features to Install
  3. New remote site.
  4. Enter and use TestNG for the description URL http://beust.com/eclipse in the URL
  5. Make sure the check box next to http://beust.com/eclipse is checked and click Next.
  6. Write your test under src/test/java with the same package name as the corresponding class you are trying to test. Name your test XXXTest. XXX = the class name of the subject class you are testing.
  7. To run this class, Right click it in Package Explorer and select Run As-> TestNG test. Your test should run successfully.

import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.*;

public class CalculatorTest {

 private Calculator calculator;
 
 @BeforeSuite protected void setUp() throws Exception {
  calculator = new Calculator();
 }

 @AfterSuite protected void tearDown() throws Exception {
  calculator = null;
 }

 @Test() public void testAdd() {
   int results = calculator.add(1, 1);
   assertEquals(2, results);
  
 }

 @Test() public void testMultiply() {
   int results = calculator.multiply(1, 1);
   assertEquals(1, results);
 }

}

TestNG has the following advantages over JUnit (Detail here)

  • Test class doesn’t extend any unit testing framework code like ”extends TestCase” and force you to name your test methods in a certain way. Instead, it uses annotation to achieve the goal. (eg. @BeforeClass/@AfterClass, @BeforeMethod/@AfterMethod, @BeforeSuite/@AfterSuite, @BeforeTest/@AfterTest, @Test, @DataProvider, @Factory).
  • For TestNG configuration, edit testng.xml file.
  • TestNG doesn’t reinstantiate your class for each test method as JUnit does. No repeat setUp and tearDown method calls. And you no longer need static field to carry state across test methods.
  • TestNG introduces test group.

@Test (groups = {“functest”})

  • Support dependency testing - if method A test is failed, there is no point to test B.

@Test (dependsOnMethods = {“verifyLogIn”})

  • Test expected exception

@Test (expectedExceptions = NumberFormatException.class})

  • Fail and rerun – TestNG will write the failed test case in testng-failed.xml and next time just rerun the failed one – save time!
  • Parametric testing – In JUnit, if you had 10 different parameter combinations to test a method, you would be forced to write 10 test cases. In TestNG, you can define one test case and then push your desired parameter patterns (for example) into TestNG’s suite files. However, I still prefer to use different method names to capture the corner cases as different inputs may give different behaviors for a method.
  • Test thread safety. The power of TestNG comes from its support of thread safety test!!

@Test(invocationCount=1000, threadPoolSize=10, timeOut=10000)
public void cachePut()
{
     m_cache.put(“foo”, “bar”);
}

Test Spring MVC Controller

Traditionally, testing J2EE Web components has been a more difficult task than testing standalone Java objects because Web components must run in some form of the server platform and they are coupled to the specifics of the HTTP-based Web interaction. To make it easy, Spring provides a mock implementation for each key interface from the Web side. Here I just list out the most common use ones:

  • MockHttpServletRequest – You most likely will find a use for this class in every single one of your unit tests. It is the mock implementation of the most frequently used interface in J2EE Web applications: HttpServletRequest.
  • MockHttpServletResponse – Use this object for mock implementations of the HttpServletResponse interface.
  • MockHttpSession – This is another frequently used mock object. (This article will review use of this class for session-bound processing later.)
  • MockServletConfig – This is a mock implementation of the ServletConfig interface. Unit testing some Web components, such as the ones the Struts framework supplies, requires you to set the ServletConfig and ServletContext interfaces implemented by MockServletContext.

On the other hand, you can make your unit test spring-aware via:

  • AbstractDependencyInjectionSpringContextTests – This is a superclass for tests, depending on the Spring context.
  • AbstractSpringContextTests – This is a superclass for all JUnit test cases using a Spring context, and as such, it is not intended to be used directly. You will most likely end up using either AbstractDependencyInjectionSpringContextTests or subclasses of AbstractTransactionalSpringContextTests.
  • AbstractTransactionalSpringContextTests – This is a superclass for all the tests that should occur in a transaction but that will normally roll the transaction back upon the completion of each test. You need to override onSetUpInTransaction and onTearDownInTransaction to manually initiate and/or commit the transaction (for instance, to flush the Hibernate session).
  • AbstractTransactionalDataSourceSpringContextTests – This is a subclass of AbstractTransactionalSpringContextTests that is geared towards the use of the Spring’s JDBC-based jdbcTemplate convenience class.

Follow the link below to find out how to test the Spring MVC classes.

http://www.devx.com/Java/Article/30067/0/page/2

Test DAO Layer

Before writing any tests for the Data Access Layer, we should consider the following things:

  • Do we want to hit the database at all or should we mock out the database communication API?
  • If we have to hit the database, do we want to hit the real production version of the database or do we want to hit an in-memory lightweight database?

The answer is that it is too much of work to test just the interaction between dao and database. And It is much more meaningful to have the test hits the database to exercise the schema, stored procedure and more. For the 2nd question above, I would have each developer has his own db instance running locally and the database should be the same as the one we use in production. This way we can avoid sql compatibility issue related to using in-memory database like hsql instead. On top of it, if you can make sure the schema version is in sync with your code during test automatically, it will eliminate lots of headache down the road.

http://www.buunguyen.net/blog/unit-testing-the-data-access-layer.html

Write integration test in Service Layer

http://www.infoq.com/articles/testing-in-spring

Leave a comment Continue Reading →

Spring MVC – Part 1

Introduction of Spring MVC

I have heard that Spring MVC is cleaner and well-design than Struts 1.x. I found it no surprise as Spring already wins the heart of most J2EE developers like us. I decide to take a look at Spring MVC and see how I can logically map my concept from Struts to Spring MVC. After I go through the framework, I feel that they are pretty close logically. However, the code I write in Spring MVC gives 2 main advantages: Portable and Testable.

The request flow of Spring MVC

  1. The Client requests for a Resource in the Web Application.
  2. The Spring Front Controller, which is implemented as a Servlet (DispatcherServlet), will intercept the Request and then will try to find out the appropriate Handler Mappings.
  3. The Handle Mappings is used to map a request from the Client to its Controller object by browsing over the various Controllers defined in the Configuration file. With the help of Handler Adapters, the Dispatcher Servlet will dispatch the Request to the Controller.
  4. The Controller processes the Client Request and returns the Model and the View in the form of ModelAndView object back to the Front Controller.
  5. The Front Controller then tries to resolve the actual View (which may be Jsp, Velocity or Free marker) by consulting the View Resolver object.
  6. Then the selected View is rendered back to the Client.

springmvc1.JPG

How Spring MVC renders the response?

In controller:

View pdfView =Map modelData = new HashMap(); ModelAndView mv1 = new ModelAndView(pdfView, modelData); OR ModelAndView mv1 = new ModelAndView("myView", someData); //pass string for logical view name

In configuration ([dispatcher-servlet-name]-servlet.xml) :

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"><value>/WEB-INF/</value></property> <property name="suffix"><value>.jsp</value></property> </bean>

Note: If we put the resolver above in the configuration xml, myView.jsp in the WEB-INF folder will be used to render the view. One of the dis-advantage of using Internal Resource View Resolver is that the name of the View file (whether it is a Jsp File or the Pdf File) must be present in the Web Application Context.

<bean id="beanNameResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean id = "myView" class = "MyPdfGenerator"/>

Note: If we use BeanNameViewResolver, the framework will search for a bean name "myView" to render the response. MyPdfGenerator could extend AbstractPdfView, so the view would be dynamically generated in pdf.

Why Spring MVC is more portable?

The Struts design is based on concrete inheritance, meaning that each custom action has to be in an inheritance hierarchy of the Struts Action component. Because Spring controllers are interfaces, any component can play the role of the controller. This gives application designers more flexibility in the design of components. At the framework component level, Struts requires use of Struts-specific objects, such as Form Beans (static or dynamic), Actions, Action Mappings, Action Forwards, and Request Processors. Spring MVC is more flexible, as all its major components are defined as interfaces. "Design by interface" makes MVC code less coupled with the framework.

Why Spring MVC is more testable?

public void final testGettingToDetails throws Exception{ MyController myController = new MyController(); myController.setDetailsView( detailsViewName ); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setMethod("POST"); request.addParameter("viewDetails", "true"); ModelAndView modelAndView = myController.handleRequest(request, response); assertEquals("Incorrect view name", detailsViewName, modelAndView.getViewName()); }

You can find the detail of how to unit test your spring mvc code here

Migrate from Struts to Spring MVC?

  1. Action -> Controller
  2. ActionForm -> POJO (request maps directly to POJO!)
  3. ActionForward -> ModelAndView
  4. struts.xml -> Spring bean definition xml (by default: [dispatcher-name]-servlet.xml)

Reference

http://spring.javabeat.net/articles/2007/06/spring-mvc-web-framework-introduction/

Leave a comment Continue Reading →