Tuesday, March 31, 2009

Using Spring Container to instantiate Struts Action Classes

In Spring ApplicationContext.xml add this

<bean id="personAction" scope="prototype" class="quickstart.action.PersonAction">
<constructor-arg ref="personService">

This is the instance of the action class which needs to be created .

In Struts struts.xml add this

<constant name="struts.objectFactory" value="spring">

This ensures the struts spring integration

Add this also

<action name="xxx" method="yyy" class="personAction">
<result name="input">pages/list.jsp</result>

In the above configuration, in the class field the name of the spring bean is
directly mentioned.

By doing so the spring container creates the action class instance for struts which is a prototype.

An other alternative to do the same is using Aspect J Weaving.

Monday, March 23, 2009

LightStreamer - Server Push Technology

Lightstreamer is a scalable and reliable Server for pushing live data to Rich Internet Applications

Based on the AJAX-Comet paradigm, it streams real-time data to any Web browser, without installing anything on the client. Both HTML and Flex applications can receive live data from Lightstreamer, as well as traditional thick clients.

Lightstreamer is a “Push Engine”, i.e. a server software that is able to push (or stream) any textual data in real-time to any types of clients across the Internet. Lightstreamer hides all the complexity of pushing data in a scalable, efficient, reliable and portable way.

Lightstreamer is useful for any application that requires the efficient delivery of real-time data through the Internet. Examples of possible applications include: financial market data distribution (stock quotes, news); online betting and gaming; live bids for e-auctions; Web-based monitoring consoles; online communities with live user interaction (messaging, chat, presence).

LightStreamer runs as a separate process which stays connected with the client to push data.The technology behind this is once the client page completes its refresh a final request is sent from the client to the lightstreamer server which is held without sending a response.The response is sent only when the item which is displayed on the client has been updated on the server.

Sample HelloWorld Program :


Saturday, March 21, 2009

Protobuf - Data Interchange Format

It is a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage etc

Protocol Buffers are a way of encoding structured data in an efficient yet extensible format.Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats.

You define how you want your data to be structured once, then you can use special generated
source code to easily write and read your structured data to and from a variety of data streams
and using a variety of languages

You specify how you want the information you're serializing to be structured by defining protocol
buffer message types in .proto files. Each protocol buffer message is a small logical record of
information, containing a series of name-value pairs.Once you've defined your messages, you run
the protocol buffer compiler for your application's language on your .proto file to generate data
access classes.

These data access classes can be in any of the languages such as C , Java ,Python etc.These provide simple accessors for each field as well as methods to serialize/parse the whole
structure to/from raw bytes. These generted classes can be shipped along with any client where
serialisation or deserialsation is required.

You can even update your data structure without breaking deployed programs that are compiled
against the "old" format.

Protocol buffers have many advantages over XML for serializing structured data.

Protocol buffers:
* are simpler
* are 3 to 10 times smaller
* are 20 to 100 times faster
* are less ambiguous
* generate data access classes that are easier to use programmatically

Ref : http://code.google.com/p/protobuf/

Java DataBases - Derby(Java DB) & HSQLDB

These are those two 100% Java databases, Derby and HSQLDB.

Apache Derby is developed as an open source project under the Apache 2.0 licence.
Derby was previously distributed as IBM Cloudscape.It is currently distributed as
Sun Java DB and comes packaged along with Java.

HSQLDB (Hyperthreaded Structured Query Language Database) is a relational database
management system written in Java.

Derby aims to be a fully functional relational database, and as such could be considered
as an alternative to "grown up" databases like Oracle and MySQL in some cases.

HSQL is more like a "toy database", providing a subset of the features of a fully
functional databases. But that subset of functionality may be all you need.

Benefits of HSQL over Derby.
- light weight (smaller libraries, less complex)
- supports in memory databases
- Simple to use

Benefits of Derby over HSQL
- much larger development community
- secured future (is part of JDK, is sponsored by IBM and Sun)
- More complete feature set (e.g. proper handling of transactions, encryption...)
- Scalability
- Performance with large Data Set

Memory Use

Derby is setup like a traditional database system where data is stored
on disk and a subset of that data is cached in a buffer cache or pool.

