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

Wednesday, June 2, 2010

Cheat Sheet

****************************************
1. Multiple Inheritance :
****************************************
Java does not allow multiple inheritance unlike C++. For ex: a child inherits behavior from two parents. So if you consider a child as an class, then it should be able to inherit from both Mom class and Dad class. So it makes sense to have this multiple inheritance. However Java does not support this. Reason as cited by many authors is, design complexity outweighs its advantages. So Java does not have it.
* However Java supports implementaion of multiple interfaces.

****************************************
2. Operator Overloading :
****************************************
There is no Operator overloading in Java. Java does overloading of + sign to concatenate strings. That is the only overloaded operator in Java. Reason for not providing this option in Java is, problems associated with operator overloading outweigh its advantages. Code becomes confusing and difficult to sustain. So they avoided it.

****************************************
3. Order of allocation in creating a new object :
****************************************
(a) Constructor of the super class is invoked. This takes first precedence.
(b) Initialization of class and object attributes. These are not attributes initialized in the constructor. But instance variables of scope class and object.
(c) Code in the constructor executes.

****************************************
4. Best way to do error handling :
****************************************
Throw Exceptions to the logical point. Caller should be able to fix the problem and re-invoke it.
Fixing the problem could be through
(a) Retry an operation
(b) Collect different data from users.
(c) Report problem back to users.

****************************************
5. Attribute scopes :
****************************************
(a) Local attributes : Declared and initialized inside methods of a class. If local attributes have same name as object attributes, you can specifically invoke object attributes by using "this" operator. "this" refers to the object here.
(b) Object attributes: Not shared between different object instances of a class. These are non-static data members of a class definition.
(c) Class attributes: Shared between all object instances created from that class. These are static data members of a class definition.

****************************************
6. Copying objects :
****************************************
Objects have references to sub objects. This leads to two types of copying - Shallow Versus Deep Copy. You need to provide an implementation for copy method to do a deep copy by traversing through all sub-objects following references. Else you will end up in shallow copy.

****************************************
7. Comparing objects :
****************************************
Just like we have Shallow Versus Deep copy, we also have Shallow versus Deep compare. So you need to provide an implementation for compare method to do a deep compare by traversing through all sub-objects following references. Else you will end up in shallow compare.

****************************************
8. Dangling pointers:
****************************************
TBD

****************************************
9. Garbage Collection:
****************************************
TBD.
Does Java support GC of circular references? - TBD

****************************************
10. MT-Safe
****************************************
1. How does locks work on synchronized methods?
Refer to this tutorial

****************************************
11. Call by value or Call by reference?
****************************************
Refer to this detailed article
CodeGuru Article

****************************************
12. Nested Classes
****************************************
Static inner nested class:
JavaWorld Article

Inner Classes
JavaWorld Article

****************************************
13. Collection
****************************************
Two concepts:
a) Collection :
It is a group of individual elements, often with some rule applied to them. Contains

(i) List -
* A List holds the elements in a particular sequence.
* Allows duplicate values.

(ii) Set -
* No sequence. Just a bag of elements.
* Does not allow any duplicate elements.

b) Map :
(i) It is a group of key-value object pairs. A Map can return a Set of its keys, a Collection of its values, or a Set of its pairs.
(ii) Like Arrays, it is possible to have multiple dimensions without extra implementation. This can be obtained by making value of a key another map.

Commonly used data structures :
-----------------------------------------------
Interface : Concrete Implementation
-----------------------------------------------
Set : HashSet
List : ArrayList
Queue : LinkedList
Map : HashMap / HashTable
SortedSet : Dictionary
----------------------------------------------

Unordered Collection Interface:
1. Collection
2. Set
3. List
4. Queue
5. Map

Ordered Collection Interfaces
1. SortedSet
2. SortedMap

Summary of interfaces


******************** END of CHEAT SHEET ********************

Wednesday, November 11, 2009

Enabling invoker servlet in apache tomcat 6.0.x

The invoker servlet is disabled in web.xml of latest apache tomcat 6.0 versions. It is not advisable to use this for the following reasons:

1. Security risk.

2. Configuration hiding - There is NO way to determine which servlets are used vs which are not used. In web.xml, every servlet is declared and mapped. In that one file you instantly have a road map to how the webapp works.

3. Back doors. Servlets which are mapped can be alternately called via the invoker by class name. Since the URL is different, all security constraints might be ignored since the URL pattern is VERY different.

4. Back doors. Bad programmers make it easier to do bad things.

5. Back doors. It may be common to use common 3rd party jars in a shared area. If that shared jar has servlets in them and that servlet has a hole in it, bad things happen.
Configuration hiding - it's important enough to say twice. Explicit declaration while a PITA, will be more helpful in the maintenance scheme of your webapp.


To enable it for quick testing:

Step-1: In home dir / conf / web.xml file, uncomment servlet definition.

Step-2: In home dir / conf / web.xml file, uncomment servlet mapping.

Step-3: In home dir / conf / context.xml, change parent element Context to
Context privileged="true" reloadable="true"

Reference:
Tomcat invoker servlet evil faqs

Thursday, September 17, 2009

Differences between HashMap and HashTable

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

For new code, use HashMap as much as possible.

If you want Keys in HashMap to be Case - Insensitive, follow this technique:
http://www.velocityreviews.com/forums/t140140-case-insensitive-keys-using-collections.html
* Store keys in LowerCase while popluating the map.
* Always use .LowerCase() on lookupKey before doing a get()

Complexity of Lookup on HashMap is not alway O(1). It depends on HashMap size. If multiple keys in HashMap match a lookupKey, then it traverses linear O(n) on matched Keys.

4 Ways to traverse HashMap - Link

Tuesday, September 15, 2009

All about try-catch-finally

try {
statements;
} catch (exceptionType1 identifier1) { // one or multiple
statements;
} catch (exceptionType2 identifier2) {
statements;
}
...
} finally { // one or none
statements;
}

* must include either one catch clause or a finally clause
* can be multiple catch clauses but only one finally clause
* the try statements are executed until an exception is thrown or it completes successfully

* a compile-error occurs if the code included in the try statement will never throw one of the caught checked exceptions (runtime exceptions never need to be caught)
* if an exception is thrown, each catch clause is inspected in turn for a type to which the exception can be assigned; be sure to order them from most specific to least specific
* when a match is found, the exception object is assigned to the identifier and the catch statements are executed
* if no matching catch clause is found, the exception percolates up to any outer try block that may handle it
* a catch clause may throw another exception

* if a finally clause is included, it's statements are executed after all other try-catch processing is complete
* the finally clause executes wether or not an exception is thrown or a break or continue are encountered

Note
====
* If a catch clause invokes System.exit() the finally clause WILL NOT execute.