Monday, December 31, 2007

A Relaxing Weekend at Eco Friendly resort



As 2007 comes to the end, we decided to go for a short weekend break at a highly recommended Eco Friendly Resort - Rumah Rehat Adeline in Gopeng, Perak. This 'Resort' which we discovered over the Internet looked just like what we are looking for ... a cheap and idyllic place to spend the holiday. This place is in a natural setting, offers only basic amenities and is a 2 hours drive from Kuala Lumpur. At first, I was quite skeptical about staying in a small hut constructed by Orang Asli (local aborigine people) in the deep jungle. Questions such as will there be mosquitoes? Is it safe to sleep in a hut without door and lock? Will I feel too hot since there is no attached air-con? and I was worried that I actually have to share a toilet with others !!!!. (Usual typical City Boy who's been spoiled by 3 - 5 stars hotel).

Anyway, all worries was gone once we reached the front entrance of Adeline's Rest House. The owner Adeline greeted us and quickly made us feel at home. Maybe we were lucky because there were not many groups (only 1) so we had a choice of a nice hut above a stream.


Our hut was on top of small stream with sounds of flowing water 24/7.


After resting for a while, Adeline invited us for a lunch -buffet style. She cooked all the dishes herself with helpers, of course.

My Yummy Lunch

Thoughts of lazing and doing nothing for the afternoon quickly disappeared when Adeline organised activities for us - caving, trekking, waterfalls, body rafting or water rafting ? She asked us excitedly during lunch and because we did not want to look like boring city folks we joined a group going for caving and the waterfalls. Unexpectedly for us, it was a "near death experience" cos we did not know that the trek was going to be an introduction giude to Survivor ! Though the 2 hours of trekking and climbing was difficult but the experience - priceless.




Me trying body rafting

After the afternoon activities, we headed back to the resort with tired body, a twisted ankle and a very hungry stomach. Auntie Adeline once again performed her magic and prepared us a very yummy dinner and BBQ in buffet style.


DSC_0160
yum yum..

After dinner, we all adjourned back to our small hut. Surprisingly the surrounding air is cool and with continuous water flowing sound, wind blowing, we quickly fell a sleep at around 10.00pm.

Next morning, we were greeted with this "poster picture of morning sunshine" below, right outside our hut windows:


DSC_0185


After our breakfast, we relax a bit around the resort, before we back to our sweet home. Overall I rate this trip 4/5 stars, and we will be back again to this lovely resort.

CIMG0538



PS: Throughout our stay on the resort, we are eying this durian (show at picture below), and hope that it will fall, well, our wish was granted, just minutes before we depart, the durain drop, Auntie Adeline quickly takes the durian, and prepare us yummy durain pancake as our farewell gift. Thanks Auntie Adeline.

DSC_0252

Friday, December 14, 2007

Glass Fish Installation from Hell, really?

I like Sun's open source application server, GlassFish, thus when I feels a bit offended when Jevgeni Kabanov wrote an article about how difficult to install GlassFish, and comments that the documentation is suck, and not friendly..

Hm, ok, to give Jevgeni Kabanov benefits of doubts, I decided to do a fresh installation of GlassFish version 2, and observe the manual installation process myself..maybe he is right, as my GlassFish always pre-bundle with Netbeans, and so far, I haven't try to install GlassFish maually myself.


So.here it go..
a) I visit GlassFish's web site at https://glassfish.dev.java.net/

b) I click on "download GlassFish v2 now" icon, and directed to this page https://glassfish.dev.java.net/downloads/v2-b58g.html
, which I presented a step by step instruction on how to install GlassFish, follows by links to download GlassFish binary for various platform

c) I choose to download GlassFish build for Linux platform, as I am running on Ubuntu Gusty. Once download, I follows the documented instruction to install GlassFish, i.e
-> java -Xmx256m -jar "downloaded.jar"
-> cd glassfish
-> chmod -R +x lib/ant/bin
-> lib/ant/bin/ant -f setup.xml

d) Once setup, I follows the quick start guide to start the application server, i.e.
->Add the install-dir/bin directory as PATH env variable
-> Start the server "asadmin start-domain domain1"

e) To verify, I open my browser, and points the URL to http://localhost:8080, which I presented a welcome page, and messages stated my server is up and running running..BTW, port 8080 is default installation port, and u could change the default port by editing the setup.xml

f) To manage the server, I point my browser at http://localhost:4848 to access GlassFish admin console, I entered my given admin user id and password (ie admin, password, adminadmin) to login to the console. I presented a very nice GUI to manage my server, and deploy my application (WAR, EAR, and etc).