HSQL by default uses MEMORY tables (for standard CREATE TABLE
statements), this always stores the entire data in memory. Thus this is
fast, but obviously consumes memory. It is useful to look a process
sizes as well as absolute times when running benchmarks.



SQLite - LightWeight DB

SQLite is a software library that implements a self-contained, serverless,zero-configuration, transactional SQL database engine.It is opensource.

It is used by Firefox,Adobe,google,Microsoft etc

SQLite is different from most other SQL database engines in that its primary design goal is to be simple:

* Simple to administer
* Simple to operate
* Simple to embed in a larger program
* Simple to maintain and customize

It has Zero-Configuration, is Server Less ,Single Database File ,Stable Cross-Platform Database
File and gives easy user friendly APIs to write into and access from the database.

Situations Where SQLite Works Well

Embedded devices and applications
Replacement for ad hoc disk files
Low Concurrency

SQLite home page http://www.sqlite.org

Sunday, March 15, 2009

Struts - Accessing Value Stack in interceptors

Values which are set in action classes can be accessed and modified in interceptors
using the struts value stack object

Code in interceptor

ValueStack valueStack = actionInvocation.getStack();

Object object = valueStack.findValue(objectName);

if (object instanceof List) {

can access here directly and modify it which will be reflected in the viewing JSP


This method of accessing of modifying the Struts value stack will have wide applications.

Tomcat Connectors

Typically Communication protocol between apache and tomcat is AJP

Apache used mod_jk to speak AJP(Apache Jserv Protocol) to tomcat .

AJP is a binary packet based protocol - hence difficult to debug and limitation on packet size

  • AJP on tomcat side

Java Connector(BIO) - Blocking IO , one thread per connection

APR Connector - Allows more connections , allows polling

Java NIO Connector

  • Tomcats Http Connectors - can replace AJP specific features ,more options , more control ,Finely tuned,easy to debug since its text based

Nio , APR Connectors, BIO - fastest when not using persistent connections

  • mod_proxy_http - for HTTP - native protocol level support for authentication and SSL

  • HTTP Connector -

o.a.coyote.http11.Http11Protocol (BIO)

o.a.coyote.http11.Http11AprProtocol (APR)

o.a.coyote.http11.Http11NioProtocol (NIO)

HTTP/1.1 aliased to Http11 and Http11Apr depending on PATH or LD_LIBRARY_PATH settings

  • AJP Connector -



AJP/1.3 aliased to the two above
Depending on PATH or LD_LIBRARY_PATH settings

  • Use BIO if

Stability is the highest priority APR and NIO are more recent
Most content is dynamic
Keep alive is not a determining factor


  • Use APR if

SSL is terminated at Tomcat
Platforms are Linux or Windows
Keep alive is important
Lots of static content
Using Comet feature


  • Use NIO if

Compiling APR is not an option
SSL is terminated at Tomcat
Keep alive is important
Lots of static content
Using Comet features


  • requirement connectors in preference order

Stability --> Bio, APR/NIO


Low Concurrency --> BIO,APR,NIO

High Concurreny with keepAlive --> BIO,APR,NIO

Hig Concurrency with no keep alive -->APR,NIO,BIO

  • The native APR connector is unstable on Solaris

Performance Optimization for Tomcat

1. Clear the webapp directory in tomcat ( unnecessary loading of example and non essential applications)

2. Remove Duplicate Logging in Tomcat which comes by default
.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler can be removed as logging is a costly operation

3. Using Asynchronous logging .
Tomcat by default using synchronous logging ,we can use log4j to change the default behavior

Synchronous logging (logging.properties) Can become a bottleneck
We don’t want disk IO to become the limiting factor

4. The following should be considered for choosing the connectors

BIO stablity, static content offloaded into other server only dynamic content is present , keep alive non essential

APR ssl terminating at tomcat (because of openssl library it uses ),keep alive imp , also servers static content

NIO ssl terminating at tomcat, keepalive imp, static content
(keep alive becomes because SSL connection is costly )

check out separate blog on Tomcat Connectors ...

5. Best practice

Maintain a separate setenv.bat file which will be automatically called by tomcat 6 , which has custom settings(also Vm params).
This helps in easy migration

Use catalina.properties for server.xml substitution variables

6. Avoid using the log() methods in the Servlet API

7. Apache log4j

– log4j.properties in /WEB-INF/classes
– log4j-x.y.z.jar in /WEB-INF/lib

no seperate initializations required

8 . Have overflow protection for logs using cronolog

Overflow protection (logging.properties) Size based rotation using JVM logger


9. In highly concurrent environments turn off KeepAlive

If its on , the socket stays connected and waits for the given time interval

10. Tuning Parameters

Maximum nr of concurrentrequests
For BIO, max nr of open/active connections

Typical values 1, 100-200
Represents the number of requests Tomcat will handle on a TCP connection
Set to 1 disables keep alive
connectionTimeout/keepAliveTimeout controls the timeout in between requests

Set to 1 if Very high concurrency


Represents nr of additional connections the OS should accept on your behalf
Useful when Tomcat can’t accept connections fast enough


Represents the SO_TIMEOUT value
Essentially, max time between TCP packets during a blocking read or write
Critical to a stable system
Also used for keep alive timeout

11. Enable caching for Static conetnt , will help in faster access from disk

Configured in element
•40MB cache (default 10MB)
•cache revalidation every 60 seconds (default 5 seconds)
•caching enabled (default true)

12. GC Settings –JDK 1.5 and 1.6


stops unauthorized shutdown of servers

Performance Optimization in Apache

1. Useful modules which could be used

mod_dbd -> Connection Pooling for other modules

mod_filter -> Dynamic chaing of filters, filters inserted based on request headers and response

mod_dumpio --> Dumps all IO to error log - in case of SSL dumping is done right before encryption and after decryption

mod_log_forensic --> helps in tracking request response , resulting in 2 lines of log for each request

mod_info - helps in giving info about all modules installed


Enabling can improve the performance by reducing IO calls for fetching the content (since all static content are served from apache)

mod_cache --> mod_disk_cache /mod_mem_cache - determines cache implementataion

3. Rewrite rules

a. Since Rewrite rules and regular expression matching are expensive can be replaced with Proxy pass where ever possible

RewriteRule ^/ws/(.*) http://localhost:8080/ws/$1 [P,L] with
ProxyPass ^/ws/ http://localhost:8080/ws/$1 [P,L]

b.Smart order of rewrite rules

The order of rewrite rules needs to be arranged in such a way that the maximum occurring instances should be available at the top , since the entire list is scanned trough for every request


RewriteRule ^/(.*\.jsp) http://localhost:8080/$1 [P]
RewriteRule ^/(.*\.do) http://localhost:8080/$1 [P]

Could be replaced with

RewriteRule ^/(.*\.do) http://localhost:8080/$1 [P]
RewriteRule ^/(.*\.jsp) http://localhost:8080/$1 [P]

Since the maximum number of requests we expect will be .do requests. This will improve performance because there will be only few jsp requests and most of the times execution can stop in the above line.

4. Also other parameters for Operating systems and GC tuning will enhance the performance

5. Graceful shutdown - handle existing request , time limit can be specified in case of long time
consuming request with property GracefulShutdownTime

6. Prefork MPM- Stable but not scalable - one process per request

Worker MPM(Preferred) - more scalable , thread safeness of libs critical - one thread per request

7. Useful Parametres

Controling Idle pool - MinspareServers /MaxspareServers




8. KeepAlives - prevents connections (socket open close for each request)

9.Avoid DNS Lookups

10. On the Fly Compression - deflate - bandwidth reduction and faster response times

Friday, March 13, 2009

Converting Jar into Exe

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications.


Filter and Ranking attributes in OSGi

In a dynamic system we can have multiple services of same bean type. In that case a consumer of a service can specify a filter to qualify the required bean as follows:

In one bundle publish the service as:

<bean id="helloService" class="com.ivy.example.service.factory.HelloServiceFactory" factory-method="getHelloService" />

<osgi:service ref="helloService" interface="com.ivy.example.service.HelloService">
<entry key="product" value="account" />

To consume the service in another bundle:

<osgi:reference id="helloService" filter="(product=account)" interface="com.ivy.example.service.HelloService" />

<bean id="testData" class="com.ivy.data.TestData" init-method="start" destroy-method="stop">
<property name="helloService" ref="helloService" /> <- dependency injection of the referenced bean

Ranking attribute can be specified while advertising a bean:

the one with the higest rank if obtained i case of two similar services

<osgi:service ref="helloService" interface="com.ivy.example.service.HelloService" ranking=”1” >

The ranking attribute is useful for determining the 'best matching' OSGi service in case multiple candidates are available.
If one needs to pin point a service then a filter should be used.

Spring in a Nutshell


The Inversion of Control (IoC) container - For Dependency Injection

Xml Configuration,Java Configeration and Property File Based Configeration

Instantiation using a static factory method,Instance factory method

Injecting dependencies - Constructor Injection,Setter Injection

Dependencies and configuration -Inner beans,Collections (list, set, map, and props elements allow properties)

Other features- depends-on,Lazy-init,Autowiring

Method Injection- for Injecting prototypes into singletons objects

Bean scopes- singleton,prototype,global,session,request,Custom scopes

Lifecycle callbacks- init,destroy

Shutting down the Spring IoC container gracefully in non-web applications

Bean definition inheritance

Container extension points- BeanPostProcessors,PropertyPlaceholderConfigurer etc

Annotation-based configuration- @Required, @Autowired, @Qualifier, @Component, @Service, @Repository

Using filters to customize scanning

Registering a LoadTimeWeaver

Aspect Oriented Programming with Spring

AOP- Aspect,Joint Point,Advice,PointCut,target,Weaving,AOP Proxy

Choosing which AOP declaration style - Spring AOP or full AspectJ

Spring AOP -- @AspectJ or XML for Spring AOP

Spring AOP APIs

Support for AspectJ load-time weaving

Transaction Managemnt

ORM Data Access - Hibernate,JDO,Oracle TopLink,IBatis,JPA etc

Spring MVC

View Technology - JSp & JSTL , Tile,Velocity,FreeMarker,XSTl , Jasper Reports

Spring Remoting

Intergration with Quartz for Scheduling

MethodInvokingFactoryBean - > to call methods of instantiated beans .


<bean id="RequestObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

<property name="targetObject" ref="createdBean"/>
<property name="targetMethod" value="methodToBecalled"/>
<property name="arguments">
<entry key="xxxxxx" value-ref="yyyyyyyy" />

Thursday, March 5, 2009

Log4j Slf4j issues in Spring Dm

If you try to use log4j in any application under Spring DM we may get some ClassNotFound exceptions . The issue could be the following

com.springsource.slf4j.org.apache.log4j-1.5.6.jar - is present in

springsource-dm-server-ee-1.0.2.RELEASE\repository\bundles\ext directory and it shares a package org.apache.log4j

Now when you put your log4j jar into repository\bundles\usr - it also shares the same package
org.apache.log4j .

Hence one in the repository is resolved first . So all requests to classes in the log4j jar within package org/apache/log4j will give ClassNotFound Exceptions as it looks for these classes in slf4j jar .

The easiest way i resolved this was by deleting com.springsource.slf4j.org.apache.log4j-1.5.6.ja from the repository . This change did not affect any logging of the spring Dm server.

Another way to solve this is

Import-Package: org.apache.log4j;bundle-symbolic-name="com.springsource.org.apache.log4j"


Updating bundle inside a PAR

Currently it is possible to update a bundle within a PAR only through spring tool suite.
This is done through the Deployer MBean - JMX.

This flexibility is not available running a standalone spring Dm server.

May be the future versions of the Spring DM server will support this.


Tomcat Version In Spring Dm OSGi

Spring DM Server comes with Tomcat 6.0.18, which I believe is the latest one.

You can see the latest version by looking at

DM_SERVER_HOME/repository/bundles/ext/ and

look at Catalina bundles (i.e., com.springsource.org.apache.catalina-6.0.18.jar)

Log4j/Struts Behaviour in OSGi

Log4j/Struts behaves weird if the these jar are put under repository, because this single static instance inside these jars are shared by all other bundles.

Example: Struts(struts properties),log4j(log4/properties)

All the properties are written into static members.Since the single instance is shared by both the bundles applications, the value of static references will be overridden and both the application will use the same settings.

This case is not specific to spring Dm , it will also occur when common configuration object
is put under common lib in tomcat.

Example: log4j/struts jar in tomcat common lib

Struts interceptor code for execution before and after action or result

The code to be executed before and after action class execution needs to be written in the intercept
method of the interceptor.

<code before action invocation>

String result= ActionInvocation(object).invoke();
(By this time the display page is already constructed in memory)

<code after action invocation>

return result

In the above case though the <code after action invocation> will execute it will not be able to modify
the values in the resulting page.

This is beacause the flow is as follows

<Interceptor b4 action> --> Action --> Result Formed(In memory) --> <Interceptor after action>

So the modifications made after the interceptor will only be seen in the next to next pages;

If the interceptor needs to modify the values which is need in the immediate next page
then we need to use


this will ensure that the post processing is done before the result object is constructed.Hence ensuring that the
change in the post processing of the interceptor is visible in the next pages

Wednesday, March 4, 2009

Error when converting struts jar into bundle with Bnd

I did face errors when converting struts jar into bundles using bnd tool.

The problem was the name of the package:


The package pt-br contains a - sign. According to the Java spec, this is not a package name. The OSGi specification does therefore not allow you to export a package that includes a - sign.

Once i removed these packages from the manifest file , it worked fine .

Bnd tool for converting jars into bundles OSGi

This provides a easy way of converting jars into bundles.This does a brute force check and writes every package present in the jar as export and all imports in the java files inot manifest imports.

The command to convert jar into bundle is

java -jar bnd.jar wrap xxx.jar

Its better to check in the Spring Repository for the available bundle before converting it from a a jar to bundle.


Ref :



Improving Eclipse performance

Try the below configuration on experimental basis to improve this performance

In the eclipse installation directory parallel to eclipse.exe you will find a file called eclipse.ini

modify it to have the following changes

Change the XXMaxPermSize to 256M
Change the min and max heap size to be 512
Restart eclipse.


Tiimout params for spring remoting

All properties can be set for spring remoting including connection timeout.

The HttpInvokerProxyFactoryBean takes in httpInvokerRequestExecutor as a parameter which in turn takes in httpClient(org.apache.commons.httpclient.HttpClient).

Hence all properties for HttpClient as timeout , connectiontime etc can be set.

Code snippet for injecting httpclient into the connection object(with timeout for 5 seconds)

<bean id="httpParamObject"
<property name="httpClient">
<bean class="org.apache.commons.httpclient.HttpClient">
<property name="timeout" value="5000" />

<bean id="testServer"
<property name="serviceUrl"
value="" />
<property name="serviceInterface"
value="com.pg.server.IServerImpl" />
<property name="httpInvokerRequestExecutor" ref=" httpParamObject" />


Jnotify - monitor file system Events

JNotify is a java library that allow java application to listen to file system events, such as:

* file created.
* file modified.
* file renamed.
* file deleted

JNotify works on both Windows (Windows 2000, XP, Vista) and Linux with INotify support (Kernel 2.6.14 and above).


Strut 2 performance Tips

Set devmode false

Set template caching true

Define custom interceptor stack. Remove interceptors that are not required.

In classes we can create a templates folder and customize the way js files and templates are loaded.

Ref: http://struts.apache.org/

Removing tomcat from Spring Dm to reduce memory

By commenting out the servlet subsystem, there should be no Tomcat running in dm Server ß

In profile.config comment as indicated below to disable the tomcat instance.

/* * SpringSource dm Server profile manager default configuration file. */
"profile": { "version" : 1.0, "name" : "web", "subsystems" : [/* "com.springsource.server.servlet", "com.springsource.server.web" */], "optionalSubsystems" : [/* "com.springsource.server.management" */] }}

