Computer science

Computer science Its purely dedicated for all the topics regarding computer science. From programing to simulation. Each bit is entertained... Feel free to discuss

24/10/2017

What's New in Spring Framework 5.x

New Features and Enhancements in Spring Framework 5.0

JDK 8+ and Java EE 7+ Baseline

Entire framework codebase based on Java 8 source code level now.
Improved readability through inferred generics, lambdas, etc.
Conditional support for Java 8 features now in straight code.
Full compatibility with JDK 9 for development and deployment.
On classpath as well as module path (with stable automatic module names).
Framework build and test suite passes on JDK 9 (runs on JDK 8 by default).
Java EE 7 API level required in Spring's corresponding features now.
Servlet 3.1, Bean Validation 1.1, JPA 2.1, JMS 2.0
Recent servers: e.g. Tomcat 8.5+, Jetty 9.4+, WildFly 10+
Compatibility with Java EE 8 API level at runtime.
Servlet 4.0, Bean Validation 2.0, JPA 2.2, JSON Binding API 1.0
Tested against Tomcat 9.0, Hibernate Validator 6.0, Apache Johnzon 1.1
Removed Packages, Classes and Methods

Package beans.factory.access (BeanFactoryLocator mechanism).
Package jdbc.support.nativejdbc (NativeJdbcExtractor mechanism).
Package mock.staticmock removed from spring-aspects module.
No support for AnnotationDrivenStaticEntityMockingControl anymore.
Packages web.view.tiles2 and orm.hibernate3/hibernate4 dropped.
Minimum requirement: Tiles 3 and Hibernate 5 now.
Dropped support: Portlet, Velocity, JasperReports, XMLBeans, JDO, Guava.
Recommendation: Stay on Spring Framework 4.3.x for those if needed.
Many deprecated classes and methods removed across the codebase.
A few compromises made for commonly used methods in the ecosystem.
General Core Revision

JDK 8+ enhancements:
Efficient method parameter access based on Java 8 reflection enhancements.
Selective declarations of Java 8 default methods in core Spring interfaces.
Consistent use of JDK 7 Charset and StandardCharsets enhancements.
JDK 9 compatibility:
Avoiding JDK APIs which are deprecated in JDK 9 wherever possible.
Consistent instantiation via constructors (with revised exception handling).
Defensive use of reflection against core JDK classes.
Non-null API declaration at the package level:
Nullable arguments, fields and return values explicitly annotated with .
Primarily for use with IntelliJ IDEA and Kotlin, but also Eclipse and FindBugs.
Some Spring APIs are not tolerating null values anymore (e.g. in StringUtils).
Resource abstraction provides isFile indicator for defensive getFile access.
Also features NIO-based readableChannel accessor in the Resource interface.
File system access via NIO.2 streams (no FileInput/OutputStream used anymore).
Spring Framework 5.0 comes with its own Commons Logging bridge out of the box:
spring-jcl instead of standard Commons Logging; still excludable/overridable.
Autodetecting Log4j 2.x, SLF4J, JUL (java.util.logging) without any extra bridges.
spring-core comes with ASM 6.0 (next to CGLIB 3.2.5 and Objenesis 2.6).
Core Container

Support for any annotations as indicators for optional injection points.
Functional style on GenericApplicationContext/AnnotationConfigApplicationContext
Supplier-based bean registration API with bean definition customizer callbacks.
Consistent detection of transaction, caching, async annotations on interface methods.
In case of CGLIB proxies.
XML configuration namespaces streamlined towards unversioned schemas.
Always resolved against latest xsd files; no support for deprecated features.
Version-specific declarations still supported but validated against latest schema.
Support for candidate component index (as alternative to classpath scanning).

Spring Web MVC

