Thursday, December 26, 2013

Resolving duplicate collection reference with @NamedQuery

Considering a scenario where I have 2 tables, one table called user, the other table call authority. There is one-to-many relationship, which means each user could have multiple roles. Table below illustrate how this relationship is constructed in database.

Users table

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | NO   | PRI |         |       |
| password | varchar(32) | YES  |     | NULL    |       |
| enabled  | int(11)     | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

Authority table

+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| username  | varchar(10) | NO   | MUL | NULL    |       |
| authority | varchar(10) | NO   |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+ 
On Java site, each table is being mapped to the corresponding Java entity as illustrate below:

User entity

@NamedQuery(
 name="findByUser",
 query="select u from User u join u.roleList r where r.userId = :username ")
@Entity
@Table(name="users")
public class User {
 ...

 @OneToMany(targetEntity = Role.class, cascade = {CascadeType.ALL})
 @JoinColumn(name="username")
 private List roleList;

 ...

Role entity

@Entity
@Table(name="authority")
public class Role {
 ...
With this setup, I don't see any defect in the first run because the test data are a combination of one user pair with one role. The problem comes only when there is one user pair with two roles, I notice that the roleList will contain duplicate data. To prove my statement, I did some scanning on the data retrieve from the query.
  ...

  User theUser = emf.createEntityManager().createNamedQuery("findByUser", User.class).setParameter("username", username).getSingleResult();
  System.out.println(theUser.getRoleList());
  ...
Code snippet above shows that theUser.getRoleList() is having duplicate data as it is showing the same memory location [org.huahsin.Role@1b332d22, org.huahsin.Role@1b332d22] in the console. This problem is due to the Authority table is missing primary key. Add a primary key into Authority table will fix this problem. A lesson learn, whenever working with JPA, it is best to have the primary key declare in database to allow JPA to have a clear view on the relationship.

Wednesday, December 25, 2013

Evolving query from database to JAVA

Last time if I want to make a query through Session interface, I will invoke createQuery as shown below:
session = getSession();
Query query = session.createQuery(“from org.huahsin.Book”);
List<Book> booklist = query.list();
This way I only tackle for one single table. Somehow this need to work together with Hibernate mapping file. If the mapping file is missing, error would be seen like this

org.hibernate.hql.ast.QuerySyntaxException: Book is not mapped [from Book]

If I someone that could standalone without any dependency on Hibernate mapping, createSQLQuery would be a great help. This API is so friendly that it could allow me invoke a native SQL query and also able to tackle for multiple tables free of charge. So nice.
session = getSession();
Query query = session.createSQLQuery(“select ... from ...”);
But free thing doesn't mean good quality, some time this could be (very) error prone. Besides that, there is also another problem when retrieving the result set, it is so horrible. See code below.
for( Object row : query.list() ) {
 Object[] col = (Object[]) row;
    
 System.out.println((String)col[0]);
 System.out.println((String)col[1]);
 ...
}
Be cautious when working with the code snippet above because I have to ensure I'll never run out of array bounds and make sure I know which col index I'm working with. Since the retrieve object are Object type, I have no idea which type I should cast (String or BigDecimal), sometimes could easily lead to ClassCastException error.

Fortunately, software engineering is evolving, and it wouldn't just stop in that way. A better resolution has come into picture - Java Persistence Architecture. With this new technology, I'm not require to create XML mapping and retain my work in POJO, just that some new element has been introduce. For example, as the sample shown below, I need to declare which table does this POJO interact with? And how the column is being map on which field? In this case the User POJO class is map to users table, and the username field is the primary key corresponding to what have been declare in that table.
@Entity
@Table(name="users")
public class User {

 @Id
 private String username;

