Tuesday, June 23, 2009

Cities hosting I.T Companies in the U.S

-          Atlanta

-          Seattle

-          Chicago

-          San Francisco

-          Bay Area

-          Detroit

-          Massachusetts

Sunday, June 21, 2009

Command Design Pattern

When one object has to issue a request to another object without know anything about the object that is receiving the request or the operation that is being requested.

Following is a class diagram of various entities:



invoker - the object that needs to make the request without knowing receiever
Command - the interface that specifies the APIs that Command implementations must realize/implement.
CommandImpl - A implementation of Command that contains logic to realize command. Usually delegates to a receiver.
Receiver - Object that contains the actual business logic to realize the request. This usually has no web or struts context.

For example the struts framework must invoke application logic without knowing which application object is receiving the request or what operation is being performed by the application object. To achieve this, struts exposes Action interface. Application action classes must implement the struts action interface. The responsibility of the struts action implementation is to realize the business functionality. To do so, the action implementation usually invoke a application object (a pure business object that has no dependency on struts or has not web context). This application object, in the context of Command Design Pattern, is referred to as a receiver.

The struts ActionServlet handles the in-bound request and invokes RequestProcessor.process method. This method as part of the many things it does, has a reference to an Action implementation (specified in struts-config.xml) and invokes Action.execute(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) without knowing which action implementation it is invoking or the operation it is performing..

The Action interface is a good example of Command component in Command design pattern.



Struts classes: Source

Saturday, June 20, 2009

Drools basics

Source

What is a Rules Engine?

If you've ever taken a series of conditional statements, tried to evaluate the combinations, and found yourself writing deep nested logic to solve a problem, these are just the sorts of entanglements that a rule engine can help you unrave.

Complex business rules when expressed as rules are easier to understand.

What is a business rule?

Its a business-oriented statement that encompasses a business decision. Often implemented by a if-then statement.

e.g.

Given a car and a driver, if all of the following conditions are met:
The car is red
The car is in a sport class
The driver is male
The driver is between the ages of 16-25

The consequence is a 20% insurance premium increase.

These business rules are not new: they are the business logic that is the core of many business software applications. If you're a developer, you've seen these rules time and again expressed as a subset of requirements. They're statements like "give a twenty-percent discount on orders over three items on Mondays" or "we don't insure sixteen-year-old males on supersport motorcycles."

The difference is in how the rules are implemented in the code. Traditionally these rules are written as if-else statements in application code. In drools, these rules are specified in Business rules form.

A rules engine takes these rules and executes them. Apart from that the engine also facilitates creation, deployment, storage, versioning and other administrative functions on rules.

Given a set of rules, the rules engine needs to determine whether a given rule should be selected for execution or not. Once selected for execution, the engine needs to determine the order in the selected rules must be executed in.

The rules engine uses a matching algorithm to determine which rules to execute. Drools uses a matching algorithm called Rete. Rete constructs a tree of business rules. Each node is a rule. Each leaf in the rules tree is a rule consequence (e.g. increase premium by 20%). A Fact (an applicant of age 21 applied for insurance for a green sedan [a 4 door car]) enters the top of the fact tree. Based on whether or not the fact satisfies a rule in a node, the fact navigates through the tree until it hits a leaf or a rule consequence. Treat, Leaps, Rete II and Rete III are improvisations of Rete.

Rules engines make sense when there is a certain level of complexity in the rules. If the rules are trivial or if every rule has to be run on every fact, then the overhead of using the rules engine may not be necessary. If the rules are complex, then the overhead makes sense.

Different rule engines expect rules to be specified in different ways. In java drools rules can be specified in xml files or java annotations or java POJOs that are wired with spring.

an example drools 3.0 .drl file:
package com.insurance.auto
import com.insurance.auto.Driver
import com.insurance.auto.Car
import com.insurance.auto.Policy
import com.insurance.auto.Style
import com.insurance.auto.Color
import com.insurance.auto.Percentage;
rule "High Risk"
when
Driver( male=true, age >= 16, age <= 25 )
Car ( style == Style.SPORT, color==Color.RED )
$p: Policy ()
then
$p.increasePremium( new Percentage( 20 ) );

