Asterisk-java + Spring

Those who don’t know about Asterisk Java, its a wonderful java library to talk to a asterisk server through AGI & AMI. We are using it heavily to control our Asterisk box from our “main application”. Our main application is a full fledged spring application running on tomcat. At first we were running the asterisk java components (AGIServer , AgiScripts etc) as a normal java application but soon we wanted our AgiScripts to talk to our spring beans Or even better, we want our agi scripts to be Spring beans.

The beauty of the spring and asterisk-java library is that they were made for each other! Asterisk java library was written in wonderful object-oriented way with clear separation on dependencies. So it was very easy to define the AGIServer and all its dependencies as Spring Bean. So We can inject the MappingStrategy with our own implementation of “BeanNameAwareAGIMappingStrategy” which implements ApplicationContextAware looks like this

 @Override
 protected AgiScript createAgiScriptInstance(String beanName) {
        Object bean = applicationContext.getBean(beanName)
        if(bean == null) {
           throw new IllegalArgumentException(\"No bean with name: [\" + beanName +\"] found. Make sure that you have all beans defined which are there in your fastagi-mapping.properties\");
        }

        if(!(bean instanceof AgiScript)) {
          throw new IllegalArgumentException(\"spring bean : \" + beanName + \" must implement org.asteriskjava.fastagi.AgiScript interface\");
        }

        return (AgiScript) bean;
}

So now, instead of defining fully qualified classnames in your “fastagi-mapping.properties”, you only give the bean name and our mapping strategy looks it up from the application context. So your plain agi scripts can talk to your dao, services and do all sort of fancy things! Isn’t that wonderful!