Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Design Considerations for Audit Trail Implementation

Auditing the operations in any application is a very common requirement for security and auditing purpose. Auditing can be done at various levels with varying level of details. Overall prime requirements for Audit Trail are:
  • Collect enough information to determine, 
    • Who has done the changes, 
    • What are the changes, 
    • When these changes have been done, Locale etc
    • What user scenario was in action, i.e. the operation context
  • To capture all user actions, even if some of these are not reaching to DB or would be interacting with external services directly (rare, but happens in some cases)
  • Successful and unsuccessful logons or other security related operations
  • Management of collected audit data, which could be very large. 
  • Search operations on collected data
  • Display the collected data to Users in presentable format as and when demanded 

Considering above requirements, there are various design approaches to implement the audit trail in system. Few of these are given below (considering a JEE application, however, many of these are generic)

  1. Implement DB triggers to capture any change in data states and log in audit tables
  2. Log audit data in business services, which means collecting the required data in each business service operation and log it using some abstract Audit service to some data store
  3. Using generic logging framework like Log4J to log the auditing information to desired format and data store and later parse these logs to extract the required data
  4. Interceptors based approach to intercept all operations, collect the data and log it through Audit service. Here interceptors can be of DAO layer interceptors like Hibernate Interceptors or Service level interceptor using AOP.

All of these approaches have their own pros and cons. As obvious, one approach can not be fit for all. Application state, project requirements and scope can define the right set of implementation. So lets discuss the pros and cons of each of these approaches to understand it more.

Database triggers

Database triggers can do really well and nothing can escape from the triggers. Once these are set carefully on all levels, all changes are bound to pass through these and hence will be captured in audit tables.

Pros:

  • Whether it is simple user operation, or any change is being done by DB admin; all kind of changes will be captured by triggers.
  • A comparatively simple approach, in aspect, that no code change is required and it can be implemented directly at database level without disturbing the code.

Spring RoutingDataSource to Work with Multiple DataSources - II

In previous article, we have discussed about using Spring 'AbstractRoutingDataSource' to dynamically routing the database call to desired database (i.e. data source). This is very handy feature and useful in various scenarios. 

One important use case can be in multi-tenant application. In multi-tenant application, one of the database design consideration can be to use separate database for each tenant. It helps to keep the data of each tenant separate, and would be good for performance also. And, good design would require to use the same application layer code to work with all tenant and their specific database. In this scenario, use of 'AbstractRoutingDataSource' can help to achieve these design considerations. Extend the AbstractRoutingDataSource to create a custom 'MultiTenantRoutingDataSource'. Use a thread local application context state holder to maintain the tenant state for current flow. Use this thread local context in extended 'MultiTenantRoutingDataSource' to return the tenant specific data source. Again keep in consideration please, that Routing Data Source will be invoked by TransactionManager before starting the transaction only. Once transaction is started, data source can not be changed. 

Let us see the example of data source definition in Context for dynamically switching between OLTP and Reporting Database: 

<bean id="dataSourceOltp" name="oltpDataSource" class="..PooledDataSource">
<property name="targetDataSource">
<jee:jndi-lookup jndi-name="jdbc/DB" cache="true" />
</property>
</bean>


<bean id="dataSourceReportDb" name="dataSourceReportDb" class="..PooledDataSource">
<property name="targetDataSource">
<jee:jndi-lookup jndi-name="jdbc/ReportDB" cache="true" />
</property>
</bean>

<bean id="customDataSource" class="com.a.b.common.db.DBCustomRoutingDataSource ">
<property name="targetDataSources">
<map key-type="com.a.b.util.DataSourceConstants">
<entry key="OLTP_DB" value-ref="dataSourceOltp"/>
<entry key="REPORT_DB" value-ref="dataSourceReportDb"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceOltp"/>
</bean>

<bean id="txAwareCustomDS" name="txAwareCustomDS" class="org.springframework.jdbc.datasource.Transac tionAwareDataSourceProxy">
<property name="targetDataSource" ref="customDataSource">
</property>
</bean>

<bean id="CustomTxManager" class="org.springframework.jdbc.datasource.DataSou rceTransactionManager">
<property name="dataSource" ref="txAwareCustomDS" />
</bean>


In above context definition, we may define data sources for multiple tenants in place of OLTP or Reporting Database. To extend the design further for multiple tenants, definition can be made dynamic.

Important Note:

If you are using TransactionAwareDataSourceProxy with DataSourceTransactionManager, it should always be the outer most wrapper in the hierarchy. Keep data sources hierarchy as following:

TransactionAwareDataSourceProxy > Routing Data Source > Lazy Data Source > Pooled Data Source

Reason is, DataSourceTransactionManager will never work with TransactionAwareDataSourceProxy, rather it picks the wrapped data source to work upon. DataSourceTransactionManager has special handling for TransactionAwareDataSourceProxy to work with actual DataSource wrapped in it. So it is important to keep the TransactionAwareDataSourceProxy as outer most layer. Or otherwise, DataSourceTransactionManager will not be able to handle the transactions properly. Read more at following links:

Java Technology Enthusiasts - How to set Transaction Manager Programatically
Spring Forum - Problem in Managing Managing Transaction with AbstractRoutingDataSource

------------------------------------------------------------------------------------------------------------
Hope it will help. Please share comments for addition. You may contribute by:
  • Posting your comments which will add value to the article contents
  • Posting the article link on Social Media using 'Social Media Bookmark' bar
  • Consider joining us at 'Java Technology Enthusiasts' linkedin group to participate in discussions
  • Connecting with 'VedantaTree' on Facebook

Spring RoutingDataSource to Work with Multiple DataSources

Finally back to blogging. It was a long journey to get ready, pick the pen (i.e. computer) and start writing again. Writing is a matter of habit.

Today we are going to discuss about using multiple data sources with Spring Transaction Management. Scenario is,

  • Application is having lot of legacy code
  • Application needs to work with more than one databases
  • There are some legacy methods in application which are supposed to work with any one of the database depending upon use case. Same method could be invoked with different data source context for other transaction.
  • Application is using Spring Transaction Management
  • Requirement of Spring Transaction Management is to declare data sources and associated transaction manager with application context (1 to 1 relation)

What would be the initial design considerations. 
  • Define all required data sources in application context
  • Define corresponding transaction managers too
  • Use any of the Persistent Template to implement the DAOs.
  • Define desired transaction behavior on service methods

We are done with basic infrastructure code. In above steps, missing part is how to tell application code about which data source to be used from multiple data sources defined in context. It can be done by specifying the specific transaction manager (related to desired data source) with Service transactional attributes. Transaction manager can be defined either at class level or at method level. Or a good approach could be to use Transactional advice and define the transaction manager in context configuration with a pattern to identify the methods. 

A general workflow would be; whenever any service method is called using Spring Framework, Spring will see if there is any transaction proxy available for that method. If yes, transaction proxy will get invoked. It will work with defined transaction manager and will start a new or use existing transaction (based on transaction attributes). It will also try to attach the connection with the current transaction (thread local based implementation). Connection will be retrieved from the data source which is associated with the transaction manager (defined in context). This connection will be linked with current transaction as synchronized resource. Please note, that connection may be attached lazily in case of 'LazyConnectionDataSourceProxy'. In this way, Spring enables the scenario to use multiple data sources in application based on specified transaction manager.  All the methods invoked during the service call, or from nested methods will go to the database which is associated with current transaction manager (and the data source).

What is SwingWorker

Swing is not thread safe as discussed with previous article. That means that any task which can take long time in execution should not be performed in Event Dispatcher Thread (EDT). Otherwise the EDT will be blocked and so the whole UI. So the solution, to perform the time intensive operations, is:

  • Start a new thread from EDT
  • Perform the heavy, time consuming task in this new thread
  • When task is done, update the Swing UI state or call any operation in EDT
  • EDT will invoke the operation

To perform above steps, we need to create a thread for time consuming task and also need to devise a mechanism to invoke the Swing Operation in EDT once the task is done (inter-thread communication). This involves some of the multi-threading code and may need to repeat it again and again with every such requirement. To abstract this code, and simplify this task; Java provides a SwingWorker class to hide all the complexities and hence the repeated work to perform these operations. It is an abstract class, which should be extended and some of its methods should be overridden to get the work done.

SwingWorker class has following important methods.

execute()
This method is the main method which should be called to start the work of SwingWorker class. As soon as you call this method, SwingWorker will give call to do the time consuming task in a new thread (described below).