g) To deploy one of my application, I click "Deploy web application(.war)", select my war file, and click deploy, and just like that, my application is up and running..

That's it, the whole process takes less then 20 minutes (depends on how fast ur internet connection is to download the installation jar), and all the steps above are well documented at GlassFish's installation and quick start guide. I admit the installation process is "out of norm" and could be improve, but to go to the extends and claim it is installation from hell is bit too extreme, isn't?

Peace!

Monday, November 19, 2007

Beautiful Krabi

Do u ever read your cable TV guide?

Do u? If not, do yourself a favor and call ur Cable TV provider to cancel your TV guide subscribtion. By doing that, you'll be a part of making our earth greener.

Thanks!

Monday, November 05, 2007

Automatic Remote Logging Management via JMX.

Wow, the post title definitely sound “very technical”, and I do hope that it will attract more readers here. :-)

It all started a weeks ago, where I have accidentally discovered a “hidden JDK 5 treasure” (from Daniel Fuch, blogs http://blogs.sun.com/jmxetc/) , called java.lang.instrument, a Java package that provides services that allowing Java language agents to instrument programs running on the JVM. Most people use it for profiling, or pre-instrument purpose.


But I have a idea, why don't we create a logging management wrapper, which allows us to wrap any Java application, and provide us some logging management functionalities without any modification on our application source code. The logging agent will offer the following:

  • Abilities to change log level (debug, info, warning, error) on any configured logger dynamically without restart.
  • Abilities to locate any configured log output files.
  • Abilities to browse (either head, or tail) any configured log files.
Base on requirements above, I come out JMXMBean interface below:


public interface RemoteLoggingMBean {
  public void activateDebug(String loggerName);
public void activateInfo(String loggerName);
public void activateWarning(String loggerName);
public void activateError(String loggerName);
/**
* Retrieve current configured log output files base on given logger.
* The system will only return log files with the following appender
* org.apache.log4j.DailyRollingFileAppender, org.apache.log4j.FileAppender
* org.apache.log4j.RollingFileAppender;
* @param loggerName
* @return Array of file name with relataive file path points to current running directory.
*/
public String[] retrieveCurrentConfiguredLogFiles(String loggerName);
/**
* Similar to Unix head command, read a text file forward from the beggining
* of the file till it reaches line limit, or EOF
* @param fileName the logFileName.
* @param linesToRead, Number of line to be read.
* @return JMX CompositeData with the structure of StartFilePointer (SimpleType.Long),
* EndFilePointer(SimpleType.Long), LogMessages(SimpleType.String)
* @throws java.io.IOException
*/
public CompositeData headLog(String fileName, int linesToRead) throws OpenDataException, IOException;
public CompositeData headLog(String fileName, int linesToRead, long fromFilePointer) throws OpenDataException, IOException;
public CompositeData tailLog(String fileName, int linesToRead) throws OpenDataException, IOException;
public CompositeData tailLog(String fileName, int linesToRead, long fromFilePointer) throws OpenDataException, IOException;
}

The rest of code is delivered by using various JMX and Apache Log 4J API, which I am not going to discuss here, as this is obviously not JMX nor Java Logging tutorial.

If u interest, u could download the whole project source from here. Is not under any copy write protection. U are welcome to download it, modify it, change the author name, use it or distribute it to anyone. IMHO, The IT have to many unfair patents, or copy protection law, which in a way, have stop us on moving forward.

Anywhere, back to topic. To use the wrapper on any Java application that use Apache Log4J for logging, follows steps below:

  1. Either download the binary RemoteJMXLoggingAgent.jar, or build it from the source
  2. Put the binary to your application class path, make sure it sit together with log4j.jar
  3. Append the line at your Java Application startup script
"-javaagent:(deploy directory)/RemoteJMXLoggingAgent.jar
-Drmi.agent.port=AnyRMIPort (optional, default=3000)"


That's it, u application is now able to offer above Remote Logging management functionalities via JMX. To test this, open jconsole from any PC, and connect your remote application via the JMX URL below:
service:jmx:rmi:///jndi/rmi://hostname:rmi_port/remoteLoggerAgent

The Mbean on managing your application logger is called "org.coolboy.RemoteLoggingManager", have fun!


Tuesday, October 23, 2007

Before upgrade to Windows Vista..

Seriously, think twice before u upgrade, o consider open, secure and free alternative Linux OS. Out of so many Linux distribution, I strongly recommends Ubuntu Gusty.
Here why:
  • Needs goods reasons why Linux is better OS compare with Windows> looks here.
  • It just work - Upon installed, ubuntu detected my all my devices, and install drivers correctly, this include my media card, wireless network, video, usb, and etc.
  • Dell start selling PC/notebook with Ubuntu pre-installed, other vendor like Lenovo will follows soon.
  • If u impressed Windows Vista offer "Wowo wow"3D desktop effect, well, looks what Ubuntu Gusty + Compiz offer:


  • Linux could run Windows applications such as MS Outlook, PhotoShop, IE, even MSOffice (If u really really have to, but do consider use open office..) either via Wine (A windows emulator), or via Windows XP vmware image. User could create an empty OS image using VMware server (Free), and install Windows XP (Using legal Windows XP licenses, off course), and install applications on the vm image created.


Seriously, do u really have to upgrade to Windows Vista, post your doubts on my comments page, I am more happy to help here

Thursday, October 18, 2007

[Blog Action Day] - Watch Planet Earth

Ops, I suppose to post a blog on saving our planet earth at 15-Oct-2007 for Blog Action day, and I forgot about it.. , shit...I am getting old...:-(

Anywhere, since I am not very good about environment statistic, political issues on green effort, and how we could really help, I link up few environmentalist's blog for ur reading:

For me, my suggestion is simple. Go and get Planet Earth Series from BBC, (rent it, purchase it, or steal it from ur friend), spend a weekend, and watch it together with your family. I personal guarantee u will amaze and appreciate how beautiful our planet earth is.


Then, just think that, most of beautiful scenes or animals we seen from the series will probably disappear in 1-2 years time...shouldn't we all do somethings to preserve our beautiful lands...

Tuesday, October 09, 2007

[Google Idea] SMS Protect Me

Last month, a 8 years old girl was kidnapped, sexually assaulted and murdered. Till now, our police still trying their very best to looks for the monster. Almost every month, there always a news about a girl being kidnapped, rapped, or worst being killed. I am shocked when and where the accident happen, it happen while the victims taking late bus home, jogging early morning at public park, waiting to be pick up by friend, or taking car from shopping mall car park, and normal routine u and me are doing every day. I feels sick and upset when reading this kind of news.. What is going wrong with our world? what have happen to our soul? I am constantly thinking how technology could help to prevent his kind of situation, and this is how I come out the idea of SMS protect me service.


Here how it work.

  1. First, user needs to register themselves via a portal, given their contact detail, and group of 5 emergency contact numbers (User relative and friend).

  2. Upon registration, user are given a pair of PIN number, one number is use for protect me event registration (see below), one PIN number is use for emergency.

  3. When user feels unsafe at any place at any time, he/she could register a protect me event via SMS, with the format of [user pin] [event's detail] [event duration]. Here are few examples:

    • I waiting my friend to pick me up at office building A, and my pin code is “1234”, I will key in “1234, waiting friend at Office Bulding A, Gate 2, 20 minutes”

    • I am taking a cab back home at late night, “1234, taking cab number WEB1023 home, 30 minutes”

    • I am going to take my car from public car park, “1234, taking my car at Shopping Mall Apple, car park at floor B2, bay 92, 10 minutes”

  4. User send in the protect me event to a local service center number, system will registered the event

  5. When event expired, system will sends user confirmation SMS to end the protect me event

  6. To reply, user have to key in their pin number, follow by “yes” to end the protect me event, or “extend 10 minutes” to extend the event.

  7. If system didn't received user's confirmation after certain retry, system will send alert SMS message to his/her configured emergency contact numbers, if user's Telco provider provide Location base services, system will find user location, and alert his/her friend about user location.

  8. The emergency number is use when user are in danger, thus is in short and easy to send, user are just require to key in the emergency pin number, with any detail if needed, and send to the local service center number, system will straight away notify user friend and family.

  9. The emergency number is also useful when user force to terminate a protect me SMS event, thus, instead of using user given pin to end the event, user could always use their emergency pin to indicate they are in real danger.


Some possible options on extending the services

  • Integrate with local police patrolling system.

  • Partner with insurance company, user are charge per protect me SMS event, in case on any unwanted incident happen, user are insured.

  • Integrate with Phone GPS syetem.
So, what do u think? do share me your thoughts on the comments page, stay tune for my next idea.

PS: As always, if anyone (perhaps Yahoo Inc.) find these ideas interesting and wants to further build up those ideas, do drop me an email.

Wednesday, October 03, 2007

[Survey] Are we depends on MSN/Yahoo Messganger too much?

I just discovered that many of my team members like to communicate with each other over MSN, even they just sit beside with others!
Out of curiosity, I pull one of them in my office, and ask them why, and here are their "official" reasons:
a) Keep it low - They don't wants to bother other people, and prefer quiet conversation.
b) Audit log - They could record the conversation
c) Is the "in" things, and I belong to older generations..

