Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, March 25, 2016

Connecting to ElasticSearch

      Elasticsearch is a real-time distributed search and analytics engine. Elasticsearch, like most NoSQL databases, is document based storage in json format. An index is a flat collection of independent documents. An index really is a logical namespace pointing to one or more physical shards. Shards as containers for data, documents are stored and indexed in shards.

Elasticsearch supports two types of Java clients: Node Client and Transport Client. Transport client is typically used in java application and is considered to be efficient as it bypasses the process of marshalling & unmarhsalling of request to & from JSON which is typically done in most of the Rest based client.

Using TransportClient in your java application and connecting to elastic is incredibly simple, look at the following code to believe it.

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;

public class ElasticRepository {
 private static final String ELASTIC_URL = "localhost";
 private static final String ELASTIC_PORT = "9300";
 private static final String ELASTIC_CLUSTER = "localhost";
 private static final String ELASTIC_USERNAME = "username";
 private static final String ELASTIC_PASSWORD = "password";
 private final static String ELASTIC_INDEX = "indexName";
 private final static String ELASTIC_TYPE_NAME = "typeName";

 public static void main(String[] args) {

  Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", ELASTIC_CLUSTER)
    .put("shield.user", ELASTIC_USERNAME + ":" + ELASTIC_PASSWORD)
    .build();

  TransportClient transportClient = new TransportClient(settings);
  // Your random record/index id
  String indexId = "123";
  String sourceData = "This is the data source to be persisted in elastic";
  try {
   TransportAddress transportAddress = new InetSocketTransportAddress(
     ELASTIC_URL, Integer.parseInt(ELASTIC_PORT));
   transportClient.addTransportAddress(transportAddress);

   transportClient
     .prepareIndex(ELASTIC_INDEX, ELASTIC_TYPE_NAME, indexId)
     .setSource(sourceData).execute().actionGet();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   transportClient.close();
  }
 }
}

Elastic Shield is an enterprise security tool to protect data in the elastic server. It provides role based protection to your data at the index level. You need to have an authorization in order to read or write to/from a specific index that is being protected through shield. Once elastic is protected by the shield the above code may not work and fail to connect. It would now require an authentication token in its request header.
Take a look at the code below,


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.shield.authc.support.SecuredString;

import org.elasticsearch.shield.authc.support.SecuredString;

public class ElasticRepository {
 private static final String ELASTIC_URL = "localhost";
 private static final String ELASTIC_PORT = "9300";
 private static final String ELASTIC_CLUSTER = "localhost";
 private static final String ELASTIC_USERNAME = "username";
 private static final String ELASTIC_PASSWORD = "password";
 private final static String ELASTIC_INDEX = "indexName";
 private final static String ELASTIC_TYPE_NAME = "typeName";

 public static void main(String[] args) {

  Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", ELASTIC_CLUSTER)
    .put("shield.user", ELASTIC_USERNAME + ":" + ELASTIC_PASSWORD)
    .build();

  TransportClient transportClient = new TransportClient(settings);
  // Your random record/index id
  String indexId = "123";
  String sourceData = "This is the data source to be persisted in elastic";
  String token;
  try {
   token = basicAuthHeaderValue(ELASTIC_USERNAME,
     new SecuredString(ELASTIC_PASSWORD.toCharArray()));
   TransportAddress transportAddress = new InetSocketTransportAddress(
     ELASTIC_URL, Integer.parseInt(ELASTIC_PORT));
   transportClient.addTransportAddress(transportAddress);
   transportClient
     .prepareIndex(ELASTIC_INDEX, ELASTIC_TYPE_NAME, indexId)
     .putHeader("Authorization", token)
     .setSource(sourceData).execute().actionGet();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   transportClient.close();
  }
 }
}

You would require elasticsearch-shield-1.0.2.jar, commons-codec-1.10.jar in your classpath. Line #34 shows how to generate a token using Shield's UsernamePasswordToken class. Once you have the token generated, you will need to set it into TransportClient's header as shown in line #41. This way you could connect to elastic by authenticating shield. 

That's it, happy coding...!

Reference:

Monday, December 23, 2013

Springify The Strategy Pattern - Part 2


