Archive | June, 2007

Adopt Hibernate in your application

Introduction to Hibernate 
Hibernate is the most popular ORM tool in the market. To summarize, it provides the following key features:

  1. Support its own object query language HQL
  2. Transparent persistence - keep track of all loaded objects and automatic change detection through snapshot comparison. To do that, it uses CGLIB to create runtime proxies for persistent objects through dynamic bytecode generation. So, it is better in performance and no need to modify persistent objects for marking it dirty.
  3. Deal with different SQL dialects and in turn provides us a single abstraction layer.
  4. Support pluggable cache strategies – 2 levels of caches: Session vs Session Factory.
  5. Control how the dependent objects be loaded (eg. lazy loading). However, Hibernate Session that originally loaded the affected persistent objects needs to still be open to make lazy loading work. It is recommended to execute such operations within transactions, which will keep the same Hibernate Session open for the lifetime of the entire transaction. If you need lazy loading beyond the scope of your transactions – for example in web views – you need to resort to the Open Session in View pattern.

How Spring helps us to work with Hibernate?
Spring provides us HibernateTemplate that can save us from biolerplate code like dealing with JDBC. Below are the benefits we obtain from this:

  1. Hibernate Session will automatically be synchronized with Spring transaction.
  2. Leverage the normalized exception model

Open Session in View
If you want to do lazy loading during view rendering, you might face a problem that the original transaction has already ended in the service layer and thus closed the Hibernate Session that loaded the given persistent object. One solution for the problem would be to process the entire HTTP request, including view rendering within a single transaction. However, it is not an ideal solution because it would hold database lock until view rendering has been completed. The common solution is the Open Session in View pattern. Transactions end in service layer, but the associated Hibernate Session remains open until view rendering has been completed. This releases database locks early but still alows for lazy loading in the view. NOTE: you can only do that while web and service layer are co-located b/c your Hibernate Session cannot pass via ThreadLocal in remote setting.

Leave a comment Continue Reading →

Migrate Struts to Spring MVC

How Spring MVC works?
Many people suggest me to use Spring MVC instead of Struts. I decide to take a quick look at that. Before I give you a comparsion chart, I think it is good to outline the core mechanism that Spring MVC uses to achieve the goal. Here it is:

  • A dispatcher servlet, which will intercept incoming requests.
  • A configuration that instructs the web container to route requests to the dispatcher servlet (ie. a servlet mapping)
  • Controllers (the C in MVC) that can perform the business logic and route to particular views (the V) perhaps conveying information models (the M).
  • A way for the dispatcher servlet to know which URLs to map to which controllers – called a url mapping (Decouple servlet from controller)
  • A way to determine, when a controller has done its job, how to get to the view – called a view resolver  (Decouple controller from view)

Now you know the heart of Spring MVC. It is really similar to how Struts works : ActionServlet -> Action (logic) -> View with Model (struts-mapping.xml holds the information of how to wire them up).

Reference

http://www.devx.com/Java/Article/29208/1954?pf=true

Leave a comment Continue Reading →

Spring Web Flow – basic concept

How can you implement the page flow for airline booking system with Struts alone? Before we go deep on the new technology, lets try to tackle it the old way. First, take a look at the page flow below first.

To implement a multi-step page flow in Struts,  we can chain individual actions together through the various views. Action URLs to process different events like “back” or “submit” are hard-coded into each view. Some form of ad-hoc session storage is used to manage flow state. Redirect after post is used to prevent duplicate submissions, etc. Although this is a simple and functional approach, it has a major disadvantage: the overall page flow of the web application is not clear from looking at the action definitions in the struts-config.xml file. That is to say, the flow is not explicitly defined but implicitly hide in your struts-config.xml. Besides, flexibility also suffers since actions and views cannot be easily reused.

This is where Spring Web Flow comes in, allowing you to represent the page flow of a web application in finite state machine. 

In finite state machine, a web flow is composed of a set of states. A state is a point in the flow where something happens; for instance, displaying a view (ie. ViewState) or executing an action (ie. ActionState). Each state has one or more transitions (ie. event) that are used to move to another state. In Spring Web Flow, an ActionState executes an action when entered. That action returns the logical result of its execution, and that result is mapped to a state transition. When an ViewState is entered, it will cause the executing flow to pause, and returns control back to the client with instruction to render the configured view. Later, after some user think-time, the client signals an event describing what action the user took. That resumes the flow, and the event that occurred is mapped to a state transition, which takes the user to the next step in the flow.

