Thursday, November 01, 2012

Late Adopter's Guide To JSF


'The Late Adopter's Guide' is a short composition to help developers who are busy supporting legacy (e.g. JDK 1.4, EJB 2.1, Struts 1.x, JSP) Java technologies (like me!) that they have little time to try out newer stuff or there were technical limitations trying to introduce newer stuff into existing systems. But now you are itching to learn that one technology you've been craving all along.

This post will focus on JSF (Java Server Faces).

JSF isn't a new technology but was saddled with limited functionality in its early iterations. If it were not a part of the Java EE standard, it wouldn't have survived till today. Now at version 2.1, JSF is mature and now's a good time to pick it up.

There were lots of stuff happening since version 1 till 2.1. This guide will allow you to skip the noise and brings you to the goodness of 2.1 without getting bogged down by legacy issues e.g. adding Facelets support to JSF 1.x.

My recommendation of certain APIs over others is based on personal experience, so feel free to try out others if you are compelled to do so.

So, here are the pointers to smooth JSF-ing:

1) Use JSF 2.1 (and above)
Do not use a lower version of JSF. This will save you lots of heartache. If your system does not meet the minimal requirements for JSF 2.1, then it's better to stick with existing frameworks you're currently using (if it gets the job done, why not?).

JSF 2.1 requires Java 1.5 or later, JSP 2.1, JSTL 1.2 and a Java Servlet 2.5 implementation. Tomcat 6 or 7 is recommended.

Use the latest JSF 2.1 with all its new features i.e. Facelets, parameterized methods in EL

2) Use the Mojarra JSF distribution
It's the RI (reference implementation) and stable. You can try Apache MyFaces but the real gem of JSF is not really the framework, but the component libraries.

3) Use Facelets
Forget about JSPs, even though you'll be tempted to leverage on your existing JSP skills and tools e.g. JSTL, taglibs. Facelets are just XHTML pages which is quite similar to JSPs, except that it won't allow you to embed Java code using scriptlet tags (<% %>), and you'll have to learn the new EL (expression language) syntax which is not JSTL but is almost functionally the same. However, if you have JSTL or OGNL background, then EL will be a piece of cake for you.

Facelets also has in-build support for page templating, so there's no need for 3rd-party page templating libraries like SiteMesh.

4) Don't worry about JBoss EL
There was a buzz about JBoss EL, where it lets you pass parameters to a managed bean's methods (Why was it not included in earlier JSF version? I have no idea). These feature has been incorporated into JSF 2.1

5) Manage JSF Managed Beans via Spring
If you are an ardent Spring user, then it's recommended to use Spring to manage JSF's managed beans' dependencies. JSF's dependency injection framework is decent but you'll definitely miss Spring's more powerful and sophisticated features.

Or you can go CDI if you want to go standard Java EE.

6) Use a component library
The best thing about JSF is there are so many component libraries to choose from. RichFaces, OpenFaces, IceFaces, you name it.

But if you want to skip R&D and dive right into the action, I recommend to start with PrimeFaces. But chances are that if you are comfortable with a particular library, you won't be inclined to switch. Caveat emptor?

If you don't want to use a component library, you'll be missing most of the goodness that JSF has to offer.

You can use multiple component libraries in a single web application, but it would be messy and incur unnecessary overhead in memory.

Summary

Well, I hope this abridged guide is a good start for you to look in the right direction in learning JSF. Lots of good tutorials in the wild :)


Thursday, October 04, 2012

Springing to Spring's Defense

Lately there have been less Spring-related articles posted (or probably publicized). Some took it as a sign of decline in its popularity. What about the silent majority? Well, I believe that this bunch of people are not undecided, but are already happy saving the world from oblivion using Spring. Here's my story.

This blog entry's title is funny as in actual fact, Spring doesn't need any defending. It has been around since the early 2000s, when J2EE was exciting but full of teething issues. Ever since its introduction, the Java community has been gobbling every bit of goodness that came out of Rod Johnson's team. I can happily say that even though Spring has sort of 'matured' and may be daunting to a beginner, it still does one thing really well: IoC. Other Spring sub-projects are complements that build upon an already solid framework, which is really "true reuse" in action.

So, without further adieu, here's what I like about Spring that keeps me coming back to it:

1. Solid IoC Framework
This is worth repeating here. From the simple DTD to the flexible XML schemas and config annotations, the features for applying dependency injection made almost all hand-made singletons, factories unnecessary.

2. Great utility APIs
An example: JdbcTemplate made hand-coded DataSource-Connection-PreparedStatement-ResultSet (prone to connection leaks) code blocks obsolete. However using it doesn't require using the IoC container, which is great for refactoring legacy code without introducing drastic architectural changes. There are dozens more of such utility APIs that I won't elaborate here and leave it to the reader to explore.

