Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

2008/09/03

Simple tip: Inject the nested class in Spring context

It's a simple tip and is not mentioned in Spring reference docs:

When you want create a bean in Spring which is a nested class of some owner class, use the "$" to separate the owner class name and the nested class name like following example:

<bean class="org.balah.OwnerClass$NestedClass"
.....

Don't use the convention like "org.balah.OwnerClass.NestedClass" that is used in the source code usually. Because the Spring will use Class.forName() similar mechanism to find the class specified in the bean definition. As you use the Class.forName() to load a nested class, always use "$" to let the classloader locate the exact class file from your classpathes. The "." sperated convention just confused the class resolver anf finally throw a ClassNotFoundException.

2008/04/20

Watch out for Lazy Initialization when you schedule a job

http://www.jroller.com/habuma/entry/a_funny_thing_happened_while


Spring should probably initialize those Job Scheduler more actively. Lazily initialize things like that sounds not a good idea.

Spring Security by Craig Walls

Craig Walls presented the Spring Security Session at the latest NFJS Java Conference in Seattle.

What ACEGI Offers?

- Declarative Security, keeps security details out of your code
- Authentication and Authorization, against virtually any user store
- Support for anonymous sessions, concurrent sessions, remember-me, channel enforcement, and much more
- Spring-based, but can be used for non-Spring web framework

ACEGI's moving parts:

- Security Interceptors, aspects for methods, filters for servlets
- Managers, Authentication, Access Decision, Run-As, After-Invocation
- Authentication Providers
- Access Voters

Security Intercepter - First line of defense
Authentication Manager - Verifies user identity 
Access Decision Manager - Determines if the authenticated user has authority to access the secured resource, by aggregating the result from the Voters
Run-As Manager - Temporarily replaces user's Authentication object for the duration of the current secure invocation
After Invocation Manager - Reviews the object returned from a secured invocation, allows for 'after-the-fact' security

The problem of ACEGI

Every time you use Acegi... A fairy dies... It's a great framework but is very hard to use.

- Lots of moving parts
- Lots of options
- Everything is a <bean> with various options injected with <property>
- Requires lots of XML

Spring Security 2.0

- Released last week (Apr.15th)
- All the Same goodness with some new stuff with much less XML
- Provides a new security configuration namespace for Spring that hides <bean> <property>
- Provides auto-configuration

Method Security

- Intercepting method using Spring AOP
- Or, Annotation Driven

2007/11/07

Manageable Spring Application - enable JMX in minutes

We are keeping talking about manageability of an application. Why is it so important? Because at any stage of the application lifecycle, you need a way to probe the some key aspects of the application's internal status and take appropriate actions to change the application's behaviors as a consequence. Without it, you just guess the application's runtime status and never able to steer it per your needs.

But hold on, it's easy to talk about manageability. And it's really a great idea in the air until you want put it in a concrete base in your application. It's so cumbersome, tedious and error prone to make an implementation. There are couples of option you could choose to inject the manageability in your application:

  1. Your own proprietary mechanism.
  2. Standard SNMP
  3. JMX

Forget about option 1, smart as you, don't want invent any wheel. Well, SNMP (Simple Network Management Protocol) sounds good: standardized, bunch of tools and applications and really structured, until you dig in the details of all the ugly OID (Obejct Identification) definitions, binary format, pure data driven approach. And difficulties of debugging. Plus extra cost for those usable commercial SNMP tools and editors.

Fortunately, we are in campus of Java, which is so far the only language and platform that put the serious crucial enterprise aspects intrinsically in the body, especially manageability in an offer as JMX. For the people working for .Net, either they just don't know what is the manageability, or struggling with various proprietary approaches or annoying SNMP stuffs.

Best of the best in Java application manageability is that we have the generous platform MBean Server as a gift from SUN in new version of JVM, which save your efforts looking for a MBean server; we have the JConsole as tool to directly craft your JMX management GUI frontend; and the offer from Spring's JMX supports. Combine them together, you can make any Java application JMX enabled in minutes.

Here is a simple example called MockServer. It's just a simple socket server for any mock testing purpose. With JMX, you can get the information and stop it in runtime.

Following is the partial code snippets, which is definitely the beautiful POJO. No any special MBean or MXBean stuffs in it, see!

