Thursday, December 29, 2011

All about EJBs

EJB-1.0 : Basic Components - Overview (Remote Interface & Remote Home version):
Java World Link

Build your first stateless session bean:
Sun Link

EJB 2.0 : Getting Started with Enterprise JavaBeans (Uses Remote Interface and Remote Home Interface version even though local are available):
ConceptGo Link

Restrictions:
"This section describes the programming restrictions that a Bean Provider must follow to ensure that the enterprise bean is portable and can be deployed in any compliant EJB 2.0 Container. The restrictions apply to the implementation of the business methods...

* An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.
* An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances.
* An enterprise Bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.
* An enterprise bean must not use the java.io package to attempt to access files and directories in the file system.
* An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.
* The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.
* The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams.
* The enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.
* The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread; or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups.
* The enterprise bean must not attempt to directly read or write a file descriptor.
* The enterprise bean must not attempt to obtain the security policy information for a particular code source.
* The enterprise bean must not attempt to load a native library.
* The enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean.
* The enterprise bean must not attempt to define a class in a package.
* The enterprise bean must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity).
* The enterprise bean must not attempt to use the subclass and object substitution features of the Java Serialization Protocol.
* The enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject(), SessionContext. getEJBLocalObject(), EntityContext.getEJBObject(), or EntityContext.getEJBLocalObject() instead."

Interview Questions:
AppLabs Link

Core J2EE Patterns


Reference : Sun Developer Network

Tuesday, December 27, 2011

Java - DBMS

Java - Stored Procedure tutorial (From creation of class - loading, publishing, executing, trigger) :

Java Docs

Sunday, December 25, 2011

All about volatile

References:
JeremyManson Blog

Javamex

When to use volatile : http://www.javamex.com/tutorials/synchronization_volatile_when.shtml

Example usecase of volatile : Refer to javamex

Infamous Double-checked locking for singletons. - TBD

Saturday, December 24, 2011

Generics

Must read tutorial:
Sun Java Tutorial

Comparator and Comparable

References:
Link1:
http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

Link2:
http://www.java2s.com/Code/Java/Collections-Data-Structure/WritingYourownComparator.htm

Friday, December 23, 2011

Hashcode & equals

Contract between hashcode and equals as per Java specification -

* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

* If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

* It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

--------------------------------------------
Sample Buggy code to show bug if same fields are not used to compute equals and hashCode :
--------------------------------------------
package com.examples;

public final class Box {

private final int ssn;
private final int age;

public Box(int ssnval, int ageval) {
ssn = ssnval;
age = ageval;
}

// Magic number 31 (odd and prime) as seed just like java String.
public int hashCode() {
return 31 + ssn;
}

public boolean equals(Object that) {

if (this == that) {
return true;
}

if (! (that instanceof Box) ) {
return false;
}

if ((this.ssn == ((Box)that).ssn) && (this.age == ((Box)that).age)) {
return true;
}

// Bug in code as there is a mismatch of fields between equals and hashcode.
return false;
}

}

package com.examples;

import java.util.*;

public class Test {

public static void main(String[] args) {
Box b1 = new Box(10, 20);
Box b2 = new Box(10, 25);

if (b1.hashCode() == b2.hashCode()) {
System.out.println("Box objects b1 & b2 - hashcodes are same");
} else {
System.out.println("Box objects b1 & b2 - hashcodes are NOT same");
}

if (b1.equals(b2)) {
System.out.println("Box objects b1 & b2 - equals are same");
} else {
System.out.println("Box objects b1 & b2 - equals are NOT same");
}

Map boxmap = new HashMap();
boxmap.put(b1, "TestVal");

String val1 = boxmap.get(b1);
String val2 = boxmap.get(b2);
System.out.println("Val1 = " + val1);
System.out.println("Val2 = " + val2);

}

}

Output demonstrating the bug : val2 is null because of broken contract.
-------------------------------
Box objects b1 & b2 - hashcodes are same
Box objects b1 & b2 - equals are NOT same
Val1 = TestVal
Val2 = null


