Monday, October 17, 2011

Java Exceptions

You must be familiar with java compile errors, the most common ones being syntax errors, missing return statements, using uninitialized variables, attempt to access non-static members from static method, etc..

The compiler is optimized to detect them for you and asks you to correct them before they can be run. However, compiler's ability to detect errors is limited. Some errors are not known until runtime. These are called exceptions. On most of the sites, you must have heard it to be 'abnormal' or 'unexpected' but the whole gist of it is the fact that they are undetermined at compile time.

So why care about something you cannot handle anyway.. You can always run and check what error it gives !
Hmmm, first of all handing over an unpredictable code is a bad idea. Secondly, hurray!! We can handle exceptions. We may not be able to be precise on what exactly may go wrong during runtime but then we can make use of the known types of exceptions a particular task may throw.

For this, lets classify Exceptions on the basic of how they may be handled:
Some exceptions are expected to be handled for sure before compilation. These are meant to assure recovery or make the program predictable even in worse scenarios. Example, if a file that is to be opened does not exist or if a user inputs an invalid data type.. These can be foreseen and MUST be handled. These exceptions are called Checked Exceptions.
Then there are exceptions which are caused due to logical errors. We are expected to make the code bug free rather than handling them. They are called as Runtime Exceptions. It is optional to handle it.

Then what are errors? In java exception terminology, 'Error' is beyond the reach of a programmer. They cannot be predicted or recovered from. They are caused mainly at hardware level and not our concern !!

By the way, in java, Exception (which actually is an event) is class-ified and any exception (but not error) thrown are objects of this class - Exception.

Lets clarify more on the above:
  • Checked exceptions MUST be handled. They mean to serve User Errors.
  • Runtime exceptions and Errors are together called, 'Unchecked exceptions'.
  • Runtime exceptions can be fixed by bug fixes and through logic. They mean to serve Programmer Error.
  • Errors are not in our hands.
  • In Java, there is this class - Exception. Any exception thrown is an object of this class ;)

A look into Exception classes and Hierarchy now:

We know by now that all classes have java.lang.Object as a superclass directly or indirectly.
You can see the class 'java.lang.Exception' which encompasses all checked exceptions and runtime exceptions.

Some common checked exceptions are:

Runtime Exceptions:

You must be clear with the hierarchy to proceed..
The Exception class contains some methods that we may need while handling exceptions instances:
  • getMessage() - gives info of the exception.
  • getCause()
  • printStackTrace() - gives info and also prints it to System.err (error o/p stream)
  • getStackTrace()

So ready to write handlers?
Well, before that let us check out the flow of exceptions.
Say your program flow is as below:

Main() -> makeTree() -> checkRoot() -> printTreeToFile()

Scenario 1:
makeTree() handles IOException.
checkRoot() handles EOFException.
printTreeToFile() throws FileNotFoundException.

Will the exception be handled? Which method will handle it?
For this, you must start to know some basic Exception hierarchies. Here's help with the same..

Since printTreeToFile() does not handle any exception, it is propagated to its calling method, checkRoot(). checkRoot() doesn't handle it too and so it's propagated to makeTree() {visualize call stack to check the flow of unhandled exception}. Now, makeTree() handles doesn't handle it BUT it handles an exception which is super to the thrown one. Therefore it is handled here !!

Scenario 2:
makeTree() handles IOException.
checkRoot() handles FileNotFoundException.
printTreeToFile() throws FileNotFoundException.

Moving along the call stack, we see that checkRoot() will handle this.. quite obvious after understanding scenario 1.

There are many such scenarios where one needs to be able to predict the flow of an exception. However, once clear with call stack and exception hierarchy, it's easy to check on the flow.

How do we handle exceptions?
The most awaited question so far.. For this we use try-catch-finally blocks.
The code snippet that is anticipated to produce checked exceptions, which as per java MUST be handled, must be enclosed in try block.