Mem usage


WITHOUT TOMCAT - 51 MB ( so 17 MB less)

Ref :http://forum.springframework.org/showthread.php?p=216805

Aspect J load Time Weaving

I am able to inject spring container managed beans into Struts action classes using aspect-j load time weaving (without using struts2-springplugin jar ).

Add the following lines into the spring xml

<context:spring-configured />

<context:annotation-config />

This is for the identification of the annotations inside classes

<context:load-time-weaver aspectj-weaving="on"/>

This is to enable the weaving
2.include @Configurable annotation above the class name

3.Autowire any spring component bean using autowired annotation @Autowired

4.The following jars need be included (both are bundles with spring Dm server)

com.springsource.org.aspectj.weaver &
For this to work the container should be having a class loader which is capable of weaving and Spring DM server is capable of it

By adding the above @Configurable tag any class instantiated (either by reflection or by non spring container) can be associated with the beans created by spring container .The byte code injecting into the class happensthrough aspectj load time weaving.

But I am not sure how costly is this process.

Buddy Classloading Equinox Osgi

Buddy class loading offers an integration strategy that does not require modifying the Java code of existing libraries(like hibernate) , thatuse the Class.forName(String) approach to dynamically discover and load classes.The mechanism works as follows:

A Bundle declares that it needs the help of other bundles to load classes The Bundle identifies the kind of help they need by specifying a buddy policy. The policy defines what kind of bundles will be considered to be buddies. When a bundle class loader fails to find a desired class through the normal OSGi delegation model (i.e. Import-Package, Require-Bundle, and local classpath), its buddy policy is invoked The invoked buddy policy discovers a set of buddies and consults each one in turn until either the class is found or the list is exhausted.

