Thursday, September 27, 2012

Tomcat's Architecture


Tomcat's Architecture and the main configuration file "server.xml"
Tomcat is an HTTP server. Tomcat is also a container that can execute Java Servlet, and converting JavaServer Pages (JSP) and JavaServerFaces (JSF) to Java Servlet. Tomcat employs a hierarchical and modular architecture as
illustrated:

Tomcat's main configuration file is the "server.xml", kept under the $CATALINA_HOME\conf directory.
Context (Application or Webapp)
A web context is a single web application (webapp). It is the lowest-level container, that you can define
components such as Realm and Valve. By default, all webapps are kept under the $CATALINA_HOME\webapps
directory (as configured in the <host> element appBase attribute.
A Java webapp may contain many types of files, such as HTML, CSS, Scripts, images, JSP, servlet, utility classes,
external library jar-files. A Java webapp must follow a strict directory structure as depicted in the Servlet/JSP
specifications. This enables deployment in a Java-capable web server (such as Apache Tomcat and Glassfish). The
resources must be kept in the correct directories and sub-directories.
The URL of a webapp, by default, is the same as the base directory name (or context root) of the webapp.

Webapp's Directory Structure
The directory structure of a webapp is as follows:


·        "ContextRoot": contains the resources that are visible and accessible by the web clients, such as HTML, CSS,Scripts and images. These resources will be delivered to the clients as it is. You could create sub-directories such as images, css and scripts, to further categories the various resources.


o   "ContextRoot\WEB-INF": This directory, although under the context root, is NOT visible to the web users. In other words, it is NOT accessible by the clients directly (for security reason). This is where you keep your application-specific configuration files such as "web.xml". It's sub-directories contain program classes, source files, and libraries.


§  "ContextRoot\WEB-INF\src": Keeps the Java program source files. It is optional but a good practice to separate the source files and classes to facilitate deployment.

§  "ContextRoot\WEB-INF\classes": Keeps the Java classes (compiled from the source codes). Classes defined in packages must be kept according to the Java package directory structure.

§  "ContextRoot\WEB-INF\lib": Keeps the libraries (jar-files), which are provided by other packages, specific and available to this webapp only.


o   "ContextRoot\META-INF\": This is also a hidden directory, to keep resources and configurations (e.g., "context.xml") related to the server. In contrast, "WEB-INF" is for resources related to this web application, independent of the server.


Webapp-Specific Configuration Files
These are the configuration files specific to a webapp: 

(a) WEB-INF\web.xml
(b) META-INF\context.xml.


You can configure a webapp in many ways: 

(a) Write a <context> element in server.xml under <Host> element,
(b) contextRoot\META-INF\context.xml
(c) conf\Catalina\localhost\webapp.xml
(d) conf\context.xml


Tomcat's Directory Structure

Tomcat installation provides these directories:

bin: for Tomcat's binary codes.

conf: global configuration applicable to all the webapps. The default installation provides:
One policy file: catalina.policy for specifying security policy.
Two properties files: catalina.properties and logging.properties,
Four configuration files: server.xml (Tomcat main configuration file), web.xml (global web application
deployment descriptors), context.xml (global Tomcat-specific configuration options) and tomcatusers.
xml (a database of user, password and role for authentication and access control).
The conf also contain a sub-directory for each engine, e.g., Catalina, which in turn contains a sub-subdirectory
for each of its hosts, e.g., localhost. You can place the host-specific context information (similar to
context.xml, but named as webapp.xml for each webapp under the host).

lib: Keeps the JAR-file that are available to all webapps. The default installation include servlet-api.jar,
jasper.jar (JSP), jasper-el.jar (EL). You may also keep the MySQL JDBC driver (mysql-connectorjava-
5.1.xx-bin.jar), and JSTL (jstl.jar and standard.jar) here.

logs: contains the engine logfile Catalina.yyyy-mm-dd.log, host logfile localhost.yyyy-mm-dd.log,
and other application logfiles such as manger and host-manager. The access log (created by the
AccessLogValve) is also kept here.

temp: temporary files used by Tomcat.

webapps: the default appBase - web applications base directory of the host localhost.

Tuesday, September 25, 2012

ResultSet Vs RowSet








A ResultSet
 maintains a connection to a database and because of that it can’t be serialized and also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be serialized because it doesn’t have a connection to any database and also it can be sent from one class to another across the network.

More on RowSet:

  • A RowSet can be  connected  or disconnected
  • A disconnected rowset gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the data source, but most of the time it does not have a connection open. While it is disconnected, it does not need a JDBC driver or the full JDBC API, so its footprint is very small. Thus a rowset is an ideal format for sending data over a network to a thin client.
  • A connected RowSet is like a wrapper around the ResultSet. 

Implementation: 


A CachedRowSet class—a disconnected rowset that caches its data in memory; not suitable for very large data sets, but an ideal way to provide thin Java clients, such as a Personal Digital Assistant (PDA) or Network Computer (NC), with tabular data  

A JDBCRowSet class—a connected rowset that serves mainly as a thin wrapper around a ResultSet object to make a JDBC driver look like a JavaBeans component  

A WebRowSet class—a connected rowset that uses the HTTP protocol internally to talk to a Java servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly update a set of rows


Monday, September 24, 2012

Externalization






There might be times when you have special requirements for the serialization of an object. For example, you may have some security-sensitive parts of the object, like passwords, which you do not want to keep and transfer somewhere. Or, it may be worthless to save a particular object referenced from the main object because its value will become worthless after restoring.
Unlike Serializable interface, Externalizable interface is NOT a marker interface
One thing you can do with Externalization is that you can store extra information into object like STATIC variables and transient variables or you can add more information if you have any business need. One good example is compressing and uncompressing of data to send it through network or converting one format to other like a BMP image to JPEG or GIF format.

You can control the process of serialization by implementing the Externalizable interface instead of Serializable. This interface extends the original Serializable interface and adds writeExternal() and readExternal(). which are to be overridden for the purpose of object serialization process.

writeExternal() method is used to save the contents of an object.
readExternal() method is used to restore the contents of an object.

·         These two methods will automatically be called in your object's serialization and deserialization, allowing you to control the whole process.
·         These methods are implemented by the class to give the class a complete control over the format and contents of the stream for an object and its supertypes.
·         These methods must explicitly coordinate with the supertype to save its state. These methods supersede customized implementations of writeObject and readObject methods.

There is one major difference between serialization and externalization:
When you serialize an Externalizable object, a default constructor will be called automatically; only after that will the readExternal() method be called.

If you inherit some class from a class implementing the Externalizable interface, you must call writeExternal() and readExternal() methods when you serialize or deserialize this class in order to correctly save and restore the object.

How serialization happens?

  1.  JVM first checks for the Externalizable interface and if object supports Externalizable interface, then serializes the object using writeExternal method.
  2. If the object does not support Externalizable but implement Serializable, then the object is saved using ObjectOutputStream.
  3. Now when an Externalizable object is reconstructed, an instance is created first using the public no-arg constructor, then the readExternal method is called. Again if the object does not support Externalizable, then Serializable objects are restored by reading them from an ObjectInputStream.



 Externalization Code
public class FirstClass implements Externalizable
{
        SecondClass secondClass;
        public void writeExternal(ObjectOutputStream out)
        {
                secondClass.writeExternal(out);
        }
        public void readExternal(ObjectInputStream inp)
        {
                secondClass = new SecondClass();
                secondClass.readExternal(inp);
        }
}

class SecondClass implements Externalizable
{
        String str;
        public void writeExternal(ObjectOutputStream out) { out.writeUTF(str); }
        public void readExternal(ObjectInputStream inp) { str = inp.readUTF(); }
}


Saturday, September 15, 2012

DDL vs DML vs DCL





DDL(Data Definition Language)
Statements are used to define the schema
No Rollback
Doesn't make entries in Log File
Auto Commit
Triggers are not fired

·         CREATE
·         ALTER
·         DROP
·         TRUNCATE
·         COMMENT
·         RENAME

DML(Data Manipulation Language)
Statements are used to manage the data within the schema
Can Rollback
Make entries in Log File
No Auto Commit
Triggers are fired

·         SELECT
·         INSERT
·         UPDATE
·         DELETE
·         MERGE
·         CALL
·         EXPLAIN PLAIN
·         LOCK TABLE

DCL(Data Control Language)
·         GRANT
·         REVOKE

TCL(Transaction control Language)
These are used to manage the changes made by DML Statements. It allows statements to be grouped together into logical transactions

·         COMMIT
·         SAVEPOINT
·         ROLLBACK
·         SET TRANSACTION  

Friday, September 14, 2012

Triggers and Cursors




Trigger


A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed.

Types of PL/SQL Triggers
There are two types of triggers based on which level it is triggered.
1) Row level trigger - An event is triggered for each row updated, inserted or deleted. 
2) Statement level trigge- An event is triggered for each sql statement executed. 

