If you want to write rules in a Java program you have lot of choices. You can use a third party library like Drools or use the JAVA built-in JSR-94 reference implementation. In WSO2 Carbon, there is a component that abstract the behaviour of different rule engine and give you a unified API. Currently it has plugged into Drools and JAVA built-in JSR-94 implementation.

The rule component in WSO2 Carbon platform mainly used by WSO2 ESB product to mediate messages according to the given business rules. But the component is written to facilitate any requirement of using business rules in WSO2 Carbon platform. I had such a requirement in past few days and manage to use the rule component easily with the help of the component author, indika@wso2.com. So I thought it is worth sharing my experience in here.

Here You will be preparing the following stuff.

1. Rule configuration -

We can use this to provide the information about the rule implementation we are going to use, the rules (You can write rules inline or provide a reference to an external file) and the input and output adapter information.

<configuration xmlns="http://www.wso2.org/products/rule/drools">
<executionSet uri="simpleItemRuleXML">
<source key="file:src/test/resources/rules/simple-rules.drl"/>

<!-- <source>

<x><![CDATA[
 rule InvokeABC
 // rules inbuilt to the rule conf
 end

 ]]>
</x>
</source> -->
<creation>
<property name="source" value="drl"/>

</creation>
</executionSet>
<session type="stateless"/>
<input name="facts" type="itemData" key="dataContext"></input>

<output name="results" type="itemData" key="dataContext"></output>
</configuration>


2. The RulesĀ  -

You can write rules inline in the above configuration or put it in a file and refer it from a key which can be refered from the ResourceHelper (described below).

import java.util.Calendar;

rule YearEndDiscount
when
$item : org.test.pojo.SimpleItem(price > 100 )

then

Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.MONTH) == Calendar.JANUARY) {

$item.setPrice($item.getPrice() * 80/100);
}

end

3. Data Context -

The context object that can be used to feed and retrieve data from and to rule engine. Here is the data context for my application.

public class SimpleDataContext {

    public List<NameValuePair> getInput() {

        // in reality the data will be retrieve from a database or some datasource 
        List<NameValuePair> itemPairList = new ArrayList<NameValuePair>();
        SimpleItem item1 = new SimpleItem();
        item1.setName("item1");
        item1.setPrice(50);
        itemPairList.add(new NameValuePair(item1.getName(), item1));

        SimpleItem item2 = new SimpleItem();
        item2.setName("item2");
        item2.setPrice(120);
        itemPairList.add(new NameValuePair(item2.getName(), item2));

        SimpleItem item3 = new SimpleItem();
        item3.setName("item3");
        item3.setPrice(130);
        itemPairList.add(new NameValuePair(item3.getName(), item3));

        return itemPairList;
    }

    public void setResult(Object result) {

        if (!(result instanceof SimpleItem)) {
            System.out.println("it is not a SimpleItem");
        }

        SimpleItem item = (SimpleItem)result;
        System.out.println("Item: " + item.getName() + ", Price: " + item.getPrice());
    }

}

And the Item I’m going to manipulate using rule is a simple bean like this,

public class SimpleItem {
    String name;
    int price;
    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public int getPrice() {

        return price;
    }

    public void setPrice(int price) {

        this.price = price;
    }
}

4. Data Adapter

You have to adapt the input and output with the rule engine. Mostly here you only have to wrap the data context. The advantage of having the data adapter is, a data adapter always associated with a input/output type. So in the rule configuration I can provide the type for the input and output. If you see my rule configuration above, you see the input/output type is marked as “ItemData”. Here is my custom data adapter that is associated with the “itemData” type.

public class SimpleDataAdapter implements
        ResourceAdapter, InputAdaptable, OutputAdaptable {

    // the type associated with the adapter
    private final static String TYPE = "itemData";
    public String getType() {

        return TYPE;
    }

    public Object adaptInput(ResourceDescription resourceDescription, Object tobeadapted) {

        if (!(tobeadapted instanceof SimpleDataContext)) {
            return null;
        }

        SimpleDataContext dataContext = (SimpleDataContext)tobeadapted;
        return dataContext.getInput();
    }

    public boolean adaptOutput(ResourceDescription description,
                               Object value,
                               Object context,
                               ResourceHelper resourceHelper) {

        if (!(context instanceof SimpleDataContext)) {
            return false;
        }

        ((SimpleDataContext)context).setResult(value);
        return true;
    }

    public boolean canAdapt(ResourceDescription description, Object ouptput) {
        String key = description.getKey();
        return key != null && !"".equals(key);
    }

}

5. Resource Helper

Resource Helper will map the keys refered from the configuration to JAVA objects. This is mostly used in mediation rule configurations which can extract the message data using a key or an xpath. In this example, we don’t have much keys refering from the configuration only the rule file and the data context.

public class SimpleResourceHelper extends ResourceHelper {