Full Servlet 3.1 signature support in Spring-provided Filter implementations.
Support for Servlet 4.0 PushBuilder argument in Spring MVC controller methods.
MaxUploadSizeExceededException for Servlet 3.0 multipart parsing on common servers.
Unified support for common media types through MediaTypeFactory delegate.
Superseding use of the Java Activation Framework.
Data binding with immutable objects (Kotlin / Lombok /

04/05/2017

Hurry up.. Only 10 seats. Batch starting soon... call now: 7978190729

Difference Between Collection And Collections in JAVA.In java programming, Collection is used in every part of java like...
09/04/2017

Difference Between Collection And Collections in JAVA.

In java programming, Collection is used in every part of java like core java, servlet, JSP and all frameworks. And interviewer also ask many questions at the time of interview on Collection. What is the difference between Collection and Collections ? that the most confusing question of collection. Many persons heard it first time. So now I discussing with you about some main difference between Collection and Collections. Then I will explain the functionality and methods of each other separately one by one.

Both are looking similar by name “Collection And Collections”. Both Collection and Collections are available into Java Collection framework but both are used different-different purpose.

Major difference between Collection and Collections are:

Collection and Collections are packed into java.util package.
is top most Interface of collection framework whereas Collections is an class of java.util package.
interface consist of many sub-interfaces like as List, Set, Queue whereas class consist of many static utility methods like sort(), reverse (), synchronisedCollection() etc.

Collection interface only used to store group of objects into a single Collection object. On the other hand Collections class is used to perform some operation on object of Collection.
Collection Interface
According to Java, Collection is parent interface of all the other child interfaces and classes of Collection framework. But actually, it is not top interface of Collection. It extends from Iterator interface and acquire all functionality of Iterator interface. Collection is bundle of many objects and treat as an single object. All the operations that you perform on data can be performed on Collection.

We can’t implements it directly into any class. It provides many other sub-interfaces like List, Set etc. But in the case of sub-interfaces we can implements them directly. Collection provide some abstract class who implements the sub-interfaces like AbstractList, AbstractSequantialList, AbstractSet. After sub-interfaces Java provide concrete classes whose object we can create directly and store object them.

Concrete Classes Of Collection
List :

ArrayList
LinkedList
Vector
Set :

HashSet
LinkedHashSet
TreeSet

Similarly map is also part of collection framework but it doesn’t use any property or functionality of Collection interface. All the methods of Map interface are different to the Collection’s method.

In case of List we use add() method to insert any object in collection but map use put() method.

of Collection interface
All the methods of Collection interface are public and abstract. Some main method of Collection interface are mention below…….

boolean add()
boolean addAll(Collection c)
Iterator iterate() … It comes from Iterable Interface
void clear()
boolean contains(Object o)
boolean isEmpty()
int hashCode() …… It comes from Object Class
boolean remove(Object o)
int size()
Object [] toArray()
Collections Class
It is an utility class into Java Collection framework reside in java.util package. Collections class has only static utility functions which are used to perform operations on objects of Collection.

of Collection Class
Some main methods of Collections Class are mention below…….

Collections.max()
Collections.min()
Collections.sort()
Collections.shuffle()
Collections.binarySearch()
Collections.disjoint()
Collections.copy()
Collections.reverse()

31/03/2017

JDBC Drivers

A JDBC driver is a software component which enables a Java application to interact with a database. To connect with individual databases, JDBC requires drivers for each database. The JDBC driver felicitates connection to the database and implements the mechanism for transferring the query and result between client and database.

There are 4 (four) types of JDBC drivers.

1. JDBC-ODBC bridge
2. Native-API driver
3. Network-Protocol driver (Middleware driver)
4. Database-Protocol driver (Pure Java driver) or thin driver.

Type 1 driver – JDBC-ODBC bridge

The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that uses the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls.

Type 1 driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the underlying operating system the JVM is running on. ODBC must be installed on the computer having the driver and the database must support an ODBC driver. The use of this driver is discouraged. Any application using a type 1 driver is non-portable.
Sun (now Oracle) provided a JDBC-ODBC Bridge driver: sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.

Advantages
· Any database for which an ODBC driver is installed can be accessed, and data can be retrieved.
Disadvantages
· Performance overhead since the calls have to go through the JDBC bridge to the ODBC driver, then to the native database connectivity interface.
· The ODBC driver needs to be installed on the client machine.
· Not suitable for applets, because the ODBC driver needs to be installed on the client.
· Specific ODBC drivers are not always available on all platforms; hence, portability of this driver is limited.
· No support from JDK 1.8 (Java 8) onwards.

Type 2 driver – Native-API drive

The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.
Advantages
· As there is no implementation of JDBC-ODBC bridge, it may be considerably faster than a Type 1 driver.
Disadvantages
· The vendor client library needs to be installed on the client machine.
· Not all databases have a client-side library.
· This driver is platform dependent.
· This driver supports all Java applications except applets.

Type 3 driver – Network-Protocol driver (middleware driver)

The JDBC type 3 driver, also known as the Pure Java driver for database middleware, is a database driver implementation which makes use of a middle tier between the calling program and the database.
The middle-tier (application server) converts JDBC calls directly or indirectly into a vendor-specific database protocol. The type 3 driver is written entirely in Java. The same client-side JDBC driver may be used for multiple databases.
It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care of by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access.
Advantages
· Since the communication between client and the middleware server is database independent, there is no need for the database vendor library on the client. The client need not be changed for a new database.
· The middleware server can provide typical middleware services like caching (of connections, query results, etc.), load balancing, logging, and auditing.
· A single driver can handle any database, provided the middleware supports it.

Disadvantages
· Requires database-specific coding to be done in the middle tier.
· The middleware layer added may result in additional latency, but is typically overcome by using better middleware services.

Type 4 driver – Database-Protocol driver (Pure Java driver)

The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol. Type 4 drivers are platform independent as they are written in Java. They install inside the Java Virtual Machine of the client. This provides better performance as it does not have the overhead of conversion of calls into ODBC or database API calls.
As the database protocol is vendor specific, the JDBC client requires separate drivers, usually vendor supplied, to connect to different types of databases.
Advantages
· Completely implemented in Java to achieve platform independence.
· These drivers don't translate the requests into an intermediary format.
· The client application connects directly to the database server. No translation or middleware layers are used, improving performance.
· The JVM can manage all aspects of the application-to-database connection; this can facilitate debugging.
Disadvantages
· Drivers are database specific, as different database vendors use widely different network protocols.

21/03/2017

Default Methods in Java 8:

With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.

When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.

Example of Default Method:

public interface Account {
default void OpenAccount(){
System.out.println("This is the Account Interface . . . .");
}
}

public class SavingAccount implements Account{
public void OpenSavingAccount(){
System.out.println("This is the Saving Account Class . . . .");
}
}

public class Main {
public static void main(String[] args) {
SavingAccount sa=new SavingAccount();
sa.OpenAccount(); // Default method of interface is called
sa.OpenSavingAccount();
}
}

Upon executing the Main class, we get the following output.

This is the Account Interface . . . .
This is the Saving Account Class . . . .

Default Methods and Multiple Inheritance
In case of multiple Inheritance, where both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.

interface InterfaceOne
{
// Default method
default void show()
{
System.out.println("Default InterfaceOne");
}
}

interface InterfaceTwo
{
// Default method
default void show()
{
System.out.println("Default InterfaceTwo");
}
}

public class MainClass implements InterfaceOne, InterfaceTwo
{
// Overriding default show method
public void show()
{
// use super keyword to call the show
// method of InterfaceOne interface
InterfaceOne.super.show();

// use super keyword to call the show
// method of InterfaceTwo interface
InterfaceTwo.super.show();
}

public static void main(String args[])
{
MainClass d = new MainClass();
d.show();
}
}

Upon executing the MainClass, we get the following output.

Default InterfaceOne
Default InterfaceTwo

Important Points:
1. Interfaces can have default methods with implementation from java 8 onwards.
2. Interfaces can have static methods as well similar to static method of classes.
3. Default methods were introduced to provide backward comparability for old interfaces so that they can have new methods without effecting existing code.

19/03/2017

ANDROID VERSION HISTORY.

#1. Android 1.1

Android 1.1 Version was released on 9 Feb, 2009

#2. Android 1.5 Cupcake.

Android 1.5 Cupcake was released on 30 April, 2009 which was totally based on Linux kernel 2.6.27. Android 1.5 was the first release officially use a codename based on a “dessert item” which is known as Cupcake.

#3. Android 1.6 SDK – Donut

Android 1.6 Donut was released on Sep 15, 2009 which was based on Linux kernel 2.6.29.

#4. Android 2.0 SDK – codenamed Eclair

Android 2.0 Codenamed Eclair was released on Oct 26, 2009 which was based on Linux kernel 2.6.29.



#5. Android 2.2 Froyo

Android 2.2 Froyo was released on May 20, 2010 which was based on Linux kernel 2.6.32

#6. Android 2.3/2.3.7 Gingerbread

Android 2.3 Gingerbread SDK was released on Dec 6, 2010 Which was based on Linux kernel 2.6.35

#7. Android 3.0/3.2 Honeycomb

Android 3.0 Honeycomb was released on Feb 22, 2011 which was based on Linux kernel 2.6.36. This first device using this version was Motorola Xoom tablet, was launched on 24 Feb, 2011.

#8. Android 4.0 Ice Cream Sandwich

Android 4.0 Ice Cream Sandwich was released on Oct 19, 2011 which was based on Linux kernel 3.0.1. Google’s Gabe Cohen Started this Android 4.0 Version with “theoretically compatible” which production on any Android 2.3.x device.

#9. Android 4.1 Jelly Bean

Android 4.1 Jelly Bean was announced on June 27, 2012 at the Google I/O conference by Google which was based on Linux kernel 3.0.31. This Android 4.1 Jelly Bean was released to the Android Open Source Project on July 9, 2012. The first Android 4.1 Jelly Bean device is Nexus 7 tablet which was released on July 13, 2012.

#10. Android 4.4 Kitkat

Android 4.4 Kitkat was announced on Sep 3, 2013 by Google. This Android 4.4 was optimised to run on a huge range of smartphone then oldest Android Version, Having 512 MB RAM

#11. Android 5.0/5.1 Lollipop

Android 5.0 Lollipop was released on Nov 12, 2014.

#12. Android 6.0 Marshmallow

Android 6.0 Marshmallow was released on May 28, 2015 during Google I/O.

#13. Android 7.0 Nougat

Android 7.0 Nougat is the latest version of Android which will be release in the month of August or September 2016. If you really want to know full details of Android Nougat then visit Wikipedia

The features of the upcoming JAVA 9. exclusively on Computer science page... These top features of java9:  light-weight ...
18/03/2017

The features of the upcoming JAVA 9. exclusively on Computer science page...

These top features of java9:

light-weight JSON API —:
which is a source of great speculation right now about how truly useful this feature will be (as proposed by the community process).

HTTP 2 Client — for HTTP 2.0 and web sockets.

API Improvements — :
To improve the API for controlling and managing OS processes.
Improved contended locking —for increasing performance between threads.

Code Cache —:
To improved ex*****on time for complicated benchmarks.

Java Compilation (Part 2) —:
Makes the sjavac tool available in the default JDK.
Source Code — :
organizes JDK source code into modules.

07/03/2017



The basic Accessibility Modifiers are of 4 types in Java. They are

1. public
2. protected
3. package/default
4. private

There are other Modifiers in Java. They are

1. static
2. abstract
3. final
4. synchronized
5. transient
6. native
7. volatile

Access Modifiers are used at 2 access levels in Java. They are

# Top-level for Classes & Interfaces
# Member-level for Classes & Interfaces

#1) Access Modifiers for Top-level Classes & Interfaces

Only 2 basic access modifiers are applicable for Top-level Classes & Interfaces. They are Public and Package/Default modifiers.

:
If top level class or interface within a package is declared as Public, then it is accessible both inside and outside of the package.
Default: If no access modifier is specified in the declaration of the top level class or interface, then it is accessible only within package level. It is not accessible in other packages or sub packages.

:
If no access modifier is specified in the declaration of the top level class or interface, then it is accessible only within package level. It is not accessible in other packages or sub packages.

2) Accessibility Modifiers for Members:

Members:
If members are declared as public inside a class then such members are accessible to the classes which are inside and outside of the package where this class is visible. This is the least restrictive of all the accessibility modifiers.

Members:
If members are declared as protected then these are accessible to all classes in the package and to all subclasses of its class in any package where this class is visible.

Members:
When no accessibility modifier is specified for the member then implicitly it is declared as Default. These are accessible only to the other classes in the class’s package.

Members:
This is the most restrictive of all accessibility modifiers. These members are accessible only with in the same class. These are not accessible from any other class within a class’s package also.

Other modifiers are:

Members:
* Static members are the members with Static keyword in their declarations.
* Class variables are called as Static variables. * These members belong to the class not to the object i.e. they are not instantiated when the class instance is created.
* The values of these variables are not part of the object state.
* The static variables are initialized to their default values (if explicit initialization is not specified) at the time of class loading.
* The Static methods are called as class methods. A static method can directly access other static members in the class. It cannot access instance (non-static) members of the class. But it can always use a reference of the class type to access its members both static and non-static.

Members:
*. Final variable is a constant; its value cannot be changed after its initialization.
This applies to instance, static and local variables including parameters that are declared as final.
*. A final variable of primitive data type cannot change its value once it has been initialized. A final variable of a reference type cannot change its reference value once it has been initialized, but the state of the object it denotes can still be changed.