I talked about how to implement strategy pattern in springapplication in my previous post. Here I want to show you how Spring Annotations can make our lives easier to implement these patterns.
Spring 2.5 version introduced way to configure the dependency injection using annotations. This eliminates all those XML files in an application that just defined beans and bean wiring. Now annotation allows you to configure these inside the bean (component).

Some of the annotations that I will be using were @Autowired, @Resource, @Component, @Service etc.
All right let’s get into the code, I will take the second approach from the previous article and configure it using annotation. The new configuration XML looks like this,

<context:component-scan base-package="xyz.xyz.strategy"/>

What happened to all bean definitions? What is this component scan?
Well annotation based configuration eliminated the bean definition in the XML. Instead we enable spring auto component scanning of components in the base package where it can scan, detect, instantiate and wire all these beans (components).

Now let’s look at the beans again. You will have to go back to your strategy implementation classes like RegularShippingCostStrategyImpl etc. and add @Service or @Component annotation to the class as shown below,
@Service
public class RegularShippingCostStrategyImpl implements ShippingCostStrategy {
//calculation code
}

@Service
public class PremiumShippingCostStrategyImpl implements ShippingCostStrategy {
//calculation code
}

@Service
public class PrimeShippingCostStrategyImpl implements ShippingCostStrategy {
//calculation code
}

 
Your ShippingCostService class with added annotation below,
@Service
public class ShippingCostService {
 
 @Autowired
 private ShippingCostContext shippingContext = null;
  
 public double calculateShipping(Item item, String memberStatus){
  double cost = shippingContext.calculateShipping(item, memberStatus);
     return cost;
 }
 
}

 
Now look at this strategy context class,
@Component
public class ShippingCostContext {
 
 @Autowired
 private PrimeShippingCostStrategyImpl primeShippingStrategy = null;
 
 @Autowired
 private PremiumShippingCostStrategyImpl premiumShippingStrategy = null;
 
 @Autowired
 private RegularShippingCostStrategyImpl regularShippingStrategy = null;
        
 public double calculateShipping(Item item, String memberStatus){
       double cost = 0.0;
       if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PRIME))
          cost = primeShippingStrategy.calculate(item);
       else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PREMIUM))
          cost = premiumShippingStrategy.calculate(item);
       else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_REGULAR))
          cost = regularShippingStrategy.calculate(item);
    
       return cost;
 }
   
}

Now run the same test to check this out.
The same can be achieved for the first approach as well by simply switching auto wire strategy implementation classes from strategy context class to service class.
About the third approach is not all required since spring auto scan and auto wire simplifies the implementation already. But in case if you are interested here is how you can do it.

<context:component-scan base-package="xyz.xyz.strategy"/>
   
<util:map id="strategies" map-class="java.util.HashMap">
       <entry>
         <key>
           <util:constant static-field=" xyz.xyz.strategy.StrategyConstants.MEMBER_REGULAR"/>
          </key>
            <ref bean="regularShippingCostStrategyImpl" />
         </entry>
         <entry>
             <key>
              <util:constant static-field=" xyz.xyz.strategy.StrategyConstants.MEMBER_PREMIUM"/>
             </key>
             <ref bean="premiumShippingCostStrategyImpl" />
         </entry>
         <entry>
             <key>
              <util:constant static-field=" xyz.xyz.strategy.StrategyConstants.MEMBER_PRIME"/>
             </key>
             <ref bean="primeShippingCostStrategyImpl" />
         </entry>
   </util:map>

The XML context will have to define the spring util Map with key and ref value as shown above. You will then have to Autowire the map into the strategy context like this,
@Service
public class ShippingCostContext {
 
 @Resource
 private Properties strategies;
 
 public double calculateShipping(Item item, String memberstatus){
        double cost = 0.0;
        if(strategies.containsKey(memberstatus)){
         ShippingCostStrategy shippingCostStrategy = (ShippingCostStrategy)strategies.get(memberstatus);
         if(shippingCostStrategy != null)
          cost = shippingCostStrategy.calculate(item);
        }
               
 return cost;
 }


That’s all, the strategy pattern is now spring annotated. The spring annotations are quite powerful and simplify the configuration.

Friday, July 27, 2012

Springify The Strategy Pattern