The above example clearly shows that Java collection uses hashCode first to go to the appropriate bucket. Then uses equals() to see if object matches.

Bug fix: Change hashCode() to use 31 + ssn + age.

*** Note that the above sample uses Immutable Box object demonstration - all final, private and one-shot object construction.


References:
------------
* Implementing HashCode - http://www.javapractices.com/topic/TopicAction.do?Id=28

* http://tech-read.com/2009/02/12/use-of-hashcode-and-equals

Thursday, December 22, 2011

Immutable Objects

* Immutable objects - http://www.javapractices.com/topic/TopicAction.do?Id=29

Advantages and disadvantages of immutable objects :
http://www.codeinstructions.com/2008/07/immutable-classes.html

Terminology:
Value Object : http://c2.com/cgi/wiki?ValueObject

Sunday, December 11, 2011

Struts-1 Basics

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:
* Open source
* Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
* Implements the JSP Model 2 Architecture
* Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.



All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:

** From View to Action :
A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function.

** From Action to View :
After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser.

=====================
Struts Components
=====================

The Controller :
-----------------------
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.
The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.
Action Classes

It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.

View Resources
-------------------
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.

ActionForms
-------------------
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

Model Components
--------------------
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:
* JavaBeans
* EJB
* CORBA
* JDO
* any other

=============
SEQUENCE FLOW
==============


The following events happen when the Client browser issues an HTTP request.

* The ActionServlet receives the request.
* The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
* During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks :-

* Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
* Decides which action class to invoke to process the request.
* Validate the data entered by the user.
* The action class process the request with the help of the model component. The model interacts with the database and process the request.
* After completing the request processing the Action class returns an ActionForward to the controller.
* Based on the ActionForward the controller will invoke the appropriate view.
* The HTTP response is rendered back to the user by the view component.

References:
-----------
Exadel Site
Site-2

Wednesday, December 7, 2011

Conversion and Casting

Tracing technique for casting (primitive data types)
******************************

byte ---> short ---> int ---> long ---> float ---> double
char ----> int ---> long ---> float ---> double

In the above chart, if you can trace path from one element to another element, then that cast is safe (or) implicit cast happens.
For ex: conversion of byte to float is fine as you can trace the path. Reverse (float to byte) is not safe as you cannot trace the path.

****************************************************
Primitive Data Type - Conversion (Implicit Casting)
****************************************************

For primitive data types, this happens in the following cases

1. Assignment operations
int i;
double d;
i=10;
d=i; // Implicit Casting happens here

2. Method call

int i=10;
foo(i); // Implicit Casting happens here

public void foo(long l) {
...
}

3. Arithment promotions
int i =10;
long l = 20;
long result = l/i; // Implicit Casting happens here as part of arithmetic promotions.

****************************************************
Primitive Data Type - Explicit Casting
****************************************************
int i;
long l;
l = (long) i; // Works - even though this is not necessary. Implicit cast happens if we don't specify it.
i = (int) l; // Explicit casting. Narrow down cast always needs Explicit casting. This compiles and works. But result could be unexpected as most significant bits will be lost.


****************************************************
Object References - Conversion (Implicit Casting)
****************************************************
TBD.

****************************************************
Object References - Conversion (Explicit Casting)
****************************************************
TBD.

Reference:
Java Certification Book.

Boxing/Unboxing - Primitive Type wrappers

Java provides Auto Boxing/Un-boxing functionality as we cannot use primitive types to store in Collection framework (deals with Object References).

For each primitive type in Java, we have an equivalent Object wrapper.

boolean - Boolean (1 bit storage for primitive data type)
byte - Byte (1 byte storage for primitive data type)
short - Short ; char - Character (2 bytes storage for short or char - primitive data types)
int - Integer (4 bytes storage for primitive data type)
long - Long (8 bytes storage for primitive data type)
float - Float (4 bytes storage for primitive data type)
double - Double (8 bytes storage for primitive data type)

Boxing / Unboxing functionality in Java does implicit casting during
- assignment
- method invocation.

For examples and more details, refer to the following tutorial
Java Tutorial

Is intern() on String worth the effort?

Link to the analysis

http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html