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

Monday, June 16, 2008

Gridify your Spring application with Grid Gain @ Spring Italian Meeting 2008

Last Saturday I've been at the Spring Italian Meeting in Cagliari, for an enjoyable meet-up with colleagues, friends, and Spring-passionate users.
First of all, thanks to Massimiliano Dessi', the man behind this event ;)
Then, if you lose my presentation about Grid Computing, Grid Gain, and the Spring Framework, here it is:



I really enjoyed presenting it, and I think attendees enjoyed it too: probably because I gave three cool Sourcesense hats to people which made me some questions about the presentation topics ;)
Too bad I can't give you any Sourcesense hat, but I can write down some of the most interesting questions!

Enjoy!

Q: Splitting a task into jobs and sending them to grid nodes involves some overhead due to data transfer: do you have any percentage number that shows you when this overhead is too high compared to what you gain by parallelizing your jobs?

A: I don't believe in magic numbers :)
I'd like to answer your question in a different way: just keep your overhead as little as possible by applying data affinity, that is, by keeping jobs and the data they need together, trying to minimize data transfers.
If you'll not transfer any data, your overhead will be at its minimum.

Q: You talked about data affinity and data grid solutions: what about my database?

A: For really scaling out your application, you must scale your full application stack: hence, your database must scale, too.
I think one of the most effective ways of making you database scale is to partition it, by splitting data into several instances and making every job access a different partition, depending on the data it needs.
Another strategy would be to use a master/replica scenario, where you have a master instance and several read-only replicas, which you map your jobs to for read-intensive operations.

Q: Is there any Grid Gain success story? Do you really use it?

A: Yes, we do :)
We recently developed for the Italian Public Broadcasting Service a custom Content Management System with extended capabilities for life cycle management and rule based publishing of editorial contents.
The publishing infrastructure is made up of a Grid Gain based application managing the publishing cycle of all public web sites, ranging from the main web portal to all related web sites.
It has been implemented for linearly scaling out the publication process from one to hundred sites, by distributing publishing operations on grid nodes, each one capable of publishing contents of one or more sites independently from others: this means that with a number of physical nodes equal to the number of sites to publish, the whole publication process would linearly scale by taking the same time as there were just one site.

Sunday, December 10, 2006

Spring Modules 0.7 and XT Framework Highlights

Hi guys,

I'm pleased to announce here the new Spring Modules 0.7 release.
We have made several changes (you can find the general changelog here), so I suggest you to update to the new release.

Talking about the XT Framework, here is a short list of the most important changes:

XT Modeling Framework :

  • New annotations for better controlling the DynamicBeanIntroductor behaviour.

XT Ajax Framework :

  • Enhanced integration with Prototype and Scriptaculous JavaScript libraries (in particular, full support for effects and drag and drop).
  • New components, in particular the JspComponent, which let you dynamically send JSP contents through Ajax.
  • Support for mapping more Ajax handlers to the same web path.
  • Enhanced DefaultValidationHandler, for easy Ajax validation.

Take a look at the whole XT documentation for a full taste of all XT Framework features ... any feedback will be very welcomed!

As a final, yet important, note, I'd like to thank all the Spring Modules community, and all Spring Modules developers: it's always a pleasure to work with keen guys!

Friday, December 08, 2006

Spring 2.0 and the P-Namespace

Some days ago Rod Johnson blogged about an undocumented feature of Spring 2.0: the so-called P-Namespace, which permits you to shorten the XML configuration.
This feature has been very well welcomed by the developers community, because it clearly makes the Spring XML configuration easier to manage and read, without running into the burden of writing a custom namespace handler.

I strongly suggest you to give it a try.

As a consequence, many people started asking more, and in particular many people I know asked about the possibility of applying the same kind of configuration to collection and map properties.
Too bad, this seems to be impossible, but I'm here for giving my two cents about another (documented) way of configuring collections, that is IMHO easier to read. It uses the P-Namespace and the util schema, here is a sample:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p=" http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<util:set id="contents">
<bean id="c1" class="org.acme.Content" p:name="c1"/>
<bean id="c2" class="org.acme.Content" p:name="c2"/>
<bean id="c3" class="org.acme.Content" p:name="c3"/>
</util:set>

<bean id="container" class="org.acme.Container" p:name="container" p:contentList-ref="contents"/>

</beans>

As you can see, you have to simply configure your collection with the util schema (that makes it reusable, too), and then inject it with the P-Namespace!