            The strategy pattern, sure we have heard enough and used enough many times before. But if you are wondering how effectively one could use this pattern in a spring powered application then here are few approaches. I wouldn’t waste time talking about strategy pattern. So let’s get started with some code, consider a typical eCommerce company offering various levels of savings on shipping cost based on the type of memberships. So let’s keep this logic simple here to try out various approaches.

First thing First
  Here are few basic components of strategy pattern first. Start with an interface ShippingCostStrategy.java as shown below,
public interface IShippingCostStrategy {
    public double calculate(Item item);
}

Now write few possible strategy implementations like below,

public class PrimeShippingCostStrategyImpl implements IShippingCostStrategy {
     public double calculate(Item item) {
        double cost = 0.0;
        //Calculate the shipping for prime members 
        return cost;
     }
} 
public class PremiumShippingCostStrategyImpl implements IShippingCostStrategy {
     public double calculate(Item item) {
        double cost = 0.0;
        //Calculate the shipping for premium members 
        return cost;
     }
}
public class RegularShippingCostStrategyImpl implements IShippingCostStrategy {
     public double calculate(Item item) {
        double cost = 0.0;
        //Calculate the shipping for regular members 
        return cost;
     }
}
public class Item {
   private int itemId;
   private String code;
   private double price;

   public Item() {
      super();
   }
 
   public Item(int itemId, String code, double price) {
      super();
      this.itemId = itemId;
      this.code = code;
      this.price = price;
   }

   //All the getter and setter methods are omitted for brevity
}

Define these beans in the shippingCost-context.xml like below and these are required no matter what the approach is,

<bean id="primeShippingStrategy" class=" xxx.xxx.PrimeShippingCostStrategyImpl" />
<bean id="premiumShippingStrategy" class=" xxx.xxx.PremiumShippingCostStrategyImpl" />
<bean id="regularShippingStrategy" class=" xxx.xxx.RegularShippingCostStrategyImpl" />


Approach #1
             In this approach we will keep our context for the strategy simple meaning we will let the client (service) to take the responsibility of determining the possible right strategy implementation class and setting in to the context.
The calculateShipping method in the context will then call the calculate method on the strategy that is being set.
The ShippingContext.java we got here is as shown below,

public class ShippingCostContext {
   IShippingCostStrategy shippingCostStrategy = null;
 
   public double calculateShipping(Item item){
      return shippingCostStrategy.calculate(item);
   }
 
   public void setShippingCostStrategy(IShippingCostStrategy shippingCostStrategy) {
      this.shippingCostStrategy = shippingCostStrategy;
   }
  
}

Let’s look at the ShippingCostService that is being the client for this strategy.
Here we are injecting all the strategy classes and context into this client.

public class ShippingCostService {

   private PrimeShippingCostStrategyImpl primeShippingStrategy = null;
   private PremiumShippingCostStrategyImpl premiumShippingStrategy = null;
   private RegularShippingCostStrategyImpl regularShippingStrategy = null;
   private ShippingCostContext shippingContext = null;
 
   public double calculateShipping(Item item, String memberStatus){
      double cost = 0.0;
      if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PRIME))
         shippingContext.setShippingCostStrategy(primeShippingStrategy);
      else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PREMIUM))
         shippingContext.setShippingCostStrategy(premiumShippingStrategy);
      else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_REGULAR))
         shippingContext.setShippingCostStrategy(regularShippingStrategy);
   
      cost = shippingContext.calculateShipping(item);
    return cost;
 }

 //All the setter and getter for the above attributes goes here

}//End of ShippingCostService

Now the spring configuration would be straight forward,


<bean id="shippingContext" class=" xxx.xxx.SpringShippingCostContext" />
<bean id="shippingCostService" class=" xxx.xxx.ShippingCostService" >
   <property name="primeShippingStrategy" ref="primeShippingStrategy"/>
   <property name="premiumShippingStrategy" ref="premiumShippingStrategy"/>
   <property name="regularShippingStrategy" ref="regularShippingStrategy"/>
   <property name="shippingContext" ref="shippingContext"/>
