Thursday, May 31, 2012

Application Server v/s Web Server



A Web server can be either a computer program or a computer running a program that is responsible for accepting HTTP requests from clients, serving back HTTP responses along with optional data contents, which usually are web pages such as HTML documents and linked objects on it.

An application server is the kind of software engine that will deliver various applications to another device. It is the kind of computer found in an office or university network that allows everyone in the network to run software off of the same machine.


A web server and an application server may differ on the following points:

Comparison chart




Application Server
Web Server
Protocols:
Supports HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page (static content) or
delegates the dynamic response generation to some
other program such as CGI scripts or Servlets or JSPs in the application server.
Exposes business logic and dynamic content to the client
through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.
Job:
application server is used to serve web based applications and enterprise based applications (i.e sevlets, jsps and ejbs...). because application server contains web server internally.
web server is used to serve web based applications. (i.e servlets and jsps)
Examples of popular server products:
  • Weblogic server
  • Sun Java Application server
  • Apache Geronimo
  • Apache Tomcat
  • Microsoft IIS
Clients can include:
GUI’s, Web Servers
Web browsers, search engine robots
What is it?:
A server that exposes business logic to client applications through various protocols including HTTP.
A server that handles HTTP protocol.
Functions:
To deliver various applications to another device, it allows everyone in the network to run software off of the same machine.
Keeping HTML, PHP, ASP etc files available for the web browsers to view when a user accesses the site on the web, handles HTTP requests from clients.
Functionality:
Adds functionality
Does not add any
Introduction (from Wikipedia):
An application server is a software framework that provides an environment in which applications can run, no matter what the applications are or what they do.
Web server can refer to either the hardware (the computer) or the software (the computer application) that helps to deliver content that can be accessed through the Internet.



Function

The main function of a web server is keeping files active for web site browsing, 24x7. Any time lost is known as down time which means that at that point, the website and its pages will not be viewable. Any good web hosting company tries to keep their downtime to less than a fraction of a second to be successful. An Application server facilitates this process and tries to make for easy data access of an application.

Multi Threading

The Web Server does NOT support the concept of multi-threading.
In Application Server we have features like connection pooling, isolation pooling, multi-threading, and majorly the Transaction feature which is not there in Web Server.

Web servers (programs) are supposed to serve requests quickly from more than one TCP/IP connection at a time.Consider that Internet Explorer or Firefox Web Browser is a local program on the user's hard drive, whereas the web pages themselves are not. The web pages are actually stored on the hard drives of other computers, and these are known as web servers.

Application server products typically bundle middleware to enable applications to intercommunicate with dependent applications, like Web servers, database management systems, and chart programs.

Load Limit

A web server (program) has defined load limits, because it can handle only a limited number of concurrent client connections (usually between 2 and 60,000, by default between 500 and 1,000) per IP address (and IP port) and it can serve only a certain maximum number of requests per second. 
On the other hand, an application server has a much higher capacity.

Model

Webserver delegation model is fairly simple, when the request comes into the webserver, it simply passes the request to the program best able to handle it (Server side program). It may not support transactions and database connection pooling.  Web servers support to deploy .war files only while Application servers support to deploy .war and .ear files.
Application server is more capable of dynamic behaviour than webserver. An application server can be configured to work as a webserver.

History

The first web server owes its origin to Tim Berners-Lee when as part of a new project  to his employer CERN(European Organization for Nuclear Research). In 1989 he wrote two programs which led to the implementation of the first web server. The Application server first came up in the 1990's.
It can be said that a Web server is a subset of an application server. Application servers and web servers are beginning to blur into each other with the expansion of the Internet and Web 2.0 technologies.  In most instances currently, software is hosted on web servers, and then downloaded to the local hard drive, where it is installed on the local computer. In the new model that fuses the web server and application server, the software would be hosted online and the user could access it and use it as needed, generally, at a lower rate than if he or she were to purchase the software new.

Tuesday, May 29, 2012

Different ways to create objects in java





There are Five different ways to create objects in java:

A. Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way.

 MyObject object = new MyObject();


B. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();


C. Using clone() The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();


D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();


E. Using  classloader

this.getClass().getClassLoader().loadClass(“com.amar.myobject”).newInstance();

Monday, May 21, 2012

Coupling vs Cohesion


If members of a class do not depend on each other, the class is said to have no cohesion (no togetherness)
The goal is to design software with low coupling (not none) and high cohesion.

The reason is that with low coupling, changes and errors in one location will not propagate to the rest of the code,
with high cohesion, code that depends on each other is kept close to each other.

