Tuesday, December 25, 2012

prngd can be resolve with apr package with AIX v5.2

Ever wonder how AIX is going to look like? Thank GOD I was given a chance to interact with this alien. My task is to install subversion package into AIX, I was lucky that this alien know rpm, otherwise I have no idea how to continue the installation without using apt-get or yum. The installation process never get easy, I have to resolve the dependencies one by one. rpm really help me out in this situation where this command will list out the dependencies required when the particular dependency package isn't there.
At one point when I was installing apr package (which is one of the Subversion dependency), it prompt me an error complaining that prngd wasn't install.
# rpm -ivh apr-1.4.6-1.aix5.1.ppc.rpm
error: failed dependencies:
        prngd is needed by apr-1.4.6-1
        AIX-rpm < 5.2.0.0 is needed by apr-1.4.6-1
The documentation has stated clearly that prngd is required only in AIX v5.1 but mine is AIX v7.1, why this happen? Googling around couldn't find any solution, until I found the AIX open source packages, just download the latest version of apr, which is apr-1.4.6-1.aix5.2.ppc.rpm and install it to give it a try. And the solution is:

It works!

Tuesday, December 11, 2012

Don't extract gz file with tar command.

Usually when I unzip tar.gz file, I use this command: tar -zxvf file1.tar.gzBut this time is a gz file, tar command doesn't work that way. I tried gunzip, the file is extracted but the content gone weird. Then I try gzip -d file1.log.gz, check on the content, it looks perfect.

Monday, December 10, 2012

Spring-security 3.x doesn't work well with spring 2.x

Now only I spot that in my pom.xml file contain spring.jar is version 2 whereas the rest of the Spring component are version 3 and above. No wonder I have this error shown in the Eclipse console:

Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.getLocalName(Lorg/w3c/dom/Node;)Ljava/lang/String;
 at org.springframework.security.config.SecurityNamespaceHandler.parse(SecurityNamespaceHandler.java:71)
 at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
 at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
 at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
 at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
 at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
 at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
 ... 43 more

Found a related problem from StackOverflow. It is either upgrade spring.jar version or remove it.

Sunday, December 9, 2012

Don't flush a session after an exception occurs

Few days ago, the team and I was running a performance test using JMeter, and found this error happen during the test. I was seeing this error from the log:

ERROR 2012-12-06 16:00:43,721 [ModuleABoImpl:2626]- [Unable to Finish Calculation for record ID 11223344]
    org.hibernate.AssertionFailure: null id in org.huahsin.moduleA.model.PojoA entry (don't flush the Session after an exception occurs)

...
...
[ERROR   ] Non-atomic batch failure.  The batch was submitted, but at least one exception occurred on an individual member of the batch. Use getNextException() to retrieve the exceptions for specific batched elements.
[ERROR   ] Error for batch element #0: One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by "1" constrains table "TableSpaceA.ModuleATable" from having duplicate values for the index key
...
...
[ERROR   ] an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)


It seems that the web app not able to handle concurrent access on the data, and took us very long hours effort to figure out the root cause. We revert the code, do a few round testing, and we found that the particular table, ModuleATable must have a primary key column define in the table. This column doesn't serve any purpose but just to resolve this problem.

Initially I was though that Hibernate have cause the problem, but eventually it is not. Experience learned is that I need to think out from a box every time looking at a problem.

Sorting 2 columns in an Pojo class

When I was about to off, there is one late change requirement which need to be done before next day morning. User want the data to be sort rather than just leave it wild. Not there yet, the sort criteria has to be done on two columns. Graphic below shows the work need to be done. Take note that null value must be in the first place.



I know this could be done by using the sort method from Collections class, but my experience is only on one column sort, but I'm not sure whether the sort method is smart enough to handle my requirement. My logic thinking shows that if Column A is sorted, then I further sort on column B. In the same time I was thinking to write a custom bubble sort to cater for this requirement, but it was already late night. Without further thinking, I choose to challenge sort method (>.<*), and I come out this code:
public void sorting(ArrayList< mypojo > theList) {
  
  Collections.sort(theList, new Comparator< mypojo >(){

    @Override
    public int compare(MyPojo o1, MyPojo o2) {
    
      if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) < 0 ) {
        return -1;
      }
      else if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) == 0 ) {
        if( o1.getColumnB() == null || o2.getColumnB() == null ) {
          return 1;
        }
        else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) < 0 ) {
          return -1;
        }
        else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) > 0 ) {
          return 1;
        }
        else {
          return 0;
        }
      }
      else {
        return 1;
      }
    }
  });
}

And it works like charm. :o)

Saturday, December 8, 2012

My future in C++


I have been watching this video for the fifth time. I never get bore with this video as I was really inspired by Herb Sutter to continue my journey in C++. Remember last time I made up my mind to discontinue MSVC++ 6.0 journey as Microsoft has change the nature behavior of C++ since the launch of .NET. 

Now Microsoft has bring back the C++11 standard, a more organize foundation has been setup (isocpp.org) which is a single platform to get all news about C++ (Herb Sutter's blog used to be my main reference last time) and now I can even write C++ code for Windows Phone device. This could be my second device which allowing me to write C++ code beside Samsung Bada device.

There are so much fun in C++ now, I'm so excited about it. "The C++ King Is Back! Hold The King."

Sunday, December 2, 2012

The relationship between Serialization and Inheritance

There is no method defined in Serializable interface. It is just a marker interface that marked on a class that it support serialization. It is also important to know that ObjectOutputStream can write both objects and primitive types, as it implement ObjectInput and DataInput interfaces. The serielization mechanism will follow object references and write whole hierarchies of objects. However, if any superclass of an object is not serializable, then the normal object creation using constructor is call, start from the very first non-serializable superclass, all the way up to the Object class.

A code is worth a thousand nonsense:
public class Person {

   private String name;
 
   Person() {
      System.out.println("Person constructor is called.");
   }

   ...
}

public class Student extends Person implements Serializable {

  private static final long serialVersionUID = 8306482247141552618L;

  public Student(String name, long ID) {
    super(name);
    this.ID = ID;
  }
  ...
}

The code shows that Person class is not implement Serializable whereas Student class did. By the time during the deserialization happened to Student object, the default constructor of Person class is called. Thus "Person constructor is called" will output in the console.
FileInputStream inputFile = new FileInputStream("saveObject");
ObjectInputStream inputStream = new ObjectInputStream(inputFile);
  
Student student = (Student) inputStream.readObject();

Customizing Serialization in JAVA

Take a look at this program. If I try to compile this, the compiler will throw NoSerializableException.
public class Unicycle implements Serializable {

 private static final long serialVersionUID = 3843396491741625744L;

 private Wheel wheel;
 
 public Unicycle( Wheel wheel ) { 
  this.wheel = wheel; 
 }
 
 public String toString() {
  return "Unicycle with " + wheel;
 }
}

public class Wheel {

 private static final long serialVersionUID = -8786651610841969855L;

 private int wheelSize;
 
 public Wheel( int ws ) { 
  wheelSize = ws; 
 }
 
 public String toString() { 
  return "wheel size: " + wheelSize; 
 }
}

public class Main {

 public static void main(String args[]) throws IOException, ClassNotFoundException {

  Main main = new Main();
  
  main.writeData();
  main.readData();
 }
 
 public void writeData() throws IOException {
  
  FileOutputStream outputFile = new FileOutputStream("storage.dat");
  ObjectOutputStream outputStream = new ObjectOutputStream(outputFile);
  
  Wheel wheel = new Wheel(65);
  Unicycle uc = new Unicycle(wheel);
  
  System.out.println("Before writing: " + uc);
  
  outputStream.writeObject(uc);
  outputStream.flush();
  outputStream.close();
 }
 
 public void readData() throws IOException, ClassNotFoundException {
  
  FileInputStream inputFile = new FileInputStream("storage.dat");
  ObjectInputStream inputStream = new ObjectInputStream(inputFile);
  
  Unicycle uc = (Unicycle) inputStream.readObject();
  
  System.out.println("After reading: " + uc);
  
  inputStream.close();
 }

}

Perform 2 tasks in order to get this fix:
  1. The Wheel class has to be declared as transient in Unicycle class. (Note)
  2. Implement private void writeObject(ObjectOutputStream) and private void readObject(ObjectInputStream) in Unicycle class.
Note that these 2 methods isn't part of any interface, and accessible by the JVM even though it is declared as private. Below is the sample code of Unicycle class that implement these 2 methods:
public class Unicycle implements Serializable {
 ...

 transient private Wheel wheel;

 private void writeObject(ObjectOutputStream oos) {
  try {
   oos.defaultWriteObject();
   oos.writeInt(wheel.getWheelSize());
  }
  catch( IOException e ) {
   e.printStackTrace();
  }
 }
 
 private void readObject(ObjectInputStream ois) {
  try {
   ois.defaultReadObject();
   int wheelSize = ois.readInt();
   wheel = new Wheel(wheelSize);
  }
  catch( IOException e ) {
   e.printStackTrace();
  }
  catch( ClassNotFoundException e ) {
   e.printStackTrace();
  }
 }
}

This is what JAVA called Customizing Serialization.

rsync is a very good tool for backup

Before starting my Fedora upgrade, I am required to backup my /home directory before unexpected thing happened to my code. Last time I used the most stupid by copying the whole directory from one hard disk to another, now I am smart, I use rsync. A very friendly command I found in this article and this article.

Since I'm doing it at my local PC, basically the syntax is like this:
rsync -av --exclude 'rubbish' --exclude 'Downloads' \
/home/kokhoe /media/external_disk/home/kokhoe
The command above will backup my /home directory except for rubbish and Downloads directories.

Wednesday, November 28, 2012

Create new user account in SVN

Just a reminder to myself. In order to create a new user in SVN, I'm require to use following command like this:

htpasswd -m < path-to-svn-auth-file > stupid

The above code will create a new user, stupid, after this a new password for this user account will be prompt. The stupid user account can be spot easily by opening the file because the user name is not encrypt but the password is encrypted.

I been doing this for few thousand time since early of this year, but I still couldn't remember such a simple command. When the new server has arrive, I need to configure this for the whole department. I need to be prepare to myself.

Good luck and sigh~

Monday, November 26, 2012

Playing cheat code in Jasper iReport

where 1=1 $P!{Parameter_value}, this code is so beautiful.

I learned a trick on how could I handle false condition on dynamic SQL generation in Jasper iReport. In a conditional SQL select statement, result set is return only if the condition is true, otherwise I'll see nothing. Usually this is what I did everyday.

Now I have a weird requirement, if the condition is not match (meaning false), I still want to see the result set without the condition. That can be done, but my way, no way, so much ugly. Until I meet where 1=1 $P!{Parameter_value}, this guy did a very good job in keeping the code clean. I like this guy, a very smart guy.

I suppose to put the condition validation of a select statement in the where clause, but I take it out instead. Giving an order to Jasper to hold this value for me, say Parameter_value. Now I append 1=1 at the end of the where clause, become this where 1=1. The first time I see this code I though it was a joke because this query will always return a valid result set.

Magic happened when I append $P!{Parameter_value} after where 1=1. Jasper will always compile the Parameter then only compile the whole query statement. If the condition given in $P!{Parameter_value} is valid, then the result set with conditional validation is returned. If the condition given in $P!{Parameter_value} is invalid, then query will become where 1=1, with an empty string at the end, and since 1 always equals to 1, thus it will just return anything without the conditional validation.

This code is like playing cheat, I love it, and like it.

Friday, November 23, 2012

Dirty work to speed up WAS Liberty Profile

When Websphere Application Server Liberty Profile, aka WAS Liberty Profile is first launch, I was really get attracted by its light weight Servlet container. After 3 months of using it in my new project, I found following point.
  1. The start up time is fast because of the JSP compiled classes, JAVA compiled classes, and other resources is not loaded inside the container. Since it is nothing inside the container that's why it is fast.
  2. The run-time is very slow because it needs time to load all the resources and compiled classes before the web app is render on browser. If looking at how Tomcat is work, it will load all the resources during the server start up. 
  3. During the clean process, WAS Liberty Profile took less than 0.0001 sec whereas Tomcat took some time (more than 1 sec) to clean. This could be means that WAS Liberty Profile don't store old cache after server has been stop whereas Tomcat still storing it.
  4. Another thing I have spot on WAS Liberty Profile is that once the web app is loaded at first time, the subsequent load time will back to normal. I think this could be means that once it is load, a copy is cached in client site, but not server side.
There are too many assumption made by myself, don't take it serious, all of them are nonsense. Back to the question, there are actually people out there is making some good work to speed up the server. But it is not document in WAS Liberty Profile documentation, do it at my own risk.

Append this code at the end of Servlet.xml file, and then restart the server.

Wednesday, November 21, 2012

To amend the commit message on SVN under Windows

Another concern on using SVN as source version control is when programmer did something wrong with the commit message. In order to allow amendment on the commit message, I am required to have pre-revprop-change hook script ready.

Doing it in Windows always have extra steps. Save a copy of this pre-revprop-change template file locate under the /hooks directory into .bat extension, replace the code with the one I got from this article. What a nice and clean code.

@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

Done with first step, now come to second step, is to edit the commit message or adding a commit message. If the commit message is already there, use this command to remote access the SVN server to modify the commit message.
svn propedit --revprop -r 25 svn:log \
http://128.230.9.166/svn/trunk/TheJava.java "Update a commit message." \
--editor-cmd notepad.exe
This is to tell SVN that I'm going to update the commit message on revision 25 where the particular file is located at http://128.230.9.166/svn/trunk/ directory using notepad as editor.

If --editor-cmd is not provided, this will assume that the SVN_EDITOR environment variable has been set, otherwise an error will be prompt "None of the environment variables SVN_EDITOR, VISUAL or EDITOR are set...".

If the commit message isn't there, then use this command to add a new commit message.
svn propset -r 25 --revprop svn:log \
"new log message" http://128.230.9.166/svn/trunk/TheJava.java

This is to tell SVN that I'm going to add a new commit message on revision 25 where the particular file is located at http://128.230.9.166/svn/trunk/ directory

Tuesday, November 20, 2012

Setup SVN pre-commit hook script under Windows

It has been so long for me to have this feature to be ready before a project start since long long time ago. I'm talking about SVN under Windows environment. I would like to have a feature when the code is submit, the server will first verify whether the comment is empty. If it is, block them from commit the code.

There has been a time where I feel so frustrated on my team member who never put any comment on their code end up giving me a hard time to trace back their code. And feel so stupid that digging down each revision changes to open up each file to verify and review their code. But I do not have such luxury time for me to do this setup. Until this week, the UAT is sign-off, I take up the opportunity to continue my work.

There is a template code with a filename, pre-commit.tmpl is ready for use locate inside the directory /hooks, but never got a chance to execute it because the code is for *NIX and not for Windows. I am required modify the code provided from this article in order to get it work under Windows.


@echo off
:: Stops commits that don't include a log message of at least 6 characters.      
@echo off

setlocal

rem Subversion sends through the repository path and transaction id
set REPOS=%1
set TXN=%2        

svnlook log %REPOS% -t %TXN% | findstr ...... > nul
if %errorlevel% gtr 0 (goto err) else exit 0

:err
echo --------------------------------------------------------------------------- 1>&2
echo Your commit has been blocked because it didn't include a log message. 1>&2
echo Do the commit again, this time with a log message that describes your changes. 1>&2
echo --------------------------------------------------------------------------- 1>&2
exit 1

There are few thing I need to take note of:
  1. The pre-commit file must be saved as bat or exe file extension.
  2. The pre-commit file must locate under the /hooks directory.
  3. Remember to restart the svn server service when done these changes.

Sunday, November 18, 2012

Successfully install Syntax Highlighter into my Blogger

Cheers. Finally I have successfully configure Syntax Highlighter into my blogger. Thanks to Scott Meyers's post on how this could be done and I really appreciate his effort on posting it up.

Before this, I did try to install Syntax Highlighter from Google code but failed to configure it. Then I tried snipt.net, but this one is a bit slow and cumbersome because I need to edit it somewhere then post it back here. What if their server gone down, or their services has gone? That's why I so keen to Syntax Highlighter because of its functions are self-contained. Meaning I no more require to edit some where and post a link here.

With this post from One Q, One A blog, things is much more easier. It really goes into a level where I don't need my brain to do the configuration. And the most annoying one is transforming angle bracket '<' and '>', I use this tool called Encode/Decode HTML Entities to handle this for me.

Below is my experiment usage of Syntax Highlighter on XHTML code:
  1. I put my code right under the compose mode inside the Blogger. (Before this I have already encode those HTML entities.)
  2. Define a xhtml brush in HTML mode in the beginning of the code, like this: <pre class="brush:xhtml;">
  3. Put this </pre> at the end of the code.
Sample Output
<h:form id="theForm">
  <h:commandLink id="tri_HiddenEvent" value="Trigger Hidden Event" onclick="triggerHiddenEvent(); return false;"/>
      
  <p style="display:none">
    <h:commandLink id="hiddenCommand" styleClass="button" action="#{helloBean.doHiddenCommand}">
      <f:ajax execute="@form"/>
    </h:commandLink>
  </p>
      
  <ui:remove>f:ajax doesn't support inputHidden</ui:remove>
<h:form>
There are a lot more brushes available for all kind of code in this manual. Enjoy blogging.

Emulating IE9 through JSF PhaseListener

I need to emulate my JSF page to behave like IE9 although I'm using IE7. I know that in order to achieve this I must have the following meta tag to be include in my client code, like this:

<meta http-equiv="X-UA-Compatible" content="IE=9">

There is a source mention this should be done using JSF PhaseListener. By adopting that solution, I have this code:

I have tested the above code and its working fine. The code will actually emulate all pages in IE9 in the particular webapp and I have no intention to limit its implementation to a particular page. Anyhow this could be done using this solution.

Oh yah... Before I forgot, I need to register my custom made phase listener class in faces-config.xml file in this way, otherwise it wouldn't work.

JSF doesn't recognize '&' symbol in JavaScript

I don't know there is something I should take note of when using JavaScript in JSF. I found this is interesting to share out when using && operator in JavaScript like this:


This will create an error in JSF because JSF unable to interpret ampersand symbol. To fix this problem, I must not use ampersand symbol. And replace it with this & amp;& amp; in order to make JSF happier.

Saturday, November 17, 2012

My CPU is ready for virtualization

I own an i5 CPU. Just did a quick check on my CPU whether it support for virtualization. Sent out this command egrep '^flags.*(vmx|svm)' /proc/cpuinfo to my computer and I got this bunch of nonsense:

flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid
This means that my CPU is ready for virtualization, otherwise it wouldn't print anything.

I can't sudo yum-complete-transaction in Fedora

I use to be a fans of Ubuntu because of its convenient and ease of use. To execute a command with root privileged in a rush, just do the following:

sudo yum-complete-transaction

But I don't know how to do this in Fedora. Thus I need to separate the command by execute su first, then only yum-complete-transaction. I did tried on other command with sudo but only this one failed.

Just curious why yum-complete-transaction can't work with sudo?

Thursday, November 15, 2012

Fedora 16 has an unfinished transaction?

I was doing an update in Fedora 16, but the process isn't complete and throw me a weird message.
There are unfinished transactions remaining. Please run yum-complete-transaction as root.
Not sure what is happening, just follow the given instruction and there is a bunch of nonsense as shown below is thrown to me. After this command execution, everything went normal. What a fun?!!

Tuesday, November 13, 2012

select 1 row from a table in DB

In Oracle, I do this:

select * from table where rownum = 1;

In DB2, I do this:

select * from table fetch first 1 row only;

In Informix, I do this:

select first 1 * from table;

Conclusion: To master SQL, don't think it is easy.

Saturday, November 10, 2012

JavaScript is platform dependant

I am feeling so bad on this issue, but I have no choice. When requirement come into my hand, I must get it done. Majority of my development was done on IE, and the initial requirement was targeted on IE as well. When requirement change request to target on other browser like Firefox, Safari, Google Chrome, and Opera, I am required to get the job done as well.

Initially I though everything should be fine, but eventually it is not where the unload event doesn't support in Firefox. Some suggest me that I should use onbeforeunload in Firefox. I had tried it and it's really work. Below is the code snippet on how this could be done.

Here I made the 2nd mistake, once I put in the code snippet, and I forgot to remove this code unload="onUnload()" from body tag. This end up the page sending the request twice to the server during unload event. Thus it is advisable to take it out if the code snippet exists.

But one bad news is Opera doesn't support onunload and onbeforeunload at all.

Dirty way to handle browser close action in JSF

There is a requirement where I need to do some update in the backing bean before exit the browser. Unfortunately JSF doesn't have such event handling for me. Googling around doesn't seems much help, thus I choose to use the dirty way by simulating a click event to trigger the function called in backing bean when unload event is invoke.

Here is the code:


  1. Put a commandLink in hidden form and execute the click simulation in JavaScript when page is unload.
  2. When the unload event is invoked, click event is triggered, and doCloseProcess will get trigger.
  3. Update the necessary stuff there then done.

Handling close event in Firefox and Safari.

My last week was a nightmare. The problem on handling close event in Firefox and Safari is the most tricky code I had ever encounter in my life.

I was trying simulate a click event in JavaScript by doing this:

Interestingly this is working find in IE except Firefox and Safari. Asking around in StackOverflow and I got this so called 'special handling' on Firefox and Safari. This piece of code is required in order to get the click event work and it is also support IE version greater than 8.

The right way of passing parameter in JSF

One day I was trying to pass a parameter from XHTML into the Backing Bean by doing this:


Asking around whether this is right or wrong and I was told that this isn't the right way. It suppose to be like this:

Sunday, October 28, 2012

Tomcat:run will cause backing bean target unreachable

The same piece of source code is working just fine without Maven but there is error whenever run running with maven goal tomcat:run.

/hello.xhtml @16,59 value="#{helloBean.name}": Target Unreachable, identifier 'helloBean' resolved to null

This appear that there is a backing bean called HelloBean is not being configure properly. But looking at the programming syntax, everything is just fine and perfect. See the piece below:

I just discover something from @alehro's answer in stackoverflow. That problem is actually referring to Jetty but surprisingly this is also apply to Tomcat. The workaround on this problem is to change the maven goal to tomcat:run-war.

Saturday, October 27, 2012

Accidently configure javax.servlet-api to compile scope

There is a mistake in maven configuration. Actually I am trying to run a maven build with this command install tomcat:run in maven goal. But maven lead me to this error:

java.lang.ClassCastException: javax.faces.webapp.FacesServlet cannot be cast to javax.servlet.Servlet

Guess what? I have mistakenly configure the javax.servlet-api to compile scope. Basically Tomcat has already provide this package, thus it is not require to deploy again. To fix this, just set the scope to provided and I am done.

JSF can only work with javax.servlet-api instead of servlet-api

Recently I come across this error when I am configuring maven for JSF development:

java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/webapp/FacesServlet

According to the answer given by BalusC in stackoverflow, he claim that:

"This problem is caused by having multiple FacesServlet class files of different versions in the runtime classpath, which in turn means that you've multiple JAR files containing the JSF API in the runtime classpath."

This give me a clue that I have did something wrong in the maven configuration. A quick spot on the maven configuration, I found out that I am using servlet-api package.

To get this fix, I replace servlet-api with javax.servlet-api.

Sunday, October 14, 2012

Exception throw when rendering JSF with JSP extension?

I didn't know that there could be an error when I am trying to render a JSF application with JSP extension.

I was running my Tomcat server. With JSF servlet mapping like this:


Suppose I should enter this URL http:// localhost:8080 / web6 / sample.jsf, and change the JSF extension to JSP, this could turn Tomcat server throwing an exception javax.servlet.jsp.JspException: Cannot find FacesContext:

Full stack trace:

Sunday, September 30, 2012

WAS Liberty Profile has a weird requirement

There is a weird requirement on using Websphere Application Server Liberty Profile where the workspace path must not have any space in the folder name, especially in Windows. This is apply to any WAS version.

This happen during the runtime mode where the server is started, and wait till the web is being loaded. Then there is a bunch of error complaining that the JARs in WEB-INF/lib are not found even though the path is correct.

I use to put my workspace right under my user account folder, say C:/Documents and Settings/huahsin68/workspace. This is due to the practice influence from Linux where my development path is like this /home/huahsin68/workspace.

Notice that I don't have any space in between the workspace path under Linux, no wonder I don't see any error in Linux.

Sunday, September 23, 2012

Finishing the LibreOffice build

This is the output when LibreOffice finished the built. It took less than 2 hours to make the build on an i5 + 8GB ram PC. Remember last time I was building it on a C2D + 2GB ram PC, it took more than 8 hours to complete the build.

Such a big difference.

Full stack trace of the build


gb_Deliver_deliver file was missing?

My intention is to make a partial build on accessibility module of LibreOffice, but end up an error being thrown by the compiler complaining the file gb_Deliver_deliver was missing.

I was consult that I am require to build all the pieces in LibreOffice before continue on the individual module. In other words, I need to do this:

./autogen.sh
make

Full stack trace of the build

LibreOffice compilation stop building at ridljar

The build was stop at ridljar module. And the compiler complaining that SSOExceptions.idl was missing. Why this happen? According to the fellow developers, this could happen when the source code is downloaded without making a clean build. In other words, to solve this problem, a clean build is a must whenever the source code were first check out.

Notice that the console output showing javac compile error, invalid jdk 1.7? That one must be solve by issuing following command before build.

Full stack trace of the build

Note on Tomahawk commandSortHeader usage.

I had a hard time on creating a sortable table using JSF Tomahawk in last week. After a long searching, try and error, it is not that hard actually.

From the existing t:dataTable code, wrap the column header with t:commandSortHeader and add two more properties, sortColumn and sortAscending, into t:dataTable, just like the code shown below.

Add two member variable into the backing bean and implement Comparable interface just like this:

Here are some notes on the usage:
  1. sortColumn property in t:dataTable indicate which column name that triggered the sort. The column name is reference from the columnName property of t:commandSortHeader.
  2. sortAscending property in t:dataTable indicate the particular column sort in ascending/descending order.
  3. The JAVA class, theBean, must implement Comparable interface in order to provide the sorting facility.
  4. In the sample code above, I only have one column to sort, thus the compare function only implement one sort. If there is more than one sort, simply expand the if-else statement.

Monday, September 17, 2012

Type Attribute "xmlns:h" must be declared for element type "html"


I get this error when I have the XHTML code ready just as simple as the code shown below and without the web.xml ready.


Sunday, September 2, 2012

Why I like Runnable more than Thread?

When creating a thread in JAVA, there are 2 reasons why I choose to implementing Runnable interface is more preferable than extending Thread class.

Reason 1
Extending Thread class will limit the subclass from extending other class.
Reason 2
I am just interest in Runnable class rather than extension of Thread class.

Sunday, August 26, 2012

Why JSF date always minus one day?

On last Wednesday, I was assigned a defect on a date issue. "Give me 1 hour to fix this." I answered to my supervisor. At the end of the day, my supervisor come to me, and I reply "The defect still haven't fix. =.=" ".

Here is the problem background. I have a JSF date input control. Whenever the form is submitted, the date value capture in the backing bean will becomes GST time zone, but my expectation is GMT time zone. Without doing a deep research on this will never know there is a design issue in JSF. JSF was using UTF as default time zone whereas I am using GMT time zone. To secure my date, I always have this code standing by:

Anyhow, the problem still has not fix. It took me another one day for the research. And finally I found a work around on this issue by setting the time zone in JVM server.

I was using WAS Liberty Profile server, how could I set the time zone in JVM?

WLP uses jvm.options file to specify additional start up option at the runtime. Its usage can be found in the README in wlp.install.dir. What I did was I put the jvm.options file in the same level as server.xml file, which is here -> {wlp.user.dir}/servers/.

In the jvm.options file, put this line and done.
-Duser.timezone=GMT

Monday, August 20, 2012

IllegalArgumentException cause by Serlvet mapping

Caused by: java.lang.IllegalArgumentException: Servlet mapping specifies an unknown servlet name board

This error is a real shock when I was first look at it. That's why I put it at the top most in this post. I get error during the start up of Tomcat server. I was using Maven build, initially I though it was cause by this code in pom.xml file:

But in fact it is not. Look closer on the error, it mention servlet name board. Then I though was this code cause the error in web.xml.

Something was flashing in my mind. Then only I realize that I was actually missing this code:

Guess what? Problem fixed. :o)