doInBackground()
This method should be overridden by developer to do the time consuming task. This method will be called in a new thread, other than EDT, by SwingWorker. So any task performed on this thread won't affect the Swing UI operations. Once this method is done, result will be retained by SwingWorker which can be asked by using get() method. publish() method can also be called from this method to make the intermediate results available for GUI operations.

process()
It should be overridden if we want to process any data in EDT, as and when this data becomes available during doInBackground() operation. Suppose, one program is to load the heavy file from network which is being done in doInBackground method. Depending upon the data downloaded, you want to show the progress bar or some %age downloaded in a label on UI. This can be done by putting the work to update the label or progress bar in 'process' method. From 'doInBackground' method, we need to call the 'publish' method with the values which we want to publish; like %age data downloaded in this case. SwingWorker will call process method with this data in EDT. process method then can update the UI label. One more important point, SwingWorker may coalesced the multiple calls of publish in one call to process method, if previous calls were not executed till now. So if we are calling publish with suppose '%10', '%30', and then with '%50'; it might be possible that process method is called first with '10%' and then with '30%, 50%'. Process method should handle this case.

done()
This method is called by SwingWorker when task defined in 'doInBackground' method is finished. This is a place where final Swing UI updates should be done based on outcome from 'doInBackground' method. This method is called in EDT.

Object get()
This method is used to retrieve the result of task performed by 'doInBackground' method. Point to consider, that this method is a blocking method. So calling thread will be blocked till result is not available. So it must be used carefully, as if it is called from EDT, it will block the UI operations. One of the approach to use it could be to show model dialog box till result is received.

This way, SwingWorker class save us from defining the thread safe, and multi-threaded code again and again and work as a great utility class.

Why Swing is not Thread Safe

Big questions for Swing Developers - Why Swing is not Thread Safe? What makes Sun to design the Swing in a way that it can not handle its operation in multi-threaded environment? What if they made some extra efforts to make it thread safe, many developers would be relaxing now with comparatively simpler code? And so on..

So here is the answer. Swing is not made thread safe intentionally. It was a design decision by Swing team. Why? Because thread safety always comes at a cost. And access of Swing components in multiple threads may not be required that much.

What is thread safety and Why is that costly - Thread safety means that every part of the program should be safe to access from more than one thread concurrently. Program should be able to handle the concurrent access, either by serializing the access or ensuring that it is not disrupting the shared states or operations. Serializing the access means that access should be synchronized for access by thread, which will ensure that only one thread access the code block at a time after taking the necessary lock and hence guarantee the safe access to shared states. Or design has to be done in a way that program block does not affect any shared state or won't disrupt any operations due to concurrent access to states. Both of these changes are costly in term of performance or/and application design/development.

Why Multiple Thread Access may not be required - Because most of the UI operations are done in event fired by UI itself which are sequential in nature. There are few cases when we want to touch UI functions or states in parallel threads, like if we want to perform some time intensive operation to load the data and want to keep the UI active. But these cases are limited.

So if requirement to work in multi-threaded environment is very limited, and cost to make the code ready for multi-threaded environment is high; rationale is not to implement it. However, there should be provision using which developers can manage the UI operations in multiple threads environment also as mentioned above in case of loading heavy data in parallel.

This is what Swing Team analyzed and decided. Result is a high performing GUI development library for most of the scenarios with a capability to work with multiple threads also if required.

AWT vs Swing vs SWT

AWT, Swing and SWT are three main User Interface development technologies in Java. All three can be used to develop the desktop applications. Now the question is, which one to use and when? Each of these has its own pros and cons. In this article, we shall try to understand the pros and cons of each of these.

Let us start with AWT being the first Java GUI toolkit. It comes with standard Java packaging and hence no specific installations are required. This is the simplest form of GUI toolkit, where Java provide basic set of components, layout managers, events etc to design the desktop application.

AWT is dependent on host GUI controls (native peers). For every component in AWT, one equivalent host GUI control is built. This means, AWT directly utilizes the GUI control features set provided by host and is entirely dependent on this for available features. That is why it is called Heavyweight components library. As all the host does not support all the UI control, Sun decided to provide the least common denominator from all the UI controls available on different hosts. This means that AWT is having very limited set of controls and even lacks the generally required components nowadays like Tree, Table etc. If any application needs any of these components, it needs to be develop from scratch. That is a big task to develop the components which are quite commonly required in all kind of applications.