</bean>

         
Simple class to test this out,
public static void main(String args[]) {
   ApplicationContext context = new ClassPathXmlApplicationContext("shippingCost-Context.xml"); 
   ShippingCostService shippingCostService = ShippingCostService)context.getBean("shippingCostService");
  
   String memberStatus = StrategyConstants.MEMBER_PREMIUM; //REGULAR, PREMIUM, PRIME
  
   Item item = new Item(1, "PREMIUM", 20.00);
   double cost = shippingCostService.calculateShipping(item,memberStatus);
   System.out.println("Shipping cost: for Member type: "+ memberStatus+ ", cost: "+cost);
}

Approach #2
             In this approach we are transferring the responsibility of determining the right strategy from client to the context.
So we will have to inject all the strategy implementation classes into the context as shown below,

public class ShippingCostContext {
  
  private PrimeShippingCostStrategyImpl primeShippingStrategy = null;
  private PremiumShippingCostStrategyImpl premiumShippingStrategy = null;
  private RegularShippingCostStrategyImpl regularShippingStrategy = null;
 
 
  public double calculateShipping(Item item, String memberStatus){
     double cost = 0.0;
     if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PRIME))
         cost = primeShippingStrategy.calculate(item);
     else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_PREMIUM))
         cost = premiumShippingStrategy.calculate(item);
     else if(memberStatus.equalsIgnoreCase(StrategyConstants.MEMBER_REGULAR))
         cost = regularShippingStrategy.calculate(item);
     return cost;
  }
 
  // All the setter and getter for the above attributes goes here
}


As we see the calculateShipping method in context will determine the call to the right strategy class based on the new parameter memberStatus. There by we freed the ShippingCostService from making the decision of injecting the right strategy implementation class into the context.

public class ShippingCostService {
 
     private ShippingCostContext shippingContext = null;
 
     public double calculateShipping(Item item, String memberStatus){
         double cost = 0.0;
         cost = shippingContext.calculateShipping(item, memberStatus);
         return cost;
     }
 
     // All the setter and getter for the above attributes goes here

}

The spring configuration for this approach would be,


<bean id="shippingContext" class=" xxx.xxx.SpringShippingCostContext" >
     <property name="primeShippingStrategy" ref="primeShippingStrategy"/>
     <property name="premiumShippingStrategy" ref="premiumShippingStrategy"/>
     <property name="regularShippingStrategy" ref="regularShippingStrategy"/>
</bean>


<bean id="shippingCostService" class=" xxx.xxx.ShippingCostService" >
     <property name="shippingContext" ref="shippingContext"/>
</bean>


We could test this approach out using the same test class code as given above in approach 1.

Approach #3
            The third approach improvises the approach 2 by introducing a map of available strategies.
So introducing any new strategy would just be a matter of configuring rather than coding in context.

Look at this code for context under this approach,

public class ShippingCostContext {
     private Map shippingStrategies = new HashMap(); 
  
     public double calculateShipping(Item item, String memberstatus){
         double cost = 0.0;
         if(shippingStrategies.containsKey(memberstatus)){
            IShippingCostStrategy shippingCostStrategy = (IShippingCostStrategy)shippingStrategies.get(memberstatus);
         if(shippingCostStrategy != null)
             cost = shippingCostStrategy.calculate(item);
  }
  
     return cost;
 }
 
     public void setShippingStrategies(Map shippingStrategies) {
         this.shippingStrategies = shippingStrategies;
 }
}

Context now holds the map of all configured strategy beans in it. This wouldn’t affect the way client invokes the strategy at all.
All it needs to do is pass an additional parameter memberStatus to the context to help determine the right strategy.

public class ShippingCostService {
     private ShippingCostContext shippingContext = null;
 
     public double calculateShipping(Item item, String memberStatus){
         double cost = 0.0;
         cost = shippingContext.calculateShipping(item, memberStatus);
         return cost;
     }
}

The configuration for this approach is simple enough as we are going to use the util schema to achieve this.
We created the property shippingStrategies of type Map with key using static fields and value would be respective bean.