# # # : # # # #
# Variables defined in Interfaces are implicitly Final.
# Final variables must be initialized before it is used.
# Final methods in a class are complete i.e. these methods has implementations and hence cannot be overridden in the subclasses.

Methods:
If method has a keyword abstract in its declaration, then such method/function is called Abstract method. Abstract methods does not have an implementation i.e. method body is not defined; only method prototype is specified in the class definition.

# # # : # # # #

#. Only instance methods can be declared as abstract.
#. Since Static methods cannot be overridden declaring abstract static method would of no use.
#. A Final method cannot be abstract and vice versa.
#. Methods specified in an Interface are implicitly abstract.

Methods:
Multiple threads can be executing in a program and at times they might try to execute several methods on the same object simultaneously.

If there is a requirement that only one thread at a time should execute a method in the object, then such methods can be declared as Synchronized. Their ex*****on will be mutually exclusive among all threads. At any given time, at the most one thread will be executing a Synchronized method on an object.

# # : Synchronized methods are also applicable to Static methods of a class.

Fields:
Objects can be stored using serialization. Serialization transforms objects into an output format which is helpful for storing objects. Objects can later be retrieved in the same state as when they were serialized, meaning that fields included in the serialization will have the same values at the time of serialization. Such objects are said to be Persistent.