    public ReturnValue findByKey(String key, Object source, Object defaultValue) {

        if (!(source instanceof SimpleDataContext)) {
            return new ReturnValue(defaultValue);
        }

        SimpleDataContext dataContext = (SimpleDataContext)source;
        if (key.startsWith("file:")) {

            String filename = key.substring("file:".length());
            try {

                BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
                return new ReturnValue(in);
            } catch (Exception e) {

                return new ReturnValue(defaultValue);
            }
        }
        if (key.startsWith("dataContext")) {

            return new ReturnValue(dataContext);
        }
        return new ReturnValue(defaultValue);
    }

    // there are few more methods to be implemented, which can just leave not implemented for this example
    }
}

That is all the accessories. Now you will be able to write the rule engine execution code.

File ruleConfigFile = new File(ruleConfigFilename);
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(ruleConfigFile));

//create the builder
StAXOMBuilder builder = new StAXOMBuilder(parser);
//get the root element (in this case the envelope)

OMElement ruleConfig =  builder.getDocumentElement();
EngineConfiguration configuration =
        new EngineConfigurationFactory().create(ruleConfig, new AXIOMXPathFactory());

EngineController
        engineController = new EngineController(configuration, new SimpleResourceHelper());
        final ResourceAdapterFactory factory = ResourceAdapterFactory.getInstance();

ResourceAdapter adapter = new SimpleDataAdapter();
String adapterType = adapter.getType();
if (!factory.containsResourceAdapter(adapterType)) {

    factory.addResourceAdapter(adapter);
}

SimpleDataContext simpleContext = new SimpleDataContext();

if (!engineController.isInitialized()) {
    engineController.init(simpleContext);

}

if (engineController.isInitialized()) {
    engineController.execute(simpleContext, simpleContext);

}

WSO2 announced an another round of release of their famous SOA products.

