Tuesday, September 3, 2013

Encapsulation | how to achieve encapsulation in Java


Encapsulation:


Before moving into the concept and definition, first of all i would like to ask you one thing. Do you know about capsule (medicine)? Have you seen capsule .?

Everyone has the same answer for the above questions. that is YES

If you know a capsule , definitely you knew about encapsulation.

How a capsule will look like?

As every one knows that the medicine which is wrapped is the capsule.

How Capsule related to Encapsulation: 


Just like a capsule(which wraps up medicine) , wrapping up  the data is called Encapsulation in OOPS. Encapsulation is a mechanism of hiding the data 
( variables/methods ) from the external world.

In java a class is the best example of Encapsulation

How to achieve Encapsulation in Java:


In java, Encapsulation can be achieved by using access specifiers (especially private modifier). 

As we know a private access specifier specifies access with in the class (local access), the data can't be exposed to the other classes (in same application or different application).


Let me elaborate this with an example.

CapsulateData is the class with some variables as given below.



As accountNumber, accountName are private variables they can't be accessed outside the class.

If we try to do so, following will be the result.





Here as accountName and accountNumber are private fileds, we can't access them in other classes(not only variables , even private methods also).

From this, we can clearly understood that the data
 (accountName , accountNumber ) is hidden by the class from the outside world, which we consider to be encapsulation.




Monday, September 2, 2013

Abstraction in OOPS | How Abstraction can be achieved in JAVA


Abstraction:


We all know that abstraction is one of the characteristics of Object Oriented Programming System (OOPS). If you ask someone "what is abstraction?" the most common possible answer that you hear is .. "Abstraction is hiding some important features or data ..bla ..bla..bla "

The question is ..what is hiding ..? where you are hiding..? which part you are hiding ..?

Is hiding something is the correct definition for abstraction ?

then what it (abstraction) really means?

Here it goes:


In simple words i can say.. "Abstraction implies providing something.. but not everything"

i will consider one real time example to illustrate it in much better way.




Suppose there is an aeroplane flying in the sky. We know that it is flying, but we don't know how exactly it is flying and what are the underlying mechanisms, working and all. 

this is what we are looking for.. "abstraction"

How to achieve Abstraction in Java:


By using abstract classes or interfaces , we can achieve abstraction in Java.
As we all know that abstract classes, interfaces contains abstract methods (ofcourse abstract classes may or may not contain) i.e , only method declarations.

By looking at the method declaration we can estimate what exactly the method is doing, what it is going to return. But we don't know how exactly the abstract method will be implemented.

We came to know about the implementation, once we provided the method implementation in the classes which implement the corresponding abstract class or interface.

Example for the above illustration:


Let us consider an interface ( you can take abstract class also) Addicted.




In the above interface, getAddictedListOfPersons() is the abstract method (by default all the methods in an interface are public abstract ) which returns list of all the addicted persons. By looking at the method declaration we can infer this.
(As per the java documentation we should give proper names to the methods and variables)

But we don't know how exactly the method will be implemented in it's (interface) implementation classes.

Following are the implementation classes for the interface Addicted.


The class AddictedToJava is providing implementation to the abstract method which returns the list of persons who were addicted to Java.



The class AddictedToAndroid is providing implementation to the abstract method which returns the list of persons who were addicted to Android.


Now , by looking at these implementations we came to know that the implementation is different in both of the implementation classes for the interface(Addicted).

Only after providing implementation, we came to know how exactly the method was implemented.

This is considered to be abstraction what i mentioned in the begining of the article.

Abstraction ------> Providing something.. but not everything  





Thursday, May 30, 2013

Reading cookies from browser using core java

Cookie:

A cookie is a piece of information sent by server(web program) to client(browser).

A cookie will have a name and a value which will be stored in browser's cache.
There are two types of cookies available.

--> Persistent cookies and 
--> Non Persistent cookies

Persistent cookies will be stored in browser's cache even though we have closed the browser until some time specified in the web program in which they got created.

Non Persistent cookies will be removed from the browser's cache whenever we close the browser.

In JSE edition, java.net package provides the feature of reading cookies from browser.

This can be illustrated as shown.

CookieManager will manages all the cookie related tasks and will be helpful in getting cookies.

As part of CookieManager interface we have some final static fields available to set the cookie policy.

Content policy describes the acceptance state of cookies. i.e, which cookies to be accepted and which should be rejected.

The cookie policy has predefined policies namely ACCEPT_ALL, ACCEPT_NONE and ACCEPT_ORIGINAL_SERVER

ACCEPT_ALL is to accept all cookies , ACCEPT_NONE  is to reject all cookies and ACCEPT_ORIGINAL_SERVER is to accept cookies from original server.




A sample program to read the cookies stored in browser with java net package is as shown.