Sunday, August 19, 2012

JSF doesn't work well with Spring

On last week, I had been struggling on how could I integrate JSF and Spring together in a proper way. Since I am using JSF 2.0, I do know that I am required to have the following code to be place in faces-config.xml file:

< application >
  < variable-resolver > 
    org.springframework.web.jsf.DelegatingVariableResolver
  < /variable-resolver >
< /application >

And my authentication bean and main screen bean was declared using session scope (consider the following code), but I am still not able to show my welcome string in the page.

@ManagedBean(name= "authBean" )
@SessionScoped
public class Authentication {

   @ManagedProperty( value="authVo" )
   private User user;

   /** getter and setter of user **/
}

@ManagedBean(name= "authVo" )
@SessionScoped
public class User {
   
  private String logonUser;

  /** getter and setter of logonUser **/
}

@ManagedBean(name= "mainBean" )
@SessionScoped 
public class MainScreen {
 

   private String welcome = "Welcome to main screen";
   
   /** getter and setter of welcome **/
}

After a long searching on the root cause, I found this code in mainScreen.xhtml file cause the problem:

< h5 >
  You are currently logon as: 
  < h:outputText value= "#{authBean.authVo.logonUser}"/ >
</ h5 >
...
...
...
< h:outputText value= "#{mainBean.welcome}"/ >

