Cricinfo Live Scores

Wednesday, February 27, 2008

Design Pattern (GOF): Structural Pattern : Builder

Definition

Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.

To reuse classes and make new class compatible with existing ones. For example, A clean system is already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the existing system.

Example

interface Clean {
public void makeClean();
}
class Office implements Clean{
public void makeClean() {
System.out.println("Clean Office");
}
}
class Workshop implements Clean{
public void makeClean() {
System.out.println("Clean Workshop");
}
}

interface Extra extends Clean{
public void takeCare();
}
class Facility implements Extra{
public void makeClean() {
System.out.println("Clean Facility");
}
public void takeCare() {
System.out.println("Care has been taken");
}
}
In order to reuse Workshop and Office classes,
we create an adapter interface Extra and
add new job takeCare in the system.

class Test {
static void Jobs (Extra job) {
if (job instanceof Clean)
((Clean)job).makeClean();
if (job instanceof Extra)
((Extra)job).takeCare();
}
public static void main(String[] args) {
Extra e = new Facility();
Jobs(e);
Clean c1 = new Office();
Clean c2 = new Workshop();
c1.makeClean();
c2.makeClean();
e.makeClean();
}
}
Author
Kazi Masudul Alam

Sunday, February 24, 2008

Returning more than one value from a function

A function can only have one return value. In Access 2, there were a couple of ways to work around this limitation:
  • Use a parameter to define what you want returned. For example:
    Function MultiMode(iMode As Integer) As String
    Select Case iMode
    Case 1
    MultiMode = "Value for first Option"
    Case 2
    MultiMode = "Value for second Option"
    Case Else
    MultiMode = "Error"
    End Select
    End Function
  • Another alternative was to pass arguments whose only purpose was so the function could alter them:
    Function MultiArgu(i1, i2, i3)
    i1 = "First Return Value"
    i2 = "Second Return Value"
    i3 = "Third Return Value"
    End Function

VBA (Access 95 onwards) allows you to return an entire structure of values. In database terms, this is analogous to returning an entire record rather than a single field. For example, imagine an accounting database that needs to summarize income by the categories Wages, Dividends, and Other. VBA allows you to declare a user-defined type to handle this structure:

    Public Type Income
Wages As Currency
Dividends As Currency
Other As Currency
Total As Currency
End Type

You can now use this structure as the return type for a function. In a real situation, the function would look up your database tables to get the values, but the return values would be assigned like this:

    Function GetIncome() As Income
GetIncome.Wages = 950
GetIncome.Dividends = 570
GetIncome.Other = 52
GetIncome.Total = GetIncome.Wages + GetIncome.Dividends + GetIncome.Other
End Function

To use the function, you could type into the Immediate Window:

    GetIncome().Wages

(Note: the use of "Public" in the Type declaration gives it sufficient scope.)

Programmers with a background in C will instantly recognize the possibilities now that user-defined types can be returned from functions. If you're keen, user-defined types can even be based on other user-defined types.


Collection
Kazi Masudul Alam

Changing Array Size

When you want to declare array in VBA and change the array size
you can go like this.

Dim list1() as String

When you want to first use it, set the size:

Redim List1(10)

When you want to change size and lose the contents

Redim List1(20)

If you want to increase size and retain the contents

Redim Preserve List1(30)

Author
Kazi Masudul Alam

OOA/OOD/OOP

Object-Oriented Analysis

  • It's general, and thus reusable.
  • Information access is enough. Objects that don't need information can't get to it. Objects that do need information can get to it (i.e., either they have it, or they have an instance variable that points to an object that has it.)
  • Responsibility, control, and communication is distributed. One object doesn't do everything. Makes it easier to reuse, easier to develop and manage.
  • Minimize assumptions of language or system. Try to describe the world, not a program.
  • Define objects not functions or managers. Objects are nouns.
  • Don't include things you don't need, even if it is part of the real world. Sure, everything is made up of molecules, but you probably don't need a molecules class.
  • Good hierarchy is always linked by IsA relationships.
  • Attributes and services should be factored out as high in the hierarchy as possible.
  • It should be easy to add on to, and thus reusable.
  • There should be little or no redundancy.
  • Again, objects are NOUNS.

Object-Oriented Design

  • Implementable. You can see how you'd write code from here.
  • Complete. It's obvious that the OOA is right because everything you need to do is (1) covered in the OOD and (2) matches the OOA.
  • Removes unnecessary middlemen. If A needs to reach B, but can only do it through C...think about allowing A to reach B directly.