For example, creating a new FileInputStream may cause FileNotFoundException which is a checked exception and must be handled. Therefore, we handle it by writing it in a try block as below.

   file = new FileInputStream(fileName);
   x = (byte);

Simple, isn't it.. Some basic rules to remember:
  • Every try block MUST be succeeded by EITHER catch block OR finally block.
  • All three blocks can also be written if required.
  • A try block can have multiple catch blocks.
  • It can have only one finally block ATMOST.

What is catch block used for?
The try block is only meant to contain the lines of code that could throw exceptions. However, if the try block is followed by catch blocks, then the closest suitable block that can handle that particular exception is chosen to handle it.

   //Protected code
}catch(ExceptionType1 e1)
   //Catch block
}catch(ExceptionType2 e2)
   //Catch block
}catch(ExceptionType3 e3)
   //Catch block
   //The finally block always executes.
Say in the above try block, ExceptionType2 is thrown.. This will be handled by the second catch block.
If the try block throws an exception which is subtype of ExceptionType1, then the first catch block will handle it

Important things here to be noted:
  • Finally block MUST always be placed as the last block.
  • The order of catch blocks if handling exceptions in hierarchy must be  from the most specific to general type of exception.
  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • Any code cannot be present in between the try, catch, finally blocks. 
This is not all folks! There is a lot more to Java Exceptions..

If a method wants its calling method to handle an exception, it can skip the try-catch-finally and just SPECIFY that the exception can be thrown with throws clause. This will cause the exception to further up to the calling method on the call stack which again must either handle it or specify it for its calling method to handle.
So how do we specify?
By using throws clause..

public void printTree() throws IOException{

What happens here is, if any line of code in printTree() throws an exception or if any exception has propagated to this method, then as it has specified using throws clause, this exception will be handled to its calling method to be handled. Note that the exception that has been specified here is IOException and therefore only this exception can be propagated. For all other exceptions it may throw, it should handle or specify.

We can create and throw exceptions as well.

How to throw an exception?
For this we use a throw statement.

throw new EmptyStackException();

Note that 'throw' can be used to throw a java.lang.Throwable exception which means it can throw checked and runtime exception.
In the above example, EmptyStackException is a runnable exception (unchecked). Runtime exceptions indicate invalid client code or invalid usage of client API. Throwing this runtime exception will give the client useful information on recovery.

How to declare/create exception?
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.

class MyException extends Exception{
Why would I create my own exception?
As mentioned in Oracle Documentation, if you say yes for any of the following, then it means you need to create your own exception.
  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?


What about chaining exceptions?
As we saw, we can throw an exception using throws clause. If in handle code of of one exception, you are throwing another exception and so on, then it is called chained exception.
There is not much of space science to it. The gist of this lies in how you can utilize this feature in your logic.

Already Tired??
Well, we are done with the basics but this topic is more about how well you can put it to use rather its than rules and syntax.

Coffee Break:
Checked exceptions MUST be handled. They mean to serve User Errors.
Runtime exceptions and Errors are together called, 'Unchecked exceptions'.
Runtime exceptions can be fixed by bug fixes and through logic. They mean to serve Programmer Error.
Errors are not in our hands.
In Java, there is this class - Exception. Any exception thrown is an object of this class. ;)
Every try block MUST be succeeded by EITHER catch block OR finally block.
All three blocks can also be written if required.
A try block can have multiple catch blocks.
It can have only one finally block ATMOST.
Finally block MUST always be placed as the last block.
The order of catch blocks if handling exceptions in hierarchy must be  from the most specific to general type of exception.
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever a try/catch block is present.
Any code cannot be present in between the try, catch, finally blocks.



Wednesday, July 20, 2011

Design Pattern

Life is full of problems. Some problems occur frequently and are common. Keeping solutions to such problems in mind is good. This saves time in solving the problem. At least you will be knowing how to approach the problem. Its not necessary that you approach it the same way or use the same solution but then you will be aware of the known solution that may help you to make your own solutions... better one :)