3. Great 'glue' APIs
You like Struts, Quartz, Velocity, Freemarker, even Axis? How about JSF, Struts2, Hibernate or JPA? Spring has the integration code necessary for you to use a wide variety of other frameworks/APIs without attempting to supercede them. Spring even complements with its own offerings e.g. Spring MVC, Spring Web Services and Spring Security. You are not forced to accept the entire Spring stack. Just pick and choose.

4.Pick & Choose
Code-wise and even package-wise, Spring now comes in modules packed in different JAR files. The Spring developers wisely decided to abandon the "1 JAR to run them all" approach and let's the users include only the minimal JAR files required to use a specific feature.

5. Unit-Testing Support
EJB3 and above has better support that its predecessors but there's still no beating Spring with its support to run the IoC container outside of the application server. I use this feature everyday :)

Well, I'll stop here. I want to continue saving the world with Spring. Have a good day.

Friday, September 28, 2012

Turbo-charge your Android emulator for faster development


I came across an article, which claims to boost the Android emulator's performance using Intel's Hardware Accelerated Execution Manager (HAXM) driver. It got me excited and I decided to verify this claim. This blog entry is my story.

My tools:

  • Android SDK r20.0.3
  • Intellij Community Edition 11.1.3


Basically, the special 'enhancement' provided by Intel is a special x86 Atom system image which utilizes the HAXM driver that enables better emulator performance. I'll not repeat the technical details here, you can access the links below for more info.

Caveat: This trick only works on Intel hardware and with the Virtualization Technology for Directed I/O (VT-d) enabled (usually via BIOS).

Also, Intel x86 system images are currently (as of this blog posting) available for Android versions 2.3.3 (Gingerbread), 4.0.3 (ICD), and 4.1 (Jelly Bean) only.

To avoid headaches, set the environment variable ANDROID_SDK_HOME to point to your Android SDK root folder before proceeding.

High-level steps:
1. Download & install relevant packages via Android SDK Manager
2. Create Android Virtual Devices (AVD)
3. Create an Android Module project in IntelliJ CE
4. Test launching the Android application using the AVDs

1. Download relevant packages via Android SDK Manager

Launch the SDK Manager and ensure the following is installed:

  • Intel x86 Atom System Images (shown below is for Android 2.3.3)
  • Intel x86 Emulator Accelerator (HAXM)



Next, you'll need to install the HAXM driver manually. Go to the Android SDK root folder and navigate to extras\intel\Hardware_Accelerated_Execution_Manager. Execute file IntelHaxm.exe to install.

2. Create Android Virtual Devices (AVD)

Launch the AVD Manager and create 2 AVDs with the same options but different Target:

  • DefaultAVD233 - Android 2.3.3 - API Level 10
  • IntelAVD233 - Intel Atom x86 System Image (Intel Corporation) - API Level 10




3. Create an Android Module project in IntelliJ CE

In IntelliJ, create a new project of type "Android Module", as shown:



Under "Android SDK", select the appropriate Android platform. You'll need to point to your Android SDK root folder in order to choose the appropriate build target. As shown below, "Android 2.3.3" is chosen:



Ensure that the "Target Device" option is set to Emulator, then click "Finish" to complete the project creation.

4. Test launching the Android application using the AVDs

Ok, we'll test using the default Android 2.3.3 AVD first.

At the IntelliJ menubar, select "Run" > "Edit Configurations...". Go to the "Target Device" section. At the "Prefer Android Virtual Device" option, select "DefaultAVD233". Then Run the Android application. After a while, you should see the emulator window with the "Hello World" message.

To run with the Intel AVD, choose the "IntelAVD233" instead.

What's most exciting is the speed of the emulator launch (timed from clicking 'Run' in IntelliJ up to the 'Hello World' message is shown in the emulator). The rough timings recorded using my notebook (Intel i3 380M, 3GB RAM):

  • DefaultAVD233 - 1m 7s
  • IntelAVD233 - 35s


Wow, that's fast (~50% faster), without tuning other parameters to speed things up even further.

References:
http://www.developer.com/ws/android/development-tools/supercharge-your-android-emulator-speed-with-intel-emulation-technologies.html
http://software.intel.com/en-us/articles/installing-the-intel-atom-x86-system-image-for-android-emulator-add-on-from-the-android-sdk
http://stackoverflow.com/questions/1554099/slow-android-emulator
http://developer.android.com/sdk/index.html
http://www.jetbrains.com/idea/download/

Thursday, September 27, 2012

