Monday, June 18, 2012

Infinispan and Twilio integration

You have a good old JavaEE transactional application where you have done all right things such as database index, caching etc so that its performance is good. If you are really careful and want to make sure that it keeps performing well and scaling well as well, you would use Infinispan [1]. ;-) For some extraordinary reasons, imagine that when an entry gets added to the cache, you want to get notified right away. I will show you in this blog how you can integrate Twilio with cache events in Infinispan so that you get an SMS when a cache entry is created.


  • You need to create a cache event listener which is simply annotating a POJO with listener annotation and annotating relevant methods for event you are interested in.
    @Listener
    public class InfinispanTwilioCacheListener
    ...
    @CacheEntryCreated
    public void print(CacheEntryCreatedEvent event) {
    ..
    }
    
    
    
  • Register this listener to your cache, not at cache manger. See Listeners and Notfications for details.
    defaultCacheManager().getCache(CACHE_NAME).addListener(new InfinispanTwilioCacheListener());
    
    
  • Create a utility method to get SmsFactory from Twilio Rest Client.
    private SmsFactory getTwilioSmsFactory () {
    if (client == null)    
       client = new TwilioRestClient("YOUR_TWILIO_SID", "YOUR_TWILIO_TOKEN");
       Account mainAccount = client.getAccount();      
       SmsFactory smsFactory = mainAccount.getSmsFactory();
       return smsFactory;
    
    
  • Send an SMS. You would add this in your method annotated with @CacheEntryCreated
     Map smsParams = new HashMap();
     smsParams.put("To", "VALID_PHONE_NUMBER");
     smsParams.put("From", "TWILIO_PHONE_NUMBER"); 
     smsParams.put("Body", "A cache entry got created" + event.getKey().toString());
     try {
        this.getTwilioSmsFactory().create(smsParams);
     } catch (TwilioRestException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Here is a screenshot of my phone when an SMS was sent.
Note, if you are using a trial account then you can not call or send an SMS without verification of that number which obviously makes sense. If the number is not verified then you will get an exception like : "com.twilio.sdk.TwilioRestException: The number XXXXX is unverified. Trial accounts cannot send messages to unverified numbers; verify XXXXX at twilio.com/user/account/phone-numbers/verified, or purchase a Twilio number to send messages to unverified numbers"


You can find the complete code at https://github.com/prabhatjha/infinispan-examples which is forked from https://github.com/mgencur/infinispan-examples .


[1] I work with Infinispan and JBoss Data Grid