I hope you'll find it useful!

Wednesday, October 18, 2006

Integrating Prevayler into Spring: ease your persistence with Prevayler-Template.

System prevalence is a term coined by Klaus Wuestefeld, denoting a transparent persistence solution.

Let me give some more details for understanding what that means.

A prevalent system is a system made of business objects which obey the following rules:

  • They must be serializable.

  • The must be deterministic, that is, given some input to a business method, it must always return the same output.


A prevalent system is always fully kept in RAM and data is persisted through object serialization, by wrapping all business operations into command objects, serializing commands and all contained business objects into a log file, and executing them.
Then, when the system recovers after shutdown, all commands are read from the serialized log and executed again, recreating a perfect replica of the system prior to its shutdown.
This makes your system (and all its business objects):

  • Persistent, thanks to object serialization.

  • Transactional, because each command represent a single transaction and is executed in isolation.

  • Incredibly fast!



This is just a short (and partial) introduction: more details can be found here and here.

Prevayler is a Java, Open Source, implementation of a framework for achieving system prevalence.
It is widely used in environments where classical persistence solutions are not suitable or unwanted.
Moreover, it is simple to use, but requires you to sligthly change the way you code your application, because:

  • Many applications use the well-known Data Access Object (DAO) pattern for implementing persistence layer logic, while Prevayler (as the prevalence concept dictates) uses plain command objects and requires you to wrap your business methods with them, removing the need of a pure data access layer.

  • You have to care about the infamous baptism problem.



The Spring Prevayler-Template project aims at solving these problems, by providing a Prevayler-based implementation of the DAO pattern and the Spring Data Access architecture used for ORM frameworks, which let you create a prevalence system with totally transparent business objects persistence by simply respecting the rules above, common to all prevalence systems, and by:

  • Adding an (automatically managed) identifier property to your business objects.

  • Implementing a standard Data Access Object, as you would do with Hibernate or alike.

  • Configuring it into the Spring application context.


No additional code, no mappings, no annotations ... nothing more.

Let me show you a concrete example.

First, take a bunch of business objects, say a Person, an Employee and a Company:


public interface Person extends Serializable {

public void requestEmployment(Company company);
}


public interface Employee extends Person {

public void workAsAMad();
}


public interface Company extends Serializable {

public void employ(Person person);
}



Then, implement your business objects and assign them a simple identifier property:


public class PersonImpl implements Person {

private Long id;

public void requestEmployment(Company company) {
// ...
}
}


public class EmployeeImpl implements Employee {

private Long id;

public void workAsAMad() {
// ...
}
}


public interface CompanyImpl implements Company {

private Long id;

public void employ(Person person) {
// ...
}
}



That's all you need to do with your business objects.

Now, let us write a Data Access Object using the PrevaylerTemplate.
The classes showed below are a Prevayler-based porting of the well-known Hibernate generic DAO:


public interface IGenericDao<T, PK extends Serializable> {

public PK create(T newEntity);

public void update(T entity);

public void delete(T entity);

public T read(PK id);
}


public class PrevaylerGenericDao<T, PK extends Serializable> implements IGenericDao<T, PK> {

private PrevaylerTemplate prevaylerTemplate;
private Class<T> entityType;

public PrevaylerGenericDao(Class<T> type) {
this.entityType = type;
}

public PK create(T newEntity) {
this.prevaylerTemplate.save(newEntity);
return (PK) newEntity.getId();
}

public void update(T entity) {
this.prevaylerTemplate.update(entity);
}

public void delete(T entity) {
this.prevaylerTemplate.delete(entity);
}

public T read(PK id) {
return (T) this.prevaylerTemplate.get(this.entityType, id);
}

public PrevaylerTemplate getPrevaylerTemplate() {
return prevaylerTemplate;
}

public void setPrevaylerTemplate(PrevaylerTemplate prevaylerTemplate) {
this.prevaylerTemplate = prevaylerTemplate;
}
}



As you may note, the PrevaylerTemplate is used as it were a standard, maybe Hibernate based, data access template.

Finally, you need to configure it:


<bean name="prevalentSystem" class="org.springmodules.prevayler.system.DefaultPrevalentSystem">
<property name="prevalentClasses">
<list>
<value>Person</value>
<value>Company</value>
</list>
</property>
</bean>

<bean name="prevaylerConfiguration" class="org.springmodules.prevayler.configuration.PrevaylerConfiguration">
<property name="prevalentSystem" ref="prevalentSystem"/>
<property name="prevalenceBase" value="classpath:testPrevalenceBase"/>
</bean>