The state machine model can be reused anywhere, including environments like Struts, Spring MVC, Tapestry, JSF, and even Portlets. Besides, The page flow in a web application is clearly visible by looking at the corresponding web flow definition (in an XML file or Java class). The page flow now is clearly and explicitly specified in web flow definition (either in XML file or Java class). And it is self-contained and reusable in multiple situations. On top of that, it has a clear, observable lifecycle that is managed for you automatically.

Q & A

Q1) “… since the executing flow is paused when a ViewState is entered, and control is returned to the browser, how is the same flow picked up and resumed on subsequent events?”  The answer is the client tracks the unique id of the executing flow, and provides it as input when the next event is signaled. This is typically done using a hidden form field. This is the concept of continuation.

<input type=”hidden” value=”<c:out value=”${flowExecution.id}”/>”>

Q2) “What about decision state and subflow state?”  Decision state decisions what transition to take with conditional logic embedded. For a flow that is independent from the main flow, you can model it as subflow. When a subflow state is entered, a child flow is spawned. The parent flow is suspended until the child flow ends. This lets you view your application as a set of self-contained modules – flows – that you can easily embed in multiple situations in a consistent manner. By the way, you can pass information to the subflow.

Q3) “What about the end states of the state machine?”  When an end state is entered, the active flow session terminates. Upon termination, all resources associated with the flow are cleaned up for you automatically. So, a new scope “flow” is introduced that spans multiple requests but shorter than a session.

Q4) “When should I use web flow?”  It should be noted that Spring Web Flow is not a one-size-fits-all solution. As you’ve seen, it’s a stateful system that automates the management of page flows that drive business processes. It should not be used when simpler, stateless solutions are more appropriate. For example, it should not be used where sites require free navigations, where the user is free to “click around” anywhere they please. Spring Web Flow is designed to power controlled navigations, where the user is guided through a process with a clear business goal and lifecycle.

Reference

TheServerSide Spring Web Flow Article

Spring Web Flow Architecture

Spring Web Flow – Practical Introduction

Official Spring Web Flow Site

Leave a comment Continue Reading →

Pentaho Reporting Framework – Architecture

I am looking into Pentaho currently for my project. It looks very promising so far. Here is the video that talks about the architecure of it. Enjoy.

Leave a comment Continue Reading →

Flex – Event Propagation

There are different kinds of events in the Flex world. An event can be generated from user gesture, return of requests and component lifecycle. Use event is a two step process, (1) You need to write the handler (2) You need to register the handler to the event hook. To register event, there are two different ways:

Inline MXML way:

<mx:Button id=”myButton” click=”myhandler(event)”/>

Actionscript way:

myButton.addEventListener(MouseEvent.CLICK, myhandler);

The code above does the same job.  However, addEventListener provides more advanced control like event propagation and event priority. Event in Flex can be dispatched implicitly (user clicks on a button, the event is dispatched by the system) and explicitly (you can programmatically trigger an event).

Event propagation is an important topic for Flex programming. So, I will try to talk about what I have known on this topic here. Feel free to correct me if I am wrong. As I know, event propagation has three phases. They are capturing, at target, and bubbling. If you have an Application A contains a VBox B that has a Button C. When an user clicks the Button C, it first goes through “capturing phase”. In this phase, the event propagation through the topmost parent of C (ie. stage) and continue walk down the display object hierarchy until it reaches the original target (ie. C). The path for capturing phase is stage -> root -> A -> B -> C. When the event reaches C, the “at target phase” will be started and it just involves one object (ie. C). After that, the event bubbles up following the reverse path of the capturing phase and walk its way back up to root (C -> B -> A -> root -> stage). This is called “bubbling phase”.

fig02.jpg

As the event makes its way though each phase and each object within those phases, it calls all of the listener functions that were added for that event. This means that clicking on the Button C doesn’t limit the event to C, A and B also receive the event. Actually, they receive the event twice, once in the capturing phase and once in the bubbling phase.