If I remove the first outputText, the setter of MainScreen class will get invoked, welcome string is shown, otherwise it don't. Meaning that, if I invoke the authBean first, then I can only see the property of authBean, otherwise I will only see mainBean. Now I know that each screen can only have one bean associate with it. Does it really behave in that way when Spring integrate into JSF?

One of my colleague argue that it shouldn't happen in this way, since the Bean was already declared in session scope, it should be seen globally. But that one was JBoss Seam.

Anyhow there is still work around on this. I just need to follow the Spring way, which is the Spring IoC way, to retrieve the logonUser and showing welcome string.

In the mean time, I need to look into the magic of JBoss Seam.

Sunday, August 12, 2012

Maven + Eclipse = Amazing!

On last weekend, I am starting to use Maven for my home development. Before this it was very clumsy, every time when I building the project, it is very annoying that the compiler could not find the appropriate jar dependencies on this particular jar. By using Maven, the compiler no longer complaining on jar dependencies, rather it manage the dependencies for me.

When I first setting up Maven, I use to write XML code. To be frank, I don't really like this work because it took me a lot of effort to figure out the coordinate. To me, this is so much annoying. I don't care, just give me the latest version will do.

Thus I pass this job to Eclipse. BTW, I am just Linux version of Juno Eclipse in Fedora 17, there might be some different with previous version because I found out that the plugins tab in my Eclipse was missing, not really sure does it happen to previous version as well. My previous experience with Maven is editing the POM file without going through the UI, please forgive me on the laziness to find out the truth.