There are different buddy policies like registerd,global etc which can be mentioned in the manifest headers.

This buddy policy is spcific to equinox implementaion and may not be found in all Osgi implementataion.

The use cas eof this is each bundle need not mention an import and still can use the class of the bundle. Its use case is in packages like hibernate which do a class.forname on custom code .


Fragment bundles in OSGi

Fragments are bundles that are attached to a host bundle by the Framework.Attaching is done as part of resolving: the Framework appends the relevantdefinitions of the fragment bundles to the host’s definitions before the hostis resolved. Fragments are therefore treated as part of the host, including any permitted headers.

These fragemnt bundles will not have a seperate class loader. these will belaoded by the same bundle class loader.For a bundle to be a fragment it has to mention fragment host in its manifest file.

This property of fragments can just be used for a logical seperation of classes , examples could be resource bundles which can be packed in to a seperate bundle.

Since these fragment bundles use the same class loader as the host bundlle there is no provision of seperately refreshing the fragment bundle

Ref : http://osgi.mjahn.net/2008/03/13/half-bundle-half-jar-%E2%80%93-the-nature-of-fragment-a-blessing-or-a-curse/

Bundles having same package structure for export :Require bundle Split packages

I was stuck in cases where i had two bundle having the same package structure and they wanted to share these classes.
Osgi just looks into only one of this package and then for any further requests it will look into this folder, if not found gives a class not found exception even though its present in the other bundle.
This case can be solved by using the concept of split packages.
The bundle which needs classes from multiple bundles having the same package structure should define those two bundles as Require-Bundle in its manifest headers in the order in which it should look for.
By doing so the environment ensures that both the bundles will be scanned one after the other to look for the requested classes.
Still i would prefer to refactor the jars than use this feature of require bundle.

