Monday, May 14, 2012

Configuring Custom Session identifier

Lets assume customer has a policy that each web application must have an alternative session identifier than that the default JSESSIONID. In this case they wanted to set it to applicationname_sessionid.

It is possible that they perhaps have in there infrasturucture some other applications to enforce certian security restrictions , such as a requests has to have a specific session identfier.

1. To configure custom session identifier in weblogic, we need to modifiy the application related WEB-INF\weblogic.xml file. We need to add the cookieName parameter and value applicationname_sessionid under tags session-param


CookieName applicationname_sessionid


1. To configure custom session identifier in websphere, we need to add the custom property SessionRewriteIdentifier at web container level.

To specify custom properties for session management, use the following steps:

1.In the administrative console click Servers > Application Servers > server_name > Web Container Settings > Web container.
2.Under Additional Properties select Custom Properties.
3.On the Custom Properties page, click New.
4.On the settings page, enter the property that you want to configure in the Name field (SessionRewriteIdentifier ) and the value that you want to set it to in the Value field (applicationname_sessionid).
5.Click Apply or OK.
6.Click Save on the console task bar to save your configuration changes.
7.Restart the server.

Thursday, February 10, 2011

How to make class Immutable like String

1. make your class final, so that no other class can be inherited
2. Make sure that all variables are final and private.
3. No setter methods.
4. Provide a constructor which can take values to these variables.

Example:

final class MyImmutableClass
{
// instance var are made private & final to restrict the access

private final int count;
private final double value;

// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
count = paramCount;
value = paramValue;
}

// provide only methods which return the instance var
// & not change the values

public int getCount()
{
return count;
}

public double getValue()
{
return value;
}
}

// class TestImmutable
public class TestImmutable
{
public static void main(String[] args)
{
MyImmutableClass obj1 = new MyImmutableClass(3,5);

System.out.println(obj1.getCount());
System.out.println(obj1.getValue());

// there is no way to change the values of count & value-
// no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

Monday, January 17, 2011

When providing a user defined class to HashMap or HashTable what methods needs to be overridden?

You should override the equals() and hashCode() methods from the Object class. The default implementation of the equals() and hashcode(), which are inherited from the java.lang.Object uses an object instance’s memory location (e.g. MyEmployeeObject@8d52g38h). This can cause problems when two instances of the Employee objects have the
same id but the inherited equals() will return false because it uses the memory location, which is different for the two instances. Also the toString() method can be overridden to provide a proper string representation of your
object. Points to consider:

• If a class overrides equals(), it must override hashCode().
• If 2 objects are equal, then their hashCode values must be equal as well.
• If a field is not used in equals(), then it must not be used in hashCode().
• If it is accessed often, hashCode() is a candidate for caching to enhance performance.

Vector Vs ArrayList

Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization
will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList.


Data growth


Internally, both the ArrayList and Vector hold onto their contents using an Array. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance
hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program
will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later.
If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.


Usage patterns


Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end
of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements
at index i and higher over by one element. So what does this all mean?


It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1). However, indexing an element is a bit slower -- O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.

When to use an abstract class and interface

When to use an abstract class?:

In case where you want to use implementation inheritance then it is usually
provided by an abstract base class. Abstract classes let you define some default behaviour and force subclasses to provide any specific behaviour.

When to use an interface?: For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently,

you should prefer using interface to abstract. Justification for using interfaces
is that they solve the ‘diamond problem’ of traditional multiple inheritance.

What is the difference between aggregation and composition?

Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole.

For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.

Ex:

Class employee {

private Department dept;

//setter and getter methods
}

dept can exists even if we delete employee class.since dept can be a member of another class.

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.

For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

Ex:

class Employee {

private Department dept = new Department();

}

If employee is deleted, department also deleted.

Difference between NoClassDefFoundException and ClassNotFoundException

A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading) but the runtime system cannot find the referenced class.

Ex: Employee e = new Employee();


A ClassNotFoundException is thrown when an application tries to load in a
class through its string name using the following methods but no definition for the
class with the specified name could be found:

1. The forName(..) method in class - Class.
2. The findSystemClass(..) method in class - ClassLoader.
3. The loadClass(..) method in class - ClassLoader

Ex: Class employeeClass = Class.forName("com.samples.Employee") ;

Tuesday, September 21, 2010

Core J2EE Design Patterns

J2EE Design patterns are divided into 3 types

1. Presentation Tier
2. business Tier
3. Integration Tier