Flavors:
The rule server can be embedded or can run as a server. If the application using the rules is already in a distributed env. (like EJB, web services, corba etc..) then hosting the rules in a server is better otherwise embedded mode is good.

Tuesday, June 16, 2009

Logging call stack

There may be situations where in you only want to log the call stack (to find out how a method got invoked). An easy way to do this is to throw a new java.lang.Exception(“”). Catch it and log it in the log file. This way you can have the call stack for a method invocation without having the bebug.

 

        try

        {

            throw new java.lang.Exception("Dummy exception to display call stack");

        } catch (java.lang.Exception e)

        {

            log.debug("stack trace", e); // This will print the exception on to the log file

        }

Wednesday, June 10, 2009

Using commons bean library to get all properties of a bean

    public String[] getFieldValues( DataObject bean )

    {

        List<String> fieldValues = new ArrayList<String>();

        try

        {

            // TBD: handle null key

            fieldValues.add(PropertyUtils

                .getSimpleProperty(bean, "key")

                .toString());

 

            PropertyDescriptor[] properties =

                PropertyUtils.getPropertyDescriptors(bean);

            for (PropertyDescriptor property : properties)

            {

                String propertyName = property.getName();

                Object propertyValue =

                    PropertyUtils.getSimpleProperty(bean, propertyName);

                if (null != propertyValue

                    && !propertyValue.toString().isEmpty())

                {

                    fieldValues.add(propertyValue.toString());

                }

            }

        }

        catch (Exception ite)

        {

            // TBD: handle this

        }

        return fieldValues.toArray(new String[0]);

    }

 

Friday, June 05, 2009

Thursday, June 04, 2009

What is GWT (Google Web Toolkit)

You write in java and GWT compiles to javascript. Different dialects for each browser generated.

 

Used to write rich client applications like think client applications. GWT is a client side. Had remote procedure calls to made server side calls. On server side ur on ur own.

 

JSF and other web framework support GWT. So GWT can be used to make ajax requests and handle them with server side frameworks like JSF or struts to handle the request on the server side.

 

Put the pedal to the metal (use a tech. to achieve traction). :-)

 

 

 

New Features in Java 1.5

  1. Generics: Collection<Student> students;
  2. Enhanced looping: for (Student currentStudent : students)
  3. Autoboxing and unboxing: Integer x = 4 // boxing; Integet y = 5 //boxing; System.out.println(x+y); //unboxing
  4. Enums: instead of static final constants e.g. enum colors {WHITE, GREEN, BLUE}
  5. Variable number of arguments:

·         Use sparingly and try not to overload variable argument methods as it becomes difficult to figure out which method will get invoked. They are invoked when no other method signature matches the call.

·         Zero or more arguments can be passed for variable arguments

·         Variable arguments can only be used as the final set of argument in a method

e.g.

…..func1(String one, String… args) // correct

…..func1(String… args, String one) // not correct

 

Old:

public class Test2

{

        public static void main(String[] args)

        {

                System.out.println(contact(",",new String[]{"one", "two", "three"}));

        }

 