Lets move on. When open up the POM file, there is a dependencies tab. Clink on that there is a Add button in it. Click on that will bring up a dialog just shown as the picture below:

Notice that the top section consist of Group Id field, Artifact Id field, and Version field. Forget about this section unless you really sure what you need on a particular jar. Then the section right below is my favourite, it consist of a search key field and a search result. Just type in anything here, and Eclipse will find it for me. When there is a result, just double click on the entry, Eclipse will handle the coordinate for me.

This is the greatest part of using Maven in Eclipse. Once done editing on the POM file, save it, and Eclipse will trigger the download. This was amazing!!

Anyhow, I still need to update the build path although Eclipse have done the download. Don't get me wrong, I am not require to configure the project build path. I just type this command:

mvn eclipse:eclipse -Dwtpversion=2.0

Go to Eclipse, right click on the project > Maven > Update Project, and then say "I am Done!".

Tuesday, July 17, 2012

Nexus get time out error on Fedora 17

There was a weird error in Fedora 17 when I was trying to start up Nexus. I got this in my wrapper.log:

wrapper  | Startup failed: Timed out waiting for signal from JVM.
wrapper  | JVM did not exit on request, terminated
wrapper  | JVM exited on its own while waiting to kill the application.
wrapper  | JVM exited in response to signal SIGKILL (9).
wrapper  | Reloading Wrapper configuration...
wrapper  | Launching a JVM...

Basically this was telling me that my PC was heavy loaded until the JVM was not able to response in a short time. So how? To solve this issue, goto {nexus_root}/bin/jsw/conf/wrapper.conf, look for wrapper.startup.timeout, and increase the value.


At first I increase to 200, I still get the time out error. But at least I can see this in my log:


jvm 1    | -------------------------------------------------
jvm 1    |
jvm 1    | Initializing Nexus (OSS), Version 2.0.6
jvm 1    |
jvm 1    | -------------------------------------------------



Then I increase to 500, and I see this message:

jvm 1    | 2012-07-17 20:55:22.453:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8081




This message showing me that the nexus was successfully start-up. FYI, I am not running this in VM, I run this in a machine that make up of Intel i5 processor, 8GB ram, and Fedora 17 as host OS.

Saturday, June 23, 2012

Telling the web server to show my error message

My research on error page has been done. It was just as simple as by adding following code into web.xml:

< error-code >
   < exception-type > java.lang.Throwable <  exception-type >
   < location > /jsp/MyErrorPage.html < /location >
< /error-code >

The above pieces is to tell the server that whatever shit throwing out, just show MyErrorPage.html, and hiding the meaningless stack trace from users.

The hardest post I had ever write.

I have been writing this post for few times. And it has been review and revise for few times due to the post is too technical and not enough nonsense.

I was thinking whether this will only happen in Informix. I was trying to construct a dynamic SQL that create a trigger which will attach to a table. This could be a very long string, there are 2 candidates taking up this challenge, the varchar, max size is 255 bytes, and lvarchar, max size is 32k bytes.

This text is reference from IBM Informix:

For variable-length strings longer than 255 bytes, you can use the LVARCHAR data type, whose upper limit is 32,739 bytes, instead of VARCHAR. Because LVARCHAR is implemented as a built-in opaque data type, however, you cannot access LVARCHAR columns in distributed queries of remote tables.

Guess what, both of them failed in the test. It is due to the table contain too much fields(columns) in it. It just too long. I think we need a data architecture in our team to take care of this.

To work around this issue, I have to chop the string into portion end up a very ugly SQL code. The most bad code I had ever wrote in my life. Below are the sample code:

execute immediate "CREATE TRIGGER " || trigger_name || " UPDATE OF " || field_name || " ON " || table_name || " REFERENCING OLD as post NEW as pre FOR EACH ROW ( INSERT INTO ( " || shadow_table_name || " ) VALUES ( " || the_value || " )) "

Too bad.

Sunday, June 17, 2012

I feel the great prosperity in 2012