Various positive points of AWT are:
  • It is very stable toolkit
  • It is thread safe, which means it can work well in multi-threaded environment also. 
  • It disposes the controls automatically, so application need not to worry about it.
  • UI in AWT can be created in any sequence using bottom up or top down i..e we can start from parent to children or from children to parent; in any order actually. 

Solution for 'NullPointerException' on Eclipse Startup

We faced a scenario where we abruptly had to kill the java while eclipse was running on system. However, when we tried to run the Eclipse again, it just get hanged and console/logs exposed us following error:

[weblogic@localhost oepe-indigo-12.1.1.0.1]$ /home/weblogic/Programs/Oracle/oepe-indigo-12.1.1.0.1/eclipse -vm /usr/java/jdk1.6.0_33/bin
LogFilter.isLoggable threw a non-fatal unchecked exception as follows:
java.lang.NullPointerException
at org.eclipse.core.internal.runtime.Log.isLoggable(Log.java:101)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.safeIsLoggable(ExtendedLogReaderServiceFactory.java:59)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.logPrivileged(ExtendedLogReaderServiceFactory.java:164)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.log(ExtendedLogReaderServiceFactory.java:150)
org.eclipse.equinox.log.internal.ExtendedLogServiceFactory.log(ExtendedLogServiceFactory.java:65)
org.eclipse.equinox.log.internal.ExtendedLogServiceImpl.log(ExtendedLogServiceImpl.java:87)
org.eclipse.equinox.log.internal.LoggerImpl.log(LoggerImpl.java:54)
org.eclipse.core.internal.runtime.Log.log(Log.java:60)
org.tigris.subversion.clientadapter.javahl.Activator.isAvailable(Activator.java:92)
org.tigris.subversion.clientadapter.Activator.getClientAdapter(Activator.java:67)
org.tigris.subversion.subclipse.core.SVNClientManager.getAdapter(SVNClientManager.java:127)
org.tigris.subversion.subclipse.core.SVNClientManager.getSVNClient(SVNClientManager.java:94)
org.tigris.subversion.subclipse.core.SVNProviderPlugin.getSVNClient(SVNProviderPlugin.java:462)
org.tigris.subversion.subclipse.core.status.RecursiveStatusUpdateStrategy.statusesToUpdate(RecursiveStatusUpdateStrategy.java:62)
org.tigris.subversion.subclipse.core.status.StatusCacheManager.refreshStatus(StatusCacheManager.java:270)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.refreshStatus(FileModificationManager.java:220)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.resourceChanged(FileModificationManager.java:161)
org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:291)
org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:285)
org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:149)
org.eclipse.core.internal.resources.Workspace.broadcastPostChange(Workspace.java:395)
org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:1530)
org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:45)
org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

And the solution we found was, it happens because some of the metadata file got corrupted during abrupt exit. So we follows the steps mentioned below to get eclipse started again:
  1. cd .metadata/.plugins
  2. mv org.eclipse.core.resources org.eclipse.core.resources.bak
  3. Start eclipse
  4. It will start but will show errors with opened tabs. This is because we have changed the resources folder, which eclipse use for managing the resources
  5. Close all opened tabs
  6. Exit from Eclipse
  7. Delete any newly create org.eclipse.core.resources folder
  8. Rename back the 'org.eclipse.core.resources.bak' to 'org.eclipse.core.resources'
  9. Start Eclipse
  10. It should start fine with all projects
 Hopefully you won't face any problem further, but will depend on scenario. Please share your experience if that was different.

Which is the Best Free Load Testing Tool?

We have been assigned the work to find the best Load Testing tool from Free Tools domain. We also need to evaluate it against some best paid tools. Requirements were:
  • Tool should be free and preferably open source
  • It should be very stable and mature
  • It should be able to generate any amount of load without any software limit. Hardware can be increased as per requirements. 
  • It should be able to generate the concurrent load in concurrent running threads
  • It should support running JUnit test cases out of the box
  • It should support recording of Test Cases for UI, which can be played back later with load
  • Generated reports should be extensive in information and preferably in format also
  • Tool should be in active development
  • Out of the box support for various other interfaces will be a plus
With explorations, we found following tools famous and highly recommended in their categories:
  • Apache JMeter - Free and Open Source
  • Grinder - Free and Open Source
  • HP Load Runner - Paid, just to have a good comparison
Our exploration for above three tools is:

Basics of Java Message Service - II