<bean id="shippingContext" class="xxx.xxx.ShippingCostContext" >
   <property name="shippingStrategies">
     <map>
       <entry>
         <key>
           <util:constant static-field="xxx.xxx.StrategyConstants.MEMBER_REGULAR"/>
         </key>
           <ref bean="regularShippingStrategy" />
        </entry>
        <entry>
            <key>
             <util:constant static-field=" xxx.xxx.StrategyConstants.MEMBER_PREMIUM"/>
            </key>
            <ref bean="premiumShippingStrategy" />
        </entry>
        <entry>
            <key>
             <util:constant static-field=" xxx.xxx.StrategyConstants.MEMBER_PRIME"/>
            </key>
            <ref bean="primeShippingStrategy" />
        </entry>
    </map>
  </property>
</bean>


<bean id="shippingCostService" class=" xxx.xxx.ShippingCostService" >
      <property name="shippingContext" ref="shippingContext"/>
</bean>


Make sure to add the util namespace and shema location information to the header beans of the context xml like as shown,


xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd"


That’s it you are ready to test your strategy using the same test class above.

Final Note
    The advantage of approach 1 is, the client will be in control if the business logic in client (service) that determines the strategy to use is inseparable or tightly coupled. The same advantage could turn into a disaster with tight coupling. So approach 2 would bring in the much needed loose coupling and let strategy context take care of determining the right strategy. This brings in an opportunity to add more business intelligence into the context. The last approach as you saw definitely improvises the overall strategy to implement the strategy pattern in spring. Sure there must be even better approaches out there and if you do have one please share.

Reference
  1. Reference to the strategy pattern.
  2. Reference to the Spring Util schema documentation.


Sunday, April 29, 2012

Rules for Java Application


Well, I am sure you have heard enough about rules and rule engine. But if you are scavenging for a quick start tutorial with simple example then you are on the right place. The example supplied with this article uses jRuleEngine v 1.3. Let me first throw few lines out on the rules and rule engine just to fill you.

What is a rule?
Rule is a business rule that validates the data under certain circumstances.
Simply rule is nothing but the business logic that we code in our service classes using if else statements.
Lets take a typical shopping cart as an example and say if couponCode.equals(“TRY10”) then apply 10% off of the total amount in the cart. So checking the various coupon codes is one rule inside the OrderService class. Applying 10% off is an action that goes with the rule if it is applicable.
Now imagine, coding one dozen coupon codes and applicable actions around it inside the service class. This is a very simple scenario but enough to start thinking of kicking this logic out of service class. This is where we would end up using the rule engine so that business can drive these variants without code changes.

What is a rule engine?
A rule engine is simply an interpreter of these rules or if/then statements. Theoretically you give the input to this rule engine, tell the set of rules to apply on the input and expect the desired output.
So now these rules can be defined in external files in the format of xml and other proprietary formats that adhere to RuleML standard or simply drive the rules from database tables.

Enough explanation, let’s get our hands dirty
So say this ecommerce company makes various seasonal coupons available for their customers. Just for the brevity we will consider each coupon has expiration date and discount percent. So the shopping cart application should be managing these coupons more effectively in order to cope with business ideas. It’s time to bring in the rule engine.

First thing first
            Let’s get started with rules. We could drive these rules through 2 ways, xml or database tables as I mentioned earlier.

Loading rules through XML
            Take a look at the code snippet below


<rule-execution-set>
    <name>CouponRule</name>
    <description>Rules to apply coupon discounts</description>
</rule-execution-set>
 

We just defined a rule execution set with name and description to look up later.

Now we could use synonymn element as name itself suggests, define a handler for any input objects that could be referred inside the rule xml and rule engine.


<synonymn name="order" class="com.rule.model.Order" />
<synonymn name="coupon" class="com.rule.model.Coupon" />
 


Now we could define a rule using rule element like below,   


<rule name="Rule10" description="10% discount coupon rule" >
    <if leftTerm="coupon.getName" op="=" rightTerm="TRY10" />
    <if leftTerm="coupon.isValid" op="=" rightTerm="true" />
    <then method="order.applyCoupon" arg1="10.00" />
    <then method="order.setComment" arg1="Applied 10% off." />
</rule>
 