The idea is that the OOD is where you patch the pieces together, where you make sure that messages are caught, important information is known at the right places, that all the important services are accounted for.

Object-Oriented Programming

  • NEVER change a reused class! Use subclasses.
Collection
Kazi Masudul Alam
Software Engineer

Wednesday, February 20, 2008

Excel VBA Variables Lifetime & Scope


In Excel, when coding in VBA, we can use what are know as variables to store information. These variables (as the name suggests) can be varied and changed to store different data information. As soon as a variable loses scope it loses its stored value.

Excel VBA Variables Levels

There are 3 levels at which we can dimension (Dim) variables. These are;

1) Procedure-Level
2) Module-Level
3) Project-Level, Workbook Level, or Public Module-Level

Each of these levels differ in scope and lifetime. This is discussed below

Procedure-Level Variables

These are probably the best known and widely used variables. They are dimensioned (Dim) inside the Procedure itself. See Example below;

Sub MyMacro ()
Dim lRows as Long
'Code Here
End Sub

All variables dimensioned at this level are only available to the Procedure that they are within. As soon as the Procedure finishes, the variable is destroyed.

Module-Level Variables

These are variables that are dimensioned (Dim) outside the Procedure itself at the very top of any Private or Public Module. See Example below;

Dim lRows as Long

Sub MyMacro ()

'Code Here
End Sub

All variables dimensioned at this level are available to all Procedures that they are within the same Module the variable is dimensioned in. Its value is retained unless the Workbook closes or the End Statement is used.

Project-Level, Workbook Level, or Public Module-Level

These variables are dimensioned at the top of any standard public module, like shown below;

Public lRows as Long

All variables dimensioned at this level are available to all Procedures in all Modules. Its value is retained unless the Workbook closes or the End Statement is used.

Author

Kazi Masudul Alam

Tuesday, February 19, 2008

JavaScript Events

JavaScript Events are items that transpire based on an action. A document event is the loading of an HTML document. A form event is the clicking on a button. Events are objects with properties.

Event Properties

  • x -Mouse x coordinate when the event happened.
  • y -Mouse y coordinate when the event happened.

JavaScript defines five types of events which are form, image, image map, link, and window events. Events are associated with HTML tags. The definitions of the events described below are as follows:

Form Events

  • blur - The input focus was lost.
  • change - An element lost the focus since it was changed.
  • focus - The input focus was obtained.
  • reset - The user reset the object, usually a form.
  • select - Some text is selected
  • submit - The user submitted an object, usually a form.

Image Events

  • abort - A user action caused an abort.
  • error - An error occurred.
  • load - The object was loaded.

Image Map Events

  • mouseOut - The mouse is moved from on top a link.
  • mouseOver - The mouse is moved over a link.

Link Events

  • click - An object was clicked.
  • mouseOut - The mouse is moved from on top a link.
  • mouseOver - The mouse is moved over a link.

Window Events

  • blur - The input focus was lost.
  • error - An error occurred.
  • focus - The input focus was obtained.
  • load - The object was loaded.
  • unload - The object was exited.
Author
Kazi Masudul Alam

Introduction to AJAX

Description: Everybody till now must have atleast heard about AJAX (Asynchronous JavaScript And XML). This example will give you an idea about how you can implement simple AJAX interaction in your web application.

Purpose of using AJAX

The main purpose of using AJAX is to asynchronously get the information from the server and update only that area of the web page where this information fetched needs to be displayed, avoiding refresh of the entire page. The other advantage of this is, the web page can hold minimal required data and retrieve rest as needed based of events.

How is all this possible.

Its possible by writing a JavaScript code in your web application, which uses XMLHttpRequest object to communicate with the server and get the data asynchronously.

The first step is to create and configure the XMLHttpRequest object.

  • Currently there are two implementations of this object, ActiveXObject is Internet ExplorerXMLHttpRequest works with other browsers. So a check is made before creating the object, like this,

    var httpRequest;
    specific, and
    if (window.ActiveXObject) // for IE
    {
    httpRequest
    = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) // for other browsers
    {
    httpRequest
    = new XMLHttpRequest();
    }
  • Now configure the object by setting the HTTP method, GET or POST, the URL of the server side element, like a servlet or cgi script, which this object will communicate with, and the third parameter is a boolean value which decides whether the interaction should be synchronous or asynchronous, where true means asynchronous.

    httpRequest.open("
    GET", url, true);
  • Then set the name of the JavaScript function, which will handle the callback from the server side element.

    httpRequest.onreadystatechange
    = function() {processRequest(); } ;
  • Now make the call,

    httpRequest.send(
    null);

Second step is to handle the response from the server which is always in XML form.

The server element can return the actual data in XML form or the formatted HTML code. This processing is done in the JavaScript function, which is specified as the callback function. The first thing to do in this method is to check the XMLHttpRequest object's readyState, value 4 indicates that the call is complete. Then check for the status, which is the HTTP status code, value 200 means HTTP is successful. Following is how the method looks,

function processRequest()
{
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
//process the response
}
else
{
alert("
Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
}
}
}

The third step is to process the response received.

The response is stored in responseText of the XMLHttpRequest object. The response is always in the XML form and the object representation of this XML is stored in responseXML
Following code shows how this is done.

of the XMLHttpRequest object. This XML can be parsed in the JavaScript itself using the DOM API to obtain the actual data.
//The method getElementsByTagName, gets the element defined by the given tag
var profileXML
= httpRequest.responseXML.getElementsByTagName("Profile")[0];

//The node value will give you actual data
var profileText
= profileXML.childNodes[0].nodeValue;

Once we get the actual data, now the last step is to update the HTML.

The way to do that is by modifying the DOM (Document Object Model) of the HTML page. This can be done within JavaScript using the DOM API. JavaScript can get access to any element in the HTML DOM and modify it after the HML is loaded. This ability to dynamically modify the HTML DOM object within JavaScript plays very important role in AJAX interaction. The document.getElementById(id) method is used to get reference of the element in DOM. Where id, is the ID attribute of the element you want to modify. In this example the element is DIV with the ID attribute "profileSection".
Following code shows how to modify this DOM element with the data received,

//Create the Text Node with the data received
var profileBody
= document.createTextNode(profileText);

//Get the reference of the DIV in the HTML DOM by passing the ID
var profileSection
= document.getElementById("profileSection");

//Check if the TextNode already exist
if(profileSection.childNodes[0])
{
//If yes then replace the existing node with the new one
profileSection.replaceChild(profileBody, profileSection.childNodes[
0]);
}
else
{
//If not then append the new Text node
profileSection.appendChild(profileBody);
}

How does web page interact with this JavaScript

To tie this interaction with your web page, you need to first identify the part of your web page which will be updated dynamically and mark it with DIV tag and provide it an id, like,

="profileSection">



Identify what event will update the marked area, like clicking on a link, mouseover a image etc. trap this events using JavaScript and call the JavaScript function which creates the XMLHttpRequest object.

What does server side element need to take care of?

While sending the response back the server should set the Content-Type to text/xml, since the XMLHttpRequest object will process this type of request. Also you can set the Cache-Control to no- cache to avoid the browser caching the response locally. The server should always send back data in XML format. The data should be a valid XML format and parse able by the JavaScript. If your data contains characters not friendly with the XML parsers, use the CDATA section in your XML

Author
Kazi Masudul Alam

Deployment of WebLogic Server Applications

Weblogic directory structure or deployment of weblogic server application, the best article is

Deployment of Weblogic Server Application

JBoss Directory Structure

The binary distribution unpacks into a top-level JBoss install directory, often referred to as the JBOSS_DIST directory. There are four sub-directories immediately below this:

NOTE: Some directories are dynamically created when you start JBoss. Some directories may not exist in older versions.

  • bin: contains various scripts and associated files. This is where the run and shutdown scripts, which start and stop JBoss, reside.
  • client: stores configuration and jar files which may be needed by a Java client application or an external web container. You can select archives as required or use jbossall-client.jar.
  • docs: contains useful information
    • docs/dtd: contains the XML DTD used in JBoss for reference (these are also a useful source of documentation on JBoss configuration specifics).
    • examples: contains optional configurations:
      • bindingmanager: example configuration for the binding service for running multiple copies on jboss with different ports on the same machine.
      • jca: example JCA configuration files for setting up datasources for different databases (such as MySQL, Oracle, Postgres) and access to legacy EIS systems.
      • jms: example configurations for different jbossmq persistence, state manager and connection factorys
        • standalone: a script to make a minimal jbossmq server configuration
      • jmx: additional and legacy management deployments
      • netboot: a web application used when netbooting jboss
      • remoting: an early access of the remoting service from JBoss4
      • tomcat: scripts for installing different versions of Tomcat
      • varia: additional services
        • loadbalancer: a deployment for running jboss as a http loadbalancer
  • lib: jar files which are needed to run the JBoss microkernel. You should never add any of your own jar files here.
  • server: each of the subdirectories in here is a different server configuration. The configuration is selected by passing the option -c to the run script.
    • : a server configuration started with the -c option
      • conf: configuration files including the bootstrap services in jboss-service.xml
        • props: default users/roles properties files for the jmx console (from 4.0.2)
        • xmdesc: XMBean descriptors for those MBeans with extended descriptions
      • lib: static jar files for the services
      • deploy: services and applications that are hot deployed
      • data: data files that survive reboot
      • tmp: temporary files that do not survive reboot
      • work: work files for Tomcat
    • minimal: a minimal jndi and jmx kernel
    • default: the default configuration (does not include clustering or corba)
    • all: all services including clustering and corba
      • farm: deployments in here are hot deployed across the cluster
      • deploy-hasingleton: deployments in here are only run on one node in the cluster at a time

When one application will be deployed it can be deployed in \\server\\deploy or it can deployed in \\server\\deploy

Deployment Structure

Enterprise Archive Contents

Enterprise Archive (.ear) component follows the standard directory structure defined in the J2EE specification.

Directory Structure of .ear archive

/

.war and .jar files

|_Meta-inf

-----|_ application.xml

In the .ear file .war,.jar and application.xml file are packaged in the above format.

Enterprise Archive Contents

Web component follows the standard directory structure defined in the J2EE specification.

Directory Structure of Web Component

/

index.htm, JSP, Images etc..

|_Web-inf

-----web.xml

-----|_ classes

-----|_ servlet classes

-----|_ lib

----- jar files


/Kazi Masudul Alam
Software Engineer

Sunday, February 17, 2008

Object Oriented Javascript (Inheritance)

We will see in this article how we can implement inheritence in JavaScript. Superclass and subclass creation and implementation will be shown here.

This is the extend function that creates the superclass and subclass relationship.
function extend(subclass, superclass) {
function Dummy(){}
Dummy.prototype = superclass.prototype;
subclass.prototype = new Dummy();
subclass.prototype.constructor = subclass;
subclass.superclass = superclass;
subclass.superproto = superclass.prototype;
}
Here Person is Super Class. Its toString function is set like this

function() {
return this.first + ' ' + this.last;
};
////////////////////Super Class////////////////
function Person(first, last) {
this.first = first;
this.last = last;
}

Person.prototype.toString = function() {
return this.first + ' ' + this.last;
};

Now we will create a subclass named Employee

////////////////////Sub Class////////////////

function Employee(first, last, id) {
Employee.superclass.call(this, first, last);
this.id = id;
}
extend(Employee, Person);

Employee.prototype.toString = function() {
return Employee.superproto.toString.call(this) + ': ' + this.id;
};


Output of the html will be like this

John Dough
Bill Joi: 100

References:
http://kevlindev.com/tutorials/javascript/inheritance/index.htm

Author:
Kazi Masudul Alam
Software Engineer

Introduction to Object Oriented JavaScript

JavaScript is an excellent language to write object oriented web application. It can support OOP because it supports inheritance through prototyping as well as properties and methods. Many developers cast off JS as a suitable OOP language because they are so used to the class style of C# and Java. Many people don't realize that javascript supports inheritance. When you write object-oriented code it instantly gives you power; you can write code that can be re-used and that is encapsulated.

What's so great about objects?

Objects work so well because they act just like real life objects- objects have properties and methods. So if we were talking about a lamp, a property of it may be its height or width, say 12cm. A method of it may be to shine (an action). And when it's shining, its brightness property would be of a greater value than when it wasn't.

JavaScript gives you the ability to make your own objects for your own applications. With your objects you can code in events that fire when you want them to, and the code is encapsulated. It can be initialized any amount of times.

Creating objects using new Object()

There are several ways to create objects in JavaScript, and all of them have their place. The simplest way is to use the new operator, specifically, new Object():

We define a custom object "person," then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties.

Creating objects using Literal Notation

Another inline way of defining an object is via literal notation. Supported in JavaScript1.2 and above, it's a more robust form of creating an object on the fly:

Literal notion can contain arrays or arbitrary JavaScript expressions or values.

While using the new operator or literal notion to create a custom object is both simple and logical, the biggest shortcoming is that the result is NOT reusable- we cannot easily initialize different versions of the created object. For example with the first demonstration above, if the person's name is not "Tim Scarfe", we would need to redefine our entire object just to accommodate this change.

Author:
Kazi Masudul Alam
Software Engineer