The fields are declared with keyword Transient in their class declaration if its value should not be saved when objects of the class are written to persistent storage.

class sample implements Serializable{
transient str varStr; // transient field declaration
int varInt; // instance field declaration
}

Fields:
During ex*****on, complied code might cache the values of fields for efficiency reasons. And as multiple threads will access the same field, caching is not allowed to cause inconsistencies when reading and writing the value in the field.

The Volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field which could cause unpredicted results when the field is accessed by multiple threads

class sample {
volatile int varInt; // volatile field declaration
}
3) Accessibility Modifiers for Nested Classes & Interfaces

Interfaces:
Access modifiers can be used in Nested interfaces. An interface declared within another class or interface is called a Nested interface. A top-level interface is the one which is not nested.

Only one type of nested interface is available in Java based on declarative context, Static member interface. These are interfaces defined with keyword Static inside the top-level interface or class or in another Static member class or interface. It can be instantiated like a normal top-level interface or class, no enclosing instance is required for this interface instantiation.

Classes:
Access modifiers are also used in Nested classes. A class declared within another class is called a Nested class. A top-level class is the one which is not nested.

They are 2 categories of Nested classes based on the declarative context. They are

# # member classes
# # classes

Inner classes are defined in 3 different categories. They are:

# # -static member classes
# # classes
# # classes

member classes:
Classes which are defined with Static modifier inside the top-level class or other Static member class are called Static member classes. It can be instantiated like a normal top-level class; no enclosing instance is required for this class instantiation.

All the 4 accessibility modifiers i.e. Public, Protected, Package & Private are applicable to Static member classes’ declaration.

-Static member classes:
Classes which are defined without Static modifier inside another class are called non-static member classes. An instance of a non-static member class always has an enclosing instance associated with it.

The accessibility modifiers i.e. Public, Protected, Package & Private, abstract, final are applicable to Non-Static member classes’ declaration.

classes:
These classes are defined in the context of a block as in a body of the method or normal local block, just as local variables defined in a method body or local block. An instance of a local class has an enclosing instance associated with it, if it is declared in non-static context.

No accessibility modifiers are applicable for Local classes.

classes:
These are defined as expressions and instantiated on the fly. An instance of anonymous class has an enclosing instance associated with it, if it is declared in non-static context.

No accessibility modifiers are applicable for Anonymous classes.

# # # : A Nested Class or Interface cannot have the same name as any of the enclosing classes or interfaces.

Methods:
Native Methods are also called as Foreign methods. Such methods implementation is not defined in Java but in another programming language.

These methods are specified in the class as method prototypes with prefix with keyword native, no method body is defined in the Java class.

java STRING vs STRING BUILDER vs STRING BUFFER
04/03/2017

java STRING vs STRING BUILDER vs STRING BUFFER

What is the difference between include action and incude directive in jsp?Directive Include: 1.Included the resources at...
03/03/2017

What is the difference between include action and incude directive in jsp?

Directive Include:
1.Included the resources at translation time.
2.It supports only static resources.
3.If any changes are done in the JSP that are not freqently changed.
4. Incude directive will give compile time error if the file not exist.


Action Include:
1.Included the resources at request processing time.
2.It supports static & dynamic resources.
3.If any changes are done in the JSP that are change freqently.
4. and include action will show runtime error if the file not exist.

