RSS Feed for This PostCurrent Article

Using XStream to Store Business Rule


Download Source Code

There are times there are some business rule that are complicated to be stored in database. I have tried to use JBoss Rule for storing business rule, but later found that it is an overkill.

After some googling, I found several Java serialization frameworks like SIMPLE, XStream, XMLBeans, JAXB, etc.

Below I provided a simple example to store business rule using XStream.

Let’s said I need to store details about a Person together with his Account details (of course I could have done it using a database table easily, but then there are situations that the logic is very complicated to be represented in database).

 

public class PersonRule extends BaseRule implements IRule {
private String name;
private int age;
private String occupation;
@XStreamImplicit(itemFieldName = “accounts”)
private List<account> accounts;

As you can, I am storing the person details together with a list of accounts for that persons.

Below is the code to serialize and deserialize the objects.

PersonRule person = new PersonRule();
person.setName(“Jackson”);
person.setAge(32);
person.setOccupation(“Programmer”);

List<account> accounts = new ArrayList<account>(2);
Account account = new Account();account.setAccountNo(“1234”);
account.setPassword(“pass1”);
accounts.add(account);account = new Account();
account.setAccountNo(“4567”);
account.setPassword(“pass2”);
accounts.add(account);
person.setAccounts(accounts);
String xmlString = person.toXML();

System.out.println(xmlString);
PersonRule newPerson = (PersonRule) BaseRule.fromXML(xmlString, PersonRule.class);
System.out.println(newPerson.getName());
System.out.println(newPerson.getAge());
System.out.println(newPerson.getOccupation());

for (Account acc : newPerson.getAccounts()) {
System.out.println(acc.getAccountNo());
System.out.println(acc.getPassword());
}

The serialized XML string is as below

<person> <name>Jackson</name></person>
<age>32</age>
<occupation>Programmer</occupation>
<accounts>
<accountno>1234</accountno><password>pass1
</password></p>

</accounts>
<accounts>

<accountno>4567</accountno>
<password>pass2</password>
</accounts>


Trackback URL