Feeling so great now. Reviewing my pass, it has been a tough time for me. Back to 2010 and 2011, it was a challenging time for me to change my career to be a mobile developer or to be a JAVA developer. Looking at the future of C++, most of the job are mainly focus on mediation work, which is to me, could be a rather boring.

To quickest way to choose my career path is do it together. How? I first started off to get some freelance job on mobile work to test my ability while maintaining my day job. This was a real challenge to me because I got no coding experience on mobile development, yet, my time management is a real sucks.

In the mean time, I start to discover JAVA programming. This is for my next career advancement. Again, this is another tough time for me. Basically I need to focus on 3 things:
  1. Mobile programming
  2. Java programming.
  3. Day job task assignment. (as I required to study C++ Boost programming)
There was a crash time in 2011, when I was in the midst of transitioning my skill from C++ to JAVA, where I need to pick up my skills in Spring and Hibernate while tackling problems in mobile development. Anyhow, I manage to overcome every single issues, thanks to the support from forum on mobile development, and great helps from my architect, Mr. Kah Wai, in boosting up my JAVA skills.

A big thank you to him because he teach me everything on JAVA, and now I am able to work independently and execute every JAVA tasks assigned to me. Since I have joined this company, I have been proposing to adopt some new JAVA technology into the development. I would like to emphasize that I don't know all this thing, just that I knew what need to be done, but I don't know how. I know because my architect told me a lot of issues happened in JAVA development. I really appreciate on the help from him.

Reaching to age 30, it is a next checkpoint on my destination. I am very clear that my direction is on JAVA. Not only that, I am also contributing my work to open source during my free time, and enjoying my hobby in the weekend.

Work life balance. Cheers~

Why @Required not working?

In order for @Required to function properly, even though I have the code below in place, but it still doesn't guarantee the code is working fine.

public class MyClass {
   private MyObject theObject;
   @Required
   public void setObject(MyObject theObject) {
      this.theObject = theObject;
   }
}

I have to put in extra code in the Spring configuration file in order to get it work.

In Spring configuration, the header must have this:

< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" />

After the header, put in this:

   < context:annotation-config />

Assuming code below exists in the Spring configuration file.

   < bean id="myClass" class="org.huahsin68.MyClass" >
      < !-- < property name="theObject" >
         < ref bean="theObject" /> -- >
      < /property >
   < /bean>

When the code is run, immediately the compiler will response this:

Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'theObject' is required for bean 'sequenceGenerator'

Sunday, June 10, 2012

Where the hell is jawaws?

In Fedora, the javaws wasn't install inside /bin directory. When I was trying to run a jnlp file in the terminal, I get this error:

jawaws: command is not found...

Where the hell does this program sit? I dig into the JDK directory and found out that this program was hiding inside the /bin folder. Why this program wasn't install into the /bin by default?

Saturday, June 9, 2012

2 types of Spring Configuration

There are 2 types of specification you can put in the beginning of the XML in Bean configuration file.

One is using Spring 2.0 DTD to import the valid structure of a bean configuration. Here is the sample how it look like at the top of the configuration file:

< !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd" >

< beans >
   ...
< /bean >

The other one is using XSD to define the valid structure of an XML bean configuration file.

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

Take noted.

Sunday, June 3, 2012

Consider it done! Soldier!

Working in corporate company will having a well known issue, which is the ranking issues. Senior staff will have more privilege to get the very own knowledge whereas lower ranking staff will usually hiding themselves. Why this happen? This is because it has been a culture in the company.

Who say I am not allow to voice out my opinion even though you are more senior than me? Like what happen in my previous company, I challenge my development manager and even the project manager. I took up the challenge because I am ready for it, I will work very hard on it, and be ready to any subsequence impact that might happen in it. Any nonsense, especially those senior staff bluffing at me, I don't care, I just keep moving forward.

I am trying to encourage my team to voice out their opinion, any feedback and critics. Like for example if you found out Birt is much more better than Jasper, go ahead to prove it, make a POC, present to the team, time needed for the implementation, etc.

Just show everything, bring up everything because I know you can. Don't be shy because it just an excuse to hide the problem. You are a very brave soldier, I honour you and salute you. This is the beginning of innovation, creative thinking, not afraid of failure, the team will not growth without these group of soldiers.

I don't care whether there is a glass door shielding the manager's cubicle or they don't. This is a sick culture. I want to change, by moving my first step, bring in the change, growth the team.


Take one more example, I just have 1 year working experience in JAVA, but my team lead very trust on me because I never failed to him. Compare to previous company, I am a very experience C++ programmer, but I am never a senior staff, my opinion in the team are sucks, rubbish, and nonsense. Did you realize the difference? One with many years working experience in C++ and another one is just one year experience in JAVA.


The point is never failed any thing, any tasks that has been assigned to you. "Consider it done! Soldier!" I have this mind set since last year, which is my first year in JAVA. I work very hard to solve every problems, I work non-stop, I work on weekend and public holiday, long working hours. It is a tired process, I know. But I never give up. Now I am acquired the technology and experiences I learned, that's why I never failed anything to my team lead in my current position.


Now is your turn, you have far more working experience in JAVA. Show yourself, soldiers! Let me honour you.

Sunday, May 27, 2012

Audit trail front end design

I need a centralise work on audit trail front end. I don't want each module to have their own audit trail layout format. Thus I make a generic bean that could store the result and publish it into a generic table that shows pre-data on the left and post-data on the right. Yes, this bean is playing the main role connecting the back-end and front-end.

Besides that, I need flexibility, and I don't want to change my core everytime you have new field introduce in the table. Thus I made another bean to represent that fields in each the table. Instead of table, I would rather say view because each audit trail module will have different representation of a module. e.g. claim module, payroll module, and etc.

Lets reveal the design.


I made an abstract audit header object, and an abstract audit content object. The purpose of making them abstract is to increase its flexibility design when interacting with controller class. Thus the controller class do not care about the type of audit, "I don't even want to know! Please leave me alone." Controller class says.

Each header must come with a content. At least one content. Thus I made a composition associate between audit header and audit content. How? By using the black diamond. I use composition (black diamond) instead of aggregation (white diamond) is because of my way of design. I want each audit must come together with at least a content, otherwise don't render this page.

I use generalization to realize the type of audit. As shown in the picture, the audit header and audit content is realize the claim audit.

If the content are ready to be distribute, the controller class will collect it and put it into a public access Bean object.

As shown in the diagram above, the controller class is the middle man who trigger the request and distribute to JSP page. In JSP page, user still have to tell what type of audit content should the controller class to retrieve.

Saturday, May 19, 2012

High level design of audit trail system

This is the high level architecture design of my audit trail system. Initially I though Hibernate Interceptor could be great help, but when I found out that we are using WAS datasource, there is no way for me to use that in our system. Thus, I need to think a way out. After few weeks of design, POC, and testing, finally I come out this design.



I though this is an audit trail system, but why the design look like a database log? I have this feeling at the design stage. If I make a database log, I understand that the IO transaction will gonna eat up the resources, but we need to judge what is the most important one? Resource cost how much? Data integrity cost how much. It has been a hard time for me to put this consideration when designing the system. Thus I decide to make both.

