Saturday, November 21, 2009

AOP - AspectJ,Spring - Compile Time ,Load Time ,Run Time(Proxy)

Spring AOP - Runtime - Using Proxy

Steps

1.Spring Application Context - Bean Declarations

For enabling this proxy approach add
<aop:aspectj-autoproxy />

Note :

Do not be misled by the name of the element: using it will result in the creation of Spring AOP proxies. The @AspectJ style of aspect declaration is just being used here, but the AspectJ runtime is not involved



Aspect Declaration
<bean id="myAspect" class="com.test.aop.MyAspect"></bean>

Method where aspect will be applied
<bean id="test" class="com.test.aop.Test" init-method="init" />

Wrapper calling test
<bean id="testB" class="com.test.aop.Wrapper" init-method="init">
<property name="test" ref="test"></property>
</bean>


2. Classes

  • Aspect Class

@Aspect
public class MyAspect {

@Before("execution(* com.test.aop.Test.*())")
public void myMethod()
{
System.out.println("calling my before aspect");
}

}

  • public class Test {

public void init()
{
System.out.println("init in test method");
}

}


  • public class Wrapper {

private Test test;

public void setTest(Test test) {
this.test = test;
}

public void init() {
test.init();
}

}

3. OutPut(In Spring DM)

System.out I init in test method
System.out I calling my before aspect
System.out I init in test method

Only when the init method is called through testB bean ,the aspect is bound.

Now when init method of test bean is called , the aspect is still not bound.(init methods cannot be proxied).

This is because the way spring life cycle works :

Spring life cycle

Phase 1 - Validate bean definitions
Phase 2 - Bean definition post processor(replacing property values)
Phase 3 - Bean Instantiation
Phase 4 - Bean post initialization(setters and init methods -in order) & Proxy creation

In the above example bean 'test' first cycles through phase 1,2,3 and 4. Hence after the init method is called, the proxy is created.But when testB is created in its init(phase) call to bean test will call teh aspect (as bean test lifecycle is complete)

One more important thing to note is that Cg lib will be used to create proxy here as teh class doesnt implement any interface.(Else jdk dyanmic proxies would have been used)

Aspect-J Load Time Weaving
(This may have issues with Spring DM
http://forum.springsource.org/showthread.php?t=80504
)

Same code as above except some change in the configurations.

1. Replace <aop:aspectj-autoproxy /> with <context:load-time-weaver/>.

2. Add aop.xml in META-INF directory

<!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>

<!--works without this -->
<weaver>
<include within="com.test.aop.*" />
</weaver>

<aspects>
<!-- weave in just this aspect -->
<aspect name="com.test.aop.MyAspect" />
</aspects>

</aspectj>


3. Class to test the application in standlone mode

public class StandAloneLoadTimeWeaving {

public static void main(String args[])
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml",StandAloneLoadTimeWeaving.class);
Test t =(Test)ctx.getBean("test");
t.init();
}

}

Ref: http://www.springbyexample.org/examples/aspectj-ltw.html
http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-aj-ltw


4. Add the following parameter when running

-javaagent:spring-agent.jar


Aspect J Compile Time Weaving(Build Time)

Same as Loadtime weaving needs aop.xml (but no need to add spring agent while running)

Command to compile the code

java org.aspectj.tools.ajc.Main –inpath <src_code_directory> -outjar <output_jarname.jar>

Ex:java -cp aspectjtools.jar;aspectjrt.jar org.aspectj.tools.ajc.Main -inpath . -outjar test.jar

The output jar will have code which is instrumented by the aspect.

You can download aspectj from this site

http://www.eclipse.org/aspectj/downloads.php

Wednesday, November 18, 2009

Writing Custom Namespaces in Spring

1. Application context xmls looks as below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:test="http://www.test.xyz/schema"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.test.xyz/schema http://www.test.xyz/schema-1.0.xsd">

<test:person name="suji"/>
</beans>

Now the xsd mentioned in the schema location should map to something.

2. You shoudl have a spring.schemas file in the META-INF directory

http\://www.test.xyz/schema-1.0.xsd=com/test/test-1.0.xsd

This maps the schema to teh lcoation of teh xsd

3. Xsd looks like

<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.test.xyz/schema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">

<xsd:element name="person">
<xsd:complexType>
<xsd:annotation>
<xsd:documentation>
Configures all required interactions with the named Control Bus configuration
</xsd:documentation>
</xsd:annotation>
<xsd:attribute name="name" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Identifies group-name of a Control Bus this configuration defines
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:element>

</xsd:schema>

We have a single element person with attribute as name which is a string.

4. Now each element in the xsd should map to a resolver.

This can be mentioned in spring.handlers file which is also in the META-INF directory

http\://www.test.xyz/schema=com.test.PersonNamespaceHandler


5. Implementaion of PersonNamespaceHandler

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class PersonNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("person", new PersonParser());
}

}


6. Parser implementation