PL/SQL Trigger Execution Hierarchy
The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected. 
3) Then AFTER row level trigger fires once for each affected row. This events will alternates between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

Syntax of Triggers

The Syntax for creating a trigger is:

 CREATE [OR REPLACE ] TRIGGER trigger_name 
 {BEFORE | AFTER | INSTEAD OF } 
 {INSERT [OR] | UPDATE [OR] | DELETE} 
 [OF col_name] 
 ON table_name 
 [REFERENCING OLD AS o NEW AS n] 
 [FOR EACH ROW] 
 WHEN (condition)  
 BEGIN 
   --- sql statements  
 END; 




Example

Row Level: This trigger will insert a record into the table 'product' after each row is updated.
 CREATE or REPLACE TRIGGER After_Update_Row_product 
 AFTER  
 insert On product 
 FOR EACH ROW 
 BEGIN 
 INSERT INTO product
 Values('After update, Row level',sysdate); 
 END; 
 / 
Statement Level: This trigger will insert a record into the table 'product' after a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER After_Update_Stat_product 
 AFTER 
 UPDATE ON product 
 BEGIN 
 INSERT INTO product 
 Values('After update, statement level', sysdate); 
 End; 
 / 

 Cursors

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called theactive set.
There are two types of cursors in PL/SQL:

Implicit cursors:

These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. 

Explicit cursors:

They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed. 

Monday, September 10, 2012

Autowiring



Spring have many collaborating bean, the autowire help in making the relationship between them.
Autowiring reduces the effort of writing properties or constructor arguments. The autowiring in specified at the autowire attribute inside <bean/> element. 
We know to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file.

<bean name="beanA" class="BeanA">
   <property name="beanB"><ref bean="beanB"/></property>
</bean>
<bean name="beanB" class="BeanB" />
<bean name="beanC" class="BeanC">
   <property name="beanA"><ref bean="beanA"/></property>
   <property name="beanB"><ref bean="beanB"/></property>
</bean>

<bean name="beanA" class="BeanA">
    <constructor-arg index="0"><ref bean="beanB"/></constructor-arg>
</bean>

<bean name="beanB" class="BeanB" />

<bean name="beanC" class="BeanC">
    <constructor-arg index="0"><ref bean="beanA"/></constructor-arg>
    <constructor-arg index="1"><ref bean="beanB"/></constructor-arg>
</bean>


The Spring container can autowire relationships between collaborating beans WITHOUT using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application.

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans will not be autowired. 

Limitations with autowiring:
Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing to developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them.


Limitations
Description
Overriding possibility
You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Primitive data types
You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing nature
Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.


ModeExplanation
noNo autowiring at all. Bean references must be defined via a ref element. This is the default, and changing this is discouraged for larger deployments, since explicitly specifying collaborators gives greater control and clarity. To some extent, it is a form of documentation about the structure of a system.
byNameAutowiring by property name. This option will inspect the BeanFactory and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a master property (that is, it has a setMaster(...) method), Spring will look for a bean definition named master, and use it to set the property.
byTypeAllows a property to be autowired if there is exactly one bean of the property type in the BeanFactory. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. If this is not desirable, setting the dependency-check="objects" attribute value specifies that an error should be thrown in this case.
constructorThis is analogous to byType, but applies to constructor arguments. If there isn't exactly one bean of the constructor argument type in the bean factory, a fatal error is raised.
autodetectChooses constructor or byType through introspection of the bean class. If a default constructor is found, byType gets applied.

Thursday, September 6, 2012

ClassCastException






API Specifications for the ClassCastException:
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

So, for example, when one tries to cast an Integer to a String, String is not a subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.


Or think of a class diagram with Animal.class, Dog.class and Cat.class

Animal a = new Dog();
Dog d = (Dog) a; // no problem, the type animal can be casted to a dog, because its a dog
Cat c = (Dog) a; // raises class cast exception, you cant cast a dog to a cat


Tuesday, September 4, 2012

Encapsulation vs Abstraction



Encapsulation
Encapsulation means to capsulate data and the function into a single entity. Encapsulation is the mechanism that binds the code and data together and restricts access by the outside world.

A very good example of encapsulation is a car. All the internal working of the car, its transmission, parts, etc. is hidden from the outside world. Only the important details are mentioned like the size of the tire, number of gears, etc.

You can think of encapsulation as a way to wrap the data inside a container to restrict access from outside world. However, access to the data is provided through a well-defined interface. In java the basis of encapsulation is class. You will specify the code and variables in the form of class variables and methods. The behavior and interface of a class are fully defined by the methods of the class. Access to these methods and variables is specified using the keywords 'public', 'protected' or 'private'. 

  • Public access means anyone can access the data.
  • Private access means only the methods defined within the class can access the data.
  • Protected access means methods within the class and methods within the child classes can access the data.

Child classes are defined using inheritance. 

Thus, encapsulation is hiding of essential details from programmer's point of view



Abstraction
 Abstraction refers to hide all non-essential details from the user and display only the essential part of it. Abstraction is the process of formulating general concepts by abstractingcommon properties of instances.

Abstraction also comes in 2 forms:
control abstraction and data abstraction.

Control abstraction is abstracting the method.
Data abstraction is abstracting the data

Car is a very good example to define abstraction. A person driving the car only needs to know where the gear, clutch, brakes, etc. are present, but he does not need to know how the transmission works, how much fuel is released upon pressing the race, etc.

Abstraction is achieved by forming hierarchical classification or layers. These layers are formed as per the requirement. 

Let us talk about a car where you have 
  1. sound system (as the topmost layer)
  2. radio,cd/dvd player (that works as a second layer) 
  3. system that powers the sound system (last layer)

In java, abstraction is carried out in a way where the object works as the top most layer and all the variables and methods are accessed by it.
  1. Object
  2. Variables and Methods
 With abstraction a user is given a handle to access the data but doesn't need to know anything about the internal working of the system. 

Thus, abstraction is hiding of essential details from the user's point of view