 ...
}
This is what have been declared in users table:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | NO   | PRI |         |       |
...
...
+----------+-------------+------+-----+---------+-------+
When making a query, @NamedQuery come into play, and this is how the query being configure, just right at the top of the POJO class.
@NamedQuery(
 name="findByUser",
 query="select u from User u where u.username = :username ")
@Entity
@Table(name="users")
public class User {
 ...
To invoke this query, follow this way:
 List<users> userList;
 userList = emf.createEntityManager().createNamedQuery("findByUser", User.class).setParameter("username", username).getResultList();
 ...
Something to note when working with this method, I've gone through the pain due to my mistake when I first using it.
  1. The query is almost similar to SQL syntax, just that there are base on object entity, not the one declare in database.
  2. When something was not right in the query, error could be seen immediately after the web app is loaded. This is what they called fail-fast, never wait for error happen only when it is invoke.

Implementing a test stub pattern

First thing first, I don’t create this pattern. I got this idea when I was reading the unit testing strategy from this blog. I like this test pattern because the codes were so clean and very object oriented style. (Before this my unit test code were very messy just like spaghetti). This way, I can easily isolate my mock code into a standalone stub class without messing up with real method.

Before I start using this pattern, let’s see how this pattern could fit into my project. I pick reporting template module for this experiment, which is my favourite module because this module is like a Sergeant who able to tackle different type of reporting problem. The UML diagram below shows the real design on the report template module.

In order to utilize its reporting service, one must inherit HibernateReportService because this class was declare as abstract, and it is the only interface that has contact to the outside world, and all the initialization work are done through the constructor. The query method is the only entry point that could allow customizes query selection in order to complete the reporting job. Code snippet below shows its use:
public class MyReportService extends HibernateReportService<Object> {

    public MyReportService(...) {
        ...
    }

    protected void query() {
        ...
    }

}
There would be a difference when come to initializing the report template unit testing work. As according to the design, I don’t inherit HibernateReportServiceStubber from HibernateReportService, whereas I make a generic template of HibernateReportService type. This idea was great as it allow me to isolate the mock code or fake implementation without messing up with the real implementation in HibernateReportService. Code snippet below showing the primary piece that makes up this stub class:
public class HibernateReportServiceStubber<T extends HibernateReportService<Object>> {

 private T daoReportService;

 public HibernateReportServiceStubber(T daoService) throws Exception {
  
  // capture the DAO that going to be test
  this.daoReportService = PowerMockito.spy(daoService);
 }
 
 public T getReportService() {
  return this.daoReportService;
 }

 // more mock method down the road
} 
Here come to the unit test guy. TheReportingServiceTest is the guy that takes up responsibility to execute the test. Again this guy doesn’t inherit from HibernateReportServiceStubber but he instantiate it and execute the fake implementation provided from the stub class. Below is the sample of his hard work:
public class TheReportingServiceTest {

 private HibernateReportServiceStubber<MyReportService> reportServiceStubber;
 
 @Before
 public void setUp() throws Exception {
  reportServiceStubber = getHibernateReportService();
 }

 private HibernateReportServiceStubber<MyReportService> getHibernateReportService() throws Exception {
  return new HibernateReportServiceStubber<MyReportService>(new MyReportService (...));
 }

 @Test
 public void test(){
  reportServiceStubber.mockCodeA();
  reportServiceStubber.mockCodeB();

  ...
 }

} 
At the end of this experiment, I feel that I'm actually running a behavioural test more than running unit testing on each single detail function/method.

Return a mock value when an object is being spy

My objective is to develop a test stub that will return me a true value whenever the following method is invoked.
public class ReportService {

    protected boolean readInRawReport(Vector inputFileNameList) {
        boolean found = true;

        for( String inputFileName : inputFileNameList ) {
        ...
        ...
    }
    ...
    return found;
}
I was unit testing the code snippet above using the stub code shown below, unfortunately the test was failed due to NullPointerException happened on inputFileNameList.
public class HibernateReportServiceStubber<T extends HibernateReportService<Object>> {

 private T daoReportService;

 public void readInRawReportReturnTrue() throws Exception {
  PowerMockito.when(this.daoReportService, PowerMockito.method(ReportService.class, "readInRawReport"))
  .withArguments(Mockito.any(Vector.class))
  .thenReturn(true);
 }