Mechanisms to promote low coupling:
• private fields – renaming a field will not affect  anything outside the class.
• non-public classes that can only be seen inside a package.
• private methods that cannot be called from outside the class.

Mechanisms that allow high cohesion
• all members are visible from inside a class.
• default visibility is package


Coupling:
. . . the degree of interdependence between modules
. . . a measure of the strength of interconnection

 The more the connections between one module and the rest,
 the harder to understand that module, 
 so  the harder to re-use that module in another situation, 
 so the harder it is to isolate failures caused by faults in the module

 The lower the coupling the “better”.

• Loose coupling is a design goal that seeks to reduce the inter-dependencies; between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.
Loose coupling is a much more generic concept intended to increase the flexibility of a system, make it more maintainable, and makes the entire framework more "stable".

Tight-Coupling:-
1.   While creating complex application in java, the logic of one class will call the logic of another class to provide same service to the clients.
2.   If one class calling another class logic then it is called collaboration.
3.   When one class is collaborating with another class then there exists tight-coupling between the two classes.
4.   If one class wants to call the logic of a second class then they first class need an object of second class it means the first class create an object of second class.
5.   For example, if we have two classes called traveller and car, traveller class is calling logic of car class; in this case traveller class creates an object of car class.
6.   In the above traveller class and car classes, car class object of dependency for traveller object.
Example:-

Public class Traveller
{
     Car c = new Car ();

     Public void startJourney()
      {
           c.move();
       }
}


Public class Car
{
    Public void move()
    {

    }
}

·         In the above example traveller object is tightly coupled with car object because in place car object if you want to use bike object then, we need to make changes in Traveller class
Example :-

 Public class Traveller
{
     Bike b = new Bike ();

     Public void startJourney()
      {
           b.move();
       }
}


Public class Bike 
{
    Public void move()
    {

    }
}

Loose-Coupling:-
1.   In Loose-Coupling, when one object is depending on another class object, some external entity will provide that dependency object to the main object that external object we call as a Container.
2.   In order to get loose-coupling between objects the following two rules are required
3.   The classes should follow POJI/POJO model.
4.   Apply dependency injection mechanism.
For example:-

                                     Vehicle(interface)-----------POJI
                                             |
                              -------------------------
                             |                                |
                  Car(Class)              Bike(Class)-------POJO




 Public class Traveller
{
     Vehicle v;

     Public void setV(Vehicle v)
     {
            this.V=V;
     }

     Public void startJourney
     {
           V.move();
     }
}


·         In the above traveler class, an external entity injects either car (or) Bike object.
·         In traveler, these are no changes required we are shifting the dependency from car to a Bike.
·         In the above traveler class, we are token vehicle reference, so that an external object (Container) can injects either car object (or) Bike object, depends on requirement if a traveler.
·         In spring frame work, spring container follows dependency injection mechanism and injects the dependency objects required for a main object.
·         Spring frame work is much success because of one of the main reason is it promotes Loose-Coupling between the objects.










Cohesion:
. . . the extent to which its individual components are needed to perform the same task
. . . how tightly bound or related [a module’s] internal elements are to one another

 The less tightly bound the internal elements, 
the more disparate the parts to the module, the harder it is to understand

 The higher the cohesion the “better”.

• High cohesion is when you have a class that does a well defined job. Low cohesion is when a class does a lot of jobs that don't have much in common.
Let's take this example:
You have a class that adds two numbers, but the same class creates a window displaying the result. This is a low cohesive class because the window and the adding operation don't have much in common. The window is the visual part of the program and the adding function is the logic behind it.
To create a high cohesive solution, you would have to create a class Window and a class Sum. The window will call Sum's method to get the result and display it. This way you will develop separately the logic and the GUI of your application.


Coupling and related concepts

Encapsulation — putting in a container, packaging up, or putting a
barrier around a group of entities. “creating a module”. Often, the
programming language mechanism that provides encapsulation also
provides a means to enforce hiding.

 By itself, not directly related to coupling (although is related to modules)
Information Hiding — implementation decisions, or decisions that are
likely to change.
 If information hiding is enforced, then certain kinds of relationships between modules are not possible, and so limits the amount of coupling possible



Classic coupling measurement

 “physical” concept
 ordinal categories of relationship between two modules

Content coupling modules can directly refer to the contents of each other “bad”

Common coupling modules communicate via global data

Control coupling modules communicate by data that allows one module to directly affect the behaviour of the other

Stamp coupling modules communicate by a heterogeneous set of items,
not all of which are used

Data coupling modules communicate by parameters, where each
parameter is a single item or a homogeneous set that incorporate no
control element “good”