In previous Article, we have read about basics of JMS with some simple programs. Here we shall continue with the introduction of basic programming elements, and objects of JMS Design. These basic objects are required for every JMS program. So it is important to understand these from conceptual and working aspect.

These JMS objects are called Administered JMS objects. JMS API has come in existence to provide a standard for messaging service and to standardize the interfaces and working of various messaging service providers. But, as many of the service providers were already in market, so it was not possible to define a strict protocol. Hence, JMS defines a compratively flexible protocol which take care of client protability by providing the standard interface, however, at the same time given ample flexbility to service providers to continue with their existence implementation by just changing the interfaces. JMS Administered objects are the standard objects specified by JMS API which every service provider should implement. These are important to ensure client portability. Beyond these administered objects, service providers are free to provide their custom implementation.

Following is the list of important Administered Objects:

Object Type - Implementing Objects
-----------------------------------------------
  1. ConnectionFactory - TopicFactory, QueueFactory
  2. Connection - TopicConnection, QueueConnection
  3. Session - TopicSession, QueueSession
  4. MessageProducer - TopicProducer, QueueProducer
  5. MessageConsumer - TopicSubscriber, QueueConsumer
In brief, every JMS user needs to create a connection factory first. Connection Factory can be specific to Topic or Queue messaging module depending upon requirements. JMS API defines a separate concrete object for Topic/Queue messaging model correspodning to each interface. So once we have connection factor, it can be used to ask Connection. Connection is like a factory for session objects. Session is a kind of separate working area for each client of JMS. One connection may provide multiple sessions, and each session will have its separate working space. After getting session, next step will be to create message producer and message consumer. Session acts as factory for message producers and consumers, so it is used to create message producers and consumers. Once message producer and consumers are created, now, these can be used to produce and consume the messages. Certainly, if you want to use Topic Publish/Subscribe model, you need to use Topic type of objects or otherwise you will use Queue type of objects.

Basics of Java Message Service - I


In perivous article, we have read about basics of messaging system and come to know that how messaging can help in quite flexible and abstract integration of various software applications. Now let us move further towards basics of Java Message Service (JMS), which can help us to implement the messaging concepts read till now.

JMS is a Messaging Oriented Middleware. Middleware is the software used to connect more than one software applications (distributed also) in quite flexible manner. Middleware can be of two typs, RPC based and messaging based. RPC based Middleware is one which provided synchronous integration between two software applications. Whereas, Messaging based Middleware (MOM) is one which inetgrate two software applications asynchronously using messaging concept. Certainly nowadays, MOM are quite popular where client can not wait for response from service and hence want a asynchronous request processing. JMS comes in this category. JMS can also be used for synchronous communication with some efforts, however, that is not something for which JMS comes in existence. It is devised specially to strengthen and standardize the messaging oriented middleware software.

Before JMS, there were many messaging solutions in market from various Industry players, like from IBM, Progress Software and Fiorano etc. Problem was, these products were not following any standard specification. So suppose, today you find that Software A is meeting your requirement and use it for implementation. After one year, you met with some new requirements, and then found that A can not meet these requirements but B has these new features. But, now it was not easy to replace the messaging software due to lack of any standard API implementation. JMS has solved this problem by defining a standard to implement the messaging systems with an abstract API. Now, clients can easily switch from one to other vendor anytime as per requirement without disturbing the implementation of application.

Hence JMS is a specification which defines an API allowing java based applications to utilize the features of any JMS compliant MOM software, without sticking to any one implementation. It provides a right level of abstraction from proprietary implementation of MOM systems. JMS is not an actual product. Actual products are still coming from indepdent software product companies like IBM, Progress Software etc. However, now, these products are adhering to the protocol defined by JMS specification, and hence following a standard approach with many of their specific advance features like load balancing, persistence, fault tolerance and administration etc. JMS is also implemented in J2EE in form of Message Driven Beans. Hence it becomes a intrinsic part of J2EE specification now.

Basic Concepts of Messaging System

JMS (Java Messaging System) was developed to cater the need of flexible integration design among various application or within application components.

In simple Java application, if we need to integrate one component/application with other, we have to have the reference of target with source. It means that one object must be aware about other object. It results into a tight coupling. It can be made flexible further by using different patterns like Factory, Service Locators and Directories but still objects used to be aware about each other type with a defined integration protocol like method signature. Now when architects want more flexibility, where one object is completely unaware about existence of other object and can simply say that I need this type of message. This is an ultimate flexibility in integration.