Saturday, February 16, 2008

Design Pattern (GOF): Creational Pattern : Prototype

The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.

Again let’s try and understand this with the help of a non-software example. I am stressing on general examples throughout this write-up because I find them easy to understand and easy to accept as we all read and see them in day-to-day activity. The example here we will take will be of a plant cell. This example is a bit different from the actual cloning in a way that cloning involves making a copy of the original one. Here, we break the cell in two and make two copies and the original one does not exist. But, this example will serve the purpose. Let’s say the Mitotic Cell Division in plant cells.
Let’s take a class PlantCell having a method split(). The plant cell will implement the interface Cloneable.

Following is the sample code for class PlantCell.

PlantCell.java

package creational.builder;

/**
* Shows the Mitotic cell division in the plant cell.
*/
public class PlantCell implements Cloneable {


public Object split() {


try {



return super.clone();
}catch(Exception e) {
System.out.println("Exception occured: "+e.getMessage());
return null;
}


}
}// End of class

Now let’s see, how this split method works for PlantCell class. We will make another class CellDivision and access this method.

CellDivision.java

package creational.prototype;
/**
* Shows how to use the clone.
*/
public class CellDivision {

public static void main(String[] args) {
PlantCell cell = new PlantCell();

// create a clone
PlantCell newPlantCell = (PlantCell)cell.split();
}

}// End of class

One thing is you cannot use the clone as it is. You need to instantiate the clone before using it. This can be a performance drawback. This also gives sufficient access to the data and methods of the class. This means the data access methods have to be added to the prototype once it has been cloned.

Author:
Kazi Masudul Alam
Software Engineer

Wednesday, February 13, 2008

Java Server Faces (JSF)

JavaServer Faces technology includes:
  • A set of APIs for representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.
  • A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.

Designed to be flexible, JavaServer Faces technology leverages existing, standard UI and web-tier concepts without limiting developers to a particular mark-up language, protocol, or client device. The UI component classes included with JavaServer Faces technology encapsulate the component functionality, not the client-specific presentation, thus enabling JavaServer Faces UI components to be rendered to various client devices. By combining the UI component functionality with custom renderers, which define rendering attributes for a specific UI component, developers can construct custom tags to a particular client device. As a convenience, JavaServer Faces technology provides a custom renderer and a JSP custom tag library for rendering to an HTML client, allowing developers of Java Platform, Enterprise Edition (Java EE) applications to use JavaServer Faces technology in their applications.

Ease-of-use being the primary goal, the JavaServer Faces architecture clearly defines a separation between application logic and presentation while making it easy to connect the presentation layer to the application code. This design enables each member of a web application development team to focus on his or her piece of the development process, and it also provides a simple programming model to link the pieces together. For example, web page developers with no programming expertise can use JavaServer Faces UI component tags to link to application code from within a web page without writing any scripts.

Developed through the Java Community Process under JSR-127, JavaServer Faces technology establishes the standard for building server-side user interfaces. With the contributions of the expert group, the JavaServer Faces APIs are being designed so that they can be leveraged by tools that will make web application development even easier. Several respected tools vendors were members of the JSR-127 expert group, which developed the JavaServer Faces 1.0 specification. These vendors are committed to supporting the JavaServer Faces technology in their tools, thus promoting the adoption of the JavaServer Faces technology standard.

The expert group is actively developing the specification for JavaServer Faces version 1.2. To check its current status, please see JSR-252.

Example

A quick start tutorial can be

You can download the source code from here

make sure the application have the following jars.

jsfks\WebContent\WEB-INF\lib\commons-beanutils.jar
jsfks\WebContent\WEB-INF\lib\commons-collections.jar
jsfks\WebContent\WEB-INF\lib\commons-digester.jar
jsfks\WebContent\WEB-INF\lib\commons-logging.jar
jsfks\WebContent\WEB-INF\lib\jsf-api.jar
jsfks\WebContent\WEB-INF\lib\jsf-impl.jar
jsfks\WebContent\WEB-INF\lib\jstl.jar
jsfks\WebContent\WEB-INF\lib\standard.jar


Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Spring: A basic application

Spring is grate framework for development of Enterprise grade applications. Spring is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. Spring framework can be used in modular fashion, it allows to use in parts and leave the other components which is not required by the application.

Features of Spring Framework:

  • Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy
  • Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
  • AOP Framework: Spring is best AOP framework
  • MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework..