Wow, the third point actually hurt me..but I tend to not agree with the first two points.
First, I believe verbal communication is far more effective than typing words in the chat windows, one can't simply shows his/her emotion or body languages over MSN (Although some will argue of using Smiley icons is as effective as our body language). And two, we are team mates, why we like to record our conversation? To protect ourself?

I am lost here, can't imagine what will happen 5-10 years later? Do I have to SMS my Son for dinner, even he is just upstairs playing computer game?

Monday, October 01, 2007

We are living on a very unfriendly world..

My post about Car Pool idea created a lot of heated discussion. Couple of my friends commented that although, in general, they like my idea. they do concern about security, question like "what if car pool partner is a crazy person, or a rapist", or "how could I trust my Car Pool Partner if we never meet before", and etc.

This has strike me a lot of thinking, and wonder what's happening to our world?
I still remember when I was young, I always go out and play with my neighbor's kid for hours before dinner time, and most of time, out of our parent's vision. We always go back on time for dinner, and Mom/Dad seldom question us where we went, how's our school, as long as we finished our homework before bed time.

I remember back then, where there 's not Astro (Our Boardband TV provider), we always pass our rental Hong Kong TV series video tape to each other, and returned our tape just before the due date. My mom always exchanges food with my neighbor, and we always "pijam" (i.e borrow) things from each other. When there is new people move into our area, we always go and help, and that always ends with a welcome tea party.