Presentation Tier Design Patterns

1. Front Controller
2. Service to workers
3. Dispatcher view
4. Composite View
5. View Helper
6. Intercepting Filter
7. Application Controller
8. Context Object pattern

Business Tier Design Patterns

1. Business Delegate
2. Service Locator
3. Session Façade
4. Application Service
5. Business Object
6. Message Façade
7. Transfer Object(Value Object)
8. Transfer Object Assembler
9. Value List Handler
10. Composite Entity

>Integration Tier Design Patterns

1. Service Activator pattern
2. Data Access Object (DAO)
3. Domain Store

Design Patterns

What is a design pattern
a practical, proven solution to a recurring design problem

Design patterns are divided into two types

GOF Design Patterns
Core J2EE patterns

GOF Design patterns:

Gang of four design patterns are divided into 3 trypes
1. Creational
2. Structural
3. Behavioral

Creational patterns are ones that create objects for you, rather than having you instantiate objects directly

Structural patterns help you compose groups of objects into larger structures

Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program.

Creational Patterns:
Abstract Factory
Builder
Factory
Prototype
Singleton

Structural patterns:
adapter
bridge
composite
decorator
facade
flyweight
proxy

Behavioral patterns:
chain of responsibility
command
interpreter
iterator
mediator
memento
observer
state
strategy
template method
Visitor

Creational Patterns Types

Factory Method : define an interface for creating an object, but let sub-class decide which class to instantiate. This lets a class to defer instantiation to subclasses.

Builder : separate the construction of a complex object from its representation so that the same construction process can create diff. representations.

Abstract Factory : provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Prototype : specify the kinds of objects to create using a prototypical instance and create new objects by copying this prototype.

Singleton : Ensure a class only has one instance, and provide a global point of access to it.

Structural Patterns Types:

Adapter : convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.

The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter

Bridge : Decouple an abstraction from its implementation so that the two can vary independently.

Composite : compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly

Decorator : Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality.

Façade : Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher level interface that makes the subsystem easier to use

Flyweight : use sharing to support large numbers of fine-grained objects efficiently.

Proxy : which provides a simple place-holder class for a more complex class which is expensive to instantiate.



Behavioral Patterns Types:

Chain of responsibility : The responsibility of handling the request data is given to any of the members of the “chain”. If the first link of the chain cannot handle the responsibility, it passes the request data to the next level in the chain, i.e. to the next link. (a chain of classes that process request )

Command : The client invokes a particular module using a command. The client passes a request, this request gets propagated as a command. The command request maps to particular modules. According to the command, a module is invoked. (request encapsulated in an object )

Interpreter : It converts the code written in English to a byte code format so as to make possible for all the operating systems to understand it.

Iterator : which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation.

Mediator : It promotes loose-coupling of classes such that only one class (Mediator) has the knowledge of all the classes, rest of the classes have their responsibilities and they only interact with the Mediator.

Memento : without violating encapsulation, capture and externalize an objects' internal state so that the object can be restored to this state later. (store and restore object's internal state )

Observer : define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

State : allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
(provides a memory for a class’s instance variables.)

Strategy : Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
(group of classes that represent set of possible behaviors )

Template Method : define the skeleton of an algorithm in an operation, deferring some steps to subclasses. provides a method that allows sub-classes to override parts of method without re-writing it. (provides an abstract definition of an algorithm. )

Visitor : Represent an operation to be performed on the elements of an object structure. Visitor to add new function to a set of classes without having to modify them.

How to remove HTML Tags from Java String

1. You can try like this to remove html tags from string

String noHTMLString = htmlString.replaceAll("\\<.*?\\>", "");
System.out.println(noHTMLString);

2. Another complicated example