Design patterns are no different except that these are intended for problems in software design. They are reusable solutions for common problems. It may be a simple description of solution or a template. It is language independent. They are not complete solutions since they only provide description or template which needs to be converted into code for final use.

In simple words design patterns are recurring solutions to design problems. The documentation format(explaining about the design pattern) as given by Erich Gamma,Richard Helm, Ralph Johnson and John Vlissides (collectively known as the "Gang of Four", or GoF for short) in their book Design Patterns contains:
1.  Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern.
2.  Intent: A description of the goal behind the pattern and the reason for using it.
3.  Also Known As: Other names for the pattern.
4.  Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used.
5.  Applicability: Situations in which this pattern is usable; the context for the pattern.
6.  Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.
7.  Participants: A listing of the classes and objects used in the pattern and their roles in the design.
8.  Consequences: A description of the results, side effects, and trade offs caused by using the pattern.
9.  Implementation: A description of an implementation of the pattern; the solution part of the pattern.
10. Sample Code: An illustration of how the pattern can be used in a programming language.
11.Known Uses: Examples of real usages of the pattern. 
12. Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.

There are many design patterns known so far out of which 23 java design patterns are commonly practiced. They are grouped as follows

Well let me give you some brief idea on them. We will see more on it later.
Creational patterns are the ones that deal with object creation mechanism. In java, creating an object by simple statement Class_A a = new Class_A(); is hardcoding and should be avoided for having a quality software. So we should choose the object creation mechanism depending on the situations or scenario and requirement. Creational patterns include many patterns that will help us in doing this. 

Behavioral patterns define common communication patterns between objects to provide flexibility in communication. So basically it deals with object interactions. The objects should be interacting with loose coupling.

Structural patterns are patterns for realizing relationship between entities. They are for describing how objects, classes and other entities are associated with each other and therefore giving us a complete structure in abstraction.

Coffee Break
Design Patterns are for making use of solutions(predefined or known) for commonly known problems.
They are language independent.
They are description or template of solution.
They are incomplete solutions(need to be transformed into code).
Grouped under creational, structural and behavioral.

Friday, May 27, 2011

J2EE Part 3 - J2EE Containers

While writing business logic in J2EE application many programmers faced many similar problems for which they had to re-implement the solutions. Enterprise JavaBeans(EJB) was intended to handle such common concerns.

The EJB container is a runtime environment that controls the enterprise beans and provides them with important system-level services. Since you don't have to develop these services yourself, you are free to concentrate on the business methods in the enterprise beans. 
The EJB container provides solutions for common concerns to the enterprise beans such as:
1. Transaction Management
2. Security
3. Remote Client Connectivity
4. Lifecycle Management
5. Database Connection
For each enterprise bean, the container is responsible for registering the object, providing a remote interface for the object, creating and destroying object instances, checking security for the object, managing the active state for the object, and coordinating distributed transactions. Optionally, the container can also manage all persistent data within the object. Therefore the programmer can focus on the main logic and leave all this work for the container.

J2EE Client contains application client container that manages execution of application client components. 
J2EE Server contains EJB containers and web containers. EJB containers manages execution of enterprise beans. Web containers manages the JSPs and servelet components.  

Enterprise beans are server components written in the Java programming language. Enterprise beans contain the business logic for your application.
Enterprise JavaBeans technology supports both transient and persistent objects. A transient object is called a session bean, and a persistent object is called an entity bean.

A session bean exists only for the duration of a single client/server session. A session bean performs operations such as accessing a database or performing calculations. Session beans can be transactional, but normally are not recoverable following a system crash. Session beans can be stateless, or they can maintain conversational state across methods and transactions. A session bean must manage its own persistent data.

An entity bean is an object representation of persistent data maintained in a permanent data store, such as a database. An entity object can manage its own persistence, or it can delegate its persistence to its container.

Purpose of sessions bean is to perform a task for a client and is not persistent. It may have one client only. Entity bean on the other hand represents business entity object in persistent storage. It can have multiple clients. 