Once if you run the application, CookieManager will set the cookie policy to ACCEPT_ALL so that it can accept any cookie. A CookieHandler is used by the http protocol and can be registered by using setDefault().

Once we have opened the connection to the specified URL by using CookieManager we can get the CookieStore which contains a bunch of cookies related to the url. 

By using CookieStore we can get the list of cookies with their name and values

The output of the application will display list of cookies in the browser related to the url with cookie name and value.



Wednesday, May 29, 2013

Marker Interfaces , Serialization and serialVersionUID


Marker Interfaces:

An interface contains only abstract methods where as a marker interface contains no methods at all.

yeah, Marker inerface is an interface which doesn't have anything (variables or methods) in it.

examples:

Some example of Marker interfaces are..

java.io.Serializable,

java.lang.Cloneable,

javax.servlet.SingleThreadModel etc..


Why Marker Interfaces:

As Marker interfaces contains no methods why we need to use marker interfaces..? The answer is to instruct the compiler

A marker interface is used to give instructions to the java compiler. Classes that implement these marker interfaces  indicates their special behaviour to compiler.  

As of Java 1.4 Marker inerfaces exists . From Java 5 onwards, we have the concept of annotations which are used to give instructions to java compiler. So marker interfaces are deprecated later.

For e.g, if we write a class which implement Serializable interface (marker), that means we are giving instruction to compiler such that this class is eligible for serialization.


What is Serialization:

Serialization is the process of making an object to be persisted in a stream and can make that object to be tranferred through the network.

Not clear...

Here is the simple definition..

Writing (storing) an object into a stream (e.g file stream) is called Serialization.


Example:

Create a class SerialObject which implement Serializable interface. We can observe that compiler will show the warning The serializable class SerialObject does not declare a static final serialVersionUID field of type long




What is serialVersionUID:

A serialVersionUID is an unique id used by the compiler while in the process of deserialization.

By using serialVersionUID  compiler will check the class that was already serialized is same or not while deserialising it.

i.e to confirm that the class is same while serializing (writing object into stream) and deserialising (reading object from streams).

If we have not provided the serialVersionUID serialization run time will assume some id to the class.

However, as per JAVA specification it is strongly recommended to declare a serialVersionID which should be a static final of type long to avoid unexpected exceptions like InvalidClassException.

Also it should be a private member so that even it's sub classes can't access it.

Our SerialObject class with serialVersionUID and some properties is as shown.



We have declared transient variables, name and notTrransferable.

Transient Variable:

A transient variable is a variable that can't be transferred through a network or we can say , a variable which can't be serialized. That means, we can't write this variable into streams. 

To limit writing data into streams we will use transient variables in serializable classes.


Serializing :

SerializingApp is the class which is showing the process of serialization ( writing object content into file stream).

To write an object we will take the help of java.io.ObjectOutputStream which will accept java.io.OutputStream as an argument.


If the file is available in the specified location it will use that, otherwise FileoutputStream will create a file with the specified name in the specified location.

writeObject() is used to write the object's content into stream.

If we observe the output in the created file write_here.txt, it will only contain objectName and objectId since the remaining are transient and can't be transferred though a network (can't be serialised).


DeSerializing:

Reading the content from a stream and representing it again in the form of an object is called DeSerialization.

DeserialisngApp is the class which is showing process of reading the object from specified file (deserialization).

To write an object we will take the help of java.io.ObjectInputStream which will accept java.io.InputStream as an argument.


we need to specify the location of the file where we have stored our object (SerialObject) to the FileInputStream.

You can clearly observe that the class (SerialObject) which we have stored in the file stream in serialization is the same as the class which we got in deserialization.

serialVersionUID is used by the run time, to confirm that the class is same in Serialization and Deserialization.





Monday, May 27, 2013

Can we create object to Interface and Abstract class ..?


Yes...(but not directly)

We can create the object to An Interface / Abstract class.

As per the java specification we are not allowed to create object to interface and abstract class directly. But we can do that indirectly with the help of anonymous inner type.

Interface:

An interface is one which contains only abstract methods( methods don't have body).
Any variable declared inside an interface are by default public static final and should be initialised

Syntax:



Abstract Class:

An Abstract class is a class that can contain abstract methods or concrete methods( methods those have body) or both.

Syntax:



What happens when we try to create object:

We have an interface SampleInt which contains an abstract method.




SampleAbs is the abstract class with a concrete method showSampleAbs().




Now we are trying to create object to the above defined interface and abstract class in the class App




So , as the compiler is not allowing us to create the object to interface and abstract class we can say We can't create object to an interface or abstract class directly .


How to create object to interface and abstract class:

We can create the object to interface or abstract class indirectly by using anonymous inner type.

App class shows creating object to SampleInt and SampleAbs.




By providing anonymous inner class to Abstract class or interface we can say they have intantiated indirectly.

We can call showSampleAbs() by using SampleAbs object sampleAbs aswellas we can call sampleIntMethod() defined in interface by using it's instance sampleInt.


Calling methods defined inside anonymous type:


Suppose we have defined some more methods inside the implementation (anonymous class), then we can't call them by using instance since the methods not available at the time of object creation.




Calling the methods that are defined inside anonymous inner type will be as shown. 




Note:

Anonymous inner type is simply providing implementation to the corresponding abstract class / interface. 

So we are able to create object to abstract class and an interface by providing implementation in the form of anonymous inner type.

You can observe the behaviour by practising this code.



Tuesday, May 21, 2013

Hibernate(Object Relational Mapping) and working of hibernate


Hibernate:

Hibernate is one of the commonly used ORM tool to deal with database. Hibernate is a framework (software) to be used in applications that deals with database. 

What is ORM:

ORM refers to Object Relational Mapping i.e, Mapping the java objects with the corresponding relational records in the database.

Advantages over jdbc:

As we have jdbc to deal with database,but  hibernate will have more advantages than jdbc.

--> Use of hibernate will improve the productivity (less amount of code compared to jdbc)

--> Hibernate provides relations like one to one , one to many, many to one and many to many

-->  Hibernate comes with HQL ( hibernate query language), which is database independent. So we can deal with any database without changing the code.

--> If we use hibernate, no need to configure connection pool (c3p connection pool will be bundled with hibernate)

--> Hibernate supports two levels of cache (first level and second level) which improves the performance of the application.

--> In hibernate , exceptions that occur are unchecked exceptions where as in jdbc , checked exceptions will be caught and thrown by try catch.

Note:

According to the hibernate documentation, hibernate may not be the best solution for data centric applications which uses stored procedures for buisiness logic. 

Hibernate gives best result for the applications which have buisiness logic as part of java classes instead of stored procedures.


Hibernate Architecture:


As shown pictorially, java application with hibernate api code will communicate with hibernate software which will connect to the database.

Components of Hibernate:

Hibernate mainly consists of three components. They are

--> Hibernate configuration file

--> Hibernate mapping file

--> Pojo classes

Hibernate Configuration file:

A configuration file is an xml file contains the configuration details like driver class name, url, user name and password to connect with database. It also includes the mapping file information

syntax:


A hibernate application contains one configuration file with one or more mapping (hbm) files.

Hibernate mapping file: 

A mapping file (hbm) shows which table is mapped with which pojo class, and mapping the properties of pojo classes with columns of tables.

syntax: 


A Hibernate application can have one or more mapping files. We can map multiple pojo classes with tables by using <class> .

It's recommended to write seperate hbm (mapping) files for each table and pojo class.

Number of mapping files, pojo classes depends on number of tables in the database.

Pojo class:

A POJO (plain old java object) is a normal java bean with couple of setters, getters and/ or some additional methods.

syntax: 



Sample Hibernate application:

Create a java project HibernateSampleApp , add the hibernate capabilities( hibernate jar's ) to the project build path and as discussed earlier we need to have the following files.

A Hibernate Configuration file.




and Hibernate mapping file Student.hbm.xml


and a pojo class Student.java


Now create a main class SampleHibernateApp with main()



If we run the above application, we can found a table with name student in database with columns id, student_name.

As we have defined an extra property in hibernate.cfg.xml, hbm2ddl.auto will create the tables if not exists.

If it's values is update it will update the table if already exists , otherwise it will create the table in database.

show_sql property will show  the query sent to the database in console.


What's happening when we run the application:

When we run the SampleHibernateApp, hibernate will start execution by creating a Configuration object. Immediately hibernate software will call configure() which is an expensive method.

when configure() got called, hibernate will load the configuration file (hibernate.cfg.xml) into jvm's memory and will check for the properties mentioned.

 As we have defined mapping file information in configuration file, hibernate will also loads the mapping file into jvm memory and checks for the appropriate tables in database. If not exists, if we have given hbm2ddl.auto property, hibernate will create the required tables.

So calling configure() takes so much of time to do all these tasks. That's why hibernate specification says we should call configure() only once through out the life time of a project.

Once we have configuration object we can get SessionFactory object by using buildSessionFactory().

When buildSessionFactory() called, hibernate will try to connect with database with the information already stored in jvm memory ( from cfg and hbm files) and will create some basic queries for inserting, updating, deleting and retrieving and stores those queries in jvm memory.

buildSessionFactory() is also an expensive method since lot of task is going behind. We should call this only once through out the project.

A SessionFactory is an interface which can hold a bunch of Session objects.
Once we got SessionFactory we can get session object by calling openSession() which will get's the connection from database.

beginTransaction() will enable the transactions with database.

When we create object to our pojo class Student, the instance variables were initialised with default values initially (0 for int, null for string /advanced data types).

Calling setters will assign the values that we specified to the student object.

Calling session.save() will not send an insert query to the database. The student object will be associated with session object when we call save(). 

When we call commit() hibernate will check in the first level cache ( which will be created at the time of creating session object ) whether any object is associated (attached) to the session object with some code and will get the class name from object (student.getClass()).

 As hibernate already read the cfg,hbm files and stored in jvm, from that information it will get the table to which it has to send the query.

Finally , hibernate will picks the insert query that was already stored in jvm memory based on some internal registration code and will send that query to the database.

We should close the session so that the connection from the database will be given back.

Note:

Using hibernate in web based applications along with spring explained here


Wednesday, May 15, 2013

JSTL (Jsp Standard Tag Library) tags and their use

With the introduction of custom tags to remove the java code from jsp, every vendor can develop their own tags. But the problem is that, for every project in every organisation some common requirements will exists. For those, it's waste of time to develop own tags by every vendor. Instead of that Sun itself has given commonly used tags to use in our applications.

JSTL:

JSTL refers to Jsp Standard Tag Library and is a custom tag library released by Sun Micro Systems.

JSTL comes with different set of groups of tags. They are

core Tag library,
fmt tag library,
sql tag library and
xml tag library

Core Tag Library:

If we want to use core tag library in our jsp instead of java code, we need to include the tag library as shown.


prefix attribute can take any characters to use the tags in jsp. uri attribute specifies the uri of the corresponding tag library, add the jstl jar in the lib folder.

As part of Core tag library the following tags are bundled.

set:

<c:set> is used to set a value into a specific scope or to set the result of an expression into a specific scope.

syntax:


value attribute allows any value or result of any expression as shown above.
scope can be any of page, request, session and application.

redirect:

<c:redirect> is used to redirect to a specified location. Instead of response.sendRedirect() ( java code ) we can use <c:redirect>.

syntax:


url attribute specifies the location to which it has to be redirected.


out:

<c:out> is used to display the contents to the user (on the browser).Instead of out.println() (java code) we can use <c:out> in jsp.

syntax:


value attribute specifies the value to be rendered on the browser, default attribute will take the default value to be display if the resulting value is null.

catch:

<c:catch> is used to catch the exception thrown in its body.

syntax:


var attribute specifies the name of the scoped variable for the exception thrown.

if:

<c:if> is the simple conditional tag to check conditions in jsp.

syntax:


test is the required attribute here, which allows a condition check , and executes the if body incase of condition is true.

var is the name of the variable for the condition result and of type boolean (true for condition true and false for condition fail)


choose:

<c:choose> is the simple conditional tag which has child tags <c:when> and <c:otherwise>

syntax:


when:

when the condition given in the <c:choose> is true it's body will be executed , if condiction fails it will skip executing body and go for <c:otherwise>. test is the mandatory attribute where we will provide condition.

otherwise:

when condition fails in the <c:when>, then the <c:otherwise> body will be executed just like if ,else in java code.

forEach:

To perform the iterations, we will take the help of <c:forEach> which acts as for loop in jsp.

syntax:


begin and end specifies the starting and ending value of the loop to iterate and step specifies the incremental value from starting. if we have not given begin and end,and if we mentioned the items attribute to iterate over collection elements, index always starts from 0.

forTokens:

<c:forTokens> is used to iterate over set of tokens seperated by delimeter

syntax:


items specifies collection of items seperated by delimeter. here @ is considered as delimeter , we can use any character as delimter (including space).

import:

<c:import> is used to import the contents from specified url (just like jsp:include)

syntax:


or if we want to include html content also we can use like this,



url:

To create url with optional parameters we will use <c:url>

syntax:


with the given var name we can access the url in the jsp later.


param:

<c:param> is used to add parameters to the url that will be given to import tag

syntax:


The parameters mentioned will be appended to url while importing.


remove:

to remove a specific scoped variable from a specific scope <c:remove> will be used.

syntax:


after removing from specified scope, if we try to access that variable we will get null as it was removed from the scope.


fmt tag library:

fmt (formatting) tags used to format the text, numbers, date based on the locale (internationalization).

To use fmt tag library we need to include taglib,



some mostly used tags are., 

message:

this tag is used to retrieve the message from property file based on the key and bundle

synatx:


formatDate and formatNumber:

Used to format given date and number based on supplied style/ pattern.

syntax:



Similar way the other tags u can go through from the link.


Sql tag library:

sql tag library is used to deal with database opeartions. To set the datsource we have <sql:setDataSource>, to execute a query <sql:query>.

To Executes the SQL update defined in its body we can use <sql:update>


Note:

As per MVC design pattern, we should not write dao logic in jsp. So in general we will not use these tags at all.


Xml tag library:

xml tag library is used to deal with xml documents and almost all tags available as part of xml tag library are same as core tag library.

You can go through this link.

Download the source and observe the working behaviour of all tags.