02/01/2017

Implementation of a DAO Manager in JAVA…..

Step 1: Connection pooling
First of all, you will have to configure a connection pool. A connection pool is, well, a pool of connections. When your application runs, the connection pool will start a certain amount of connections, this is done to avoid creating connections in runtime since it's a expensive operation. This guide is not meant to explain how to configure one, so go look around about that.
Here Java is the language and Glassfish as the server.

Step 2: Connect to the database
Let's start by creating a DAOManager class. Let's give it methods to open and close a connection in runtime. Nothing too fancy.
public class DAOManager {

public DAOManager() throws Exception {
try
{
InitialContext ctx = new InitialContext();
this.src = (DataSource)ctx.lookup("jndi/MYSQL"); //The string should be the same name you're giving to your JNDI in Glassfish.
}
catch(Exception e) { throw e; }
}

public void open() throws SQLException {
try
{
if(this.con==null || !this.con.isOpen())
this.con = src.getConnection();
}
catch(SQLException e) { throw e; }
}

public void close() throws SQLException {
try
{
if(this.con!=null && this.con.isOpen())
this.con.close();
}
catch(SQLException e) { throw e; }
}

//Private
private DataSource src;
private Connection con;

}
This isn't a very fancy class, but it'll be the basis of what we're going to do. So, doing this:
DAOManager mngr = new DAOManager();
mngr.open();
mngr.close();
should open and close your connection to the database in an object.
Step 3: Make it a single point!
What, now, if we did this?
DAOManager mngr1 = new DAOManager();
DAOManager mngr2 = new DAOManager();
mngr1.open();
mngr2.open();
Some might argue, "why in the world would you do this?". But then you never know what a programmer will do. Even then, the programmer might forger from closing a connection before opening a new one. Plus, this is a waste of resources for the application. Stop here if you actually want to have two or more open connections, this will be an implementation for one connection per user.
In order to make it a single point, we will have to convert this class into a singleton. A singleton is a design pattern that allows us to have one and only one instance of any given object. So, let's make it a singleton!
• We must convert our public constructor into a private one. We must only give an instance to whoever calls it. The DAOManager then becomes a factory!
• We must also add a new private class that will actually store a singleton.
• Alongside all of this, we also need a getInstance() method that will give us a singleton instance we can call.
Let's see how it's implemented.
public class DAOManager {

public static DAOManager getInstance() {
return DAOManagerSingleton.INSTANCE;
}

public void open() throws SQLException {
try
{
if(this.con==null || !this.con.isOpen())
this.con = src.getConnection();
}
catch(SQLException e) { throw e; }
}

public void close() throws SQLException {
try
{
if(this.con!=null && this.con.isOpen())
this.con.close();
}
catch(SQLException e) { throw e; }
}

//Private
private DataSource src;
private Connection con;

private DAOManager() throws Exception {
try
{
InitialContext ctx = new InitialContext();
this.src = (DataSource)ctx.lookup("jndi/MYSQL");
}
catch(Exception e) { throw e; }
}

private static class DAOManagerSingleton {

public static final DAOManager INSTANCE;
static
{
DAOManager dm;
try
{
dm = new DAOManager();
}
catch(Exception e)
dm = null;
INSTANCE = dm;
}

}

}
When the application starts, whenever anyone needs a singleton the system will instantiate one DAOManager. Quite neat, we've created a single access point!
But singleton is an antipattern because reasons! I know some people won't like singleton. However it solves the problem (and has solved mine) quite decently. This is just a way of implementing this solution, if you have other ways you're welcome to suggest so.

Step 4: But there's something wrong...
Java provides a class named ThreadLocal. A ThreadLocal variable will have one instance per thread.
Let's make our INSTANCE ThreadLocal then. Modify the class this way:
public class DAOManager {

public static DAOManager getInstance() {
return DAOManagerSingleton.INSTANCE.get();
}

public void open() throws SQLException {
try
{
if(this.con==null || !this.con.isOpen())
this.con = src.getConnection();
}
catch(SQLException e) { throw e; }
}

public void close() throws SQLException {
try
{
if(this.con!=null && this.con.isOpen())
this.con.close();
}
catch(SQLException e) { throw e; }
}

//Private
private DataSource src;
private Connection con;

private DAOManager() throws Exception {
try
{
InitialContext ctx = new InitialContext();
this.src = (DataSource)ctx.lookup("jndi/MYSQL");
}
catch(Exception e) { throw e; }
}

private static class DAOManagerSingleton {

public static final ThreadLocal INSTANCE;
static
{
ThreadLocal dm;
try
{
dm = new ThreadLocal(){

protected DAOManager initialValue() {
try
{
return new DAOManager();
}
catch(Exception e)
{
return null;
}
}
};
}
catch(Exception e)
dm = null;
INSTANCE = dm;
}

}

}
I would seriously love to not do this
catch(Exception e)
{
return null;
}
but initialValue() can't throw an exception. Oh, initialValue() you mean? This method will tell us what value will the ThreadLocal variable hold. Basically we're initializing it. So, thanks to this we can now have one instance per thread.