Simple example showing both:

The customer, order and product require persistent storage and hence entity bean.

A good rule of thumb is that entity beans model business concept expresses as 'noun' since they model real world objects that are persistent. For the above example -> product, order and customer are entity beans. 

Session beans only manages the client processes and tasks. It manages activities like for the above example 'shopping activity'. It does not represent any persistent data in database. It is transient because it performs the set of activities it is supposed to and then it ends. It therefore models interactions.

Lets have a brief look at how to implement an enterprise bean:
1. you need to define two interfaces and two classes.
2. Remote Interface: defines business methods of the bean. It extends javax.ejb.EJBObject that in turn extends java.rmi.Remote.
3. Home Interface: defines bean's lifecycle methods. Therefore it includes methods for creating new beans, finding beans and removing them. It extends javax.ejb.EJBHome that in turn extends java.rmi.Remote.
4. Bean Class: actually implements bean's business methods. An entity bean must extend javax.ejb.EntityBean and a session bean must extend javax.ejb.SessionBean. Also both should extend javax.ejb.EnterpriseBean. NOTE -> This class does not implement either of the above interfaces but must have methods matching signatures of methods in Remote Interface and must implement some methods of Home Interface... We will see more on this later.
4. Primary Key: It is a simple class that provides a pointer into the database. It should implement Serializable. As we already know that only entity beans deals with persistent data, only entity beans will need primary key and session beans clearly doesn't.

You need to know two basic things before we proceed:
1. Client never interacts with Bean Class directly. It makes use of both the interfaces only to interact with stubs that are generated automatically.
2. A bean that needs services of another bean is a client to it if seen in a relative manner and therefore the above applies to it too.

Container is primarily responsible for creating 'instances' of beans and making sure they are stored properly by the server. There are many containers provided by different vendors in market providing different tools and therefore must be selected accordingly... At least one tool will deal with mapping of beans with database. Some tools will generate a code that will implement the interfaces to create bean and store it in database. This is why the Bean Class need not implement them :) 

So why did they make container... Why not just make the server do the container's work for the beans. One of the reasons is that a third party can provide containers and it can plugged into any server. The vendors can decide whether to make server or container and focus on it. One disadvantage of this container-server interface could     
be performance. Advantage follows the rule -> Higher the abstraction, greater the flexibility. Disadvantage is due to the rule -> Tighter the integration, better the performance. In the case of container-server interface the integration is not tight and hence low performance but the abstraction is at a higher level and hence the flexibility.

The responsibilities of server and container is dependent on the vendors. Many different types are available based on this and we should make a choice depending on our need.

Anyways we will talk more on EJB container only. I know we did a lot for the day... So details covered in next post and for now you can go for your coffee break :)

Coffee Break
Enterprise Beans are business object components.
Two types of beans - Session and Entity beans.
Session beans is transient.
Entity beans is persistent.
Beans contained in container.
Container handles common concerns of the app.
EJB container used for J2EE app. 
Container also manages object's database optionally
Container therefore relieves the programmer of common tasks and he can focus on business logic implementation only.
Enterprise Bean implemented by two classes and two interfaces.
Client has no direct interaction with beans.
A bean needing service from another bean acts like a client to it.
Remote Interface defines methods for the bean's business logic.
Home Interface defines methods for the bean's lifecycle.
Bean Class implements state and behaviour of beans.
Primary Key provides pointer into the database.

Wednesday, May 18, 2011

J2EE Part 2

Although a J2EE application can consist of the three or four tiers, J2EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three different locations: client machines, the J2EE server machine, and the database.


The above shows multi-tiered applications.

J2EE CLIENTS: can be web client or application client. Web clients consists of dynamic web pages generated by web components running in web-tier and web browser that renders the dynamic pages received from server in presentable format. Applet is a small client application that executes in JVM installed in web browser. Web clients are also called as 'thin clients' as they do not do heavy weight operations such as database queries or implementation of complex business logic. Another type of client is application client. Application client makes use of typical swing or Abstract Window Toolkit(AWT) APIs to provide a rich user interface.
The difference between standalone client and J2EE client is that J2EE client can connect to J2EE services.

