I created this basic DWR training and uploaded to Youtube. This video discuss about the basic setup of DWR and the sample is to perform an Ajax based validation.

Elegance in Approach

Another form of art in programming is the approach or architectural design. This topic requires strong technical background and experience, but still, designing your architecture requires artistic skills. There are many ways to skin a cat, so is there to design an architecture. Although design patterns help standardize approaches in software programming, decisions have to be made on which patterns to use, more so, to mix and match. Some patterns have similar purpose and overlaps, so choosing the best pattern requires some craftsmanship.

One major factor that affects architecture is the system requirements a.k.a. non-functional requirements, such as reliability, performance, maintainability and others. Having said that, I’m assuming that the functional requirements is already being taken care of and you are aware of what functionalities need to be supported… you’re now asking yourself how it should be supported.

Now, let’s go through some examples. When parsing a string for a certain pattern, do you use standard string operators (e.g. indexOf, substr) or regular expressions? Normally, you’d say regular expression will be easier - more readable and easier to maintain. However, there is a major performance degradation in regular expressions. So, if performance is important, you’d reconsider using indexOf. But then the maintaining such codes will be a nightmare. You might end up implementing your own parsing libraries using standard string operators - this will be a balanced between maintainability and performance. Such is a case of choosing the best approach, all solutions will perform the required functionality… but one will be better in some aspects than the other. Knowing which one works best requires some creativity and mastery. Thereby becoming your masterpiece.

There are so many scenarios that will let you weigh and analyze the different approaches, and there might be no perfect answer, only good answer. In any case, deriving the best possible approach requires some intuition, foresight and creativity. With so many factors to consider in choosing a design, you might as well leave it to your artistic skills to decide.

Many conceive that programming is a science of computational logic but that’s only half the truth. Programming is more than science, it’s an art. If you disagree, then you’re as good as someone fresh out of college - brainwashed on algorithms, computational complexity, and neural networks.

Let’s begin by putting things in proper context. Art, as defined in Wikipedia, is “a particular type of creative production generated by human beings” or in simpler terms “products of human creativity”. Such definition may have convinced you to agree, if not, then you’re likely a geek trying to find for the most efficient solution to the traveling salesman problem for the past 10 years.

Let’s cut the chase. So, what’s the art in programming?

Artistic Codes
There are many forms of art that can be expressed by your source code - and I’m referring to art as an aesthetic and visually stimulating piece - just like Picasso’s paintings or poems from Shakespeare.

Think of your source code as a masterpiece. Indention, comments, newlines, variable naming are your tools. All of these components must be balanced, easy to read, and inspiring.

The simplest form of art in your source code is “indention”. Block statements must be consistently indented thereby, making it easier to understand. Indention must also be equal in spaces - most Java programs are indented by 4 characters. Personally, I felt uneasy and can’t think clearly whenever I see misaligned codes. It just needs to get fixed otherwise, I won’t be able to think on the next steps.

“Comments” is another form of art but this requires a bit more creativity. Putting comments is not just rewriting what’s represented in the code, rather it must relate to a specific purpose. There is no need to describe the algorithm since its already shown in the code, instead explain the purpose of the code. Remember, comments are intended for humans to read so don’t write something in machine language. Here’s a classic example:

//loop the ArrayList
for (int i=0;i

instead try something more meaningful,

//let’s sum up all the values in the list
for (int i=0;i

The proportion of source codes to comments is also an art. If you’re writing more comments than the codes, then chances are the code is not readable and not well written. Unless of course you’re trying to write for efficiency. To illustrate:

// let’s get the middle index
mid = (max+min) >> 1;

While the code above can be easily understood using mid = (max+min)/2, you may want to use the shift operator since it takes less CPU time to shift the memory register than do a division.

The third form of art in your source code is “naming”. Choosing the right name can take a lot of thinking time. The worst variable names are generic x and y. Always use something more meaningful to make your codes more readable. More importantly, make sure the names are representative of its purpose.

For example, what variable name would you assign to “number of records per page”?

  • numberRecords. This can be interpreted a total number of records, or record number.
  • recordsPage. This can be interpreted are the page number or a list of records, or something else.
  • numRecordsPerPage. Might work, but probably too long.
  • recordsPerPage. The preferred name.

Again, it’s an art so there are no hard and fast rules how to name variable or method names. But always make sure that the names well represent it’s purpose otherwise, it can get confusing when you start debugging your source codes.

So you wanted a seamless deployment process to your servers without worrying about server specific settings? Just upload the war file and voila!, your production servers have the latest build. Here’s a step-by-step instruction how to achieve this.
STEP 1: Identify all your server variables.

Identify the variables that have different values across the servers such as data file locations and database settings. You will need to externalize these variables so that you don’t have to reconfigure them every time you redeploy. Some of the common variables are:

  • Local location of file/directory.
  • Server tracking variables (e.g. for web analytics)
  • Database access

STEP 2: Externalize your server variables.

The best solution I’ve found to externalize variable is a combination of JNDI and property file. The JNDI identifies which property file to use, while the property file contains the values needed for each server. You’ll need to have several property files, one for each server.

So for example, you have 3 servers that needs access to 3 separate file locations. You will then create 3 property files as follows:
server1.properties containing:

server.dataDir = /usr/home/test/data

server2.properties

server.dataDir = C:/data

server3.properties

server.dataDir = /var/www/html/test/data

Now, set your JNDI (in Tomcat) as follows:

  • Add the following line to server.xml under GlobalNamingResources:

  • Add mapping in your web.xml

  • Add ResourceLink in context.xml.

STEP 3: Add codes to access JNDI and property file.Now that you have the configurations in place, its time to tell your application to read the property files based on the JNDI settings. Create a singleton class that will retrieve the properties as follows:

try {
Context initContext = new InitialContext();
if (initContext == null ) {
throw new Exception(”Boom - No Context”);
}
Context envContext = (Context)initContext.lookup(”java:/comp/env”);
String propFilename = (String) envContext.lookup(”serverProperties”);
Properties prop = new Properties();
try {
prop.load(getClass().getClassLoader().getResourceAsStream(propFilename));
} catch (IOException e) {
e.printStackTrace();
}
… access prop, it now contains the property settings ….
} catch (Exception nex) {
nex.printStackTrace();
}

STEP 4: Test your deployment!

It’s actually that simple to configure your application to be server independent. The other thing you’d like to work on is to create an ant build that will build the war and auto-deploy the war to Tomcat.

Here’s a tip in Spring if you want certain URLs to redirect to specific JSP… For example:

http://www.ideyatech.com/magic/login.jspx -> acegi_login.jsp

http://www.ideyatech.com/magic/logout.jspx -> acegi_logout.jsp

Since Spring does not allow mapping directly to a jsp page. You need to create a controller to return the appropriate view. Alternatively, you can use URLFilenameViewController but then you’ll be limited to “prefix” and “postfix” append only. What if you wanted the mapping to be explicit as shown in example above?

My solution is to create a generic controller that will do the mapping. To do this, I’ve created a ViewMapController which behaves in almost exact the same manner with URLFilenameViewController except that mapping is explicitly specified with the filename.

In the example below, I’ve mapped /login.jspx to /jsp/acegi-login.jsp and /denied.jspx to /jsp/access-denied.jsp
STEP 1: Declare your mapping with SimpleUrlHandlerMapping

SimpleURLHandlerMapping

STEP 2: Declare your viewMapController with the view mapping. Declare your viewMapController with the view mapping.

SimpleURLHandlerMapping

STEP 3: Create the class ViewMapController.

public class ViewMapController extends AbstractController {
private Map viewMap;
private String defaultView;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String uri = request.getRequestURI();
String key;
String viewName;

int idx = uri.lastIndexOf(”/”);
if (idx > 0)
key = uri.substring(idx+1);
else
key = uri;
if (viewMap.containsKey(key))
viewName = viewMap.get(key);
else
viewName = defaultView;
return new ModelAndView(viewName);
}

public void setViewMap(Map viewMap) {
this.viewMap = viewMap;
}

public void setDefaultView(String defaultView) {
this.defaultView = defaultView;
}
}

Note: the view will be resolved using your viewResolver. In this case, in order to resolve acegi-login to \jsp\acegi-login.jsp, I’ve declared the viewResolver as:

viewResolver

That’s all folks. You now have a more flexible way to map URLs directly to your JSP pages.

I’ve seen several implementations of ACEGI on enterprise applications. However, I’ve never setup one myself until earlier today… At first, I was quite frustrated with the spring configuration as none seems to work. After looking at several articles online, I get more frustrated as everyone talks about different syntax.

So, I’ve thought of writing down some documentation on how to make ACEGI work seamless with Spring and Hibernate but then I’ll just be adding more confusion to all available articles on the net. So instead of writing step-by-step instructions, I’ll just give out pointers on how to make your learning experience easier.

Rule #1: Follow the Petclinic examples provided from the build - with the exact build number! It seems that there are name changes in ACEGI on different releases. This means that you could be reading an article about ver. 0.8 which is not applicable on ver.1.0, etc. There are differences even on minor releases (1.0.2 to 1.0.4). So stick with the tutorial that comes with build and copy the spring-config from the tutorial as is.

Rule #2: Understand the security framework. Spend a few hours studying the ACEGI configuration. This will save you time later. I tried implementing ACEGI right away and whenever I get lost, I have to dig around and learn the concepts. I believe that its much easier to read and understand first before beating yourself out… I find this article very helpful: http://www.tfo-eservices.eu/wb_tutorials/pages/spring-acegi-tutorial.php But don’t take the configurations from this tutorial as some have changed since 1.0.2 to 1.0.4. Just learn the concepts and again - USE THE PETCLININC EXAMPLE FROM THE BUILD.

Rule #3: Get ACEGI working using InMemoryDaoImpl. Divide your work by focusing on getting the security features working before integrating this with your user DB or AuthenticationService. This way you can isolate your issue to ACEGI settings only. Note: The PETCLINIC example uses MD5PasswordEncoder for password, you need to disable this by removing PasswordEncoder property in your DaoAuthenticationProvider.

Rule #4: Do not wrap settings on ACEGI properties. ACEGI settings are sensitive on newlines, it will not recognize the text if configurations are wrapped. You cannot remove append the lines nor create newlines… if configuration text is long, leave it as is otherwise, ACEGI will not recognize it. While this may seem obvious, I got caught with this problem when I used auto-format in Eclipse.

Well… This is all I have for now…. good luck learning ACEGI!

In my recent project, I’ve evaluated several Ajax Frameworks to support my web 2.0 Java based application. There are a number of framework that supports Ajax functions and most of which are independent of the back-end programming language. But then, there are Java-based Ajax frameworks such as DWR that provides direct Ajax support in Java.

Anyway, here is a run-down of some generic Ajax toolset I’ve evaluated along with some of my personal comments:

  • Dojo (http://dojotoolkit.org/) - Probably the most comprehensive Javascript toolset available. Dojo supports A LOT of functionalities ranging from fading animations to offline storage. Dojo has a good demo site that I find very useful especially when learning the functionalities. The demo site is directly associated to source code so you can immediately see the implementation details. I personally find the js validation useful and the fish-eye navigation is cool, too… Just be careful with the debug console as it breaks the page. I never use it, use FireBug instead.
  • YUI (http://developer.yahoo.com/yui/) - Yahoo provides a quite stable set of Javascript utilities too. YUI seems to be a well-thought toolset as it presents only a limited set of functionalities that you can mix and match to create more complex functions. Naturally, this presents more programming work upfront and steeper learning curve. If you wanted more control on your scripts, YUI might be good for you.
  • Script.aculo.us (http://script.aculo.us/) - Probably the most popular javascript toolset out there. The only thing I find complex here is the URL - a bit hard to type (where do I put the dots). This toolset is based on prototype which is the base javascript library used on Ruby on Rails. I personally prefer this over YUI as I find this easier to use.

I ended up using Dojo for my project for 2 reasons… more comprehensive functionality - meaning I don’t have to mix it with other tools or libraries. I am using FishEye Navigation.

Ciao!

<!– .style1 { font-family: “Courier New”, Courier, monospace; font-weight: bold; color: #0033CC; font-size: small; } .style3 {color: #0033CC; font-size: small; font-family: “Courier New”, Courier, monospace;} –>

After hearing all the buzz about Ajax, I decided to integrate my existing Struts application with Ajax. So, I surfed around looking for some good Ajax tools. Initially, I was looking at Prototype as it seems to be the most dominant Ajax platform. Then, I found Rico. Rico is an open-source JavaScript library for creating rich internet applications. This toolset contains a ton of great user-driven functionalities such as Ajax, drag-and-drop, cinematic effects, and many more.

Now I have to study Rico and learn how it can be integrated with my existing Struts application. The process for integrating with Rico is a bit tricky - the documentation lacking information. They only provide code snippets which will not work as it is. To get around with this, I extracted the actual codes from the demo and analyze the flow. It took a while to understand the flow because the codes contain other features that are not needed for the desired functionality. Anyway, I tried out the sample codes into an HTML. Once I got this working, I attached it to the jsp files. It didn’t take a long time to get it working in JSP since I had it previously working in HTML.

Tip #1: Always start with a working prototype in HTML.

In traditional Struts framework, after an action method perform its operation, it forwards to the next JSP to be displayed.

Traditional Struts

With an Ajax driven framework, the Struts action method forwards to a message.jsp instead. This jsp file displays the message to the user by updating a specific div section in the original page.

Ajax Struts

Let’s dissect the code a little more here, below are the steps to convert an existing Stuts application.

1.) Include prototype and rico javascript files in the jsp file.
2.) Register the action class and div component.
ajaxEngine.registerRequest( ‘add’, ” );
ajaxEngine.registerAjaxElement(’responseArea’);

3.) Put a div to display the message.

4.) Create a submit function which is called on submit button. Put the following codes: (convertForm method can be found here.)
function submitForm(form){
var params = convertForm(’BankAccountForm’);
ajaxEngine.sendRequest(’add’,{method:’post’, parameters: params,
onSuccess : function(req){
// do fancy effects }});
}

5.) Create message.jsp and error.jsp that will display the appropriate messages.
6.) Change your action class to forward to message.jsp or error.jsp depending on results.

Tip#2: When debugging, you can always use the onSuccess, onTimeOut or onError methods in the Ajax call. (shown in the example above)

One problem I encountered was that the jsp response is not updating the specified div. This is because the response is populated to responseText instead of responseXML. To solve this, the jsp must be forced to return an XML content.

Tip #3: Response should be in XML form, put <%@page contentType=”text/xml”%> in your jsp.

Well, this is what I have so far. I’ll be posting other tips as I explore on this more…

At ideyatech, Google Map Sample Imagewe have recently integrated an application with Google Maps to graphically display key locations. The process is quite simple. Google made Javascript APIs that can be easily integrated with existing codes. Amazingly, this nifty feature can be implemented with less than 15 lines of code.

The first step is to sign up for the API key. This generates a key string that will be included in your script to serve as your identity. Afterwards, update your page to include the necessary javascripts. This is generally an easy task for intermediate programmers. I’d rather not explain the code as Google made reasonable efforts to document the API. It took me about 15 mins to get the sample code running, a few hours to customize the page and integrate with our database. Viola!

One issue was upon us though, Google maps require latitude and longitude information about the locations. Our database contain only address information. What we need is a geo-coding functionality that can translate a physical address into long/lat. There are some open-source projects for geo-coding, but the best we have tested is Yahoo Maps. How ironic, we’re using Yahoo Maps for geo-coding which will be fed to Google maps for viewing.

The process of using Yahoo Maps API is quite simple too. First step is to sign-up for an application ID. Then construct a REST command to issue the query. The syntax is well documented, too. So, the solution is to provide a lat/long “lookup” button within your data entry screen. For usability, we applied Ajax codes to perform the on-the-fly lookup. Due to some security issues with the browser connecting directly to yahoo maps URL, we ended up calling our server which in turn makes the request to Yahoo URL. Here is the js script that makes the call and here is Java code snippet that process the request.

Now, the solution is complete. We have Google maps to display the graphical maps based on lat/long stored in the database and Yahoo geo-coding to translate a physical address to lat/long. This is what I call Web 2.0 integration.