Monday, July 18, 2016

Spring MVC UTF-8

Key points


Maven pom.xml:

   <%@ page language="java" pageEncoding="UTF-8"%>
  <%@ page contentType="text/html;charset=UTF-8" %>

Friday, June 17, 2016

Compile xsl files and store in cache to improve XSLT performance

Common code found online to do XSLT transformation. (removed non essential pieces for brevity)

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(new File(xsltPath)));
transformer.transform(new StreamSource(new File(sourceFilePath)), new StreamResult(new File(resultPath)));

The code works. But if a xslt file is relatively big and  
needs to be used over and over again to transform 
a lot of files, for example, in the batch mode, 
it may not perform well. 

The following shows a way to cache the compiled version of an xsl file, which is a 'Templates' object. This object is thread safe.

Code snippet to cache the 'Templates' object.

static final Map<String, Templates> cacheTemplates = new ConcurrentHashMap<String, Templates>();

       static TransformerFactory transformFactory = null;

       static {

     private static void init() {
         try {
             transformFactory =TransformerFactory.newInstance();
        catch(Exception e) {
            throw new RuntimeException(e);

     public static void cacheCompiled( String xsl) {
File file = null;
  StreamSource source= null;
                Templates  templates = null;
try {
file = new File( xsl);
source = new StreamSource(file);
                         templates = transformFactory.newTemplates(source); //create this once for a file, save in a cache.
cacheTemplates .put(xsl, templates );
} catch (Exception e) {
throw new RuntimeException(e);
} finally {

The above 'templates' object is basically a coompiled version of the original xsl file.  If the original file is relatively big, for example, 20KB, it takes more than 2 seconds on my local machine to transform a small file.  Without caching the templates, it takes more than 2 seconds every time.  With caching,  it takes about 0.1 seconds  for every transformation after the first time.

The basic code is like this:

//get the Templates object from cache based on the xsl file name, then get a Transformer object

Transformer transformer = templates.newTransformer();

transformer.transform(new StreamSource(new File(sourceFilePath)),
new StreamResult(new File(resultPath)));

The 'transformer' object mentioned above is not thread safe.

The SAXON parser seems becoming more popular, and the Xalan parser seems fading away.

The home edition of the SAXON parser, which is free, may be good enough for a lot of applications.

Friday, November 15, 2013

First impressions on open source ESBs

Used commercial ESB and BPMs for a couple of years, recently had a chance to evaluate some open source ESBs.

WSO2:  not easy to use, had difficulty even making the sample projects to work. No DataMapper tool, which is a big no-no to my projects.

Mulesoft ESB:  Nice documentation, instructions easy to follow, sample projects can be built and run in a couple of minutes, nice DataMapper tool in the 3.4 version.   Have not had a chance to build a relatively complex application using this.  Not sure whether the community edition is good enough to be used in the Production.

Monday, September 2, 2013

String getBytes could lead to difficult bugs

If you execute the following function,  what do you think should be the size of the 'def' byte array?

The logic is really simple: an input as byte array that have two elements, then create a string out of this with 'UTF-8' encoding, then create another byte array using this string with the same UTF-8 encoding.

public static void testStringUTF8() {
byte[] abc = new byte[2];
abc[0] = 31;
abc[1] = -117;

try {
String stringAbc = new String(abc, "UTF-8");
byte[] def = stringAbc.getBytes("UTF-8");
if (def != null) {
System.out.println("size of output byte array:" + def.length);  //print the array size

System.out.println(def[1]);  //print the second element of the output byte array

System.out.println(abc[1]); //print the second element of the input byte array

} catch (Exception e) {


Wednesday, April 11, 2012

How to invoke local EJB session beans in WebLogic

Sometimes you may have a need to invoke a LOCAL EJB session beans in a normal java class, for example, Business Delegate class, you can use ServiceLocator to locate a local EJB session bean proxy by JNDI name. Even though it is relatively easy to do so for a REMOTE EJB session bean by using the value of  'name' or 'mappedName' in the bean class definition, it is a little tricky for LOCAL session beans.

Here is what you need to do.

For exampe:

Here is an interface:


public interface PlayFacadeInf {
     public void play(String var);

Here is the implementation bean class.


public class  PlayFacadeImpl implements  PlayFacadeInf {
     public void play(String var) {
          // somthing

Here is the part of the ejb-jar.xml

display-name>myEJB </display-name>
<ejb-name> PlayFacadeImpl</ejb-name>

Here is part of web.xml


Here is part of the

private static InitialContext ctx = null;
static {
try {
ctx = new InitialContext();
catch (NamingException e) {
//... throw some exception

private static InitialContext getInitialContext() throws NamingException{
return ctx;

public static  PlayFacadeInf  getPlayFacade() throws NamingException {

PlayFacadeInf     playFacadeInf   = null;

playFacadeInf     = ( PlayFacadeInf )            

return  playFacadeInf;

Then any normal java class can use the ServiceLocator to get hold of the local ejb session bean proxy.

Sunday, February 13, 2011

JPA NoResultException marks transaction rollback in WebLogic 10.3.2

The weblogic 10.3.2 server comes with two jpa implementations: eclipselink (org.eclipse.persistence_1.0.0.0_1-2-0.jar) and openjpa (org.apache.openjpa_1.0.1.0_1-1-1-SNAPSHOT.jar).  By default, it uses the openjpa. But you can add “<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>” to the persistence.xml to use the eclipselink implementation. 

Both implementations do not handle “NoResultException” properly. The “NoResultException”thrown in a transaction would mark the transaction as rolledback, which violates the JPA specification.

Some sample code (using EJB 3) is as follows:
public class FacadeImpl implements FacadeInf {
                        DAOInf dAOInf;

                        public void findOrCreate(Long [] addressIds, PersonAddressData personAddressData) {
for (Long addressId: addressIds) {
try {
catch(Exception e) { //find failed, try to create something

public class DAOImpl implements DAOInf {

                        @PersistenceContext(unitName = "SampleJPA")
                        EntityManager em;

                        public Person findByAddress(Long addressId) {
                                                return (Person)em.createNamedQuery("someNamedQuery").getSingleResult();

In the above snippet,  if in the “for loop”, one invocation of “findByAddress” threw the “NoResultException”, the active transaction would be marked as rolledback, the “createInfo” in the “catch” block would not be able to accomplish anything. But if “@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)n the above snippet, if specification.edbackdd pselinkLogic 10.3.2
were not commented out, which means the “findByAddress” would run in a “NON transaction” context, in this case, even if the “find” function failed, the transaction could still continue, so the “createInfo” could be executed properly.

Most find functions (except findByPrimaryKey) in session bean DAOs should be marked as “Transaction NOT SUPPORTED” (@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)).

Wednesday, November 17, 2010

How to Fix Java POJO Annotations

POJO and Annotation are a big part of the java world nowadays.  Spring, EJB, JPA, Servlet,  JSF and other technologies are using annotated POJOs. The traditional definition is that a POJO is an ordinary Java Object, which means it has no dependency on any framework or container.   

But take a look at the following example:
import javax.ejb.*;

@Stateless(name = "Test11", mappedName = "")
public class Test11Bean implements Test11{
      private static final long serialVersionUID = -128L;

  protected TestSb testsb;

  public Double getCost(String name, String expedite) {
      return 0.0;
As we can see, without ejb related jar file in the classpath, this code would not compile at all. If we want to use this in a weblogic container eventually, we may add “TransactionTimeoutSeconds” and other weblogic kodo related annotations.  In this case, we need to have vendor-specific jar files in order to compile this class. 

I think some changes can be done to make it a traditionally-defined POJO.  Here is what I would do:
I would change the “import” to “@import” (or maybe another new keyword.) This will serve as a hint during the compilation, deployment and run times. During different stages (compilation, deployment and run), depending on whether the related jar files are in the classpath, different actions can be taken to generate different artifacts.

What are the benefits of doing this?
1.       Code can be reused more often.  Sometimes I want to use a JPA POJO entity class as a pure simple bean (like a data transfer object) in another project,  it would be possible if it did not have dependency on some jars.
2.       Could make the testing easier.