 ...
}

This is not supposed to happen when an object is being mock. During the investigation, I found it interesting when I’m tracing the code in debug mode, the code were actually flow into the real method, and inputFileNameList is showing NULL. My first question to myself is why do I need to bother the details implementation since I’m doing mocking? Is that mean Mockito.any() not doing his job? But later I found out I'm actually spying the test object, not mocking. Opps... To prove my justification is correct, I make some changes on the code like this:
  Vector<String> v = new Vector<String>();
  v.add("ASD");

  PowerMockito.when(this.daoReportService, PowerMockito.method(ReportService.class, "readInRawReport"))
  .withArguments(v)
  .thenReturn(true);

Now I can see inputFileNameList is having one element which shows ASD in it. The return value has nothing to do with thenReturn() and this function were totally disabled because the control has already been transfer into the hand of the real method when the test object is being spy. I wonder whether is this the right way to do this? Fortunately, I was so lucky that I manage to find the right way to do this. Thank God. Here is the correct solution on mocking the return value when a test object is being spy is shown below:
  PowerMockito.doReturn(true)
  .when(this.daoReportService, PowerMockito.method(ReportService.class, "readInRawReport"))
  .withArguments(Mockito.any(Vector.class));
This was like an English grammar, tweak from active sentence to a passive sentence.

Wednesday, December 18, 2013

Performing unit test on non-public method with PowerMockito

Recently I’m running a series of unit testing on my own works. I found out that it is quite difficult for me because my code consists of abstract classes, protected fields and protected methods. I’ve been using Java Reflection on this issue before I found the solution on PowerMockito. Somehow, I find it easier to implement it using PowerMockito due to the number of LOC is smaller and also it is much more expensive as I read in this post.

Here is the details implementation on accessing private method through PowerMockito.
objectUnderTest = PowerMockito.spy(new TheRealImplementation());

PowerMockito.doNothing()
            .when(objectUnderTest, PowerMockito.method(TheTargetClass.class, "thePrivateMethod"))
            .withNoArguments();

Assuming TheRealImplementation class is as shown below:
public class TheRealImplementation {