What we are trying to do with the above rule lines is, if coupon name is TRY10 and order date (assume) today is before or equals to expire date then apply 10% off of total order amount of the cart and set the comment. For the brevity I used comment but practically it could be a logic to mark the cart that coupon has been applied already. That’s pretty much it for one coupon rule.
Now if you have tens or hundreds of coupons then you will end up writing that many rule elements inside this xml.

Loading rules through database tables
            In theory rule in xml files should be good enough but not enough when it comes to manageability on long run. Just imagine adding hundreds of coupon rules would simply bloat the xml. Secondly xml changes would require an application restart. Using tables would bring better manageability of rules and makes it more dynamic.
OK, how do we create these rule tables and how do we define these rules in them?

Rules Class Diagram
            If you look at the jrule engine source code you would see these classes going on in their rule package.



Logical ERD
            A straight translation of the above classes would result in tables shown below in the ERD diagram. These tables represent a simple conversion of the elements defined in xml into table.



Well we could go one level up and define the rule execution set to hold these rules.
Now it is just a matter of writing insert/update statements into these tables but you could build the UI in your application to manage these rules as well. If you decide to have a UI for business to manage these rules then you will have to come up with relational tables around the required properties. I will try to cover that in my next article.

Rest of the code around rule api’s is simple and self explanatory in this example so I wouldn’t bother digging into it.

If you look into this convenience wrapper class RuleInfrastructureServiceImpl, you will notice there are utility method to get the ServiceManager, RuleAdministrator and several overloaded createRuleExecutionSet methods.

The createRuleExecutionSet could be called with input stream to load rules from xml where as called with RuleImpl object to load rules off of tables.

Ultimately you will need to create a rule session to execute rules. A rule session is a communication connection between your application code and rule engine. In theory each rule session represents one execution rule set.
It is always best practice to use a stateless rule session over stateful in most scenarios considering the performance bottlenecks.

The OrderService’s applyCoupon method would take three parameters Order, couponCode entered by the customer and rule session object.

Final Note
          Using rule engine would simplify lot of business operation around the application but would definitely takes 2 plus 2 cents to design and build such rules interfaces in the application.

Reference
          Download the source code for the example used in this article.

Wednesday, February 1, 2012

MDB listening to Oracle AQ using Sun Adapter



Sometime back I had to work on MDB implementation for JBoss 5.1 to connect to oracle AQ. I implemented the solution using Sun AQ resource Adapter.
The purpose of this article is not to justify this approach versus JBoss recommended approaches like JBoss’s default JMS messaging implementation, ESB and so on but is to make it easy for anyone that decides to go with this approach. As this implementation could easily run into many issues, this article should help you going.
Yes this is time consuming and frustrating due to the facts that,
1.  The official support for this adapter has been stopped.
2.  No supporting documents for this implementation.
3.  There are threads in few forums that talk about this implementation but it is kind of hard to put it all together.
First Thing First
Let’s get started, deploy and run the example to see it working.
1.       Download and execute the scripts from myAQ.sql in your oracle schema
a.       Make sure you have proper privileges as stated in the script file, ask your DBA if you are not one.
b.      Create queue table and queue and start the queue
c.       Important create queue table with pay load type SYS.AQ$_JMS_MESSAGE.
d.      Create a procedure from the above script file to enqueue and dequeue the messages.
e.      Run the enqueue procedure.
f.        Run the dequeue procedure, you will see the output
JMS Message is: Testing my first AQ JMS message
2.       Download the sun AQ adapter oracleAQ.rar from the resources section below and put it under your {JBOSS_INSTALL}\server\default\deploy directory.
3.       Download the myAQ-ds.xml and put it under {JBOSS_INSTALL}\server\default\deploy directory.
a.       Modify the highlighted configuration to suite your environment

<mbean code="org.jboss.resource.deployment.AdminObject" name="jboss.oracleaq:service=Queue,name=DEMO_QUEUE">
   <attribute name="JNDIName">myaq/queue/demo</attribute>
   <depends optional-attribute-name="RARName">jboss.jca:service=RARDeployment,name='oracleaq.rar'</depends>
   <attribute name="Type">javax.jms.Queue</attribute>
   <attribute name="Properties">DestinationProperties=owner\=demouser, name\=DEMO_QUEUE</attribute>