public static String removeHTML(String htmlString)
{
// Remove HTML tag from java String
String noHTMLString = htmlString.replaceAll("\\<.*?\\>", "");

// Remove Carriage return from java String
noHTMLString = noHTMLString.replaceAll("\r", "
");

// Remove New line from java string and replace html break
noHTMLString = noHTMLString.replaceAll("\n", " ");
noHTMLString = noHTMLString.replaceAll("\'", "'");
noHTMLString = noHTMLString.replaceAll("\"", """);
return noHTMLString;
}

Friday, September 17, 2010

Load the xml file from the class which is in the same Jar file

Lets assume you have a class called samle and xml file called sample.xml file. Both class and xml files are in the jar file.

If you want to load the sample.xml from the sample.class file, you need to use the following code.

this.getClass().getClassLoader().getResource("sample.xml")

Sample examples:

public class Sample {
public void callXmlMapping() {
URL url = this.getClass().getClassLoader().getResource("sample.xml");
}
}


You can create jar file with these both files and add this jar file in class path of your webapplication.

Log4j setup and configuration specific to module

Lets assume you would like to enable logging for the modules which starts with the package called com.sample.*.*.*. You need to create a log4j.properties file in \web-inf\classes folder. And place foloowing entries in the log4j.properties file. And make sure that log4j.jar file needs to be there in your class path (Ex: web-inf\lib folder)

log4j.logger.com.sample=DEBUG, sample
log4j.appender.sample.File=${user.dir}/sample/logs/sample.log
log4j.appender.sample.MaxFileSize=10MB
log4j.appender.sample.MaxBackupIndex=10
log4j.appender.sample.Append=false
log4j.appender.sample=org.apache.log4j.RollingFileAppender
log4j.appender.sample.layout=org.apache.log4j.PatternLayout
log4j.appender.sample.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c - %m%n


Now, the log messages will redirect to the location ${user.dir}/sample/logs/sample.log.

Wednesday, September 8, 2010

Repeat HashMap using JSTL tags

Lets assume You have a HashMap like this:

Map map = new HashMap();
map.put("fruits", "Apples");
map.put("Vegetables", "Tomota");
map.put("Vehicles", "Hero Honda");
request.setAttribute("itemsMap", map);


We need the following code to repeat the HashMap Using JSTL tags

c:forEach var="item" items="${itemsMap}">

Key is : ${item.key} and value is: ${item.value}



/c:forEach>

Please note that "<" is missing before c:forEach tag

Thursday, June 3, 2010

Have you aware of the problems using toUpperCase and toLowerCase method's in Java String API?

The toUpperCase() and toLowerCase() method's in String API's internally use the Locales. And hence these functions won't work with some of the locales (like turkish e.t.c).

For example consider the following toUpperCase() method code, it won't return the uppercase of the specified string value. To avoid that, you need to explicitly set English locale to the toUpperCase() and toLowerCase() method's. Here turkish language has a problems with charecter "i", so it won't return the expected value.

public class TestAgain

{

public static void main (String[] args) {
Locale locale = new Locale("tr" , "TR");

Locale.setDefault(locale);
String val = "DeleteAllVersions";
val = val.toUpperCase(Locale.getDefault());

System.out.println("val:" + val);

}
}

Iterator Vs Enumerator

1. By using iterator we can remove the value but in ennumerator we can't.

2. Enumeration is twice as fast as Iterator and uses very less memory.

3. Iterator is much safer as compared to Enumeration b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators as they fail quickly and cleanly

Iterator Vs ListIterator

Iterator : Enables you to cycle through a collection,obtaining or removing elements

ListIterator :It extends Iterator allow bidirectional traversal of list & the modification of element

Websphere - java.io.IOException: Async IO operation failed

1. The problem only happens when finishBufferResponse request is processed asynhronously and it is possible to prevent the problem by forcing all such requests to be handled synchronously. This can be done by setting the webcontainer custom property:

com.ibm.ws.webcontainer.channelwritetype=sync


2. The above errors can cause the Http connections to be terminated and can cause session timeouts. To prevent this, you may need to set this custom property

Difference between ConcurrentHashMap and Collections.synchronizedMap

1. ConcurrentHashMap - It allows concurrent modification of the Map from several threads without the need to block them.
Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

2. Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

3. ConcurrentHashMap is optimized for concurrent access.

4. Hashtable and ConcurrentHashMap do not allow null keys or null values.

Collections.synchronizedMap(Map) synchronizes all operations (get, put, size, etc).

ConcurrentHashMap supports full concurrency of retrievals, and adjustable expected concurrency for updates.

How to make read only objects - Collections

The java.util.Collections class contains the following methods to make objects read only.

1. unmodifiableList(List list)

Returns an unmodifiable view of the specified list.

2. unmodifiableMap(Map m)

Returns an unmodifiable view of the specified map.

3. unmodifiableSet(Set s)
Returns an unmodifiable view of the specified set.

ConcurrentHashMap

It allows concurrent modification of the Map from several threads without the need to block them.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations.

However, even though all operations are thread-safe, retrieval operations do not entail locking. ConcurrentHashMap is optimized for concurrent access.