Although the version numbers say this is minor patch release (Other than the Mashup Server which is shipping as a major release), in fact there are new features and improvements. Some basic new features shares among all of these products are

  1. Improved registry level transaction Support.
  2. Improved Support for deploying on top of Application Servers other than tomcat like WebSphere, WebLogic, and
    JBoss.
  3. Support for Eclipse P2 based provisioning. (Yes, you can add/remove features from these WSO2 products , see https://wso2.org/wiki/display/carbon/p2-based-provisioning-support for more details)
  4. Improved Remote Registry model

The release of WSO2 SOA platform – Carbon has unified the process of development to deployment of SOA in several aspects. Here is a list of 5 aspects unified across all the components of the SOA platform namely WSAS (The App Server), ESB (Enterprise Service Bus) and BPS (Business Process Server)

1. Unified QoS configurations – Allows you to add/drop modules for security, reliability, etc of your services + edit their policies in a unified view.
2. Unified Registry Storage – Provides a unified view over the governance of the SOA platform.
3. Unified Trackers – Availability of logs, statistics, graphs andĀ  message tracers making it easy to debug and test your system.
4. Unified User Experience – Well designed unified User interfaces allowing admins/users to get familiar with each of the components very quickly and easily.
5. Unified Extensibility – The underline OSGI environment and the design of the carbon platform itself make it possible to add new OSGI bundles as extensions to fit equally across all the products.

March 1st, 2009Composable SOA Platform

The WSO2 SOA platform comprises of

  • Application Server (WSO2 WSAS) – Enables you to provide and consume web services
  • Enterprise Service Bus (WSO2 ESB) – Enables you to mediate web service interactions
  • Business Process Service (WSO2 BPS) – Enables you to orchestrate services for your business process.
  • Registry (WSO2 Registry) Enables you to store and govern your resources.

The uniqueness of WSO2 platform is that it provides you the freedom to mix and match these components according to your requirements. Paul Fremantle, CTO of WSO2 describes this as a Composable SOA platform. You can drop ESB component to BPS instance to add mediation capabilities to your business process server or the other way around.

In the following screencast Ruwan Linton – Product Manger of WSO2 ESB explains how to get the mediation capabilities inside a web service application server, putting ESB component in to WSO2 WSAS and demonstrating their integrated operations.

February 10th, 2009WSO2 Carbon Products Released

WSO2 announced the release of the revolutionary series of products introducing a componentized design to implement SOA in cost effective and simple manner.

  1. WSO2 Web Services Application Server (WSAS) – WSO2 WSAS is an enterprise ready web services engine based on Apache Axis2. It is incorporated with many features including,
    • Data services support – Expose you enterprise data as a services in a jiffy
    • WSAS IDE – Eclipse IDE integration
    • Clustering support for High Availability & High Scalability
    • Full support for WS-Security, WS-Trust, WS-Policy and WS-Secure Conversation and XKMS
    • EJB service provider support – Expose your EJBs as services
    • Axis1 backward compatibility – Deploy Axis1 services on WSAS & Engage advanced WS-* protocols in front of legacy services
    • JMX & Web interface based monitoring and management
    • WS-* & REST support
    • GUI, command line & IDE based tools for Web service development
  2. WSO2 Enterprise Service Bus (ESB)- WSO2 ESB is a lightweight and easy-to-use Open Source Enterprise Service Bus based on Apache Synapse. Here is the listing of some of key features,
    • Proxy services – facilitating transport, interface (WSDL/Schema/Policy), message format (SOAP 1.1/1.2, POX/REST, Text, Binary), QoS (WS-Addressing/WS-Security/WS-RM) and optimization switching (MTOM/SwA).
    • Non-blocking HTTP/S transports based on Apache HttpCore for ultrafast execution and support for thousands of connections at high concurreny with constant memory usage.
    • Built in Registry/Repository, facilitating dynamic updating and reloading of the configuration and associated resources (e.g. XSLTs, XSD, JS, ..)
    • Easily extended via custom Java class (mediator and command)/Spring mediators, or BSF Scripting languages (Javascript, Ruby, Groovy, etc.)
    • Built in support for scheduling tasks using the Quartz scheduler.
    • Load-balancing (with or without sticky sessions) /Fail-over, and clustered Throttling and Caching support
    • WS-Security, WS-Reliable Messaging, Caching and Throttling configurable via (message/operation/service level) WS-Policies
    • Lightweight, XML and Web services centric messaging model
    • Support for industrial standards (Hessian binary web service protocol/Financial information exchange protocol)
    • Enhanced support for the VFS/JMS/Mail transports
    • Support for message splitting and aggregation using the EIP
    • Database lookup and store support with DBMediators with reusable database connection pools
    • JMX monitoring support
  3. WSO2 Registry – WSO2 Registry is a user-friendly, but comprehensive enterprise resource / metadata management solution. It is capable of
    • Storing and managing arbitrary resources and collections
    • Tagging, commenting and rating
    • Managing users and roles
    • Authentication and authorization on all resources and actions
    • Resource / collection versioning and rollback
    • Advanced search capabilities – tags, users, etc.
    • Built in media type support for common types (WSDL, XSD)
    • Dependency management – maintain relationships between dependent resources
    • Pluggable media type handlers for handling custom media types
    • Support for processing custom URL patterns via pluggable URL handlers
    • Support for custom query languages via pluggable query processors
    • Activity log and filtering support for the activity logs
    • Atom Publishing Protocol (APP) support for reading/writing the data store remotely
    • Subscribe to directories, comments, tags, etc. with any standard feed reader (Bloglines, Google Reader, etc)
    • Java client for remote access via APP
    • Embedded and WAR deployments
    • Web based user interface with Web 2.0 look and feel
  4. WSO2 Business Process Server (BPS) – WSO2 Business Process Server (BPS) is an easy-to-use open source business process server that executes business processes written using the WS-BPEL standard and it’s powered by Apache ODE (Orchestration Director Engine). It provides you the following features,
    • Deploying Business Processes written in compliance with WS-BPEL 2.0 Standard and BPEL4WS 1.1 standard.
    • Managing BPEL packages, processes and process instances.
    • Data Sources support.
    • External Database support for BPEL engine.
    • WS-Security support for business processes.
    • WS-RM support for business processes.
    • Caching support for business processes.
    • Throttling support for business processes.
    • Transport management.
    • Internationalized web based management console.
    • System monitoring.
    • Try-it for business processes.
    • SOAP Message Tracing.
    • Web Services tooling support such as WSDL2Java, Java2WSDL and WSDL Converter.
    • Customizable server – You can customize the BPS to fit into your exact requirements, by removing certain features or by adding new optional features.

All these products are pre-bundled components built on top of WSO2 Carbon framework which is based on the OSGI technology. In fact you can bundle the components to suite your enterprise architecture as all the major features have been developed as pluggable Carbon components.

January 31st, 2009Making Good SOA Great

WSO2 is preparing for the first major release of their enterprise java product series after adapting the OSGI technology. You can already try out the betas from the wso2.org site.

  1. WSO2 Web Services Application Server (WSAS)
  2. WSO2 Enterprise Service Bus (ESB)
  3. WSO2 Registry
  4. WSO2 Business Process Server (BPS)

With the power of OSGI you will be able to customize these products for your need just by mixing and matching the components within these products. If you like to learn more about this, just have a loot at the following ebook released by WSO2.

Making Good SOA Great

Making Good SOA Great

WSO2 has released an ebook “Making Good SOA Great – The WSO2 Story of Componentization” explaining how componentizations of middleware will improve the adaption of SOA in an enterprise IT system. And it introduces how you implement it in real systems using WSO2 carbon, the introducing WSO2 product of componentized SOA middleware.

You can see the presentation introducing WSO2 carbon from here,
Introduction to WSO2 Carbon – Componentized SOA Platform.

“WSO2 carbon is a componentized, customizable SOA Platform, You can adapt the middleware to your enterprise architecture, rather than adapt your architecture to the middleware”.

WSO2 Carbon is getting ready to come out very soon. You want to know what exactly WSO2 Carbon is?. Just check this samisa’s blog about “Carbon In Pictures”.


© 2007 Dimuthu’s Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress