Saturday 20 July 2019

Understanding Framework : Servlet Framework

Over period of time, the software industry is using lot of frameworks such as Servlet, Spring, Hybernate etc. This article will cover some of the basic concepts of framework.  It will also explore basics of servlet framework.

About Library functions

Many of us must have written C programs while taking first few steps towards the field of programming.  We all used to write a statement # include <stdio.h>…. This statement is used to include the contents of a library file called stdio.h. And we also know the fact that we include that file as it contains definitions of printf(…) & scanf(..) functions which are written by designers of C. These are called as library functions.  Thus when we use such library functions what we are doing is 

· We are reusing the code written by the designers of C
· The overall flow of execution of program is decided by us(the programmers)

The only function that designers of C have fixed is main() function.  Otherwise it will be difficult for C compiler to know the start point of a program containing many functions.

About Framework

Software designers have been developing different types of applications over period of years.  But there are many processes/modules that are common and everybody has to spend the efforts to code them.  So there was a need to free the programmers from writing these similar modules.  This would also help them to focus on the business logic of the actual application.  For example, C# designers get Toolbox containing lots of GUI controls which can be dragged on to forms.  printf/scanf functions of C, controls in toolbox etc are examples of reusable code.  Sometimes there can be similarities in the overall design and overall flow of the applications.  The ideas implemented by good designers and their experience can be used by others.  This is the main concept behind framework.  

Framework represents a set of modules that consists of reusable design of a specific software subsystem.  It specifies the overall architecture of the application and its flow.  To provide application specific software, it can be changed/extended by programmer’s code.   With respect to frameworks, an important term called “Inversion of Control” is used.  We have already discussed that the modules in the framework can be extended by programmer to contain application specific code and the flow of application is predetermined.  Generally, programmers call the code written by designers.  Here, designers of the framework call the code written by programmers.  This is called as Inversion of control.    It is also called as Hollywood Principle (“Don’t call us, we will call you”).  When framework is used, developers get following benefits-

· Less time in developing/designing, coding  and debugging,
· Reduces the cost,
· Minimizes the risk,
· Increases flexibility

Framework also has certain disadvantages –

· Since the design is predetermined, programmers may have to write functions with particular names/calling conventions.  Thus they lose creative freedom.  
· Once the design of the framework is decided, it cannot be changed in new versions of it as applications which are built using older version will fail to work.  

Understanding Servlet Framework

Introduction to Servlets

Servlet is a Java-based technology used for server-side programming in developing web applications.  Servlet and its related technologies(such as JSP)  is used for almost a decade.  It is also based on the concept of framework. Servlets are managed by Servlet Container which is a program that runs inside Web Server.  A servlet can be written for n number of web applications. But there are common tasks that servlet container has to do for each servlet while processing client requests.  They are as follows –
· Server needs to determine the lifespan of servlet program in memory
· Server needs to determine whether to load the program for each request or just once and execute it using multi-threading approach
· Creating request, response, configuration, session objects
· Communicate with other servlets if required

Since they have to be carried out for all the servlets, the servlet designers must have decided to provide these services to the servlets automatically so that the servlet programmers can spend more time on business logic of the application.  

About Servlets

Servlets are based on an interface called as Servlet.  This interface contains mainly three methods – init, service and destroy that control the life cycle of every servlet.  init method is called when the servlet is first loaded in the memory.  service method is called for every client.  destroy method is called only once, when the servlet is removed from the memory.

There are two main implementations to this interface  - GenericServlet and HttpServletServlet.  A GenericServlet is used for writing protocol independent servlets.  That means, a servlet should be executed using any other protocol such as FTP.  But such type of servlets are not used to that extent. The other class is HttpServlet that makes use of HTTP and this is used more often.  

When we have to write servlet programs, we write subclass of either GenericServlet or HttpServlet.  If we create a subclass of GenericServlet, then we override service( ) function.  If we create a subclass of HttpServlet, then we override doget( )/doPost( ) function.  The servlet objects are managed by servlet-container whose role is to provide all the services to servlets as mentioned above.  Our servlets act like components which are managed by servlet container(Component-Container Architecture).  

While writing servlets, we may come across various questions such as –

1. If servlet object is created, where do I specify class name?
2. If servlet interface contains service function, then how come doGet/doPost functions are overridden?
3. Generally object is created using  a statement like - ClassName ob = new ClassName( );
Where this statement is written? Since the functions are not static, that means object is definitely created.  But who creates the object? In fact how the statement could be written when designers don’t even know the name of classes that are being written today?
4. Why we don’t write a constructor in servlets?

Let me explain answers to all these questions using an example. Before cars were invented, man must have thought of something that moves which would help him travel faster.  Let us define an interface Movable -

interface Movable
// like servlet interface
{
    public void start();
    public void move();
    public void stop();
}

This idea was implemented by automobiles.  Let us represent it by a class AutoMobile –

abstract class AutoMobile implements Movable
//like generic servlet
{
    public void start()
    {
        System.out.println("Automobile  starts…");
    }
    public void stop()
    {
        System.out.println("Automobile stops…");
    }
    abstract public void move(); //still don’t know how to move
}

This is a general idea.  But we need a proper vehicle.  A man invented 2-wheelers. Let us represent it by a class called TwoWheeler -

class TwoWheeler extends AutoMobile
//userdefined subclass of generic servlet
{
    public void move()
    {
        System.out.println("Ride a two-wheeler...");
    }
}

This class can be instantiated and its move function can be called.  Then 4-wheelers were designed.  So let us define a class FourWheeler.  Also let is redefine move( ) operation by drive ( ) operation as drive will be a more better name for 4-wheelers.  

abstract class FourWheeler extends AutoMobile
//like HttpServlet
{
    public void move() //like service function
    {
   drive();//called inside move
    }
    abstract public void drive(); // like doGet/doPost function
}

After so many years, we see different types of 4-wheelers on road such as cars, trucks etc. Let us represent them using classes –

class Car extends FourWheeler
//like user-defined subclass of HttpServlet
{
    public void drive()
    {
        System.out.println(" Driving a car...");
    }
}

Let us see how these objects are created and called –

import java.io.*;
public class MovableDemo
// type of code which could be used by servlet container to create and execute servlet objects
{
    public static void main(String[] args) throws Exception
    {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What you want to move?:");

        String classname = br.readLine();//specify the name of class

        //in servlets, class name is mentioned generally in URL
        Class c = Class.forName(classname);
        Movable m = (Movable) c.newInstance();
        m.start();
        m.move();
        m.stop();
    }
}

This code tells you how objects of Movable type can be created and called.  If you have written JDBC programs, then you must have used Class.forName ( ).  It is used to load the class specified as argument in String form.   newInstance() function of class Class is used to instantiate the specified class.  Thus while coding MovableDemo class, it is not known what class name will be given by user.  User defines a new class, compiles and makes if available to MovableDemo. As the class is instantiated only using name, it will only call blank constructor.  Since new classname( ) approach of creating object can’t be used, it is not possible to call overloaded constructors.  Hence user can provide initialization code only in start (in servlets, init) function.  In applets as well, we have to provide initialization code in init method.  Why? Because we don’t create object of applet class.  

The way of using Movable objects is predetermined, first start, then move and then stop. We just have to write our code in these functions.  In servlets, sevlet container decides the flow of execution(that is, first init, service and then destroy).  Classes AutoMobile & FourWheeler(like GenericServlet & HttpServlet), are abstract as they contain abstract functions.  Hence they can’t be directly instantiated.  It is necessary to create subclasses of them.  

If a new type of four-wheeler is invented, it can also be executed using similar approach.  For example-

class Truck extends FourWheeler
//user-defined subclass of fourwheeler
{
    public void drive()
    {
        System.out.println(" Drive a truck...");
    }
}

This also can be executed using above approach.  Thus the designers of servlet are able to call functions of your class that you are writing today

Sunday 14 July 2019

Swag se karenge sabka Swagat!

If someone had told me that one day I would write a RAP or a SWAG type songs, I would not have believed and I would have laughed at them.  Surprisingly, it has turned into a reality! Accidents do happen, isn't it?

Sometimes in the teaching field, you may end up doing strange but interesting things while thinking out-of-the-box.  It happened with me three times.  I have already posted a "Powada" in my last blog.  But that was a decent a version of poetry.  That does not mean  that now what I am going to share is indecent :)