    private void thePrivateMethod() {
        ...
        ...
    }
    ...
}

getDeclareMethod(String, Class...) never accept null

At one day I was playing around with unit test using Java Reflection. I found it interesting when I pass in null as shown in code snippet below, a warning would be seen in Eclipse IDE.
private Method funcA;

funcA = TheClassA.class.getDeclaredMethod("funcA", null);
funcA.setAccessible(true);
Here is the warning message being shown on Eclipse IDE.
The argument of type null should explicitly be cast to Class<?>[] for the invocation of the varargs method getDeclaredMethod(String, Class<?>...) from type Class<TheTargetClass>. It could alternatively be cast to Class<?> for a varargs invocation
May be I have overlooked on the getDeclaredMethod’s declaration, as it shows:

Method java.lang.Class.getDeclaredMethod(String name, Class... parameterTypes)


The second argument is accepting a class type rather than an object. On top of that, it is a variable number of argument lists. Thus it is still acceptable if I do this.


funcA = TheClassA.class.getDeclaredMethod("funA");

Alternate way of connecting log4j to database

There is always difference between production server and development server at local PC. Take for an example on the audit trail module, this module provides audit service to an application. And this service will redirect the log4j logging activity to a database rather than storing logs to a file. The codes in SVN will always adhere to the configuration on production server, and this is how log4j configuration looks like:
log4j.appender.SEC = org.huahsin.JDBCConnectionPoolAppender
log4j.appender.SEC.jndiName = jdbc/myDatasource
If I don’t have the data source being configure at my local server (I’m using WebSphere Application Server Liberty Profile), executing that code will cause the server complaining this error:
[err] javax.naming.NameNotFoundException: jdbc/myDatasource
[err]     at com.ibm.ws.jndi.internal.ContextNode.lookup(ContextNode.java:242)
[err]     at [internal classes]
This isn’t that bad actually, if I insist choose not to configure data source at my local server, following changes need to be done in log4j configuration file:
log4j.appender.SEC=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.SEC.URL=jdbc:informix-sqli://xxx.xxx.xxx.xxx:2020/csdb:INFORMIXSERVER=online
log4j.appender.SEC.driver=com.informix.jdbc.IfxDriver
log4j.appender.SEC.user=xxx
log4j.appender.SEC.password=xxx

Monday, December 9, 2013

Compile GLUT with Cygwin required Cygwin/X X Server

Great news for today. I have resolved the problem which occured in the pass few weeks ago. This  note will be the follow up on the problem occured in previous note published in Revisit Opengl With Glut on Linux. I have an OpenGL program develop with GLUT using Eclipse IDE on Windows box. Somehow the EXE doesn't work due to the following error:

This application failed to start because cygwin1.dll was not found. Re-installing the application may fix this problem.

The missing cygwin1.dll is actually located under <CYGWIN_HOME/lib> folder. This error could be resolved easily by putting this path into the environment variable. This is Windows's SOP. After this, there is another error come in complaining that:

freeglut (PROGRAM_NAME): failed to open display ''

This error is a bit tricky. It was due to the Cygwin/X X Server was not install. Ensure the xinit package has install in cygwin, after that launch cygwin terminal, and then type this command startxwin to launch the X Terminal. Then only the EXE can be run. I did try to execute the EXE after xinit package has installed, and also did try executing it under cygwin terminal, but still failed. I think this is due to the EXE was compiled using cygwin compiler, its dependencies will also depends on X Server library, thus causing the EXE must run on top of Cygwin/X X Server.

To prove my statement, I run the same piece of code using VS Express 2012 and the EXE works like charm.

3D drawing tool for programmer

Not long ago, I dropped a question on which of the 3D characters drawing tools that is easy for programmer. I don't want it to be so complex or fantastic artwork, just enough for me to present the basic look and feel game character in the game. I want it to be able to render in all graphics card as well as the integrated graphic chip on the board. This is what I get from the expert:
  1. Wings 3D
  2. Blender
  3. MakeHuman

Sunday, December 1, 2013

Revisit OpenGL with GLUT on Linux

Remember in year 2002, the time I begin my game programming journey. The first thing I learn to program OpenGL during that time is Win32, and because I'm running on Windows machine, Win32 is the perfect option I started with Windows programming. Today, I'm revisit the OpenGL code on Linux, unfortunately Win32 is not runnable on Linux. What am I suppose to do next?

I discover that it's still doable with GLUT library. One thing that impress me is the code has nearly chop off 70% LOC just on the windows creation. Code snippet below showing the basic code framework done on GLUT:
int main(int argc, char **argv)
 glutInit(&argc, argv);
 //Simple buffer
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB );
 glutInitWindowPosition(50,25);
 glutInitWindowSize(500,250);
 glutCreateWindow("Green window");
 glutMainLoop();
}
Comparing with the code done on Win32, it is bloody disaster. I didn't show the code in this post because it is bloody long, it is reachable at NeHe's link. There are variation on the GLUT setup, Windows and Linux. On Linux, the require files are reachable through the Linux repository of my choice, and the header files always located at /usr/header, and library files located at /usr/lib.

Whereas on Windows, there is a litter tricky, and very dependent on compiler choice. I have try 3 of the compilers which there are Cygwin, MinGW, and VS 2012 Express. I failed to make it run on Cygwin and MinGW due to proprietary DLL file was missing during run-time. Luckily it is workable on VS 2012 Express. I got a bad news initially when working on VS where the Microsoft SDK doesn't come with GLUT library, it has to be download separately. I was so lucky that I found this link that drive me all the from setup till running the program. One thing to note is that I'm running Windows8 machine, putting the glut32.dll under C:\windows\system32 will not going to work, it has to be put under C:\windows\SysWOW64.

In conclusion, Linux is always the best choice for developer because it is a development box at the beginning with header and library files ready set aside on the path.