<bean name="prevaylerTemplate" class="org.springmodules.prevayler.PrevaylerTemplate">
<property name="configuration" ref="prevaylerConfiguration"/>
</bean>



There are just three objects to configure:

  • The prevalent system, defining the prevalent system implementation to use for storing your business objects. It requires you to configure the list of prevalent classes in the system, that is, the classes of business objects to persist. Note that if you need to persist a whole hierarchy, you need to specify just the base class, as it is in the sample where we configured just the Person class.

  • The prevayler configuration, defining the prevalent system implementation to use, and the location of the directory where Prevayler logs will be saved.

  • The prevayler template, defining its associated configuration bean.



That's all ... now your business objects are ready to be persisted!
And if you need to persist a new business object, just add its class to the prevalent classes configuration and do no more!

Prevayler-Template is a new born Spring module, currently available here into Spring Modules sandbox.
You can also take a look at Prevayler-PetClinic, the Prevayler-Template sample based on the well known PetClinic web application: you can find it here.

Any feedback is highly appreciated: feel free to comment on this post, or to ask a question through the Spring Modules forum.

Have fun!

Thursday, October 05, 2006

Spring 2.0 and Maven 2

And finally, the happy ending: Spring 2.0 is in the Maven 2 repository!

This is a great gift for the whole (rich) Maven 2 community.

My best congratulations to Ben Hale and the whole Spring team!

Wednesday, October 04, 2006

Great news about Spring

Hi all,

there are great news in the air about the Spring Framework.

I think all of you know that the final 2.0 version has been released yesterday, but you may not know that Spring 2.0 will be published into the official Maven2 repository in the next days: take a look here.
That's great!

In the meantime, Spring Modules 0.6 has been also published yesterday into Maven2 repository: that's great, too!

Stay tuned!

Friday, July 14, 2006

Spring Modules 0.5 and the XT Framework

Today, Spring Modules 0.5 has been released.

It contains a lot of improvements, as you can read from the announcement, among which you can find my main contribution to the project: the brand new Spring Modules XT Framework.

Born toward the end of the last year as SpringXT, you can find its old (never publicly announced) home page here, I'm proud and happy to say it is now a top level module of Spring Modules!

What is it?

Spring Modules XT, strongly influenced by modern Domain-Driven Design techniques and Ajax technologies, has a main aim: let you develop simple-to-complex business applications with your domain model in mind, and let you easily and powerfully construct the presentation layer of your domain model thanks to Spring MVC and Ajax techniques.
So, it provides an XT Modeling Framework, implementing Domain-Driven Design and AOP based techniques for enhancing your domain model, and XT Ajax Framework, an Ajax implemention which doesn't require you to learn any other framework or deeply change your application, because completely built on (and thought for) Spring MVC.

I invite you to take a look at its documentation and play with it.
It is just at its first stable release and it needs a lot of feedback!

Above all that, give the whole Spring Modules project a look, pick the module you need ... and let us know through its forum and mailing lists!

Saturday, June 10, 2006

Spring Modules 0.4 released

The Spring Modules project has released today the 0.4 version: you can find the announcement here.

It is still under deep development and maybe not ready for certain production environments, but the modules I played with (or I read of) seem to be stable, and it contains a lot of interesting stuff.

In particular, I'm very interested in the Valang Validator, because writing Spring Validators in Java is often a very tedious and error-prone task: Valang is instead a simple, yet powerful, language for declaring validation rules and applying them to beans.

I think I'll write more about Valang in one of my next posts.

In the meantime, give it a try!

Wednesday, May 17, 2006

Spring Hacks : Reflection Based Property Editors.

Property Editors are a J2SE feature used for editing JavaBeans properties from user interfaces, typically representing these properties as text values.

They are used in SpringMVC for similar purposes: representing and binding complex objects in web interfaces as they were simple, plain, properties.

A short example will clarify.
Say you have an Order owning a collection of Orders, each with its Product:


public class Order {

public String getOrderCode() { ... }

public List getLineItems() { ... }
}


public class LineItem {

public String getItemCode() { ... }

public Product getProduct() { ... }
}


public class Product {

public String getCode() { ... }

public String getName() { ... }
}



If you want to display Products in a web selection list, in order to assign a Product to a LineItem, you have to write in your JSP something like this:


<spring:bind path="command.product">
<select name="${status.expression}">
<c:forEach items="${products}" var="p">
<spring:transform value="${p}" var="pCode"/>
<option value="${pCode}">${p.name}</option>
</c:forEach>
</spring:bind>


For doing this, you have to write and configure a PropertyEditor for the Product object, in order to transform the Product object into a text value, specifically its code, and then directly bind the Product having its text representation.
The same applies if you want to bind a collection of LineItems to a Product:


<spring:bind path="command.lineItems">
<c:forEach items="${items}" var="item">
<input type="checkbox" name="${status.expression}" value="${item.itemCode}"/>
.....
</c:forEach>
</spring:bind>


You have to write a CustomCollectionEditor for the collection of LineItem objects, in order to convert the collection of line item codes to the corresponding collection of LineItems objects (take a look here for more info).

Writing PropertyEditors or CustomCollectionEditors is pretty simple: however, if you have to do a lot of bindings, each for a different object, you have to hand-write a lot of property editors, which is boring and error-prone.

Now, think a moment at how you usually transform objects to text values and vice-versa: you use an object property for obtaining a text representation (often an id), and use some kind of data access object for obtaining an object from a given text value (i.e., an object given its id).
So, let us write a generic property editor and a generic collection editor, using Java Reflection.
Here is the property editor:


public class ReflectivePropertyEditor extends PropertyEditorSupport {

private Object dataAccessObject;
private String dataAccessMethod;
private String propertyName;
private PropertyEditor stringConvertor;

public String getAsText() {
if (this.getValue() == null) {
return null;
}
else {
Method method = null;
String result = null;
try {
BeanWrapperImpl wrapper = new BeanWrapperImpl(this.getValue());
result = wrapper.getPropertyValue(this.propertyName).toString();
}
catch(Exception ex) {
throw new ReflectiveCollectionEditorException("An error occurred while using: " + this.propertyName, ex);
}
return result;
}
}

public void setAsText(String textValue) {
try {
if (this.stringConvertor == null) {
Method method = this.dataAccessObject.getClass().getMethod(this.dataAccessMethod, new Class[]{String.class});
this.setValue(method.invoke(this.dataAccessObject, new Object[]{textValue}));
}
else {
this.stringConvertor.setAsText(textValue);
Object value = this.stringConvertor.getValue();
Method method = this.dataAccessObject.getClass().getMethod(this.dataAccessMethod, new Class[]{value.getClass()});
this.setValue(method.invoke(this.dataAccessObject, new Object[]{value}));
}
}
catch(Exception ex) {
throw new ReflectiveCollectionEditorException("An error occurred while executing: " + this.dataAccessMethod, ex);
}
}

public String getPropertyName() {
return this.propertyName;
}

public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}

public Object getDataAccessObject() {
return this.dataAccessObject;
}

public void setDataAccessObject(Object dataAccessObject) {
this.dataAccessObject = dataAccessObject;
}

public String getDataAccessMethod() {
return this.dataAccessMethod;
}

public void setDataAccessMethod(String dataAccessMethod) {
this.dataAccessMethod = dataAccessMethod;
}

public PropertyEditor getStringConvertor() {
return this.stringConvertor;
}

public void setStringConvertor(PropertyEditor stringConvertor) {
this.stringConvertor = stringConvertor;
}
}


And here the collection editor:


public class ReflectiveCollectionEditor extends CustomCollectionEditor {

private Object dataAccessObject;
private String dataAccessMethod;
private PropertyEditor stringConvertor;

public ReflectiveCollectionEditor(Class collection) {
super(collection);
}

public ReflectiveCollectionEditor(Class collection, boolean nullAsEmptyCollection) {
super(collection, nullAsEmptyCollection);
}

protected Object convertElement(Object element) {
if (!(element instanceof String)) {
new IllegalArgumentException("The element to convert must be of type java.lang.String");
}
String textValue = (String) element;
Object result = null;
try {
if (this.stringConvertor == null) {
Method method = this.dataAccessObject.getClass().getMethod(this.dataAccessMethod, new Class[]{String.class});
result = method.invoke(this.dataAccessObject, new Object[] {textValue});
}
else {
this.stringConvertor.setAsText(textValue);
Object value = this.stringConvertor.getValue();
Method method = this.dataAccessObject.getClass().getMethod(this.dataAccessMethod, new Class[]{value.getClass()});
result = method.invoke(this.dataAccessObject, new Object[] {value});
}
}
catch(Exception ex) {
throw new ReflectiveCollectionEditorException("An error occurred while executing: " + this.dataAccessMethod, ex);
}

return result;
}

public Object getDataAccessObject() {
return this.dataAccessObject;
}

public void setDataAccessObject(Object dataAccessObject) {
this.dataAccessObject = dataAccessObject;
}

public String getDataAccessMethod() {
return this.dataAccessMethod;
}

public void setDataAccessMethod(String dataAccessMethod) {
this.dataAccessMethod = dataAccessMethod;
}

public PropertyEditor getStringConvertor() {
return this.stringConvertor;
}

public void setStringConvertor(PropertyEditor stringConvertor) {
this.stringConvertor = stringConvertor;
}
}