Bundle Class Path - best way to start Osgi-Bundle Class PathIntra

bundle class path dependencies are declared in the Bundle-Classpathmanifest header. This declaration allows a bundle to declare its embedded class path using one or more JAR files or directories that are contained in the bundle’s JAR file.
This was the idle use case for me , where i converted only one jar into a bundle and gave all other jars in its bundle classpath.This gave me a flexibility where i needed to merge all the jars into one.
This will help as a starting point. All the class under the bundle classpath will be laoded by the single bundle classlaoder.
I tried the same with fragment bundles but with no luck , as it threw class not found exceptions in the cases which included RMi connections.

Order of search for a class in Osgi -> Resolving Process

1 If the class or resource is in a java.* package, the request is delegated tothe parent class loader; otherwise, the search continues with the nextstep. If the request is delegated to the parent class loader and the class orresource is not found, then the search terminates and the request fails.

2 If the class or resource is from a package included in the boot delegationlist (org.osgi.framework.bootdelegation), then the request is delegatedto the parent class loader. If the class or resource is found there, thesearch ends.

3 If the class or resource is in a package that is imported using Import-Package or was imported dynamically in a previous load, then therequest is delegated to the exporting bundle’s class loader; otherwise thesearch continues with the next step. If the request is delegated to anexporting class loader and the class or resource is not found, then thesearch terminates and the request fails.