I can't recall there is many crimes back then as compare today. Now, kids always closely monitor by their parent. I hardly know my neighbor, and people in general, just don't open their heart easily as compare to the pass. What's has change?

It's is due to all the media (TV, news paper, radio, internet) like to cover bad news then good news? Or people in generally poorer as compare to past, and hence the increase of crime rate?

I have no idea...could anyone enlighten me?

Tuesday, September 25, 2007

Ideas to Google (Part III) - Google CarPool Portal

This is the third part of my series of articles published with the intention of "selling" my ideas to Google and subsequently to be recruited by Google. By the way did anyone from Google notice my blog .... ?

My third idea is the Google CarPool Portal, my contribution to make our earth greener. I admit this idea is not new as there already many CarPool portals on the web. I visited some of portals, and have yet to come across a portal that I consider a successful one. Most of portals I visited have been inactive for a long time, and for those still consider active, I only see an average one or two posts of interested looking for carpool partner per week. In my opinions, some of the reasons why such portals fail.

1) Lack of big marketing push - Success of this kind of portal is pretty much depends on users participation, the more user participate, the better. Most of the portals I visited are run by personal or community, and usually only have limited funds for Marketing.

2) Poor Location Selection - Most of CarPool portal offers only limited origin/destination selection, and often limited to zip code selection, which in my opinion, it's not comprehensive and customizable enough.

3) Poor user interface - Due to budget problem, most portal offer very basic UI for user to locate CarPool Partner.

4) Lack of incentive to do so, let's admit that, people are motivated when awarded by something.


So how can Google help?
Well, if Google do roll out a CarPool Portal, we already iron out our first problem, and if Google adopt my second idea, we solve our fourth problems. Thus, we only needs to deliver a fairly easy to use CarPool Portal to solve problems 2 and 3.

Here's my vision of Google CarPool Portal:
1. Upon login to Google CarPool Portal, user could post one or many CarPool adv, specifying travel origin, and destination using Google Earth/Google Map, where user could specify the location up to street address, or select buildings (such as office building) from Google Earth/Map. User could also entered their prefer travel time slot (e.g From 7-7.30am), and repeat of the travel (e.g Everyday excepts Weekends, once only).

2. Google will attempt to find closer match per CarPool adv, and will present user a list of adv that matches user's CarPool criteria. User could sort the list by origin, destination and travel time slot. User will get notify via Gmail on every new match found when they are not online.

3. While browsing the CarPool match list, if the match adv owner is online, user could chat (via Google Chat) to the owner to seal the deal. Else, user will have to send a private message to the adv owner, and schedule a time to discuss the CarPool adv

4. User and adv owner identity are protected throughout the conversation. The only way for user to communicate with adv owner is via private messages, and online chat from CarPool portal. Is up to the user, and adv owner when is best time to reveal their identity.

5. Once both parties agree to seal to deal, the adv will close. User and adv owner have the option to claim Google Earth points from the Car portal. Also, for security reason, user could opt on telling the portal when the CarPool going to start, who is driving, the Car Plate number, identity of both parties. This is to protect user in case of any unwanted accidents.

