Sunday, 26 February 2017

Exceptions in Java

Exceptions in Java

 An exception in Java is an event, which occurs during the execution of a program that disrupts the normal flow of the program.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, contains information about the error, including exception type and the state of the program when the error occurred and is called an exception object. Creating an exception object and handing it to the runtime system is called throwing an exception.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.


The Three Kinds of Exceptions
  • Checked exceptions − Checked exception is an exception that occurs at the compile time, and are also called as compile time exceptions. As these exceptions occur at the time of compilation of code, the programmer should take care to handle these exceptions.
  • Unchecked exceptions − Unchecked exception is an exception that occurs at the time of execution. As they occur at time of execution they are also called as Runtime Exceptions. These type of exception include programming bugs, such as logic errors or improper use of an API.
  • Errors − Errors are not exceptions, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in the code because you can rarely do anything about an error. For example, out of memory error.


Catching and Handling Exceptions
The exception mechanism in Java uses three exception handler components — the trycatch, and finally blocks.

The try Block
The try block is used to enclose the code which might throw an exception.
try {
    code
}
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.

The Catch Block
We associate exception handlers with a try block by providing one or more catch blocks directly after the try block.
try {
//some code that throws Exception
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
}
Each catch block is an exception handler that handles the type of exception indicated by its argument.
The catch block contains code that is executed if and when the exception handler is invoked.

The finally Block
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs.
finally is useful for more than just exception handling — it allows the programmer to write the clean-up code , even if there are no exceptions.
 finally{
 // code for clean up
 }

Advantages of Exceptions

  • Separating Error-Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping and Differentiating Error Types
Exceptions in Java

Exceptions in Java





Friday, 24 February 2017

Spring - Bean

Spring - Bean Definition

The objects that form the backbone of application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled and managed by a Spring IoC container. These beans are created with the configuration metadata that we supply to the container.
The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
·        How to create a bean
·        Bean's lifecycle details
·        Bean's dependencies
The above configuration metadata translates into a set of the following properties that make up the bean definition.
class
The class attribute is mandatory. The class attribute specifies the class of the bean to be constructed

id and name
Every bean has one or more ids called identifiers, or names. These ids must be unique within the BeanFactory or ApplicationContext the bean is hosted in. In an XmlBeanFactory, you use the id or name attributes to specify the bean id.

singleton or prototype
Beans are defined to be deployed in either singleton or non-singleton mode. When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.
The non-singleton or prototype mode of a bean deployment results in the creation of a new bean instance every time a request for that specific bean is done. This is ideal for situations where for example each user needs an independent user object.

By default beans are deployed in singleton mode. By changing the type to prototype, each request for a bean will create a new bean object.
In the below example, two beans are declared of which one is defined as a singleton, and the other one is a non-singleton (prototype). 
protoBean is created each and every time a client asks the BeanFactory for this bean, while singleBean is only created once; a reference to the exact same instance is returned on each request for this bean.

Spring - Bean
constructor arguments

This is used to inject the dependencies. Beans define their dependencies only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed.  The container then inject those dependencies when it creates the bean.
Inversion of Control/Dependency Injection exists in two major variants:
  • setter-based dependency injection is realized by calling setters on the beans after invoking a no-argument constructor or no-argument static factory method to instantiate the bean.
  • constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property.

bean properties
Bean properties and constructor arguments can be defined as either references to other managed beans or values defined inline. The XmlBeanFactory supports a number of sub-element types within its property and constructor-arg elements for this purpose.  This is used to inject the dependencies.


autowiring mode

It is possible to automatically let Spring framework resolve dependencies for the bean by inspecting contents of the BeanFactory. This is kown as Autowiring.  A BeanFactory is able to autowire relationships between collaborating beans.
The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans won't be autowired.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing. In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element.
 Autowiring modes





Thursday, 23 February 2017

JSP Implicit Objects

JSP Implicit Objects

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without declaring them explicitly. These objects are created by JSP Engine during translation phase (while translating JSP to Servlet). They are being created inside service method so the developer can directly use them within Scriptlet without initializing and declaring them.

There are total 8+1 implicit objects available in JSP.

The request Object
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
The response Object:
The response object is an instance of a javax.servlet.http.HttpServletResponse object. The server creates the response object to represent the response to the client.
The out Object:
The out object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
The JspWriter object contains most of the methods as the java.io.PrintWriter class.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.
The session object is used to track client session between client requests.
The application Object:
The application object is an instance of a javax.servlet.ServletContext.
Application object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
The config Object:
The config object is an instantiation of javax.servlet.ServletConfig.
The config object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
The pageContext Object:
The pageContext object is an instance of  javax.servlet.jsp.PageContext. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of pageContext object.
The page Object:
Page object is a reference to the current Servlet instance (Converted Servlet, generated during translation phase from a JSP page). We can simply use this in place of it.
The exception Object
Exception object is used in exception handling for displaying the error messages. This object is only available to the JSP pages, which has isErrorPage set to true.