4 If the class or resource is in a package that is imported from one or moreother bundles using Require-Bundle, the request is delegated to the classloaders of the other bundles, in the order in which they are specified inthis bundle’s manifest. This entails a depth-first strategy; all requiredbundles are searched before the bundle classpath is used. If the class orresource is not found, then the search continues with the next step.

5 The bundle’s own internal bundle class path is searched. If the class orresource is not found, then the search continues with the next step.

6 Each attached fragment’s internal bundle class path is searched. The fragmentsare searched in ascending bundle ID order. If the class or resourceis not found, then the search continues with the next step.

7 If the class or resource is in a package that is exported by the bundle orthe package is imported by the bundle (using Import-Package or Require-Bundle), then the search ends and the class or resource is not found.

8 Otherwise, if the class or resource is in a package that is imported usingDynamicImport-Package, then a dynamic import of the package is nowattempted. An exporter must conform to any implied package constraints.If an appropriate exporter is found, a wire is established so thatfuture loads of the package are handled in Step 3. If a dynamic wire is notestablished, then the request fails.

9 If the dynamic import of the package is established, the request is delegatedto the exporting bundle’s class loader. If the request is delegated toan exporting class loader and the class or resource is not found, then thesearch terminates and the request fails.

System packages and Extender packages in OSGi