6. There is a forum for users to post FAQ, success stories, experiences, and etc.

7. There is also a running counter from Google CarPool Portal main page showing how many Carpools adv being seals, how many petrol has been save, and most importantly, how many CO2 is save from emitted to the air.

So, what do u think? do share me your thoughts on the comments page, stay tune for my next idea.

PS: As always, if anyone (perhaps Yahoo Inc.) find these ideas interesting and wants to further build up those ideas, do drop me an email.

Friday, September 21, 2007

Introducing Mimi, my new Pug

I just realized that a lot of people are still not aware that we have brought back a new pug call Mimi few weeks ago. Mimi is a female black pug, which is rare in Malaysia, and like her brother, she is very naughty and always begging me to play with her.

Here is Mimi's Picture:

DSC_0111

As always, we will constantly update Mimi's journal at , do drop by to visit Mimi and leave a comment.

Cheers.

Wednesday, September 12, 2007

Ideas to Google (Part II) - Saving Our Mother Earth

This is the second part of a series of articles to impress Google, if you are a Google employee and reading this could you please forward this to your Recruiter, thanks.

My second idea is to make our Mother Earth a better place to live. We can't deny that our environment has change dynamically in past few years, the temperature is increasingly hotter each year, CO2 is rising, and there is more frequent floods, typhoons and thunder storms almost everywhere. Seriously, if we don't do anything now, things will get worst, and our children may be victims to this global warming phenonmenal. We need to do something and should Google take the initiative to step in to help and create an awareness (I think they should ....)?

Here I would like to introduce Google Earth Points...

FAQ
1. What is Google Earth Points
Google Earth Points is a points reward system for individual who have take extra effort and making our earth greener, and help slowing down Global Warming effect, thus everyone has better place to live.

2. What can one do with Google Earth Points
Well, a lot, Google earth points can be use to redeem any non free Google services, for example, we could redeem 100,000 Google Earth Points per 100 MB Gmail storage, or redeem 10,000 points to download a mobile application from Google partner, or increase photos upload limit, and etc.


3. How can one earn Google Earth Points
I have a lot of ideas how one can earn Google earth points but in general it could break down to the following categories:

By Personal Pledge
One will pledge how he/she is going to help to save our mother earth on Google Earth Portal (by submitting a youtube video), and the pledge must be verifiable by third party with upload video showings the promise be carry out. Google Earth Portal then will calculate Google earth points base on the pledge, and award points accordingly.

Here are some of the example:
-One could pledge to cycle to work at least one day a week to his office. His office is about 10KM away from his home, thus in a way, thus save X amount of CO2 emitted to the air, and Google Earth Points is the awarded base on X amount of CO2 emitted he save per week

-One family could pledge they will plants 4 trees at their backyard, now 4 trees will recycle X amount of CO2, and thus, they will get certain number of Google Earth Points.

-One lady pledge she will carpool with her friend.


By summiting cool ideas on saving Earth resources to Google Earth Portal
Anyone could summit cool ideas on how we could save our limited earth resources like how our electric, water, petrol usages to Google Earth Portal, a monthly competition will be carried out to all of us to vote the most coolest idea, and Google Earth Points will then be awarded base on the ranking.


From Consumer Product Vendor
Google could partner with any Consumer product vendor that produce "Greener" product (which needs to certify by some environmental control body, like organic vegetables, non chemical detergent, energy saver computer, and etc), and to give away a number Google Earth points when we purchase those product.

Why Google Earth Points
Most of time, average people (me included) do aware the environmental issue, and we do sometime put in our effort on making this earth a better place to live, but there is still more we could do..

For example, in my previous company, I know 3 of my colleague are staying nearby, but it never come to our mind of car pooling, even though the petrol price is expansive that time. I never planted a single tree in my life, I take my car out for breakfast even is just 5 minutes walk from where I stay..

Thus, with Google earth points, I am hoping this service will start cultivate people habit of doing their part on saving our mother earth.. including myself, as people love accumulate points, and get awarded, isn't it.



So, what do u think? do share me your thoughts on the comments page, stay tune for my next idea

PS: If anyone (perhaps Yahoo Inc.) finds these ideas interesting and wants to further build up those ideas, do drop me an email.








Wednesday, September 05, 2007

Google Please Hire Me (Ideas to Google)

I always wanted to work at Google so that I can bring my dog to work, enjoy yummy yummy meals and work with all the cool people at Google. Given my current status:
- A 35 years old bored software development manager and performing mostly boring management stuff.
- Technically strong but yet I believe I am not as good as most of Google staff.
- Does not hold any working permit for US/India/China