JSP Implicit Objects
JSP Implicit Objects




Wednesday, 22 February 2017

Builder Design Pattern in Java

Builder Design Pattern in Java
Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Motivation
As an application grows complex, the complexity of the classes and objects used also increases. Complex objects are constructed by using other objects and needs special handling when being constructed.
An application might need a mechanism for building complex objects that is independent from the ones that make up the object. In this scenario, one might want to try using the Builder design pattern.
Builder pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the objects representation. This way the construction process can be used to create different representations. The logic of this process is isolated form the actual steps used in creating the complex object, so the process can be used again to create a different object form the same set of simple objects as the first one.

Applicability
Use the Builder pattern when
·         The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
·         The construction process must allow different representations for the object that's constructed.

Consequences
·         Builder pattern lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product. It also hides how the product gets assembled.
·         Builder pattern isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented.
·         Builder pattern gives you finer control over the construction process.

Implementation
We will implement Builder Pattern by using following classes.
1.      Our first class would be Meal class, which represents food items in a meal. It represents a drink, main course, and side.
public class Meal {

      private String drink;
      private String mainCourse;
      private String side;

      public String getDrink() {
            return drink;
      }

      public void setDrink(String drink) {
            this.drink = drink;
      }

      public String getMainCourse() {
            return mainCourse;
      }

      public void setMainCourse(String mainCourse) {
            this.mainCourse = mainCourse;
      }

      public String getSide() {
            return side;
      }

      public void setSide(String side) {
            this.side = side;
      }

      public String toString() {
            return "Drink : " + drink + ", Main Course : " + mainCourse + ", Side Dish : " + side;
      }

}

2.      Here we create a Builder interface, MealBuilder. It methods will be used to build a meal and to retrieve the meal.
public interface MealBuilder {
   public void buildDrink();

   public void buildMainCourse();

   public void buildSide();

   public Meal getMeal();
}

3.      Our first implementation of MealBuilder is ItalianMealBuilder. Its constructor creates a meal. Its methods are implemented to build the various parts of the meal. It returns the meal using getMeal() method.
public class ItalianMealBuilder implements MealBuilder {

   private Meal meal;

   public ItalianMealBuilder() {
         meal = new Meal();
   }

   @Override
   public void buildDrink() {
         meal.setDrink("Martini");
   }

   @Override
   public void buildMainCourse() {
         meal.setMainCourse("Simple Spinach Lasagna");
   }

   @Override
   public void buildSide() {
         meal.setSide("Spring Green Risotto");
   }

   @Override
   public Meal getMeal() {
         return meal;
   }
}

4.      Similarly second implementation of MealBuilder is JapaneseMealBuilder. Its constructor creates a meal. Its methods are implemented to build the various parts of the meal. It returns the meal using getMeal() method.
public class JapaneseMealBuilder implements MealBuilder{
   private Meal meal;

   public JapaneseMealBuilder() {
         meal = new Meal();
   }

   @Override
   public void buildDrink() {
         meal.setDrink("Chuhai");
   }

   @Override
   public void buildMainCourse() {
         meal.setMainCourse("Tofu and Sweet Potato");
   }

   @Override
   public void buildSide() {
         meal.setSide("Onigiri");
   }

   @Override
   public Meal getMeal() {
         return meal;
   }
}





5.      The MealDirector class takes a MealBuilder as a parameter in its constructor. A different type of meal will be assembled by the MealDirector depending on the Concrete Builder passed in to the constructor.
public class MealDirector {
   private MealBuilder mealBuilder = null;

   public MealDirector(MealBuilder mealBuilder) {
         this.mealBuilder = mealBuilder;
   }

   public void constructMeal() {
         mealBuilder.buildDrink();
         mealBuilder.buildMainCourse();
         mealBuilder.buildSide();
   }

   public Meal getMeal() {
         return mealBuilder.getMeal();
   }
}

6.      The Main class is used as entry point to the application and demonstrate our builder pattern code.
public class Main {
   public static void main(String[] args) {

         MealBuilder mealBuilder = new ItalianMealBuilder();
         MealDirector mealDirector = new MealDirector(mealBuilder);
         mealDirector.constructMeal();
         Meal meal = mealDirector.getMeal();
         System.out.println("Italian Meal : " + meal);
        
         mealBuilder = new JapaneseMealBuilder();
         mealDirector = new MealDirector(mealBuilder);
         mealDirector.constructMeal();
         meal = mealDirector.getMeal();
         System.out.println("Japanese Meal : " + meal);
   }
}


When we execute the Main class we get the following output

Builder Design Pattern in Java
Builder Design Pattern in Java


Related Posts Plugin for WordPress, Blogger...