public class PersonParser extends AbstractBeanDefinitionParser {
private String beanName;

/* This method gets the parameters mentioned in the custom namespace and helps building
custom logic based on it */


@Override
protected AbstractBeanDefinition parseInternal(Element element,
ParserContext parserContext) {
BeanDefinitionBuilder rootBuilder = BeanDefinitionBuilder
.rootBeanDefinition(Person.class.getName());
beanName = element.getAttribute("name");

//Ensuring name is a compulsary attribute

Assert.hasText(beanName, "'name' must be provided");
rootBuilder.addPropertyValue("name", beanName);
return rootBuilder.getBeanDefinition();
}

protected String resolveId(Element element,
AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
return beanName;
}

}


7. Custom classes for Person

public class Person {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


Test case for trying out this

public class PersonParserTest {

public static void main(String[] arg){
ApplicationContext ac = new ClassPathXmlApplicationContext("config.xml", PersonParserTest.class);
Person person = (Person) ac.getBean("suji");
System.out.println("Person: " + person.getName());
}
}

Tuesday, November 17, 2009

TCCL in OSGi(Spring DM)

In order to better understand how TCCL works in OSGi i have done a sample POC.

I created 3 bundles.

Bundle A - calls Bundle B (imports Bundle B)

Bundle B -calls Bundle C (imports Bundle A)

Bundle C - instantiates class in Bundle A (No imports)

In normal cases Bundle C will fail to instantiate class in Bundle A, but this can be achieved using TCCL as follows.

ITest test=(ITest)Thread.currentThread().getContextClassLoader().loadClass("com.bundleA.external.ActionClass").newInstance();

Conclusion: Spring Dm sets TCCL to the bundle classloader where the thread initiated.

Now what if we want to instantiate class of bundle B in Bundle C , but the thread flow doesnt change. ?

This can be easily done by resetting the TCCL in bundle B's method as follows

Thread.currentThread().setContextClassLoader(Bundle2.class.getClassLoader());

BootClassPath and Sytem ClassPath in OSGI(Spring DM)

System Package

java.* can be directly used without any imports. This is neither part of boot delegation nor system packages as they are part of jdk itself.For loading these fundamental types, the OSGi platform uses parent delegation instead of the networking model; that is, it uses the class loader that started the OSGi framework to load classes instead of an OSGi class space.

None of the other public packages available in the JDK such as the javax.net or javax.xml are parent delegated which means they have to be resolved within the class space that is, bundles need to import the packages (which means there needs to be a provider) since they are not implied. The OSGi spec allows the Framework (through its system bundle) to export
any relevant packages from its parent class loader 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.
Extension bundles are a special kind of fragments that get attached only to the System bundle in order to deliver optional parts of the Framework

Boot Delegation

This allows the user to create 'implied' packages that will always be loaded by the framework parent class loader, even if the bundles do not provide the proper imports:

This option is mainly created to accommodate various corner cases especially in the JDK classes that expect parent class loading delegation to always occur or that assume that every class loader on the system has full access to the entire boot path.There are cases where boot delegation is quite handy; a good candidate being instrumentation, such as profiling or code coverage.

Ref:http://blog.springsource.com/2009/01/19/exposing-the-boot-classpath-in-osgi/

I have done samples to better understand how classloader comes into picture for loading classes at different levels by printing parent classloaders upto 4 levels.

Class loader for one of the classes of bundle in pick up.

bundle classloader ServerBundleClassLoader: [bundle=ClassPathTest_1.0.0]
bundles parent java.net.URLClassLoader@126e85f
bundles parent sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7


Class loader hierarchy for org.osgi.framework.BundleActivator

**************System bundle 0*******************
bundle classloader java.net.URLClassLoader@126e85f
bundles parent sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
I bundles parent null


Created a dummy class and added this in the classpath of dm server startup.bin.Also modified to include this java6-server.profile as org.osgi.framework.system.packages = \
(I did import this package in my test bundle)

*************SYSTEM PATH**************
bundle classloader sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
bundles parent null
I parent null


Created a dummy class and added this in the classpath of dm server startup.bin.Also modified to include this java6-server.profile as org.osgi.framework.bootdelegation = \
(Did not import this package in my test bundle)


*************BOOT PATH**************

bundle classloader sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
I bundles parent null
I parent null

Sunday, November 15, 2009

Configuring Component based logging in OSGi using Log4j

Initialize reading of the log4j xml in any of the core bundles. Ensure that this bundle doesnt get bounced often.Configure the values to include log4j xml and reload delay.The init method can look something similar to the one below.

public void initialize() {
try {
try {
String logConfig = "D://temp//poc_log_config.xml";
long configReloadDelay = (long) (1 * 30 * 1000);
if (logConfig != null && (new java.io.File(logConfig).exists())) {
if (logConfig.endsWith("xml")) {
org.apache.log4j.xml.DOMConfigurator.configureAndWatch(
logConfig, configReloadDelay);
} else {
org.apache.log4j.PropertyConfigurator
.configureAndWatch(logConfig, configReloadDelay);
}
} else {
org.apache.log4j.BasicConfigurator.configure();
}
} catch (Exception initErr) {
initErr.printStackTrace();
}
} catch (Exception err) {
}

}


The log4j xml will look as follows

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="PRODUCT1" class="com.test.anyappender">
<param name="File" value="D:\\temp\\product1\\product1log.log"/>
<param name="MaxFileSize" value="100000000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} - %m%n"/>
</layout>
<param name="Threshold" value="DEBUG"/>
</appender>

<appender name="PRODUCT2" class="com.test.anyAppender">
<param name="File" value="D:\\temp\\product2\\product2.log"/>
<param name="MaxFileSize" value="100000000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} - %m%n"/>
</layout>
<param name="Threshold" value="DEBUG"/>
</appender>

<root>
<level value="OFF" />
</root>

<logger name="test1">
<appender-ref ref="PRODUCT1"/>
<level value="INFO" />
</logger>

<logger name="test2">
<appender-ref ref="PRODUCT2"/>
<level value="DEBUG" />
</logger>

</log4j:configuration>


Now in any bundle code you can access any component logger as follows

static final Logger TEST_LOGGER = Logger.getLogger("test1");

use TEST_LOGGER.debug("any debug message");

By the above approach we can just have a single log4j bundle in the repository and not only avoid issues occuring from static variables but also can take full benefit of log4j API's.

Extending OSGi telnet for custom commands

OSGi telnet command provided by equinox can be easily extended to implement custom commands.

First we need to write a class with which implements the custom commands.the methods should start with _ to be identified as osgi telnet commands.The getHelp command needs to be overwritten ,which will display the command when help is hit on the telnet console.

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;

public class CustomCommands implements CommandProvider {
@Override
public String getHelp() {
return "***********CUSTOM COMMANDS*******************\n";
}

public void _testcommand(CommandInterpreter ci) {
ci.println("arg 1" + ci.nextArgument());
ci.println("arg 2" + ci.nextArgument());
}
}


Next step is to write a BundleActivator and register the command Provider service.

@Override
public void start(BundleContext ctx) throws Exception {
customCmd = new CustomCommands();
//created a instance of the implementation of our custom commands
ctx.registerService(CommandProvider.class.getName(),customCmd, null);

}

Dont forget to add the bundle activator class to the manifest. Manifest should include the following.

Import-Package: org.eclipse.osgi.framework.console;version="[1.0.0,1.0.0]",
org.osgi.framework;version="[1.4.0,1.4.0]"
Bundle-Activator: com.command.extender.CommandBundleActivator

JMX using Spring

JMX aims to create standard API's for managing and monitoring java applications.

Managing - changing values at runtime.

Monitoring - Reporting certain conditions.

Mbean -is a java bean with a management interface.

Mbean can expose attributes(through getters and setters) or any opertaions.Management interface can be defined statically or at runtime through interfaces.MBean Server acts as a broker between interacting beans or beans and remote clients.

Mbean server maintains a key to all registered means which is called as object name.The default protocol used is RMI , but can be changed to SOAP or Hessian.

Using raw JMX APi's is difficult , spring simplifies this.

Use the following configuration to create a MBeanServer. This will be required normally only if we are running standalone code.Else most of the containers like tomcat or spring dm provide the default MBeanServer which can be used to register the Mbeans.

<bean id="MBeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean">
<property name="locateExistingServerIfPosssible" value="true">
</bean>

Configuration to register a bean as MBean to MBeanServer.

<bean id="jmsSample" class="com.pg.MonitorService"></bean>

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<util:map>
<entry key="service:name=jmsSample" value-ref="jmsSample" />
</util:map>
</property>

By this all methods and attributes of this can be accesed using jconsole. Sometimes this may not be what we want .we would want to control the set of operations which are visible through JMX.

The Spring MbeanExporter allows the following stratergies

1. ObjectnamingStratergy - this will help in identifying the mbean in the jconsole.