In our department, we always welcome FY by conducting a function called "Computer Science Association Inauguration". Its a very challenging task to do something different for the students considering the shortage of time.  So I decided to give it a try.  I usually teach Java to the students and I love Java programming language a lot.  But some students think otherwise and they find it a bit difficult.  Irregularity and lack of practice makes it worse.  Students crack joke on the language saying "Java Java Mar Java" or "Mar Java Mit Java".  I always feel bad about it being a fan of Java language.  One day few days before the CSA function, I was returning home and I heard a popular swag type of song.  A thought came to my mind, can I write something like this.  So I searched few swag type of songs and came to know that it was "Tera buzz muze jine na de.." by someone called Badshah.  Instead of that catch line, I thought let me replace that with "Mar Java Mit Java" and wrote something like this - 

Mar java, mit java...
Mar java, mit java...

Mumbai me ek course hai 
Jis ka nam hai BSc,
CS(or IT) me admission leke
Socha let us see,
Fadoo programmer banunga
Mera tha dawa,
Vaat lag gayi meri
Jab se aya hai java 

Mar java, mit java..
Mar java, mit java.. 

Wednesday ko ek baje tha 
Practical session, 
Pehle session me sikhaya
Loops and condition, 
If ko dala, for ko dala, 
Dala expression,
Run kiya to aaya muzko
ArithmeticException....

Lab me aisa atka mai
Jaise infinite loop,
Subah na dekhi sham
Na dekhi maine dhoop,
Pass mai kaise hoga is 
Tension me baitha chup,
Next term hai Android aur, 
Ty me Hadoop.....

Mar java, mit java..
Mar java, mit java.. 

System dot exit zero...

It was sung by SY-TY students in the function(August 2018) and everyone enjoyed :)  Even though I wrote the song, I disagree to the students' feelings that Java is difficult.  So many students who dont like Java,  later get the job on Java platform only.  

Guess what, when I was doing MSc Part I, our HOD gave some topics for seminar to all of us.  I had got the topic - "Java Programming Language".  That was year 1999 that I studied and presented something related to Java which was 4 years old that time.  I never knew that the same language would give me an opportunity in VES.  Few years ago, I also got an opportunity to present Java to the TYBSc Maths teachers when it was introduced in their syllabus as Applied Component.  I will always love Java and will continue teaching it.  

Fast forward to July 2019.  This time, we were supposed to welcome our new FYs by conducting a special student induction program.  We were told to conduct in a way which would make them interested to come to college.  That Sunday, a movie "Gully Boy" was released on the TV.  I watched and enjoyed it.  Later, my mind started thinking, what if we replace "Apna Time Ayega" by "Tera Time Ayega", it would suit FY!  Many times when you are struck with an idea, your mind doesn't rest until its executed.  Like a sneeze, when you get the sensation, you can be free only when you blow it:)  So the song that came out  of my mind was like this - 

Hi hello everyone,
Kaise hai sab fy,
Welcome karne aaye
Hum Sy and Ty,

Bolo (welcome FY...)x2
(Welcome to  VES...)x2

Pehle din pe hoga thoda
Dar aur thodi jizak,
Aise feelings ko tu bol
Mere mind se khisak,

Arts Science Commerce 
Ufff kitne sare streams,
Dher saaree ummide 
Aur kaise kaise dreams,

Doubt hai kya khwab 
Tera pura ho jayega, 
To mere jaisa shaanaa 
Tuzko ek hi baat batayega,

Tera time ayega, 
Tera time ayega
(VES me aya hai to 
Khaali haat na jayega...)X3

The group of students who were supposed to welcome all the students of FY liked it very much and they performed it in the college quadrangle.  

A powada in Marathi, a swag in Hindi-Java and a Rap in Hindi-English... three different genres that I wrote have been performed so far.  So what next?  Something in English? Blues is ready...its just a question of when and where...



मन बावरे

तुम्ही "ती सध्या काय करते" हा चित्रपट पाहिला आहे का हो? असेलच आणि आवडला पण असेल. पण तुम्हाला माहिती की अशाच विषयावरचा "96...