Spring Architecture

Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are:

  1. Spring AOP
    One of the key components of Spring is the AOP framework. AOP is used in Spring:
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.

    • To allow users to implement custom aspects, complementing their use of OOP with AOP

  2. Spring ORM
    The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
  3. Spring Web
    The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.
  4. Spring DAO
    The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
  5. Spring Context
    This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
  6. Spring Web MVC
    This is the Module which provides the MVC implementations for the web applications.
  7. Spring Core
    The Core package is the most import component of the Spring Framework.
    This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic

Example Application:

A basic spring application article choice can be

You can download the source code from here.

Source Code

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Tuesday, February 12, 2008

Learnt JSF

Ha ha i am going and going and going.....
I have learnt to work with JSF(Java Server Faces)

I have seen Netbeans Visual Web JSF.
I have worked out JSF application manually in Eclipse.

Now, i believe i can work with it toooooooo..........


Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Learnt Spring

Hmm, so the learning curve is really going steep and steep....
I have completed my first steps of Spring too....

I have learnt how to use ApplicationContext for developing
Spring application.
So, now i can work with Spring tooooooo..............


Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Learnt Struts2

Hmm, Struts2 is also completed with its architecture. Now, i will be able
develop struts 2 applications i hope. So, the learning curve is growing steep
and steep...... :))



Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Learnt Struts1.x

I am feeling a great interest in JAVA and enjoying learning new
things daily. A few days ago i learnt struts1.x. I have published
that application in this blog.

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Sunday, February 10, 2008

Struts 2: Start up Application

The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

Some of the general features of the current Apache Strut 2 framework are given below.

Architecture – First the web browser request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the functions like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.

Tags - Tags in Strut 2 allow creating dynamic web applications with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.

MVC – The Model View Controller in Strut 2 framework acts as a coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.

Configuration – Provides a deployment descriptor to initialize resources in XML format. The initialization takes place simply by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.

Configuration files are re-loadable that allows changes without restarting a web container.

Other Features:

  • All framework classes are based on interfaces and core interfaces are independent from HTTP.
  • Check boxes do not require any kind of special application for false values.
  • Any class can be used as an action class and one can input properties by using any JavaBean directly to the action class.
  • Strut 2 actions are Spring friendly and so easy to Spring integration.
  • AJAX theme enables to make the application more dynamic.
  • Portal and servlet deployment are easy due to automatic portlet support without altering code.
  • The request handling in every action makes it easy to customize, when required.
Application:
The following application is a small application built following Struts2 architecture.
In this case Struts-config.xml is replaced by Struts.xml. Here Struts.xml include the file
Struts2Lib.xml.

There is no ActionForm in Struts2. To run the application one need to install Struts2.
Extract sample blank application from Struts2. And add the jars in

/WEB-INF/lib/commons-logging
/WEB-INF/lib/ognl
/WEB-INF/lib/struts2
/WEB-INF/lib/xworker

One thing to notice in the Struts2Lib.xml file is that package name or namespace has no relationship with the class packages. package name="anything/test" namespace="/anything/test" extends="struts-default"


In the Index.htm file

META HTTP-EQUIV="Refresh" CONTENT="0;URL=anything/test/HelloWorld.action"

URL=anything/test/HelloWorld.action directs the action to the HelloWorld.action.

Download the Source code

Author:
-----------------------
Kazi Masudul Alam
Software Engineer



Struts 1.x: Basic Application

What is Struts?

Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open source. Struts Framework is suited for the application of any size. Latest version of struts can be downloaded from http://jakarta.apache.org/. We are using jakarta-struts-1.1 and jakarta-tomcat-5.0.4 for this tutorial.

What is Model-View-Controller (MVC) Architecture?

Model-View-Controller architecture is all about dividing application components into three different categories Model, View and the Controller. Components of the MVC architecture has unique responsibility and each component is independent of the other component. Changes in one component will have no or less impact on other component. Responsibilities of the components are:

Model: Model is responsible for providing the data from the database and saving the data into the data store. All the business logic are implemented in the Model. Data entered by the user through View are check in the model before saving into the database. Data access, Data validation and the data saving logic are part of Model.

View: View represents the user view of the application and is responsible for taking the input from the user, dispatching the request to the controller and then receiving response from the controller and displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of view component.

Controller: Controller is intermediary between Model and View. Controller is responsible for receiving the request from client. Once request is received from client it executes the appropriate business logic from the Model and then produce the output to the user using the View component. ActionServlet, Action, ActionForm and struts-config.xml are the part of Controller.


Here i am giving a small Struts 1.x application to start off. This application contains the basic
architecture of a Struts 1.x based application.