Embedding HSQLDB server instance in Spring

I was using XAMPP happily for development until I had to host it somewhere accessible via the Internet for the client to test and use. I have a VPS that only has 384 RAM, and needing to find a way fast, I decided to install XAMPP into the VPS. Because of the low RAM, when MySQL was running, Tomcat failed to start, even though the initial Java heap size was set to 64m. I managed to host the site temporarily in Jelastic, before moving to OpenShift.

I toyed with the idea of combining the database and application server instances in 1 JVM, to reduce RAM usage (compared to running MySQL + Tomcat). After searching the Internet, I came across several articles on running HSQL server instances together with Tomcat. No doubt I have to update my site to be compatible with HSQL first, but as a POC (proof-of-concept) attempt, I decided to explore the feasibility of running the HSQL server instance in a Spring container.

There are several reasons to run the HSQL server just like a bean in Spring:
1. All-in-one configuration. Everything that is needed to be configured is done in Spring. There are examples in the Net to run the HSQL instance alongside Tomcat, but this requires adding stuff to Tomcat (see links below).
2. Application server independence. 'Theoretically' (in quotes as I successfully tested this in Tomcat only), since everything is done in Spring, there's no or little that needs to be configured in the appserver.

The HSQL server 'bean' is also meant to launch an instance in network mode (not in-process e.g. mem or file). Some reasons for this:
1. 'mem' in-process access is the fastest, but is not persistent. There are other means to initiate a 'mem' data source using Spring's spring-jdbc tags, which is a better approach.
2. 'file' in-process access is persistent, but like 'mem', it can only be accessed within the Java process.
3. Network mode (hsql) is both persistent and accessible using external JDBC client tools. This is useful for troubleshooting and verification.

After reading HSQLDB's documentation, here's the code that does the HSQL server instance bean lifecycle management:

package org.gizmo.hsql.spring;

import java.io.IOException;
import java.util.Properties;

import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;

public class HyperSqlDbServer implements SmartLifecycle
{
 private final Logger logger = LoggerFactory.getLogger(HyperSqlDbServer.class);
 private HsqlProperties properties;
 private Server server;
 private boolean running = false;
 
 public HyperSqlDbServer(Properties props)
 {
  properties = new HsqlProperties(props);
 }
 
 @Override
 public boolean isRunning()
 {
  if(server != null)
   server.checkRunning(running);
  return running;
 }

 @Override
 public void start()
 {
  if(server == null)
  {
   logger.info("Starting HSQL server...");
   server = new Server();
   try
   {
    server.setProperties(properties);
    server.start();
    running = true;
   }
   catch(AclFormatException afe)
   {
    logger.error("Error starting HSQL server.", afe);
   }
   catch (IOException e)
   {
    logger.error("Error starting HSQL server.", e);
   }
  }
 }

 @Override
 public void stop()
 {
  logger.info("Stopping HSQL server...");
  if(server != null)
  {
   server.stop();
   running = false;
  }
 }

 @Override
 public int getPhase()
 {
  return 0;
 }

 @Override
 public boolean isAutoStartup()
 {
  return true;
 }

 @Override
 public void stop(Runnable runnable)
 {
  stop();
  runnable.run();
 }
}

The abridged Spring configuration:


<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <bean class="org.gizmo.hsql.spring.HyperSqlDbServer" id="hsqldb" init-method="start">
  <constructor-arg>
   <value>
    server.database.0=file:d:/hsqldb/demobase
    server.dbname.0=demobase
    server.remote_open=true
    hsqldb.reconfig_logging=false
   </value>
  </constructor-arg>
 </bean>
</beans>



Sample output when starting Spring in Tomcat:
[Server@1e893ae]: [Thread[pool-2-thread-1,5,main]]: checkRunning(false) entered
[Server@1e893ae]: [Thread[pool-2-thread-1,5,main]]: checkRunning(false) exited
[Server@1e893ae]: Initiating startup sequence...
[Server@1e893ae]: Server socket opened successfully in 7 ms.
Sep 27, 2012 9:26:23 AM org.hsqldb.persist.Logger logInfoEvent
INFO: checkpointClose start
Sep 27, 2012 9:26:23 AM org.hsqldb.persist.Logger logInfoEvent
INFO: checkpointClose end
[Server@1e893ae]: Database [index=0, id=0, db=file:d:/hsqldb/demo
base, alias=demobase] opened sucessfully in 442 ms.
[Server@1e893ae]: Startup sequence completed in 451 ms.
[Server@1e893ae]: 2012-09-27 09:26:23.395 HSQLDB server 2.2.8 is online on port 9001
[Server@1e893ae]: To close normally, connect and execute SHUTDOWN SQL
[Server@1e893ae]: From command line, use [Ctrl]+[C] to abort abruptly