What they ask you to do is nothing more than configuring the following properties:

  • dataAccessObject : the object used for converting from a text value to the actual object; it could be a Factory, a DAO, or Repository.

  • dataAccessMethod : the method, on the dataAccessObject, to call for converting from text to object.

  • propertyName : the name of the property which will be used for the object text value (only in ReflectivePropertyEditor).

  • stringConvertor : a PropertyEditor to use for converting the string value that will be passed as argument to the dataAccessMethod (required only if it takes as argument an object that is not a String).


Then, Java Reflection will do all the boring job.

Moreover, those property editors are best configured in the Spring container:


<bean id="productEditor" class="org.acme.ReflectivePropertyEditor">
<property name="dataAccessObject"><ref bean="productDAO"/></property>
<property name="dataAccessMethod"><value>getProduct</value></property>
<property name="propertyName"><value>code</value></property>
</bean>

<bean id="lineItemsCollectionEditor" class="org.acme.ReflectiveCollectionEditor">
<constructor-arg index="0"><value>java.util.Set</value></constructor-arg>
<property name="dataAccessObject"><ref bean="productDAO"/></property>
<property name="dataAccessMethod"><value>getLineItem</value></property>
</bean>



Comments and suggestions are welcome.
Hope you'll find this useful!

Tuesday, November 22, 2005

Unit testing with the Spring Framework, Part 2

In one of my old posts, Unit testing DAO classes in the Spring Framework, I talked about how to test Hibernate based DAO classes implemented with the HibernateDAOSupport Spring template.

However, inspired by a Matt Raible blog post, I've recently started to use the AbstractTransactionalDataSourceSpringContextTests Spring class.

It's a long time since I want to post about this very interesting piece of thing.

This class provides an easy way to do unit, but I'd better say integration, tests over your Spring managed business objects and services, importing your Spring configuration, loading an appropriate Spring application context based on it, and wrapping your test methods each in a separated transaction which will be rolled back at the end of the method, avoiding so to insert test data into your database tables.

This sounds very good, because you don't have to manually configure Hibernate (it will be configured in your Spring application context), nor to manually manage transactions, nor to worry about unwanted test data!!!

So, you will simply have to:

In your test methods, you can use all normal JUnit assert methods.

Moreover, you will be able to do a lot of other cool things, like accessing a jdbcTemplate variable for making SQL queries, committing transactions instead of rolling them back, or making special setup operations before every test method in the same context of its transaction or in another one.

Take a look at its javadoc.

Good testing!

Tuesday, September 20, 2005

Unit testing DAO classes in the Spring Framework

One of the major claims of the Spring framework is its non-intrusiveness, which, among other things, permits to unit test all classes managed by the Spring container.

So, it is natural that I felt very surprised when yesterday my unit test failed two times while testing a DAO class, based on Hibernate and implemented with the HibernateDaoSupport class provided by Spring.

The first time, my unit test failed because I instantiated my DAO object directly through the no-arg constructor: no one set the Hibernate SessionFactory (normally injected by the Spring container), so this was the problem.
I solved the problem creating a SessionFactory into my unit test, and setting it into the DAO object, as I were the Spring container.

Big surprise, the unit test failed a second time, screaming for no TransactionManager found ... but there was no method for setting such a thing in the DAO object!

So, is the unit testability of Spring managed objects only valid for THAT objects NOT using DAO templates?

The answer is no, you can unit test also them.
In the case of Hibernate, simply create and set by yourself a SessionFactory, like said before, and avoid using Session objects directly into your DAO code.
Just use the template facilities, like the getHibernateTemplate().find(...) methods, or, if you must directly use Query or Criteria APIs, encapsulate the access to the Session in the HibernateCallback class provided by Spring, which automatically manages the session and its transactions.

More and more powerful, more and more lightweight.