After download the Struts1.x from the the apache extract the blank application from the example and add following jars to the WEB-INF\lib folder.

\struts-login\WEB-INF\lib\antlr.jar
\struts-login\WEB-INF\lib\commons-beanutils.jar
\struts-login\WEB-INF\lib\commons-digester.jar
\struts-login\WEB-INF\lib\commons-fileupload.jar
\struts-login\WEB-INF\lib\commons-logging.jar
\struts-login\WEB-INF\lib\commons-validator.jar
\struts-login\WEB-INF\lib\jakarta-oro.jar
\struts-login\WEB-INF\lib\servlet-api.jar
\struts-login\WEB-INF\lib\struts.jar

Download the Source files for the application

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Monday, February 4, 2008

Design Pattern (GOF): Creational Pattern : Singleton

Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as singletons—are accessed by disparate objects throughout a software system, and therefore require a global point of access. Of course, just when you're certain you will never need more than one instance, it's a good bet you'll change your mind.

The Singleton design pattern addresses all of the previous paragraph's concerns. With the Singleton design pattern you can:

  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class's clients

Although the Singleton design pattern—as evidenced below by the figure below—is one of the simplest design patterns, it presents a number of pitfalls for the unwary Java developer. This article discusses the Singleton design pattern and addresses those pitfalls.


EXAMPLE

A complete Singleton example is.

final public class ClassicSingleton { //final prevents inheritence

private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
synchronized (this) // preventing multi-threaded instantiation
{
if(instance == null) {
instance = new ClassicSingleton(); // only one time created
}
}
return instance; // many times delivered
}

}

Author:

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

Kazi Masudul Alam

Software Engineer


Sunday, February 3, 2008

Design Pattern (GOF): Creational Pattern : Factory Method

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Example

To illustrate how to use factory design pattern with class level implementation, here is a real world example. A company has a website to display testing result from a plain text file. Recently, the company purchased a new machine which produces a binary data file, another new machine on the way, it is possible that one will produce different data file. How to write a system to deal with such change. The website just needs data to display. Your job is to provide the specified data format for the website.

Here comes a solution. Use an interface type to converge the different data file format. The following is a skeleton of implementation.

//Let's say the interface is Display
interface Display {

//load a file
public void load(String fileName);

//parse the file and make a consistent data type
public void formatConsistency();

}

//deal with plain text file
class CSVFile implements Display{

public void load(String textfile) {
System.out.println("load from a txt file");
}
public void formatConsistency() {
System.out.println("txt file format changed");
}
}

//deal with XML format file
class XMLFile implements Display {

public void load(String xmlfile) {
System.out.println("load from an xml file");
}
public void formatConsistency() {
System.out.println("xml file format changed");
}
}

//deal with binary format file
class DBFile implements Display {

public void load(String dbfile) {
System.out.println("load from a db file");
}
public void formatConsistency() {
System.out.println("db file format changed");
}
}

//Test the functionality
class TestFactory {

public static void main(String[] args) {
Display display = null;

//use a command line data as a trigger
if (args[0].equals("1"))
display = new CSVFile();
else if (args[0].equals("2"))
display = new XMLFile();
else if (args[0].equals("3"))
display = new DBFile();
else
System.exit(1);

//converging code follows
display.load("");
display.formatConsistency();
}
}
//after compilation and run it

C:\>java TestFactory 1
load from a txt file
txt file format changed

C:\>java TestFactory 2
load from an xml file
xml file format changed

C:\>java TestFactory 3
load from a db file
db file format changed

In the future, the company may add more data file with different format, a programmer just adds a new class in accordingly. Such design saves a lot of code and is easy to maintain.

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Design Pattern (GOF): Creational Pattern : Builder

Definition

Construct a complex object from simple objects step by step.

Where to use & benefits

  • Make a complex object by specifying only its type and content. The built object is shielded from the details of its construction.
  • Want to decouple the process of building a complex object from the parts that make up the object.
  • Related patterns include
    • Abstract Factory, which focuses on the layer over the factory pattern (may be simple or complex), whereas a builder pattern focuses on building a complex object from other simple objects.
    • Composite, which is often used to build a complex object.

Example

To build a house, we will take several steps:

  1. build foundation,
  2. build frame,
  3. build exterior,
  4. build interior.