Thus, the chance Google granting me an interview is very, very slim, :-(

Thus, instead of going via the normal route of applying a job at Google (i.e upload my resume to Google jobs portal and throwing my CV into giant black hole), I will try another route.

Starting from today and for every two weeks, I will try to post some of my crazy ideas to Google in my Blog. Hopefully, Google HR will one day notice my creativity and call me for an interview. Wish me luck.

My first idea to Google is "Google Mobile Phone Address Book" service.


Summary:
Google mobile phone address book services comprise of the following modules:
  1. A web portal for user to manage their contacts
  2. A mobile application for user to upload and sync contacts to Google mobile phone address book portal

Why:
  1. Each phone vendor uses native address book format so there isn't an easy way to migrate our address book from our vendor to another (When you are switching phone, or lost your phone).
  2. It is difficult for user to backup their address book.


Propose Features:
  1. The propose web portal will understand address book format from different vendor and provide data conversion service.
  2. User could login to the web portal to manage their contact (insert, delete, update)
  3. User could download a customzied mobile app from the web portal that allow them to sync/update their contact to the address book portal.
  4. If user change to a new phone, he/she could download the mobile app for the new phone and request full address book download from the web portal. Web portal will automatically convert to address book data format
  5. Integrated with Gmail, user could send SMS to his/her contact using gmail interface.

That's all for now. Stay tune for my next crazy idea.

PS: If anyone finds this interesting and wants to further build up those ideas, do drop me an email.

Wednesday, July 04, 2007

I lost my little hero

My beloved little hero Donut went to Heaven 0n 3rd July 2007. No words could describe how sad and heart broken I am. He was my little hero and my best friend. Always there for me step by step. Unconditional sitting there beside me, and sharing my ups and downs.

I still remember he was always there to cheer me up, even whe he's in the great pain in his last few hours with us.

Donut..U will be missed...

Monday, May 21, 2007

100% Unit Test Code coverage using Mock, does it really matter?

I always believe delivering a comprehensive integration/functional testing code is far far more important/productive than blindly try to achieve 100% unit testing code coverage. I believe:
a) A integration/functional testing code will always deliver more test coverage then unit testing code.
b) Integration testing code allows us to capture our program error as earlier as possible, and avoid “big bang” integration error at the end.

Thus, I always have “heat and interesting” discussion with some developers where they always believe:
a) Achieve high percentage of unit testing code coverage is very important
b) unit testing code must be “unit testable”, all dependency classes/resources should be “mocked”, even sometime is so so difficult to mock such objects.
c) if our code is not testable, that must be something wrong with our design. We have to change our code to make it testable. Thus making our class final, or our class not implementing an interface, or using static methods are all bad!.

Don't get me wrong, I am not 100% against points above, and I understand important of unit testing. But believe the unit testing code we deliver must return good “Return of Investment” (ROI). Investment here mean our effort of delivering/maintaining the unit testing code. A good ROI unit testing code have the following characteristic:
a) It use “black box” approach , where we pass parameters to a method, test the method and we verified the return value against expected result, we should not care how's the methods executed, and what underlying resources being called.
b) The testing code should be easily promoted to functional/integration testing code, why reinvent the wheel?
c) The testing code must drafted base on agree use case, and tight back to your application's features. Thus, using HR application as an example, to unit test you annual leave application is always approved by your manager produce good ROI value. but to unit test your database connection pooling utilities, or utilities to read properties files or parsing a fake XML file does not produce good ROI value.

To illustrate what I mean by good ROI unit testing code, consider the following examples:


Public class OrderManager {
public boolean proceedOrder(OrderVO anOrder) {
return ( inventoryManager.hasStock(anOrder) &&
accountManager.customerGoodCreadit(anOrder.getCustomer()) &&
shipmentManager.shipmentDateOK(anOder.getPreferShipmentDate()
);

}


To unit test proceedOrder() methods using Mock:

1. First, create InventoryManager, accountManager, and shipmentManager mocks

2. Instruct our mock framework on mock methods that called, and for each mock methods call, we instruct expected return value.
3. And finally, we test return value with our expected result, and ensure mock methods being called.

Does the above code give us good ROI? IMHO, it does not...

a) It's breaking the black box testing approach, we are telling our mock framework steps by steps what mock methods will be call, and specifically ask them to return the value we set, and test method proceedOrder() return value with our expected result, which we already know what it will return in the first hand.

What happen if we wants to change the implementation, do we have to change our testing code as well.

b) It does not bring any business value...