        private static String contact(String seperator, String[] tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

New:

public class Test3

{

        public static void main(String[] args)

        {

                System.out.println(contact(",","one", "two", "three"));

        }

 

        private static String contact(String seperator, String... tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

 

Wednesday, June 03, 2009

Number types in Java


Boxing: If you use a primitive type where a Object is expected, then the compiler will auto-box it into a wrapper class. Similarly if a wrapper object is used where a primitive is expected, the compiler will auto-unbox it.

Integer x = 10; // 10 boxed into wrapper class instance x
Integer y = 20; // 20 boxed into wrapper class instance y
System.out.println(x+y); // x and y unboxed to primitives so that they can be added by passing them to the + operator

Advantages of using a Object-wrapper-of-a-primitive over using a primitive
1. Argument to methods that expect a Object such as the collection interfaces
2. To use constants defined in these wrapper classes such as min_value and max_value
3. To convert primitives to wrapper classes using methods exposed in wrapper classes

Methods exposed by sub-classes of Number
xxxValue() e.g. byteValue() returns the wrapped primitive value
static Byte | Short | Integer | Long | Float | Double valueOf (byte, short, int, long, float, double) -> primitive to wrapped type
static Byte | Short | Integer | Long | Float | Double valueOf (String) -> String to Wrapped type
int compareTo(Byte | Short | Integer | Long | Float | Double) - to compare Number instances
boolean equals(Object)
static String toString(int i), String toString() to convert primitive to String

Tuesday, June 02, 2009

Source of previous post on Business Objects

A business object

A business object is a software representation of a real life entity. The entity could be a person, process, event or place. Examples of business objects are employees, products, invoices and payments. Business objects contain business data and model business behavior/process.

 

Business objects are different from data object which only hold data and do not have any behavior.

 

There are 2 ways or 2 strategies to achieve business objects:

EJB Strategy: Uses Entity Beans to model business data (with or without Container Managed Persistence) and Session beans to model Business process.

Pojo Strategy: Use simple Pojo (Plain Old Java Objects) along with light weight persistence mechanism such as hibernate/JDO (Java Data Object) or JDBC.

Hibrid: Uses POJOs behind the scenes using EJBs. Implement session façade in session beans and use POJOs to persist data.

 

Design patterns - Session Facade

Design patterns - Session Facade (source)

Business processes involve complex manipulation of business processes. Business classes participate in several business processes. If the responsibility of orchestrating (making the calls on business objects [may be session and entity beans] necessary to achieve a business process) the business process is placed with the clients of business objects, then clients become difficult to write and business objects themselves become tightly coupled. 

The session facade defines a higher level component that abstracts the complex interactions between lower level business components. Session facade in implemented in a session enterprise bean. It provides a single interface for clients to achieve a full business process or a part of it. It also decouples lower lever business components from one another.

Facade in french means face. Hence the facade component exposes a single face for a business process.

Giving access to each small interface on the lower level business components increases network traffic and latency. 


Example: Approval of large purchase orders may be a complex business process involving several business objects. In this case a OPCAdminFacade (Order Processing Center) facade ay be introduced that exposes APIs to achieve order processing. In this case the UI code will interface with only the OPCAdminFacade and not with each of the business objects.

public interface OPCAdminFacade extends EJBObject {

public OrdersTO getOrdersByStatus(String status)
throws RemoteException, OPCAdminFacadeException;

public Map getChartInfo(String request,
Date start,
Date end,
String requestedCategory)
throws RemoteException, OPCAdminFacadeException;
}

OPCAdminFacade would be implemented in OPCAdminFacadeEJB.


The getOrdersByStatus would interface with ProcessManagerLocal and ManagerLocal to get a list of PurchaseOrderLocal entity beans. It then creates a List of transfer objects (OrderDetailsTO [transfer object]) and returns them to the client.

Web Services Notes (Source)

Web Services Notes (Source)

For 2 business applications to communicate with each other (distributed computing env.) they need. 
1. A means for find and register a service
2. A transport mechanism to access a service
3. A way to define what the input and out parameters are

RMI existed before web services. There was not a well established protocol or overlapping protocols (UDDI and ebXML) in RMI to achieve each of the above. The advantage with web services is significantly higher levels of abstraction. They are language transparent (web services written in c and java can interface with each other), Container transparent (Services hosted on heterogenous environment/servers can interface with each other) and implementation abstraction (one service fewer assumptions about the implementation of the other service thus coupling between the 2 services is reduced). 



Service provider hosts several services some of which are web services.
Service repository hosts meta information about services and are lookup by service clients
3 in diagram above indicates the address at which the service is available, the signature of the service and others
4 & 5 is client binding to the web service and their consumption of service exposed in the web service

Web services are better than RPC 
1. Web services uses XML for data interchange so there is no developer written code to marshell or unmarshell data
2. XML data is interchanged using HTTP or SMTP which are well defined standards
3. The underlying service is specified using WSDL (hosted by service provider)
4. Web services can be searched for using UDDI


WSDL (Web Services Description Language)
- (pronoinced wisdel) (a form of IDL - Interface definition language) 
- Specifies a interface in XML and defines the XML schema and thus provides the vocabulary for defining interfaces like <types> and <message>. 
- Semantics of services like synchronous request/reply synchronous reply only and asynchronous communicate
- end point and transport  of the service using <service> element i.e. who provides the service
- encoding using <binding> i.e. how to access the service