Let's use an abstract class HouseBuilder to define these 4 steps. Any subclass of HouseBuilder will follow these 4 steps to build house (that is to say to implement these 4 methods in the subclass). Then we use a WorkShop class to force the order of these 4 steps (that is to say that we have to build interior after having finished first three steps). The TestBuilder class is used to test the coordination of these classes and to check the building process.

import java.util.*;
 
class WorkShop {
    //force the order of building process
    public void construct(HouseBuilder hb) {
        hb.buildFoundation();
        hb.buildFrame();
        hb.buildExterior();
        hb.buildInterior();
    }
}
 
//set steps for building a house
abstract class HouseBuilder {
    protected House house = new House();
    
    protected String showProgress() {
        return house.toString();
    }
 
    abstract public void buildFoundation();
    abstract public void buildFrame();
    abstract public void buildExterior();
    abstract public void buildInterior();
}
 
class OneStoryHouse extends HouseBuilder {
    
    public OneStoryHouse(String features) {
        house.setType(this.getClass() + " " + features);
    }
    public void buildFoundation() {
        //doEngineering()
        //doExcavating()
        //doPlumbingHeatingElectricity()
        //doSewerWaterHookUp()
        //doFoundationInspection()
        house.setProgress("foundation is done");
    }
 
    public void buildFrame() {
        //doHeatingPlumbingRoof()
        //doElectricityRoute()
        //doDoorsWindows()
        //doFrameInspection()
        house.setProgress("frame is done");
    }
 
    public void buildExterior() {
        //doOverheadDoors()
        //doBrickWorks()
        //doSidingsoffitsGutters()
        //doDrivewayGarageFloor()
        //doDeckRail()
        //doLandScaping()
        house.setProgress("Exterior is done");
    }
 
    public void buildInterior() {
        //doAlarmPrewiring()
        //doBuiltinVacuum()
        //doInsulation()
        //doDryWall()
        //doPainting()
        //doLinoleum()
        //doCabinet()
        //doTileWork()
        //doLightFixtureBlinds()
        //doCleaning()
        //doInteriorInspection()
        house.setProgress("Interior is under going");
    } 
}
 
class TwoStoryHouse extends HouseBuilder {
  
    public TwoStoryHouse(String features) {
        house.setType(this.getClass() + " " + features);
    }
    public void buildFoundation() {
        //doEngineering()
        //doExcavating()
        //doPlumbingHeatingElectricity()
        //doSewerWaterHookUp()
        //doFoundationInspection()
        house.setProgress("foundation is done");
    }
 
    public void buildFrame() {
        //doHeatingPlumbingRoof()
        //doElectricityRoute()
        //doDoorsWindows()
        //doFrameInspection()
        house.setProgress("frame is under construction");
    }
 
    public void buildExterior() {
        //doOverheadDoors()
        //doBrickWorks()
        //doSidingsoffitsGutters()
        //doDrivewayGarageFloor()
        //doDeckRail()
        //doLandScaping()
        house.setProgress("Exterior is waiting to start");
    }
 
    public void buildInterior() {
        //doAlarmPrewiring()
        //doBuiltinVacuum()
        //doInsulation()
        //doDryWall()
        //doPainting()
        //doLinoleum()
        //doCabinet()
        //doTileWork()
        //doLightFixtureBlinds()
        //doCleaning()
        //doInteriorInspection()
        house.setProgress("Interior is not started yet");
    }
}
 
class House {
    private String type = null;
    private List features = new ArrayList();
 
    public House() {
 
    }
 
    public House(String type) {
        this.type = type;
    }
 
    public void setType(String type) {
        this.type = type;
    }
 
    public String getType() {
        return type;
    }
 
    public void setProgress(String s) {
        features.add(s);
    }
 
    public String toString() {
        StringBuffer ff = new StringBuffer();
        String t = type.substring(6);
        ff.append(t + "\n ");
        for (int i = 0; i <>
             ff.append(features.get(i) + "\n ");
        }
        return ff.toString();
    }
}
 
class TestBuilder  {
  
    public static void main(String[] args) {
       
       HouseBuilder one = new OneStoryHouse("2 bedrooms, 2.5 baths, 2-car garage, 1500 sqft");
       HouseBuilder two = new TwoStoryHouse("4 bedrooms, 4 baths, 3-car garage, 5000 sqft");
 
       WorkShop shop = new WorkShop();
       shop.construct(one);
       shop.construct(two);
    
   
       System.out.println("Check house building progress: \n");
       System.out.println(one.showProgress());
       System.out.println(two.showProgress());
   }
}
//need jdk1.5 above to compile


Author:

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

Kazi Masudul Alam

Software Engineer