  • a. KeyNamingStratergy(Default) - key passed will become the name
  • b. IdentityNamingStratergy -generates a object name dynamically
  • c. MetaDataNamingStratergy - reads object name from source level meta-data (annotations)

2. MBeanInfoAssembler

When we want to control what we are exposing through JMX this is the better approach

  • SimpleReflectiveMbeanInfoAssembler -Default -Exposes all public methods and properties
  • MethodNameBasedMbeanInfoAssembler Methods can be configured through spring xmls which will be exposed through JMX.
  • MetadataMBeanInfoAssembler what needs to be exposed is controlled using source level annotations.
  • InterfaceBasedMBeanInfoAssembler
a. Using managed Interfaces property

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<util:map>
<entry key="service:name=jmsSample" value-ref="jmsSample" />
</util:map>
</property>
<property name="assembler">
<bean
class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="managedInterfaces">
<value>com.pg.IService</value>
</property>
</bean>
</property>

</bean>

Here the jmsSample bean need not implement teh managedInterface.

b Using interfaceMapping property

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<util:map>
<entry key="service:name=jmsSample" value-ref="jmsSample" />
</util:map>
</property>
<property name="assembler">
<bean
class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="interfaceMappings">
<util:map>
<entry key="service:name=jmsSampleService" value="com.pg.IService"></entry>
</util:map>
</property>

</property>

</bean>

Thea bean jmsSample must implement the interface mentioned in interfaceMapping property

This API helps in monitoring application using JMX.

http://jamonapi.sourceforge.net/

 
Free Domain Names @ .co.nr!