This type of flexible integration can be achieved using a messaging based simple design in java.  If we want to achieve this in Simple Java implementation, we can make a Message broker kind of component. This component can provide following facilities: 
  1. Any object can register with it as message producer by specifying a specific type of message, which can be a plain string. Message broker will maintain an internal data structure to keep track of such message producers corresponding to their message types.  
  2. Any object can register with message broker as message consumer. It will also specify a type of message for which it is interested to consume the message. Message broker will maintain an internal data structure to keep track of all message consumers corresponding to message types for which these wants the messages. 
  3. Now whenever any message producer produce a message, it calls message broker API and hand over the new message to it. Message broker knows the type of message, so it searches all the message consumers registered for this message type, iterate over this list and hand over the message to each consumer. 

Basics of Java Class Loader


Java class loader is an interesting concept of Java Runtime. We know that in Java,  every executable code is stored  in .java files which are compiled to .class files. These class files are stored in file system  in plain directory structure or in jar files or probably using some other medium. When any java program runs, it needs the definition of referred class files to execute this code at runtime. Here comes the role of Java Class Loader. Whenever Java runtime needs any class file, it calls a component of Java runtime called class loader to load the desired class. Default class loaders of Java i.e. Bootstrap and System Class Loader has the logic to search for the class file in JVM and in  directories and jars included in classpath respectively. It assumes that if Java program is referring to java.lang.Object, then the definition of this class must  be somewhere on  classpath in  java/lang/Object.class hierarchy. So by default, it has the logic to search in directories and jars. Once it finds the class file, it loads it in memory, store it with in memory cache for future reference and return to the runtime. So class loader search for the class files only once, and stores it in memory data structure to be utilized on future calls. Java classes loaded from default class loader are considered as trusted classes and hence these have the access to all core classes of java library itself.

Now Java provide enough flexibility to users applications to define their own custom class loaders, which can extend the default class loaders, and can add custom logic; like to load the classes from a  network location or from database and so on. Working of class loaders generally used to be like; a custom class loader first ask the parent default class loader of Java runtime to load the requested class. If default class loader is unable to find the class, then extended class loader proceed to load that class using its specific loading algorithm.

Dependency Injection and Aspect Oriented Programming

Inversion of Control (IOC), Dependency Injection (DI) and Aspect Oriented Programming are three popular keywords in Software Designing and Programming. But these terms are quite confusing to others and to each others some time. Let us try to understand what are these terms and how these are used.

If we think about Inversion of Control, it seems like we are changing the flow of control from, and a new King is coming in picture who will control all the flow now onward. Actually it is right. Earlier when we have started with Procedural programming, we tend to have control at single point. Later when we shift to OOP, we did better by decentralizing the logic and hence the control also to respective object. However, as we move on, we still find something missing which was hard coding of object dependencies on each other. If anytime, we need to change the implementation of a specific object, it means that we need to change the code and it may probably have some impact on implementation style. Then we strive hard to find the solution for providing such flexibility in the application and devised various design patterns like Service Locator, and Factory Pattern etc.This gave us good solutions by keeping knowledge of actual object implementation away from user object and hence gives the flexibility to change the implementation at any point of time. Things moves well, and applications used to be more and more flexible in design with increased use of such design patterns. However, one end of control was still in the hand of user object. It was still aware and the one who will initiate the factory or service locator to further get the right implementation of service. But desirable stage was, when user object is just aware about type of service it wants, not the source and actual instance of this service.....

Exception Handling in Web Applications

Error Handling is an important part of any implementation. An application without Error Handling is like a patient with all door closed for diagnosis. It is a perfect time killer for developers to debug the application issues without proper error handling. Hence it is an important topic to discuss. However here we are concentrating more on error handling in web applications (using JSP, Servlets).

Motive of error handling is to capture any error generated in the application, log it to any logging system and propagate it to right point so that it can be directed to the user with all useful information. So the basic flow of error handling should be
  • Apply try-catch block with right exception type in catch around the code which may generate the error
  • Log the error using any logging mechanism. One of the popular logging system is log4j using commons logging. Ensure to use right logging level i.e. debug, info, warn, error etc
  • Apply business logic whatever is required to handle the erroneous case as per application requirement
  • If error is not manageable and condition should be propagated to user, throw the appropriate error further after wrapping the original error. Make sure that new exception should carry all user centric details which can help them to understand the cause of error, and developer centric information which can help them to debug the issue. 
  • As a general mechanism, error codes can be set to exception which can describes the reason of problem at Application and UI level. These error codes can also be used to show the localized messages on UI
  • Application Framework should provide the facility to handle any exception originated from the application and redirect it to a designated UI which can show the error details to user with all the details
  • The UI can also have the mechanism which can facilitate the user to log the issue directly in Issue Tracking system or to send email to the support staff with all the details