Now we know that the client communicates to the business tier(meaning business layer on another computing system... therefore 'tier') either directly or through the presentation tier(meaning presentation layer on another computing system... through JSPs and servelets).

Web Component: They can be servelets or JSPs. Servelets are java classes having embedded html pages for dynamically processing requests and constructing responses. JSPs on the other hand are html pages having embedded java code.
Business Component: It contains the business logic or the implementation part... implementation of all the business rules.
JavaBeans Component: They can be on client side for managing data flow between applet or any other client to the components on J2EE server or it can be on J2EE server side for managing data flow between J2EE server components and database.

EIS Tier: It includes Enterprise Resource Planning(ERP) and handles information systems. It manages all the database connectivity stuff.

Finally we get:

Coffee Break
Noramlly J2EE used is 3 tiered architecture.
The tiers are J2EE client, J2EE server and database server.
Client tier can be web client or application client.
JavaBeans components are NOT considered as J2EE components by specification.
J2EE server consists of web tier and business tier. 
Database server consists of EIS tier.

Thursday, April 28, 2011

J2EE Part 1

J2EE - Java 2 Enterprise Edition is one of the 3 java platforms, the other being J2SE and J2ME. It is set of specifications or standards consisting of many APIs useful for building java based enterprise applications. At such it is not some software to be installed but is just a bundle of many technologies having set of APIs.

J2EE applications are java applications that span over LAN, WAN and broader. They are used when it comes to distributed environment and disparate systems and also when in need to make use of its technologies.

J2EE technologies are broadly classified into two categories:
1. Component technologies
2. Service technologies

Kinds of J2EE Components:
Client Side Comonents -> includes applets.
Web Components -> includes servelets and JSPs
Business Components -> includes EJB
Web components and Business components run on Server Side...

Kinds of J2EE Services:
JNDI -> Java Naming and Directory service
JMS -> java Messaging Service
JTA -> Java Transaction API
JAAS -> Java Authentication and Authorization Service
Java Mail

J2EE is meant for building the 3 layers of java based enterprise application. The layers being:
1. Presentation Layer
2. Service/Business Layer
3. Data Access Layer


We have been talking on java based enterprise application... To clear you on it:
A computer application used to manage business services of an enterprise is called enterprise application and if the application is coded in java and is deployed into J2EE compliant application server then it becomes java based. :)
Any enterprise application generally covers 4 main tasks:
1. providing user interface(UI) to the user.
2. processing of data according to some business logic(rules)
3. interacting with database(data access)
4. storing of data
These tasks are logically divided into 4 layers
                                     A. Presentation layer
                                     B. Business/Service layer
                                     C. Data Access Layer
                                     D. Data Layer


J2EE developers are responsible for the first 3 layers while the data layer is the responsibility of database administrator(DBA).
Hope you are clear on the layers... Remember they are just the logical division. Now coming to actual or physical division...
The physical partition of enterprise application is known as 'tier'. The enterprise application can be single-tier, two-tier, three-tier, n-tier or distributed-tier depending on number of computing systems on which the layers are installed.

Lets talk more on layers... 
Presentation Layer is the user interface part of the application. If the app is web based then Servelets and JSPs are used to build it on server side. The main design patterns used in this layer are Front Controller, Model-View-Controller(MVC), Composite View.
Business/Service Layer is nothing but a code that processes data according to business logic(rules). Some important design patterns used in this layer are Service Locator, Business Delegate, Session Facade. Job of service layer is to receive the business request from presentation layer or some other service layer, communicate with data access layer to get the enterprise data, process that data using defined business rules, return the result to the requested component
Data Access layer is again a code which communicates with the database. It performs CRUD(Create, Read, Update, Delete). Therefore it is just a code communicating with database specific APIs such as JDBC. The design patterns used are Data Access Object(DTO), Data Transfer Object(DTO), Value Object. Can you guess what its job is??? It receives request from service layer, communicates with the database to perform the requested operations and sends the result back to service layer. 