No coupling there is no relationship


Cohesion and related concepts

Encapsulation — putting in a container, packaging up, or putting a barrier around a group of entities. “creating a module”.
 By itself, not directly related to cohesion (although is related to modules)

Abstraction — extracting the essential details about a concept
 A good abstraction should have good cohesion

Information Hiding — implementation decisions, or decisions that are likely to change.

 Modules with good cohesion do not make visible “non-essential” details


Saturday, May 19, 2012

Static variables vs Static Block vs Static Methods



Static variables

All the static variables are shared by all the instances, which are global variables.Hence the variable or method which we need to declare as global can be declared as static.
below is the syntax for declaring a member as static.
static int width=30;
static int length=20;

Static Block   

static{} block is executed when the class which contain static block is loaded into memory. 
i.e before the main method is called static block is used for Initialization of static members.
static{} block is not inside any method and this block will get executed only once while loading the class.

Example :

public class StaticExample {

 static{
  System.out.println("Hello");
 }
 
 public static void main(String args[]){
  
 }
}

When we run this program it will print Hello.















Static Methods

They are executed when those methods are called from another static class or method


They methods which can be invoked without creating the object of the class.
Common error while using static method:
If we try to refer any method or variable which are not static from the static  method, we will get compilation error .

static() has several restrictions:
1. Can ONLY call other static ()
2. MUST ONLY access static data
3. cant refer to super or this

Example :

public class StaticExample {

 static void printString(){
  System.out.println("Hello");
 }
 
 static void testStaticMethod(){
  printString();
 }
 
 public static void main(String args[]){
  testStaticMethod();
 }
}




Order of execution of Staic variable ,static block and  static method

As soon as the class is loaded, all of the static statements will run first .then the static block will execute.
Consider the below code to understand this much more clearly.

public class StaticTest { 
static int width=30;
static int length=20;
static void myMethod(int x)
{
System.out.println(“Value passed is = ” + x);
System.out.println(“Width = ” + width);
System.out.println(“Length = ” + length);
}
static
{
int area;
System.out.println(“Static block initialized.”);
area = width* length;
System.out.println(“Area is “+area);
}
public static void main(String args[]) {
myMethod(60);
}
}
Output of the above code is
Static block initialized.
Area is 600
Value passed is = 60
Width = 30
Length = 20


Tuesday, May 15, 2012

Transaction models




Local Transaction model
The Local Transaction model gets its name from the fact that transactions are managed by the underlying database resource manager, not the container or framework your application is running in. In this model, you manage connections rather than transactions.You can't use the Local Transaction model when you make database updates using an object-relational mapping framework such as Hibernate, TopLink, or the Java Persistence API (JPA). You can still apply it when using data-access object (DAO) or JDBC-based frameworks and database stored procedures.
You can use the Local Transaction model in one of two ways: let the database manage the connection, or manage the connection programmatically.
To let the database manage the connection, you set the autoCommit property on the JDBC Connection object totrue (the default value), which tells the underlying database management system (DBMS) to commit the transaction after the insert, update, or delete has completed, or roll back the work if it fails.
managing the connections programmatically. In this technique, you would set theautoCommit property on the Connection object to false and manually commit or roll back the connection.


Programmatic Transaction model

The Programmatic Transaction model, otherwise known as Bean Managed Transcations (BMT)
It gets its name from the fact that the developer is responsible for managing the transaction. In the Programmatic Transaction model, unlike the Local Transaction model, you manage transactions and are isolated from the underlying database connections.


In EJB
Programmer is responsible for calling the methods to start and end the transactions, EJB framework provides user transaction interface for this purpose.


Declarative Transaction model
The Declarative Transaction model, otherwise known as Container Managed Transactions (CMT), is the most common transaction model in the Java platform. In this model, the container environment takes care of starting, committing, and rolling back the transaction. The developer is responsible only for specifying the transactions' behavior. 


In EJB
The Transaction attributes are specified in the deployment descriptor. Responsibility of starting and ending the transaction remains of the container.

Both the Spring Framework and EJB 3.0 make use of annotations to specify the transaction behavior.
Spring uses the@Transactional annotation
EJB 3.0 uses the @TransactionAttribute annotation.

The container will not automatically roll back a transaction on a checked exception when you use the Declarative Transaction model. The developer must specify where and when to roll back a transaction when a checked exception occurs. In the Spring Framework, you specify this by using therollbackFor property on the @Transactional annotation. In EJB, you specify it by invoking the setRollbackOnly() method on the SessionContext.