</mbean>


<config-property name="ConnectionFactoryProperties" type="java.lang.String">jdbc_connect_string=jdbc:oracle:thin:demouser/demopassword@<host>:<port>:<sid>,host=<host>,user=demouser,password=demopassword,port=<port>,sid=<sid>,driver=thin
</config-property>

    <config-property name="username" type="java.lang.String">demouser</config-property>

    <config-property name="password" type="java.lang.String">demopassword</config-property>

 
4.       Now download all the dependency jars that are needed. Most of these libraries are part of oracle. You could handle these dependencies in 2 ways
a.       Download the following jar files from your oracle installed directory and copy them directly to {JBOSS_INSTALL}\server\default\lib directory.
aqapi.jar
bcel.jar
connector.jar
javax77.jar
jmxri.jar
oc4jclient.jar
ojdbc14.jar

b.      You could rebuild the downloaded oracleaq.rar file to include all the dependency jars above.
5.       Download the source jar file myAQ.jar and put it under {JBOSS_INSTALL}\server\default\deploy directory. Before copying you need to change some configuration in MDB, so to do that
a.       Import the jar project as EJB jar in to eclipse or any IDE of your choice.
b.      Open the java source file MyAqMessageBean.java and update the highlighted configuration through annotations.
@MessageDriven(

activationConfig = {

@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),

@ActivationConfigProperty(propertyName = "connectionFactoryProperties", propertyValue = "jdbc_connect_string=jdbc:oracle:thin:demouser/demopassword@{host:port:sid},host=<host>,user=demouser,password=demopassword,port=<port>,sid=<sid>,driver=thin"),

@ActivationConfigProperty(propertyName="destinationProperties", propertyValue="owner=demouser,name=demo_queue"),

    @ActivationConfigProperty(propertyName="userName", propertyValue="demouser"),

    @ActivationConfigProperty(propertyName="password", propertyValue="demopassword"),

    @ActivationConfigProperty(propertyName="ConnectionFactoryClassName", propertyValue="oracle.jms.AQjmsConnectionFactory"),

    @ActivationConfigProperty(propertyName="QueueConnectionFactoryClassName", propertyValue="oracle.jms.AQjmsQueueConnectionFactory")

})

@ResourceAdapter("oracleaq.rar")

c.       Now export the EJB jar directly in to the JBoss deploy directory.
6.       Now it’s time to start the JBoss server.
7.       Enqueue the message by running the procedure
8.       See the messages were picked by MDB on the JBoss console.

Issues
Here are the few issues that you could avoid though,
1.       Do not use 10g Lite since lite doesn’t come with DBMS_AQADM packages installed and so not able to enqueue or dequeue the message type SYS.AQ$_JMS_MESSAGE. There was an alternate solution suggested in some forum i.e. to run some DBMS-XXX package and I couldn’t get it to run so I decided to go for standard 10g edition as that was the only other option to get it work.
2.       Do not create the queue table with payload message type other than $AQ_JMS_MESSAGE as JBoss would talk to the AQ only if the payload is of this type.
3.       The adapter doesn't support XA connections in MDB.
4.       Now the bean listens to the first message only and any subsequent messages were simply lost. Solution to this is to update couple of files in oracleAQ.rar file. Well you should not run into this issue as I have supplied the updated rar file here. The details of those changes are in reference section.
5.       There is one minor glitch that you have to live with is when you try to stop the JBoss you will see error stack due to the JBoss thread confliction while calling releaseEndpoint method in InboundJmsResource.
6.       I tried this solution in JBoss 7.0.1 and at that time there were some issues related to registering the resource adapter with JBoss. I know recently some of those jira issues around this reported to be closed but I haven’t got back on it.
Conclusion
            This solution works perfectly considering application environment scope and limitations with one exception on shutdown. The community would surely appreciate if you share any resolutions to this issue or even better solution.
References
AQ data source configuration myAQ-ds.xml
Source Code myAQ.jar
Oracle AQ resource adapter oracleaq.rar
Oracle10g AQ SQL myAQ_10g.sql
Oracle AQ resource Adapter source oracleaq-source.rar