The OSGi spec allows the Framework (through its system bundle) to export the relevant packages from its parent classloader as system packages using the org.osgi.framework.system.packages property.As repacking the hosting JDK as a bundle isn't a viable option, one can use this setting to have the system bundle (or the bundle with id 0) export these packages itself.

Extension Bundles :Another possible option is to enhance the system bundle through extension bundles. These act as fragments;they are not bundles of their own but rather are attached to a host. Once attached, the fragment content (including any permitted headers) is treated as part of the host. Extension bundles are a special kind of fragments that get attached only to the Systembundle in order to deliver optional parts of the Framework (such as the Start Level service).

The System package entry is added using org.osgi.framework.system.packages = \ i
n java6-server.profile in the lib directory of the dm server

In both the above cases the classes are loaded by the bootclassloader and not a seperate bundle classloader.Hence these are candidates when we are considering putting classes at the boot class path.


Class.forname and classloader.loadclass - whats bettr in OSGi

ClassLoader.loadClass or Class.forName seem to be synonyms for the same basic operation:
but class.forname does additional constraint checks which can cause some problems in the context of OSGi.So it does seem reasonable to have Class.forName behavior altered to avoid loader constraint checks.
However, if Class.forName is used to call the initiating class loader, the behavior with respect to cachinga nd the returned class is quite different. In this case, when the class is first defined, it is cached by the defining class loader as expected. But it is also cached by the initiating class loader which is not expected.
As a result, all calls to Class.forName to a initiating class loader always return the same class object (thefirst one loaded), even if the implementation of the initiating class loader does not define classes or directlyconsult its own cache.
My case where class.forname didnt wrk and classloader.loadclass worked
Bundle A->class AA, extends Server,calls init

class ToBeLoaded ,exports ToBeLoaded
Bundle B->class Server, method init()->tries to load class ToBeLoaded

Ref : http://blog.bjhargrave.com/2007/07/why-do-classforname-and.html


Using Custom Class Loaders In Spring Dm -OSGi

One has to be careful while using custom class loaders in any of the bundles.This is beacuse in the context of osgi each bundle will have a classloader whose parent will be the bootclassloader.
And the hierarchy of the classes searched will be delegated from child to the parent classloader. Hence when a class is not found in a bundle, the responsibility will be delegated to the parent classloader.
When we define a custom classloader as follows
CustomClassLoader = new CustomClassaloader() - > its parent is set to the boot classloader. Hence though its inside the bundle it canot see any classes inside the bundle .
The easy way to get away from this is to set the custom class laoders parent as the bundle classloader.Now any request to the classes in the custom class loader will be delegated to its parent that is the bundle classloader and the clases will be found.