A ROI testing code for the above use case:
1. Set a InventoryManager product (say product “A”) quantities to a specific amount (say 50)

2. test the proceedOrder() by placing product A with various quantities
3. Verify the result against expectedResult

So, to conclude, if a unit testing code does not produce good ROI, do spend more time on delivering functional/integration testing code, and delivering good "ROI" usable code coverage

Apply my points to Automobile industries, we will not hear an engineer that create mock of car tires, or create a mock for road surface to test a car braking system, he/she will actually “integrate” the braking system with a set of tires (make by different rubbers), and conduct braking test on various surface (maybe on a rolling board with different surfaces)

Share me your thoughts...

Monday, April 02, 2007

If u have PS3...



Please get the Elder Scrolls IV: Oblivion...

Read the review here and here

Cheers

Tuesday, February 27, 2007

[quick tips] To Speedup your junit testing in Ant

If your development project get bigger, and have incorporated thousands of test cases, u may find that unit testing target getting slower and slower. It may come to a point your developers start to ignore test cases, or worst, don't write any test cases at all, as it will slow down build process.

Now, before u look into your unit testing code to improve the performance, why don't have a check on your Ant Junit Target (I discovered this accidentally yesterday, as I am frustrated by the slow build process). If u have setup ur Ant to fork a new JVM for unit testing target, by default, Ant will fork a new VM per Test Class, which is slow, and expansive (imagine forking 1000+ jvm for your project). To correct this, we just needs to set correct forkmode="perBatch".
i.e
junit fork="true" forkmode="perBatch"

My test result, before forkmode="perBatch", my test process take ~= 16 minutes
after, my test process take < 2 minutes

Cheers, and happy coding

Monday, February 12, 2007

[Tech Tips] Implementing Command Design Pattern via Spring Framework - Part II



The RemoteControl class needs to hold list of supported commands, and needs to delegate request to respective command class base on the pass in command string. Here is the RemoteControl source:

 1
2 package blog.coolboy.springexample.cp;
3
4 import java.util.List;
5 import java.util.HashMap;
6 import blog.coolboy.springexample.cp.command.CommandType;
7 import blog.coolboy.springexample.cp.command.Command;
8
9
10 public class RemoteControl {
11
12 private HashMap<String, Command> supportedCommands = null;
13
14 public RemoteControl() { }
15
16
17 public void setListOfSupportedCommands(List<Command> commandList) {
18 supportedCommands = new HashMap<String, Command>();
19 for(Command cmd : commandList) {
20 supportedCommands.put(
cmd
.getCommandType().getCommandString(),
cmd
);
21 }
22
23 }
24
25 public void execute(String cmdString) {
26 Command cmd = supportedCommands.get(cmdString);
27 if(cmd != null) {
28 cmd.execute();
29 } else {
30 System.out.println("The cmd->" +
cmdString
+ " is not supported!");
31 }
32 }
33
34 }
The RemoteControl will transfer a list of supported commands to internal HashMap using commandString as object key, thus, removing the needs of iterating commands list for each new command execution.

Here's the fun part, we will inject list of supported commands to the RemoteControl above using Spring XML configuration, as shown in code below:

<?xml version="1.0" encoding="UTF-8"?>

<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.0.xsd"
>

<!-- listing of supported Commands here -->

<bean id="tvOnCommand"
class="blog.coolboy.springexample.cp.command.impl.TVOnCommand"/>
<bean id="tvOffCommand"
class
="blog.coolboy.springexample.cp.command.impl.TVOffCommand"/>
<bean id="lightOnCommand"
class="blog.coolboy.springexample.cp.command.impl.LightOnCommand"/>
<bean id="lightOffCommand"
class="blog.coolboy.springexample.cp.command.impl.LightOffCommand"/>

<bean id="remoteControl"
class
="blog.coolboy.springexample.cp.RemoteControl">
<property name="listOfSupportedCommands">
<list>
<ref bean="tvOnCommand"/>
<ref bean="tvOffCommand"/>
<ref bean="lightOnCommand"/>
<ref bean="lightOffCommand"/>
</list>
</property>
</bean>
</beans>


That's all, our remote control class is finished. To roll out new Command, developer just needs to
1. declare the new command type, and it's command string at the CommandType enum
2. implements the command, and
3. inject new command via Spring Configuration.


Here are remoteControlService class to test the remoteControl

 1 package blog.coolboy.springexample.cp;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import org.springframework.context.support.ClassPathXmlApplicationContext;