There are few pieces in this design.

  1. Parameter table - Allow owner to decide which table that gonna need to audit. Just register here and let the audit engine do the rest.
  2. Stored Procedure - The audit trail engine. It read information from parameter table on what is needed to audit, create trigger and tie up with the original table, spawn a new shadow table from original table.
  3. Trigger - Act as database logger.
  4. Shadow table - Contain pre and post data of original table.
  5. Audit trail table - The main table that tells the summary story of shadow table.
I use GUID as the key to link the data across shadow table, original table, and audit trail table together. The GUID was generated from JAVA every time a record is save/update/delete. I put this key together with the BEAN object so that the system know what/which does for each audit trail entry.

The whole thing was made up from 10% work on JAVA, 60% work on Dynamic SQL and 20% work on Stored Procedure. I try not to limit the design only for JAVA, thus a lot of consideration need to think of when designing this shit.

Practice make perfect.

Essay writing is fun and interesting. Remember when I was in primary school, I hate writing just because I am lazy. There was an article mention that if someone not able to write a good essay, this person will lacking of communication skills. Does it true? I don't know. But that is not the reason for me to start writing.

What actually motivate me to start writing is because I feel bore. When I am bore, I read book, after reading, I write down my comment on the reading. As I keep writing, I learn new, the English grammar, new vocabulary, writing style. I started to feel the joy of writing, and reading. And I start writing blog.

To write a good post, I have to keep on practice non stop. No one is number one when first born, keep on learning, practicing, read more, and explore all kind of reading will make someone perfect in writing.

Happy Saturday :o)

Sunday, May 13, 2012

JARs must sit inside WEB-INF/lib

I don't know whether Netbean have this kind of problem or this only happen to Eclipse IDE. Whenever there are jars that required to be link in the project, make sure all these jars are located under WEB-INF/lib folder. Although the build path has already been configure, or you don't even configure your project's build path, I don't care. I don't care whatever reason you have, always remember that you are wrong.

As long as the WEB-INF/lib contains the jars require, it just work. I strongly highlight this to those who are new in web development. Please jot it down!

Good luck.

Connection pool in Tomcat

I like discovery channel, especially on Sunday, I will turn into this channel to watch what are the exciting and interesting news is on the show. Hey! why don't I make my own discovery channel... in JAVA ;) This gonna be more fun and exciting. xD

My solution architect require us to change the JDBC connection to connection pool, how that could be done? So easy, by configuring the datasource name in hibernate. But how is the actual work done in server site? I have no idea because the database we are using is Informix and it is shield by the server admin.

In order for me to carry on the research, I decided to do it using Tomcat. When a new Tomcat server instance is created in Eclipse, look for the context.xml. Put in following code:

< Resource name="jdbc/mydb" auth = "Container" type = "javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="abcd" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/exercise" />

In web.xml, put following code:

< resource-ref >
      < description > DB Connection < /description >
      < res-ref-name > javax.sql.DataSource < /res-ref-name >
      < res-type > javax.sql.DataSource < /res-type >
      < res-auth > Container < /res-auth >
  < /resource-ref >

That's all about it. To test out the code, make a new JSP test page, put in following code.

1st piece of code is to make a query:
< sql:query var="rs" dataSource="jdbc/mydb" >
select FIRSTNAME from CONTACT

2nd piece of code is to render the output:
< c:forEach var="row" items="${rs.rows}" >
    Foo ${ row.FIRSTNAME }< br/ >
< /c:forEach >

Saturday, May 12, 2012

JDBC isn't a good solution for database programming

Now I realize that JDBC is not a good solution in writing a program that involve database because there are a lot of code need to be done. Basically I just copy and paste the redundant code and reuse back for other purpose. So a new idea coming out to hide this redundant code by creating a wrapper class.

Brilliant right? Not really because this only help a portion of my code. There are more tedious one following up next.

Another issue was I need to handle the association on my own. Meaning that when object_A is referencing object_B like the example shown below:

public class Object_A {
    public Object_B objB;
}

Object_A.Object_B.setFunction_A();
Object_A.Object_B.setFunction_B();
Object_A.Object_B.setFunction_C();
...
...


There are many more code I need to go if my table field consist of 20 fields. This is so terrible.

Sunday, May 6, 2012

Now I know JSP and Servlet can work together

I am going back to the basic. In web development, JAVA code and JSP code are two different thing. Then how JSP code and JAVA code link up together?

The picture above showing Servlet and JSP as separate entity




In order to link them up, we need web.xml. We tell the server once we receive an URL request that look like this:
http://< ip >:< port >/< project >/< path >
The Servlet object will be initialize and do its job. This is how we should instruct the servlet to do its job in the web.xml.
< servlet >
   < servlet-name >My Servlet< /servlet-name >
   < servlet-class >org.huahsin68.MyServlet< /servlet-class >