Implementation of Login and Logout in Web Applications

Login/Logout seems like a simple operation in web application. However small information left behind can give a chance of security breach to hackers. Here is a simple and minimal workflow which we should ensure while implementing login/logout functionality in web applications.

  • Have a Security Manager on the Gateway which can authenticate and possibly authorize every new request to server. For example, it could be a ServletFilter. 
    • It should authenticate every new request to check whether user is logged in or not. 
    • If yes, does current request URL exists?
    • If yes, does user have rights on current requested URL?
  • If request is passed through Security Manager, the login  manager should do following: 
    • Clean the existing session for all application specific information.
    • Invalidate the session using session.invalidate.
    • If request is for login
      • Check if user exist for given user name and password. 
      • If not, return to right page with message
      • If yes, go ahead
      • Create a new session, for example, request.getSession (true)
      • Fill the session with all application specific information for current user like all UI structure for which current user is authorized.
      • Forward the request to home page of request application or module
    • If request is for logout
      • Forward the request to logout message page  
This is the minimal workflow to ensure the basic principles, however a lot can be added to implement the application specific security checks and to support the application structure. Like as an extension, the Security Filter which is sitting at gateway can interact with a security service to validate the current request for authentication and authorization. Similarly Login/Logout implementation can interact with Security Service to authenticate the login information and later to retrieve the user specific application settings, for example, the menu structure and UI look etc. 

This brief information may help in concept building and in basic architecture design.

How to use XDoclet and Ant to Generate Hibernate Mapping and Configuration

XDoclet is a wonderful tool to generate various kind of configuration files in declarative way, and the declaration can be done with java code. It allows Java Developers to work in Java Code files only even for all the configuration which otherwise need to be defined in XML or property files. It is very convenient way for Developers who like to have everything in Code files, and facilitate to do all configuration from same place. It makes the applications easy to maintain, and debug. XDoclet supports tags for various tools like Hibernate, EJB, JMX, JSF, and Spring etc. However here we are explaining how to use it with Hibernate. XDoclet can be used for various purposes with Hibernate, like, to generate Hibernate Mapping Files, to generate Hibernate Configuration File, and to Generate/Update the schema.

Before going into details, you should be aware that there are two active versions of XDoclet, version 1 and version 2. Difficulty is that these two versions do not seem to be in Sync. Like version 2 has many changes which are not compatible with version 1 and also has a lot of changes in API. Another problem is that it is not easy to find a good documentation for XDoclet 2, and details like the difference between version 1 and 2. We were unable to find any single document which can provide all of these information nicely, and the path to update from version 1 to 2 with all side effects and changes required. There are many changes in XDoclet tags for Hibernate in version 1 and 2. Many of old tags are not supported now. Same difference is there in ANT tasks also, which can be used to integrate the XDoclet features with ANT. Here we are taking a real life scenario for using XDoclet task in ANT for Hibernate.

Suppose, there are multiple projects dependent on one or other project for Data Objects. One project has all Global Data objects like Address, City, Country etc. Other project has some business function specific data like Employee, Supplier etc. Now Employee has a field of Address type also, which will of course be coming from Global Data Project.

What is Strong, Soft, Weak and Phantom Memory References in Java

Understanding various available reference objects in Java is quite important to develop memory sensitive applications, and for memory optimization. Java has four type of memory references which are
  • Strong References,
  • Soft References,
  • Weak References and 
  • Phantom References
However to understand the use of these reference objects, we need to understand in brief that how Java manage the memory, and how it manage the garbage. Please refer to other post at 'How does Java Manage the Memory' to understand that. Now if you are clear with the Java Memory Management Concept, understanding various kind of memory references in Java would be easy for you. The description below is given considering that the readers have read the other post as given above (How does Java Manage the Memory).

Strong Reference: The objects in memory which are referenced from memory stack (without a reference through any other kind of reference) are called strongly referenced. These objects are strongly held by program i.e. in use and hence can not be claimed by GC (Garbage Collector) for memory requirement.