References:

  • http://hsqldb.org/doc/2.0/guide/index.html
  • http://dkuntze.wordpress.com/2009/01/28/hsql-on-tomcat/
  • http://www.ibm.com/developerworks/data/library/techarticle/dm-0508bader/


Tuesday, September 18, 2012

Accessing Git Repositories using SSH behind HTTP proxy (Corkscrew, OpenSSH)


OpenShift uses SSH for its Git repositories. But at my workplace, where I need to use a HTTP proxy to access the Internet, getting TortoiseGit to connect to the Git repository seemed impossible. Out of the box, SSH can't be accessed via HTTP proxies. After vigorous searching using Google, I came across Corkscrew (http://www.agroman.net/corkscrew/README). Corkscrew enables tunnelling of TCP connections through HTTP/S proxy servers.

Since I am using Windows, and happen to use Cygwin (was required by OpenShift) and TortoiseGit, here's what I did to make it work:
1. Fire up Cygwin setup, searched for 'corkscrew', download packages
2. In my Cygwin home folder (default folder for SSH settings), open file ~\.ssh\config
3. Add/modify the ProxyCommand line (replace with your proxy IP and port) as shown in the example below:

Host *.rhcloud.com
  IdentityFile ~/.ssh/libra_id_rsa
  VerifyHostKeyDNS yes
  StrictHostKeyChecking no
  UserKnownHostsFile ~/.ssh/libra_known_hosts
  ProxyCommand /bin/corkscrew localhost 8118 %h %p

4. Open TortoiseGit's Settings window, go to Network. Check the 'Enable Proxy Server' option, and add the proxy IP and port values.
5. In the SSH client textbox, enter the path to the ssh.exe file e.g. C:\cygwin\bin\ssh.exe. This assumes that you are using OpenSSH in Cygwin. Click OK.

That's it, now you can access your Git repository via SSH behind a HTTP proxy!

Spring 3.1 - Loading Properties For XML Configuration From Database

Spring makes it easy to inject values obtained from properties files via its PropertyPlaceholderConfigurer and (pre-Spring 3.1) PropertySourcesPlaceholderConfigurer (Spring 3.1). These classes implement the BeanFactoryPostProcessor interface, which enables them to manipulate the values within the Spring XML configuration file before the beans are initialized. So if you specify ${jdbc.driverClassName} to be set to the property 'driverClassName', this variable will be replaced/swapped with the value with the key 'jdbc.driverClassName' in a properties file.

Apart from properties files, the database table can also be a place to get key-value pairs. Great, so just extend the PropertySourcesPlaceholderConfigurer, and have it read a table containing the key-value pairs, populate them and we're done!

However, there's a slight problem. If the DataSource bean also relies on values obtained from a properties file (e.g. JDBC URL, username, password), and being good Springers, inject this bean to the bean class extending PropertySourcesPlaceholderConfigurer, the bean container will fail to startup properly, because the 'jdbc.driverClassName' variable cannot be resolved. Strange, but true.

The reason for this is that any bean injected into a BeanFactoryPostProcessor class will trigger bean initialization BEFORE the BeanFactoryPostProcessor classes are run. You know, dependency injection...all depending beans have to be ready before being injected into the consumer. So this creates a cyclic-dependency kind of thing. All dependencies in the XML configuration are resolved first before the BeanFactoryPostProcessor classes are run.

So, how to go about this? Well, there's a trick you can employ. A BeanFactoryPostProcessor class has access to the ConfigurableListableBeanFactory object via the 'postProcessBeanFactory' method. From this object, you can do a 'getBean' and get a reference of any bean with an id. And guess what, you can get the vaunted DataSource bean without triggering premature bean initialization.

Let's say there's a table 'sys_param' with the following data:

 PARAM_CD        PARAM_VALUE  
 --------------  --------------
 service.charge  1.5          
 rebate.amount   15.99        
 smtp.ip         173.194.79.16

The DbPropertySourcesPlaceholderConfigurer is shown here:


package org.gizmo.labs.utils.spring;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

public class DbPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer
{
 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
 {
  DataSource dataSource = beanFactory.getBean(DataSource.class);
  DbProperties dbProps = new DbProperties(dataSource);
  
  setProperties(dbProps);
  super.postProcessBeanFactory(beanFactory);
 }
}



The DbProperties class will make use of the DataSource reference and queries the database to get the key-value pairs:


package org.gizmo.labs.utils.spring;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public class DbProperties extends Properties
{
 private final Logger logger = LoggerFactory.getLogger(DbProperties.class);
 private static final long serialVersionUID = 1L;

 public DbProperties(DataSource dataSource)
 {
  super();
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); 
  List> l = jdbcTemplate.queryForList("select param_cd, param_value from sys_param");
  
  for(Map m: l)
  {
   logger.debug("Loading from DB: [{}:{}]", m.get("PARAM_CD"), m.get("PARAM_VALUE"));
   setProperty((m.get("PARAM_CD")).toString(), (m.get("PARAM_VALUE")).toString());
  }
 }
}



To demonstrate that the values from the table are properly injected, here's the class which acts as the consumer:


package org.gizmo.labs.utils.spring;

import java.math.BigDecimal;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

public class DbPropConsumer implements InitializingBean
{
 private final Logger logger = LoggerFactory.getLogger(DbPropConsumer.class);

 private BigDecimal serviceCharge;
 private double rebateAmount;
 private String smtpIp;
 
 @Override
 public void afterPropertiesSet() throws Exception
 {
  logger.debug("I have consumed: {}", this);
 }

 public String toString()
 {
  return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
 } 
 
 public BigDecimal getServiceCharge() {
  return serviceCharge;
 }

 public void setServiceCharge(BigDecimal serviceCharge) {
  this.serviceCharge = serviceCharge;
 }

 public double getRebateAmount() {
  return rebateAmount;
 }

 public void setRebateAmount(double rebateAmount) {
  this.rebateAmount = rebateAmount;
 }

 public String getSmtpIp() {
  return smtpIp;
 }

 public void setSmtpIp(String smtpIp) {
  this.smtpIp = smtpIp;
 }

}


Last but not least, the Spring configuration (DataSource bean not shown, simplified for clarity):



<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
     <property name="order" value="1">
     <property name="locations">
      <list>
       <value>classpath:system.properties</value>
      </list>
     </property>
 </property></bean>

 <bean class="org.gizmo.labs.utils.spring.DbPropertySourcesPlaceholderConfigurer">
  <property name="order" value="2">
     <property name="placeholderPrefix" value="%{">
     <property name="placeholderSuffix" value="}">
 </property></property></property></bean>

 <bean class="org.gizmo.labs.utils.spring.DbPropConsumer" lazy-init="false">
  <property name="serviceCharge" value="%{service.charge}">
  <property name="rebateAmount" value="%{rebate.amount}">
  <property name="smtpIp" value="%{smtp.ip}">
 </property></property></property></bean>
</beans>



The first 2 bean definitions are the BeanFactoryPostProcessor classes, and to ensure the first one is run first, the 'order' property is set (lower means higher precedence).

For the DbPropertySourcesPlaceholderConfigurer, a different placeholder prefix and suffix is used for clarity (notice the placeholders for DbPropConsumer).

So, upon Spring container startup, you should be able to view a similar output as below:
2012-09-18 00:03:14, DEBUG, org.gizmo.labs.utils.spring.DbProperties, Loading from DB: [service.charge:1.5]
2012-09-18 00:03:14, DEBUG, org.gizmo.labs.utils.spring.DbProperties, Loading from DB: [rebate.amount:15.99]
2012-09-18 00:03:14, DEBUG, org.gizmo.labs.utils.spring.DbProperties, Loading from DB: [smtp.ip:173.194.79.16]

2012-09-18 00:03:14, DEBUG, org.gizmo.labs.utils.spring.DbPropConsumer, I have consumed: org.gizmo.labs.utils.spring.DbPropConsumer@189b939[
  logger=Logger[org.gizmo.labs.utils.spring.DbPropConsumer]
  serviceCharge=1.5
  rebateAmount=15.99
  smtpIp=173.194.79.16
]

Monday, September 17, 2012

MySQL 5.1 - Default Time Zone

This is the easiest way to set the default timezone in MySQL, after looking through the manual (http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html). I happen to use phpMyAdmin, an easy-to-use web UI to administer MySQL, and currently wildly popular with cloud database providers e.g. OpenShift, Jelastic and XeRound.

At the 'Home' of phpMyAdmin (I'm using version 3.5.2.2), select 'More' > 'Variables' from the top menu bar. You will be intimidated by the massive list of MySQL variables. Just type 'time' to filter the list and you should be able to find the time_zone variable (http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_time_zone) as shown:

Click 'Edit' and enter the desired timezone offset from UTC e.g. for Malaysia (MYT) is +8:00. By default, this time_zone variable is set to SYSTEM which means MySQL will take the timezone settings from the OS.

Changes to the time_zone variable is effective immediately. To test, just run a simple query e.g. SELECT NOW() FROM SOMETABLE