So now you clear on J2EE basics :)

Let me tell you more on business/service layer and then you can have your coffee break :)
We already know what is the job of service layer but in order for it to implement it, it needs some capabilities... like transactional capability, distributed computing capability, security implementation capability.    
To have these capabilities we make use of J2EE technologies(both components and services). Just scroll up and read the first three paragraphs... This should make it clear for you. 

Coffee Break
J2EE is not a software but is a set of standards/specifications having APIs to make java enterprise app.
Provides a standard for developing multi-tier enterprise services.
It is useful for building apps that span over LAN and needs to make use of its technologies.
It is platform independent.
J2EE technologies include components and services.
Business logic is organized into reusable components... so J2EE is helpful.
Layers are logical divisions of J2EE while tiers are physical partitions depending on number of computing systems used.
The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs.

Wednesday, April 20, 2011

HTTP - More...

We already are familiar with the basic idea and structure of HTTP. Well now lets move ahead... with gear 1 so no worries :)

Remember HTTP is a request/response protocol... !!! If 'no' then read the earlier post - 5 minutes of basics !!!

The key elements of HTTP request are:
> HTTP method
> Form parameters

HTTP method is nothing but the action the client wants to perform. The client may want to get something from the server or to post something to it - some data that the server can use for responding accordingly or can save it in a database for further utility. HTTP method specifies what 'action' the client performs. Basic HTTP methods are GET, POST, PUT, DELETE.

URL of course is for accessing the page the client wishes to... of the server !!!

Form parameters are some data that the client wishes to send to the server.

The key elements of HTTP response are:
> Status code
> Content - type
> Content

Status code for example can be something like 301, 302, etc... or something like 'not found', 'ok', etc...
This is information about the status of the request whether it was successful or not. So the response will tell the client the status of the request.

Content - type can be 'text', 'picture', 'html', etc... Just to specify the type of content to the client so that it can accordingly display it.

Finally the content - this is the actual text file, image or html that the server sends to the client for the request it has made.

Sunday, April 17, 2011


The term 'middleware' is generally used in the context of distributed systems. It is a software that helps two software components talk and share data. When the software components on both sides are applications, then we refer to this type of middleware as Enterprise Application Integration(EAI). Actually it acts like a glue between software components or software component and a network. It could glue application to database managers. A better way to define is to say that it 'mediates' between an application and network or between software components and software facilities as required in heterogeneous computing platform.
A simple example of middleware is Object Request Broker(ORB) that manges communication between objects. 
Middleware is used in context with High Level Architecture(HLA) that applies to many distributed systems. It is sometimes called 'plumbing' because it connects two applications and passes data between them. 
It was intended basically for following purposes:
1. For linking newer applications to older systems or applications.
2. Connecting multiple applications over a network and hence facilitating distributed processing.
3. To provide interaction between network and application or service
4. To provide interaction on network transparently.
5. To be independent of network services and always available

You could think of more uses but these are the basic ones...

A typical example of Middleware can be TCP/IP stack for telecommunications.

Some basic types of middleware are:
1. Message Oriented Middleware: Transactions or event notifications are sent between disparate systems via messages
2. Object Middleware: Consists of Object Request Brokers for communication between the objects. It is possible for applications to send objects and request services in object oriented system.
3. Remote Procedure Call(RPC) Middleware: used to call procedures on remote system. It can be synchronous or asynchronous.

There are many others... 

Coffee Break
Middleware is a glue between software components and network.
Software components can be service or application.
When glued between two applications it is called EAI
It is also called 'plumbing'
It is used in context with distributed systems.
Mainly needed for disparate applications/systems.
Serves message passing, data sharing and interaction between disparate disparate applications/systems.