Classloader hierachy in Spring Dm - OSGi

When a bundle is deployed into the spring dm the follwing will be the classloader structure
In the case of bundle

Current classlaoder ->LoaderServerBundleClassLoader: (Bundle calssloader)

Parent1 ->sun.misc.Launcher$AppClassLoader@1754ad2

Parent2 ->sun.misc.Launcher$ExtClassLoader@1833955
In the case os a class put in the boot delegation path

Current Class Loader->sun.misc.Launcher$AppClassLoader@1754ad2

Parent1 ->sun.misc.Launcher$ExtClassLoader@1833955

Parent2 ->null

Ref :http://blog.bjhargrave.com/2007/07/why-do-classforname-and.html

OSGi - Putting classes into Boot delegation path

To put any classes into the the boot delegation path in Osgi the follwoing needs to be done
add the entry into org.osgi.framework.bootdelegation
in the follwing file --> springsource-dm-server-ee-1.0.1.RELEASE\lib\java6-server.profile
Once classes are added into the this boot path there is no need to import this in any of the bundle manifests.
But the disadvantage here is that these classe are loaded by the Boot Class loader , and hence we loose the independent runtime deployments of these classes.
But this trick can be used while integrating with teraacotta or other cases , where we can give away independent deploymenta dvantage , but get flexibilty of loading these classes using boot class laoder and also have these classes directly without any imports.

The other way of getting classes under boot class path is to make it system package or extender bundle of a system package.

Osgi - Package Imports to Shared Services Benefits

Whenever a bundle gets updated in a OSgi environments the direct affect is that all bundles which have any import will also get bounced . This information is not displayed in the dm server console.
I have observed this change only by putting sysouts in the bundle activator. I feel this should not be hidden in the console.
This will also happen in the service model if the interfaces are bundled along with the implementation.
Bundle a -> Implementation & interface and provides Osgi service
Bundle c -> osgi service importer,has import for intercface packages from a
Now if we bounce the bundle a to change the implementaion bundle c also gets refreshed though we dont change the interface.
The only way to avoid this is to have a seperate bundle b with interface
Bundle b - > has interface
and now bundle c imports from bundle b , also bundle a imports from bundle b . Thus any changes in bundle a, thats the implementaion will not have any refresh of other bundles.

Modifying the web pages inside OSGi web bundle

The imapct of packaging into a web module in OSgi was that we lost the ability to modify JSp pages on the fly. This was a drawback since our teams used to modify the JSps in production environment very often.
Spring Dm has promised to avoid this change by providing a flexibilty to allow breaking of web bundles into multiple parts and allow for thier independent deployments in the future releases.
Untill then the hack could be to commit the jsp pages into the work directory and it gets reflected.
Location for change

Spring Dm(OSGi) integration with terracota

I have tried integrating terracotta with spring DM and it works fine. My use case included a instance a stand alone java,jetty web server,apache tomcat and Spring Dm connected to the same instance of terracotta sharing a custom class as the root.
The changes i had to make were
Added the Terracotta lib and shared classes under boot delegation path of Spring DM –
1. In springsource-dm-server-ee-1.0.1.RELEASE\lib\java6-server.profile org.osgi.framework.bootdelegation = \ com.tc.*,\--> àddedd this is to avoid errors from Spring DM which tries to load these classes from Bundle class loader share.* --> Classes which are shared
2 .Copied shared jar under springsource-dm-server-ee-1.0.1.RELEASE\lib\
The above changes are doen to ensure that teh shared classes are loaded by the boot classloader which will enable terracotta toidentify this class and share with other processes()stadalobe,jetty.tomcat).In teh above case since the shared jar is added intothe bootdelegation , any chage in the teracotta shared classes will need restart of the spring dm server.

The other staratergy to achive the same is by changing the classloader names in all the other processes which are connected to terracotta, but i found this more complicated and cumbersome.

Free Domain Names @ .co.nr!