7 import org.springframework.context.ApplicationContext;
8 import org.springframework.jms.listener.DefaultMessageListenerContainer;
9
10 public class RemoteControlService {
11 public static void main(String [] args) {
12 ApplicationContext context =
new
ClassPathXmlApplicationContext("/conf/remoteControlConfig.xml");
13 RemoteControl remoteControl = (RemoteControl) context.getBean("remoteControl");
14 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
15 System.out.println("Remote Control Ready, enter 'Quit' to terminate the program");
16 String txtCommand;
17 try {
18 do {
19 System.out.print("Enter your command->");
20 txtCommand = reader.readLine();
21 if(txtCommand.equalsIgnoreCase("quit")) {
22 break;
23 } else {
24 remoteControl.execute(txtCommand);
25 }
26 System.out.println("");
27 } while(true);
28 } catch (IOException ex) {
29 ex.printStackTrace();
30 }
31
32 }
33 }
Here are the try run:
------------------

Remote Control Ready, enter 'Quit' to terminate the program
Enter your command->tv.on
Switching On TV
Enter your command->tv.off
Switching off TV
Enter your command->light.on
Turning on Light
Enter your command->light.off
Turning off Light
Enter your command->quit

----------------

Isn't this fun? In the next article, I will explain how I would extends the app to support JMS and SOAP command request, using Spring, stay tune.

Friday, February 09, 2007

[Tech Tips] Implementing Command Design Pattern via Spring Framework - Part 1


I been using Spring Framework for pass few months, and I am big fans of the Framework. The framework help a lot, as we don't have to write lengthly, repetitive boring code, most application code are wire via Spring XML configuration, the framework also make our code cleaner, as it provide out of box AOP engine, developer could focus on implementing module core function, and “AOPing” other programming aspects such as transaction control, logging, security, and etc when require.

Thus, to say a big thank u on providing such great framework, and contribute back to the communities, starting from today, I will use this blog to share my experience, tips, and journal of using Spring here. Most of the write up will assume u have some basic idea of using Spring (Just do a google search on Spring tutorial).

So, my very first 2007 technical topic is “Implementing Command Design Pattern using Spring”. I will use the remote control example from very popular design pattern book, “Head First Design Patterns” from OREILLY.

The original requirement of the remote control are

1 . The remote control will have multiple buttons,
2. Each button could be program to turn on/off a household device.

I change the requirement a little, the remote control will not have any buttons, but:

1. It will accept command as a string from a console
2. Each device's command will have unique command String, such as

The very first thing we need to do is to roll out the command interface


1 package blog.coolboy.springexample.cp.command;
2
3 public interface Command {
4 public CommandType getCommandType();
5 public void execute();
6 }


Next, we needs to define an enum to hold all possible supported CommandType, each CommandType holds it's command string, which is unique. That's a helper method to return CommandType base on passing command string.
 1 package blog.coolboy.springexample.cp.command;
2
3 public enum CommandType {
4 LIGHT_ON("light.on"),
5 LIGHT_OFF("light.off"),
6 TV_ON("tv.on"),
7 TV_OFF("tv.off");
8
9 private String commandString;
10
11 // return CommandType base on passing
12 // commandString
13 public static CommandType valueOfCommandString(String cmdString) {
14 CommandType theCommandType = null;
15 for(CommandType cmdType : CommandType.values()) {
16 if (cmdType.getCommandString().equals(cmdString)) {
17 theCommandType = cmdType;
18 break;
19 }
20
21 }
22 return theCommandType;
23 }
24
25 CommandType(String cmdString) {
26 commandString = cmdString;
27 }
28
29 public String getCommandString() {
30 return commandString;
31 }
32
33 public void setCommandString(String commandString) {
34 this.commandString = commandString;
35 }
36
37 }
38

Now, implements all supported commands, below is sample code TV ON Command;

 1 package blog.coolboy.springexample.cp.command.impl;
2
3 import blog.coolboy.springexample.cp.command.Command;
4 import blog.coolboy.springexample.cp.command.CommandType;
5
6
7 public class TVOnCommand implements Command {
8
9 private final static CommandType cmdType = CommandType.TV_ON;
10
11 public TVOnCommand() {
12 // U suppose to pass in a TV instance here..
13 }
14
15 public CommandType getCommandType() {
16 return this.cmdType;
17 }
18
19 public void execute() {
20 System.out.println("Switching On TV");
21 }
22
23 }

The rest of commands (TV.Off, Light On, Light.Off) follows the same structure..

In part II, we will roll out the RemoteControl class, and use Spring to inject supported commands to the Remotecontrol, and provide remoteControlService as an interactive shell for user to test out the remote control, stay tune.