Step 5: Create a DAO
A DAOManager is nothing without a DAO. So we should at least create a couple of them.
A DAO, short for "Data Access Object" is a design pattern that gives the responsability of managing database operations to a class representing a certain table.
In order to use our DAOManager more efficiently, we will define a GenericDAO, which is an abstract DAO that will hold the common operations between all DAOs.
public abstract class GenericDAO {

public abstract int count() throws SQLException;

//Protected
protected final String tableName;
protected Connection con;

protected GenericDAO(Connection con, String tableName) {
this.tableName = tableName;
this.con = con;
}

}
For now, that will be enough. Let's create some DAOs. Let's suppose we have two POJOs: Firstand Second, both with just a String field named data and its getters and setters.
public class FirstDAO extends GenericDAO {

public FirstDAO(Connection con) {
super(con, TABLENAME);
}


public int count() throws SQLException {
String query = "SELECT COUNT(*) AS count FROM "+this.tableName;
PreparedStatement counter;
try
{
counter = this.con.PrepareStatement(query);
ResultSet res = counter.executeQuery();
res.next();
return res.getInt("count");
}
catch(SQLException e){ throw e; }
}

//Private
private final static String TABLENAME = "FIRST";

}
SecondDAO will have more or less the same structure, just changing TABLENAME to "SECOND".

Step 6: Making the manager a factory
DAOManager not only should serve the purpose of serving as a single connection point. Actually, DAOManager should answer this question:
Who is the one responsible of managing the connections to the database?
The individual DAOs shouldn't manage them, but DAOManager. We've answered partially the question, but now we shouldn't let anyone manage other connections to the database, not even the DAOs. But, the DAOs need a connection to the database! Who should provide it? DAOManager indeed! What we should do is making a factory method inside DAOManager. Not just that, but DAOManager will also hand them the current connection!
Factory is a design pattern that will allow us to create instances of a certain superclass, without knowing exactly what child class will be returned.
First, let's create an enum listing our tables.
public enum Table { FIRST, SECOND }
And now, the factory method inside DAOManager:
public GenericDAO getDAO(Table t) throws SQLException
{

try
{
if(this.con == null || this.con.isClosed()) //Let's ensure our connection is open
this.open();
}
catch(SQLException e){ throw e; }

switch(t)
{
case FIRST:
return new FirstDAO(this.con);
case SECOND:
return new SecondDAO(this.con);
default:
throw new SQLException("Trying to link to an unexistant table.");
}

}
Step 7: Putting everything together
We're good to go now. Try the following code:
DAOManager dao = DAOManager.getInstance();
FirstDAO fDao = (FirstDAO)dao.getDAO(Table.FIRST);
SecondDAO sDao = (SecondDAO)dao.getDAO(Table.SECOND);
System.out.println(fDao.count());
System.out.println(sDao.count());
dao.close();
Isn't it fancy and easy to read? Not just that, but when you call close(), you close every single connection the DAOs are using. But how?! Well, they're sharing the same connection, so it's just natural.

Step 8: Fine-tuning our class
We can do several things from here on. To ensure connections are closed and returned to the pool, do the following in DAOManager:

protected void finalize()
{

try{ this.close(); }
finally{ super.finalize(); }

}
You can also implement methods that encapsulate setAutoCommit(), commit() and rollback()from the Connection so you can have a better handling of your transactions. What I also did is, instead of just holding a Connection, DAOManager also holds a PreparedStatement and a ResultSet. So, when calling close() it also closes both. A fast way of closing statements and result sets!

Address

Bhubaneswar

Alerts

Be the first to know and let us send you an email when Computer science posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Contact The Business

Send a message to Computer science:

Share