How does Java Manage the Memory

Understanding the Java memory management system is quite important to develop the memory sensitive applications. It also helps us to optimize the usage of memory in our programs. Java maintains a stack to store all object references whichever are being in use by program. Objects actually stores in memory heap and their references are maintained on memory stack.  

Let us try to understand it with some example description. This is not what exactly JVM does, but an example only to simplify the definitions. 

As soon as we create an object in program, its information is being saved to memory with some fixed byte pattern. Now we can use the start of memory location as reference id for this object. In program, there are various kind of scopes defined by Java. These are like code block scope, method level scope, class level scope, package scope and whole program level scope etc.  These scopes generally has parent <> child <> sibling relations with each other. Now as soon as the program scope initialize, a corresponding scope data storage structure (data structure to save the scope variable and other data which will have the memory references of the actual objects in memory) can be made and pushed to memory stack. Similarly other scope structures can be made as soon as they come in existence and can be stored with their parent scope. These scope data structures remain on stack till the corresponding scope is active in program. As soon as, it gets deactivated; the corresponding data structure will be removed from stack. Take it like as program thread enters into a method, we create a scope data structure for method scope and push it to stack with its parent scope which should be class scope. Now as program thread leaves the method, we remove the corresponding scope data from the stack. Scope can interact with each other as per the language protocol because they have parent <> child relationship. This is a simplified version of memory stack with JVM. Now you can visualize scope data structures used to be created or destroyed with the activation or deactivation of corresponding program scope. 

Simplifying the Locking Mechanism in Threads

synchronized(lockObject)
{
    // do the job
}

This is one of the ways to acquire a lock on an object and then do the work in a code block with exclusive rights. Synchronization is already explained with another blog 'Mystery of Synchronized Keyword'. 

Here the question is that why we take the lock on an Object, not on current thread. Answer is fairly simple. Whenever you want to secure the admission to any premises, you never apply a lock on yourselves but you will put a lock on some other object, like on door. So the thread is the 'actor' (you) who want to perform some work in a code block (premises). Here the thread want a exclusive access on a code block where it want to work. Now procedure to have exclusive access is to have a lock for code block, so that only the current thread can have access rights to it. Here thread needs any object (door), like lockObject in above example, to have lock on the code block. 

Further we need to understand that how thread get lock using an object. To understand the story under the hood, consider that every Object is having a state within it which shows that whether any thread has lock on this object or not. Whenever any thread request the lock on any object, object checks whether its lock property is already set or not. If not, it set its property for current thread otherwise it refuse to give the lock, ask the current thread to wait till previous thread release the lock and put the thread in queue. Once the previous thread release the lock, and hence unset the property, Object picks the next thread from queue and set the lock property for it. As soon as thread get the object property set for it, it get the rights to enter in code block and to execute it.

Another example is like more than one painters are painting an house. Now painting of one room needs that only one painter works in it at a time for good output. Like first one painter should apply the putty on the wall, then the next one should apply the primer and paint and so on. To ensure that everyone follow this, painter decide to lock the door of the room whenever anyone enter inside for the work. So as soon as putty man enters the room, he locks the door from inside. When other come for the work, they find the door locked and hence wait for their turn. As soon as, first man finishes his work, he opens the door and the next painter waiting in the queue gets the access to room. 

Runtime environment of Java ensure all of this processing i.e. it puts the current thread to wait state till it gets access on current object lock property and put it back to execution after getting the property set for it. 


Mystery of Synchronized Keyword

'Synchronized' keyword is used to ensure that only one thread access a code block or a method at a time. It is very important keyword in multi-threaded programming. In multi-threaded programming, multiple threads work on the same code blocks simultaneously. But there can be some code blocks which manipulate shared data. So if multiple threads executes the same code and try to manipulate the same data, it can results in inconsistent result. For example:

public class TestSynchronized {

private int i;

// suppose param value is 5
public void testMethod( int param)
{
    // thread update i to 5
    // simultaneously other thread enters the block and update i to 10 before first thread would be able to            
    // execute next statement
    i = i + param;

    // result is expected to be 25
    // but result comes to 50, as second thread updates i to 10 before first thread executes the multiple
    //statement

    int result = i*5;

    System.println.out("thread[" + Thread.currentThread + "] result[" + result  + "]");
    i = 0;
}

}