< /servlet >
< servlet-mapping >
   < servlet-name>My Servlet< /servlet-name >
   < url-pattern>/MyPath/*< /url-pattern>
< /servlet-mapping >
When someone enter http://< ip >:< port >/MyPath. MyServlet object will get execute, and process client's request in doGet() function. In doGet(), the JSP Page will get forward using following code:

req.getRequestDispatcher("/thePage.jsp").forward(req, res);

So, is this basic enough?

Internet is really a wasting time thing in my life.

Internet is really a wasting time thing in my life. It has been a long time I take myself off from the Facebook, after that I control on the chat program usage, and recently I started to control myself on the Internet usage. I started to realize that I have been abuse the usage of the Internet because every time I go online, first thing to do is to turn on the chat program, and then mail client, after that facebook, youtube, and read blog post. I've been feeling so lost and frustrate because there are tons of information pushing into my head. Thus I am thinking set up a security control to lock myself down.

Now I have my initiative to control on the Internet usage. When every time I want to use the Internet, I have a log book jotting down the objective of the Internet usage, and time of usage. For example now I'm writing my journey in this blog, it took about 15mins to complete, and 5mins on reviewing my sentence and English grammar checking.

Doing this will required self discipline, and I'm feeling so great that I could get out from the crowd.

Sunday, April 22, 2012

Hey! Do you what servlet do?

Basically what Servlet has conform to do is following:
  1. Create and initialize servlet.
  2. Handle zero or more servlet request from client.
  3. Destroy the Servlet.

Before I resign, I need a SCRUM!!

Scrum is about daily update on what you are currently working on, so that those stupid project manager will know what is the progress status of the project. Guess what, the stupid solution architect (SSA) also thinking the same way. They are basically misunderstood the concept of daily update.

Daily update is needed on everyday status check point, so that we all know what stopping you from code fast. "Why your code so slow today?" This is what I concern about daily update to the team. The point is what technology challenge you are currently facing? Your daily R&D output or weekend R&D output? Or you inspire by someone's technology that could speed up the development.

When we slowing down our development, usually they must be requirement not firm yet or we don't know how to code. Am I right? If requirement problem, lets talk to the BA, but if code problem, then it is ours team responsibility to help out this programmer. "Please share out why your code so slow today?" This is what SCRUM meeting comes in to play. It is about agile, very quick one.

The specialize programmer will be ready in this session, scream out your pain about your challenge! "Why SQL can't code in that way!" This is what I always complaining to the team.

Thus, before I resign because of SQL can't code in that way. Lets have a SCRUM. SQL specialize will be ready for me.

Happy coding :o)

Horizontal and Verticle development in my team

This is something about development practice to speed up development time (code faster), I learn this from Kah Wai, who is my architect in my previous job. Everyone of us are assign 2 projects at a time, one for delivery project, and the other for research project.

In terms of vertical development, it is about customer. We are focus on the customer requirement, from front end screen development till back end database development, it is one strict line from the top to bottom. It is strict forward, meeting delivery deadline, stressful, tired, no programming challenge. Just code!


Whereas in terms of horizontal development, it is about technical and technology. During the vertical development, we will come across on the technology challenge. Sometime this will stop a programmer moving forward to meet the delivery deadline. Hence we need someone who is expect and specialize in the particular technology area to support the team.

For me, I was an expert in Jasper, Selenium, and Web Service. It doesn't really matter whether I am a certified or not, just that it is my responsibility to build up the strength in those key area in the team. Thus when the developer show stopper on continuing his/her task on Jasper, then I will jump in to help his/her out. Same thing, when I stuck in the JSF development, someone will have to jump in to help me out.

This is what I am currently proposing to my team lead tomorrow.

Saturday, April 21, 2012

JAVA Scanner spice me up!

When I am doing C programming, I use a lot of scanf() to capture user input. First thing first, it is a lovely function. How about doing it in JAVA? Yes, there is a Scanner object. This is cool! This bring me up to the next inspiration in programming.

How can I do better in my job?

Ever wonder how can I do better in my job? Beside helping up the team, R&D support, programming tips, what else I can do? How can I bring my best service to the team, beside consulting their code? Should I code for them? Or inspire them to code hard?

Wednesday, April 4, 2012

Steps required to operate MySQL workbench

It has been so long that I didn't playing with MySQL workbench, it was about three weeks ago if I not mistaken. So stupid that I have forgotten the steps required to operate MySQL workbench.

Just a gently reminder, for all Fedora users, before MySQL workbench can connect to the database, the MySQL service must be start first. How?
  1. service mysqld start (must do this with root).
  2. start using MySQL workbench

Sunday, April 1, 2012

Feeling disappoint

I really feeling so disappointed to myself because I have totally stop studying open source. Now I am spending most of my time on JSP, chasing myself to learn more about web development beside JAVA. I think this is due to my time planning and development, beside coding skill, it is good to have some soft skill like time management skill to complete myself. I need to consider about that.

Good luck.

Sunday, March 4, 2012

I never had a though of web development.

Never think about web development is far more advance than my expectation. I am C programmer since 2003, I know C and C++ ins and outs, pretty well. When come to web, I only know yahoo.com. Never think about how to make something like yahoo.com, never think about JAVA, never think about JavaScript is so hard to learn, never think about dynamic web-page design, and never think about database.

Saturday, March 3, 2012

Only package JASPER file into JAR

According to stackoverflow. When package a JAVA program into JAR file, the common practice is to only CLASS file into the JAR. Same goes to jasper report, the common practice is to only package JASPER file into JAR instead of JRXML file.

Need more improvement to Android developer

Trying to search a good app for printing purpose for my tablet this morning. I found out that there are plenty of apps from android market but the quality isn't really that good if compare to iOS.

Part of the reason is that quality control on Apple is very strict, just like Bada, one of my app until now (since last year) still couldn't get approval from Samsung. Indirectly this give me an impression that Android app's quality is not up to the standard.

The quality issue could be partly due to the particular Android developer. They should take up the responsibility. I am a programmer too, when issue is in front of me, I will take the initiative to solve it as soon as possible. I can even skip lunch, stop facebook update, lock myself in a room, full time concentrate to the particular problem, fixed it, and deliver on time.

I think all developer (especially open source developer) should be self discipline in order to deliver a quality software. We can even compete with Enterprise software if the product is good in one day.

I do understand that there are developer very jealous to Apple, some of them even anti-Apple group. I do understand that Android developer have creative idea, without quality control, a creative idea is equivalent to rubbish at the end.

Lets learn together, lets improve together to bring up the open source community up to a quality standard. Good luck to all open source developer.

Sunday, February 26, 2012

Absolute Filters, Fuzzy Logic, Rumours

In the beginning stage of an investing process, is to select a stock. Selecting a stock is a very frustrating task to me because there are many factors I need to take into consideration. I found there are two common methods that people always do in selecting a stock: absolute filters, fuzzy logic, and rumours from newspaper.

Absolute filters is a process of screening through every stocks and filter out those stocks that doesn't meet your minimum requirement. For example, those stocks that have dividend yield more that 3% and growth rate over 15%.

Fuzzy Logic is to go through a list of interview question, such as the product, future development plan, any achievement base on the last three years track record. And then from that answer will be given a score. Those stock with high scores will be short-listed candidate into buy/sell list.

Rumours from newspaper always the last to know, and always miss out the golden opportunity to buy/sell. But don't few bad on it, some people usually overlook the opportunity that hide inside the newspaper.

Saturday, February 25, 2012

gnome-vfs is require for the compilation

There was an error when I issue the command ./autogen.sh when I was compiling LibreOffice where I couldn't find a compatible version of gnome-vfs package in Fedora 16. Below is the detail output of the error:
configure: error: Package requirements (gnome-vfs-2.0 >= 2.6.0 ) were not met:
No package 'gnome-vfs-2.0' found
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
Alternatively, you may set the environment variables GNOMEVFS_CFLAGS
and GNOMEVFS_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
According to developer guide, there are some dependencies are required before the compilation can begin. gnome-vfs is one of it. Here is the text of the solution:

sudo yum install gnome-vfs2-devel

The journey with Libre Office has began

My journey with Libre Office has began. Long long time ago, I was trying to start up a journey with Open Office. At the end we break off due to the lacking of documentation at the start up stage and the development speed was terrible slow.

Now I have continue my journey with Libre Office, hope it will bring me a wonderful and exciting journey.

Boredom and fascination

I just downloaded a book with title Think Complexity from greenteapress.com. When I was reading the preface section, I was trying to understand the motivation that drive him to wrote this book. He wrote this book is due to the reason of boredom and fascination.

When the message reached me, I translate it into this form: boredom of weekend, and fascination of the book. This is true. I love theory and prove, hope this book could greatly improve on my problem solving skills.

Sunday, February 19, 2012

Beware of case statement in Informix

I just realize there was a difference between Informix and Oracle when using case statement. Let's take a look at the sample code below:

select
   case
      when Col1 = 'A' then "Blank"
      when Col1 = 'B' then "Portfolio"
   end Channel
from table_A;

Need to be aware that the length of the Channel column will follow the value with longest length stored inside the particular column. Thus those values with shorter length will append with white-space at the end of the string.

In this case, the length of Portfolio is 9, then the length of Blank is 5, as a result, the actual string for blank is [Blank    ]. Do take note that if you want to do string comparison, you have to trim the string from Channel in order to get the actual string. If not, the result will always return false.

Good luck.