/**
* A mock Socket server.
*/
public class MockServer implements Runnable{
private String name="";
private int port = 80;
private boolean bSSL = false;
private int sotimeout = 2*60*1000;//2 minutes

private ServerSocket listeningSocket = null;
private boolean bStop=false;
private long connCounts = 0; //Ongoing total connection counter.

public MockServer(String name, boolean isSSL, int port, int sotimeout){
this.name = name;
this.bSSL = isSSL;
this.port = port;
this.sotimeout = sotimeout;
}

public String getName(){
return name;
}

public int getPort(){
return port;
}

public boolean isSSL(){
return bSSL;
}

public int getSotimeout(){
return sotimeout;
}

public boolean isStopped(){
return bStop;
}

public void stop(){
bStop = true;
try {
listeningSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

protected void createListeningSocket() throws IOException {
ServerSocketFactory factory = (bSSL? SSLServerSocketFactory.getDefault():ServerSocketFactory.getDefault());
listeningSocket = (ServerSocket) factory.createServerSocket(port);
}

public void run(){
System.out.println("Server: "+getName()+" started.");
try {
createListeningSocket();
while (!isStopped()){
Socket worker = listeningSocket.accept();
//Spawn a thread to handle the request.
fork(worker);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (null!=listeningSocket){
try {
listeningSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Server: "+getName()+" stopped.");
}

protected void fork(Socket worker){
Thread wt = new Thread(new Worker(worker));
wt.start();
}

public long getConnCounts(){
return connCounts;
}
protected synchronized void addCount(){
this.connCounts++;
}
protected synchronized void minusCount(){
this.connCounts--;
}

protected class Worker implements Runnable {
private Socket socket=null;

protected Worker(Socket socket){
this.socket = socket;
}

public void run() {
addCount();
byte[] buf = new byte[1024*10];//10K buffer
InputStream is;
OutputStream os;
try {
//Read request from socket input stream.
is = socket.getInputStream();
int size = is.read(buf);
is.close();
//Process the request.
byte[] resp = processRequest(buf, size);

//Write back the response to socket output stream.
os = socket.getOutputStream();
os.write(resp);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null != socket){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
minusCount();
}
}
}

//Subclasses to override it.
protected byte[] processRequest(byte[] buf, int size){

return buf;//echo it.

}
}

/**
* A mock server services to manage the mock servers.
*/
public class MockServerService {
private Set<MockServer> servers = null;

public void setServers(Set<MockServer> servers){
this.servers = servers;
}

protected void init(){
if(null != servers){
for(MockServer server: servers){
new Thread(server).start();
}
}
System.out.println("Service initialized.");
}

public Set<MockServer> getServers(){
return servers;
}

public void stop(){
if(null != servers){
for(Server server: servers){
server.stop();
}
}
System.out.println("Service stopped.");
}
}

Then we need an application entry point and integrate with Spring.

public class MockServer {
public static void main(String[] args){
AbstractApplicationContext ctxt = new ClassPathXmlApplicationContext("context-mockserver.xml");
ctxt.registerShutdownHook();
MockServerService service = (MockServerService) ctxt.getBean("mockServerService");
service.init();
}
}

the context file for Sring defining the beans.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="mockProcessor0" class="MockServer" >
<constructor-arg index="0" value="Server1"/>
<constructor-arg index="1" value="false"/>
<constructor-arg index="2" value="80"/>
<constructor-arg index="3" value="120000"/>
</bean>
<bean id="mockProcessor1" class="MockServer" >
<constructor-arg index="0" value="Server2"/>
<constructor-arg index="1" value="false"/>
<constructor-arg index="2" value="90"/>
<constructor-arg index="3" value="120000"/>
</bean>
<bean id="mockProcessor2" class="MockServer" >
<constructor-arg index="0" value="Server3"/>
<constructor-arg index="1" value="false"/>
<constructor-arg index="2" value="100"/>
<constructor-arg index="3" value="120000"/>
</bean>

<bean id="mockServerService" class="MockServerService">
<property name="servers">
<set>
<ref local="mockProcessor0"/>
<ref local="mockProcessor1"/>
<ref local="mockProcessor2"/>
</set>
</property>
</bean>
</beans>

Until now, nothing to do with JMX. You can run it as a normal Spring application. You can use JConsole to connect with it locally, if you run the application in this command line:

java -cp . -D-Dcom.sun.management.jmxremote MockServer

This is the snapshot of JConsole MBeans tab. Besides the default threads, memory etc. JVM MXBeans, you can't do anything else to this application.

Now, let's just simply tweak the context file, then see what happens. Add this extra block just at the end of the context file.

...

<bean id="mockServerService" class="MockServerService">
<property name="servers">
<set>
<ref local="mockProcessor0"/>
<ref local="mockProcessor1"/>
<ref local="mockProcessor2"/>
</set>
</property>
</bean>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=MockProcessor0" value-ref="mockProcessor0"/>
<entry key="bean:name=MockProcessor1" value-ref="mockProcessor1"/>
<entry key="bean:name=MockProcessor2" value-ref="mockProcessor2"/>
<entry key="bean:name=MockServerService" value-ref="mockServerService"/>
</map>
</property>
</bean>
...

Here it is! The new JConsole MBeans tab populated with your beans. Now you can see the name of each bean and stop it just by invoking the corresponding stop() method of that bean. Done! You can manage your Spring application now!






In a nutshell, following this pattern, you can tweak any of your applications to be manageable in minutes:

  1. Define the management interfaces for your Object.
  2. Spring your application and expose the object as MBean you want control. Nevertheless, Spring is a extremely noninvasive container, don't be afraid. The things need you Springlize is just make a context file for beans, add less than 5 lines of code to create the application context and put the spring.jar in your classpath. Everything is so familiar to you in a POJO world.
  3. Enable the JVM JMX platform MBean server in command line with -Dcom.sun.management.jmxremote and run it.
  4. Launch the JConsole and connect to the application then control it in your hands.

2007/10/23

Bean Definitions Tip1: Avoid Circular References

Spring is a really powerful framework, which is not only providing the JEE similar or much better and lighter container services, but also providing a straightforward declarative and configuration driven bean definition model. With the flexibility and capability of bean definition mechanism, especially when you unleashing the power of XML schema based context file introduced since Spring 2.0, you can almost do any sorts of bean wiring, parameter configuration, application assembling tasks. After you use it, I bet you will forget all the unpleasant and cumbersome JEE configuration files and the coarse grained Enterprise Beans. However, when dealing with bean definitions, it's still very tricky and the similar problems probably happen as in your traditional programmatic approach.

One typical problem is that the bean definition circular referencing. This is the circumstance under which there are beans relying on each others instance before they could be instantiated by Spring container.

For below example:

public class BeanA {
BeanB b;
public BeanA(BeanB beanB){
b = beanB;
}
public void print(String s) {
System.out.print(s);
}
public void foo(){
b.foo();
}
}

public class BeanB {
private BeanA a;
public BeanB(BeanA beanA){
a = beanA;
}

public void print(String s){
a.print(s);
}

public void foo() {
System.out.print("foo!");
}
}

public class TestStub {
public static void main(String[] args){
AbstractApplicationContext ctxt= new ClassPathXmlApplicationContext("beandef.xml");
}
}

...bean definitions in beandef.xml ...

<bean id="beanA" class="BeanA">
<constructor-arg ref="beanB" />
</bean>
<bean id="beanB" class="BeanB">
<constructor-arg ref="beanA"/>
</bean>

When you run TestStub, it will show following exception (pay attention to the underline):

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanA' defined in class path resource [beandef.xml]: Cannot resolve reference to bean 'beanB' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanB' defined in class path resource [beandef.xml]: Cannot resolve reference to bean 'beanA' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanA': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanB' defined in class path resource [beandef.xml]: Cannot resolve reference to bean 'beanA' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanA': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanA': Requested bean is currently in creation: Is there an unresolvable circular reference?

It's a simple sample of bean circular reference. Specifically, the container tried to instantiate "beanA" first, then it found "beanA" need a reference of "beanB" as constructor argument; subsequently, it tried to create an instance of "BeanB" as "beanB", but this time the "beanB" need a "beanA" instance as a constructor reference argument that is still creation pending waiting for "beanB". This situation confused the container and it can not resolve all the bean references. Then it came the complains of exception. This circular reference problem was caused by circular references of bean by means of Constructor Injection.

To solve this issue, one option is that replace constructor reference to "beanA" of "beanB" with a setter injection. Then the container will not try to create the "beanB" with the "beanB" reference at same time. Instead, it will defer this by injecting the "beanA" reference latter on via "setter" method of "BeanB" after the "beanA" has been created. The same changes happen to "BeanA". It needs some tweaks to the code and bean definitions as well.

public class BeanA {
BeanB b;
public BeanA(){
}
public void setBeanB(BeanB b){
this.b = b;
}
public void print(String s) {
System.out.print(s);
}
public void foo(){
b.foo();
}
}


public class BeanB {
private BeanA a;
public BeanB(){
}

public void setBeanA(BeanA a){
this.a = a;
}
public void print(String s){
a.print(s);
}

public void foo() {
System.out.print("foo!");
}
}


...

<bean id="beanA" class="BeanA">
<property name="beanB" ref="beanB"/>
</bean>
<bean id="beanB" class="BeanB">
<property name="beanA" ref="beanA"/>
</bean>

...

This time, the Sping was very happy to create all the beans.

An alternative option is still workable for this case but a lit bit tricky related with bean instantiating order. We can ask "beanA" injected "beanB" by setter, whereas "beanB" can still use the constructor injection. But wait, the order of bean definition is very important. You can not let constructor injected "beanB" defined before setter injected "beanA".

public class BeanA {
BeanB b;
public BeanA(){
}
public void setBeanB(BeanB b){
this.b = b;
}
public void print(String s) {
System.out.print(s);
}
public void foo(){
b.foo();
}
}

public class BeanB {
private BeanA a;
public BeanB(BeanA a){
this.a = a;
}

public void print(String s){
a.print(s);
}

public void foo() {
System.out.print("foo!");
}
}

...

<bean id="beanA" class="BeanA">
<property name="beanB" ref="beanB"/>
</bean>
<bean id="beanB" class="BeanB">
<constructor-arg ref="beanA"/>
</bean>

...

This works very well. If you move the "beanB" definition before "beanA", it will not work because the "beanA" will need a creating "beanB".

In a nutshell, the circular reference problem is very typical for a sophisticated "Spring" application if you did not cook it very well. It will cost you time to debug and fix it. But not just that. Because the nature of configuration driven of "Spring", the same bean definition file itself could have huge chances to be manipulated by different personnel, thus, more chances of introducing new errors regarding the "Spring" competency level. I will talk about in future sessions how to address this issue by establishing your project or organization level bean definition schema extended from "Spring" base schema. In this way, it mandates some of important project wise constraints for bean definition, such as available tags, bean types, data types etc. Thus, it could reduce some errors caused by arbitrary string parameters or typos in bean definition files for your project.

It's strongly recommended to use setter injection for bean wiring and bean reference injection. If it's very necessary to do constructor based reference injection, and unfortunately involved with circular reference, please well comment or document the bean definition and put notices for future maintaining people. You don't just want someone else happened to ruin your whole fragile bean constructor injection hierarchy someday, do you?

2007/10/12

SpringContextAware JUnit TestCase

In order to run Junit test case outside of a J2EE container, the test case need to initialize the Spring framework properly. I created this abstract class SpringContextAware, which extends from junit.framework.TestCase and initialize the Spring framework in it's setUp() method. User Test Cases that extends from this class will be running with Spring context loaded already.

public abstract class SpringContextAware extends TestCase {
public SpringContextAware(String name){
super(name);
}

public void setUp() throws Exception{
if (SpringApplicationContext.getApplicationContext()==null) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{
// list your context files here
"context-service.xml",
"context-hibernate.xml"
});
ctx.registerShutdownHook();
}
}

public void tearDown() throws Exception{
}
}


Here is the SpringApplicationContext class, basically it allows java classes not defined as a spring bean to be able to access the Spring Application Context.

public class SpringApplicationContext implements ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
return SpringApplicationContext.context;
}

/**
* This method is called from within the ApplicationContext once it is
* done starting up, it will stick a reference to itself into this bean.
*
* @param context a reference to the ApplicationContext.
*/
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringApplicationContext.context = context;
}

/**
*This is about the same as context.getBean("beanName"), except it has its
* own static handle to the Spring context, so calling this method statically
* will give access to the beans by name in the Spring application context.
* As in the context.getBean("beanName") call, the caller must cast to the
* appropriate target class. If the bean does not exist, then a Runtime error
* will be thrown.
*
* @param beanName the name of the bean to get.
* @return an Object reference to the named bean.
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}


This bean itself however, needs to be defined in the Spring Context XML file:

<!-- provide access to spring application context -->
<bean id="springApplicationContext" class="com.blah.blah.SpringApplicationContext">
</bean>


Any comments are welcome :)

EHCache Singleton CacheManager

Here's the problem, when we enable the hibernate secondary cache using org.hibernate.cache.EHCacheProvider, and enable ACEGI user cache using

<property name="userCache">
<bean class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
<property name="cache">
<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheName" value="AcegiUserCache">
</property>
</bean>
</property>
</bean>
</property>

They belongs to two different cache manager.

Instead of have to configure 2 different cache manager separately, have to have separate cache invalidating thread etc, we can fall back to the EHCache Singleton CacheManager.

hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider

Now ACEGI will use the same EHCache CacheManager. They can be configured in the same ehcache.xml file. Yup!

Well well... why another J2EE blog? I benefited from other people's technical blogs, and guess what, it's a good idea to contribute some of my works too. Hope it's helpful and useful, to all of your folks.