However, by default, listener cannot receive event in capturing phase because the capability is turned off. To enable it, we need to set “true” to the third parameter in “addEventListener”, the “useCapture” parameter. If you don’t do that, listener would just listen to event in the “at target” or “bubbling” phase. However, it is an exclusion setting. Once you set the “useCapture” to true, it will not receive event in other phases. To get around this, you need to use “addEventListener” twice, once with “useCapture” set to false (or omitted) and once with “useCapture” set to true.  On the other hand, any listener along the path can stop the event propagation.

In the Event object, the “target” attributed is the component where the event originated (ie. C in this example) whereas “currentTarget” attribute is the component that event currently reaches. So, this attribute’s value will be changed along the propagation path. Apart from these two properties, Event object also contains properties like type (String), eventPhase (int), bubbles (boolean), and cancelable (boolean).

Leave a comment Continue Reading →

Flex – Looking into Metatag

Have you ever used [Bindable] in Flex? Do you know it is metatag? Apart from this, there are 12 more documented metatag in Flex framework. I will list them all out here for your reference:

ArrayElementType
Data type restriction like Java Generic

[ArrayElementType("String")]
public var arrayOfStrings:Array;

Bindable
Allows for easy data synchronization within the components. Bindable can be used to bind simple data, classes, complex data, functions and event. I will talk about this metatag in more detail later.

[Bindable]
[Bindable(event="eventname")]

DefaultProperty
The DefaultProperty metadata tag is used to set a single property as a default property of a class. The 3 label controls are equivalent with “text” defined as default property in the component, so you don’t need to put <text> tag around it.

<mx:label text=”Hello”></mx:label>
<mx:label>
<mx:text>Hello</mx:text>
</mx:label>
<mx:label>Hello</mx:label>

Embed
The Embed metadata tag is used to import images into your application. There are two ways to use Embed. You can either embed the image in ActionScript and assign it to a variable. Button 1 and 2 below do the same.

[Embed(source="myIcon.gif")]
[Bindable]
public var myIcon:Class;

<mx:Button label=”Icon Button 1″ icon=”{myIcon}”/>
<mx:Button label=”Icon Button 2″ icon=”@Embed(source=’myIcon.gif’)”/>

Event
The Event metadata tag is used to declare events that will be dispatched by your custom class. Adding this metadata tag to your class definition allows you to add an event handler function to the MXML tag used to instantiate your custom class. You insert the [Event] metadata tag before the class definition in an ActionScript file, or in the <mx:Metadata> block in an MXML file.

In Actionscript:
[Event(name="myClickEvent", type="flash.events.Event")]

In MXML:
<?xml version=”1.0″?>
<mx:TextArea xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Metadata>
[Event(name="myEnableEvent", type="flash.events.Event")]
</mx:Metadata>
….
</mx:TextArea>

Effect
The Effect metadata tag is used to define a custom effect that will be dispatched when an event occurs. An effect is paired with a trigger that invokes the effect. A trigger is an event, such as a mouse click on a component, a component getting focus, or a component becoming visible. An effect is a visible or audible change to the component that occurs over a period of time. You insert the [Effect] metadata tag before the class definition in an ActionScript file, or in the <mx:Metadata> block in an MXML file. Same as Event syntax above.

[Effect(name="darkenEffect", event="darken")]

IconFile
IconFile is used to identify the filename of a jpg, gif, or png file that will be used as the icon for your custom class. While the [Embed] meta tag can be used to embed images files, SWF files, music files, video files, etc, IconFile is only used to embed a file that will be used as the icon for the custom class.

[IconFile("icon.png")]
public class CustomButton extends Button
{}

Inspectable
The Inspectable metadata tag is used to define the attributes of your custom component that you would like to display in the code hints and property inspector of Flex Builder 2.

InstanceType
The [InstanceType] metadata tag specifies the allowed data type of a property. Example below shows that you can only assign instance data type “mx.controls.Label” to variable topRow of type IDeferredInstance.

[InstanceType("mx.controls.Label")]
public var topRow:IDeferredInstance;

NonCommittingChangeEvent
TBA

RemoteClass
TBA

Style
The Style metadata tag is used to define custom style properties for your components. Simply add the Style metadata tag or tags to your class definition and then use the getStyle method to retrieve its value. I will talk about this metatag in more detail later.

Leave a comment Continue Reading →