Archive for the ‘ coldspring ’ Category

The Value Objects

Otherwise known as a transfer object is simply a design pattern for exchanging data between disparate systems. I’m working on a application with a Flex UI and a ColdFusion backend, and I initially discovered that if I return a query directly to Flex, it is converted into an ArrayCollection populated with simple Objects.

What I wanted was an array of specifically typed objects that I could cast as value objects in Flex. Here’s a very simplistic example of an Employee value object in Flex. It has two properties:

  • Employee ID
  • Employee Name

Flex Employee Value Object

package net.fusioncube.transferObjects
{
   [RemoteClass(alias="net.fusioncube.model.employee.Employee")]
   [Bindable]
   public class Employee
   {
      private var _employeeID:uint;
      private var _employeeName:String;

      /* constructor */
      public function Effort(employee_id:uint = 0,
                  employee_name:String = "")
      {
         this._employeeID= employee_id;
         this._employeeName= employee_name;
      }

        public function get employee_id():uint
        {
        	return _employeeID;
        }

        public function set employee_id(value:uint):void
        {
        	if(value != 0) _employeeID= value;
        }

        public function get employee_name():String
        {
        	return _employeeName;
        }

        public function set employee_name(value:String):void
        {
        	if(value != "") _employeeName= value;
        }
   }
}

You may have noticed the RemoteClass metadata applied to the Actionscript class. What this does is ensure that this Flex class maps directly to a ColdFusion component value object. To make a ColdFusion component value object is simple: you use the <cfproperty> tag for each property and specify each one’s type.

In this example, I’ve also added an init() method, whose use we’ll discover later.

ColdFusion Employee Value Object

<cfcomponent displayname="Employee" output="false">
   <cfproperty name="employee_id" type="numeric" default="" />
   <cfproperty name="employee_name" type="string" default="" />

   <cffunction name="init" access="public" returntype="net.fusioncube.model.employee.Employee" output="false">
      <cfargument name="employee_id" type="numeric" required="false"  />
      <cfargument name="employee_name" type="string" required="false"  /> 

      <cfset this['effort_id']       = arguments.effort_id />
      <cfset this['employee_name']      = arguments.employee_name />

      <cfreturn this />
   </cffunction>

</cfcomponent>

Converting a Query to an Employee Array

Again, as a very simple example, let’s say I have an EmployeeService component in my service layer and have a method listEmployees() that simply queries the employees table and returns all rows.

<cffunction name="listEmployees" access="public" output="false" returntype="query">
   <cfset var effortQuery = "" />

   <cfquery datasource="#variables.config.getSetting("datasource")#" name="employeeQuery">
   select e.* from employees e
   </cfquery>

   <cfreturn effortQuery />
</cffunction>

Since I don’t want to return a query, and I certainly don’t want to have two methods in every single component - one that returns a query and one that returns an array of objects - I use the handy, dandy AOP feature in ColdSpring to apply an advice that does it at runtime.

QueryToVOAdvice Advice

In this advice, I simply loop over the query’s rows and columns to create a simple structure containing the key/value pairs for each row. It then creates a new component for each query row by passing that structure to the init() function - which you saw above - and adds it to an array.

The result is an array of Employee-typed objects.

<cfcomponent displayname="QueryToVOAdvice" extends="coldspring.aop.MethodInterceptor">

   <cffunction name="init" returntype="utility.aop.advice.converters.QueryToVOAdvice" access="public" output="false">
      <cfreturn this />
   </cffunction>

   <cffunction name="invokeMethod" access="public" returntype="any">
      <cfargument name="methodInvocation" type="coldspring.aop.MethodInvocation" required="false" />

      <cfscript>
      var local = structNew();
      local.queryRow = 1;

      // Create an array to hold the value objects
      local.valueObjectArray = ArrayNew(1);

      // Store the resulting query object from the method execution
      local.queryObject = arguments.methodInvocation.proceed();

      // Loop over the query rows
      for(local.queryRow=1; local.queryRow lte local.queryObject.recordCount; local.queryRow = local.queryRow+1)
      {
         local.voStruct = structNew();

         // Loop over the query columns and create a key/value pair for each value
         // in this row of the query
         for(local.columnNum=1; local.columnNum lte listLen(local.queryObject.columnList); local.columnNum = local.columnNum+1)
         {
            local.columnName = listGetAt(local.queryObject.columnList, local.columnNum);
            local.voStruct[local.columnName] = local.queryObject[local.columnName][local.queryRow];
         }

         // Create an instance of the value object (obtained from the getValueObject method)
         // initializing it with the structure we created.  Add the value object to the array.
         arrayAppend(local.valueObjectArray, createObject('component', arguments.methodInvocation.getTarget().getValueObject()).init(argumentCollection=local.voStruct));
      }

      return local.valueObjectArray;
      </cfscript>
   </cffunction>

</cfcomponent>

ValueObject Property

For each of my beans, in this case the Employee bean, I can simply apply an advice in the definition. For this to work, I create a valueObject property in each component.

<component name="Employee">
   <cffunction name="setValueObject" access="public" output="false" returntype="void">
      <cfargument name="valueObject" type="string" required="true" />
      <cfset variables.valueObject = arguments.valueObject />
   </cffunction>

   <cffunction name="getValueObject" access="public" output="false" returntype="string">
      <cfreturn variables.valueObject />
   </cffunction>
</component>

Employee Bean Definition

Now when I define my Employee bean, I specify the type of the value object (the type that gets returned from the init() function), and then apply the advisor (shown below).

<bean id="Employee" class="coldspring.aop.framework.ProxyFactoryBean">
   <property name="target">
      <bean class="net.fusioncube.model.employee.EmployeeService">
         <property name="valueObject">
            <value>net.fusioncube.model.employee.Employee</value>
         </property>
      </bean>
   </property>
   <property name="interceptorNames">
      <list>
         <value>queryToValueObjectAdvisor</value>
      </list>
   </property>
</bean>

QueryToValueObjectAdvisor Definition

<bean id="queryToValueObjectAdvisor" class="coldspring.aop.support.RegexMethodPointcutAdvisor">
   <property name="advice">
      <bean class="utility.aop.advice.converters.QueryToVOAdvice"/>
   </property>
   <property name="pattern">
      <value>^list.*$</value>
   </property>
</bean>

The Flex Array of Typed Objects

Here’s an image of an example array I get back from ColdFusion in one of my current apps. You can see that each object was automatically converted into a Teammate (equivalent of an Employee) rather than a simple Object.

Caveat: If you’re passing back queries with a thousand or more rows, and are running CFMX 7 or older, then this solution may cause serious performance problems as object creation is notoriously “slow” in those versions of ColdFusion.

When to use autowiring in ColdSpring

Autowiring in ColdFusion

Most of you may have heard of autowiring, and many of you may have implemented it in an application by now (most likely with Spring, ColdSpring, or Google Guice).

If you don’t know what autowiring is, or are curious about how to do it, I’ll simply direct you to other people who have adequately explained it (see reference links at bottom of article) rather than doing it myself. This article is about when to use it, not how to use it.

Most people I talk to, or have read articles by, promote autowiring as a positive thing. It offers an effective way to automatically inject instantiated components into other components that require their methods. Who wouldn’t be a fan of that??

Nevertheless, there are gadflies who point out that the overuse of autowiring defeats one of the benefits of your bean definition file: a documentation tool. It is the one place in your application that clearly shows how services depends on each other. I believe this is a valid point, as I often use my definition file as a quick reference to my application’s dependencies.

Autowiring Incidental Dependencies

I prefer to use the autowiring feature for beans that are not business logic:

  • Datasources
  • Configuration settings
  • Resource libraries (e.g. Transfer ORM)
  • Transfer/Value objects

For example, several of my apps are written using Model-Glue, and I define beans to pass the application’s datasource, and transfer service:

<bean id="datasource" factory-bean="transfer" factory-method="getDatasource" />
<bean id="transferService" factory-bean="transfer" factory-method="getTransfer" />

Most of my beans require one, or both, of these services, and I’m reluctant to pass them in as constructor arguments since I consider them incidental dependencies, rather than logical dependencies. I see no benefit in having these clutter up my definition file since they offer no help to me, or anyone else, when determining if the Facility component requires the use of the Organization_Demographics component or not.

Instead of having dozens of these definitions filling up my definition file:

<bean id="DrugMapping" class="coldspring.aop.framework.ProxyFactoryBean">
   <property name="target">
      <bean class="&appCFCMapping;.model.request.item.drug.DetailService">
         <constructor-arg name="transfer">
            <bean factory-bean="transfer" factory-method="getTransfer" />
         </constructor-arg>
         <constructor-arg name="Offering">
            <ref bean="Offering" />
         </constructor-arg>
         <constructor-arg name="Party">
            <ref bean="Party" />
         </constructor-arg>
         <constructor-arg name="DetailGateway">
            <bean class="&appCFCMapping;.model.request.item.drug.DetailGateway">
               <constructor-arg name="transfer">
                  <bean factory-bean="transfer" factory-method="getTransfer" />
               </constructor-arg>
               <constructor-arg name="datasource">
                  <bean factory-bean="transfer" factory-method="getDatasource" />
               </constructor-arg>
            </bean>
         </constructor-arg>
         <constructor-arg name="datasource">
            <bean factory-bean="transfer" factory-method="getDatasource" />
         </constructor-arg>
      </bean>
   </property>
   <property name="interceptorNames">
      <list>
         <value>exceptionLoggingAdvisor</value>
      </list>
   </property>
</bean>

Instead I enjoy looking at a definition file that shows me how I’m wiring my application together.

<bean id="DrugMapping" class="coldspring.aop.framework.ProxyFactoryBean" autowire="byName">
   <property name="target">
      <bean class="&appCFCMapping;.model.request.item.drug.DetailService">
         <constructor-arg name="Offering">
            <ref bean="Offering" />
         </constructor-arg>
         <constructor-arg name="Party">
            <ref bean="Party" />
         </constructor-arg>
         <constructor-arg name="DetailGateway">
            <bean class="&appCFCMapping;.model.request.item.drug.DetailGateway" autowire="byName" />
          </constructor-arg>
      </bean>
   </property>
   <property name="interceptorNames">
      <list>
         <value>exceptionLoggingAdvisor</value>
      </list>
   </property>
</bean>

Reference Links

Joe Rinehart on autowiring
Nando demystifies autowiring
Download a small, sample app that provides autowiring code

The ColdFusion ServiceRunner - Part I

I’ve been meaning to share this for many reasons, but I’ve been bogged down with projects lately. However, it has allowed the code to mature and get streamlined a bit, so it’s good that some time has passed.

This is a pattern that we’ve come up with at work to handle remote calls to ColdFusion. It is one part of our SOA initiative that allows ColdFusion and Flex developers to make service calls to our core business components using a common approach.

I’ll start at the high level and work my way down. The reason I started this project is because early on I started to notice that there were many common entities used throughout the gamut of application used by my business unit - Facilities, Teammates, Drugs, Treatments, Patients, Doctors, etc…

Each application developer had written their own code to handle retrieving information on each of these entities. I’m sure you can see where the problem is in that, so I won’t belabor the point. To stop the fragmentation, I began diagramming how to create a common service application that could be accessed by any client in the company using a simple interface.

The Remote Call Service - RemotingService.cfc

Let’s start off with the first part of the puzzle: the simple interface for calling ColdFusion Component methods in our service application.

<cfcomponent output="false">

	<cffunction name="invokeService" access="remote" returntype="Any">
		<cfargument name="eventName" type="string" required="true" />
		<cfargument name="eventData" type="struct" required="false" default="#structNew()#" />

		<cfreturn application.beanFactory.getBean("ServiceRunner").run(argumentCollection=arguments) />
	</cffunction>

</cfcomponent>

Can’t get more simple than this. Using any remoting technology supporting SOAP, any client can invoke this component’s invokeService() method. This is the one entry point into our service application. As I’m sure you noticed by the application.beanFactory code, we’re using ColdSpring to manage all of our dependencies, AOP features, and event maps (more on this later).

The Service Response Value Object - ResponseVO.cfc

The next concept we tackled was not returning complex objects; we wanted a simple and logical structure to what gets returned to the client. Also we didn’t want the response object sitting around in memory sucking up RAM on the machine. We wanted this object to be created and destroyed on each remote request (shows below in the ServiceRunner code).

What got created was a simple Value Object that defines the keys of the response: name of the event, a success boolean, the data object, and an error structure (which is only populated if an error occurs).

<cfcomponent output="false"
	hint="Value object that is returned for every response">

	<cfproperty name="eventName"  type="string" />
	<cfproperty name="success"    type="boolean" />
	<cfproperty name="data"       type="any" />
	<cfproperty name="error"      type="Struct"/>

	<cfset this.eventName = "" />
	<cfset this.success = true />
	<cfset this.data = "" />
	<cfset this.error = structNew() />

</cfcomponent>

The Service Runner - ServiceRunner.cfc

Once we’d defined how services would be called and what the response would be, we then had to write the mechanism to actually execute the method and populate the response VO. The service runner is defined as a bean via ColdSpring (shown below) and is instantiated from the RemotingService component (shown above).

The RemotingService then calls the public run() method which creates a VO, executes the requested event using the private runEvent() method, and then returns the populated VO.

<cfcomponent output="false">

	<cffunction name="run" access="public" returntype="Any" output="false" description="Responds to remote request">
		<cfargument name="eventName" type="string" required="true" />
		<cfargument name="eventData" type="Struct" required="false" default="#structNew()#" />

		<cfset var local = StructNew() />
		<cfset var vo = createObject("component", "utility.remoting.ResponseVO") />

		<cfset vo.success 	= true />
		<cfset vo.eventName = arguments.eventName />

		<cftry>
			<cfset local.eventData = arguments.eventData />

			<cfif application.beanFactory.containsBean("event.#arguments.eventName#")>
				<cfset vo.data = runEvent(eventName=arguments.eventName, eventData=arguments.eventData) />
			<cfelse>
				<cfthrow detail="Event definition not found" message="event.#arguments.eventName# was not found." />
			</cfif>

			<cfcatch type="any">
				<cfset vo.success 	= false />
				<cfset vo.data 		= "" />
				<cfset vo.error 	= cfcatch />
			</cfcatch>
		</cftry>

		<cfreturn vo />
	</cffunction>

	<cffunction name="runEvent" access="private" returntype="any" output="false" hint="Calls the event defined in the EventMaps definition file">
		<cfargument name="eventName" type="string" required="true" />
		<cfargument name="eventData" type="Struct" required="true" />

		<cfset var local = structNew() />
		<cfset local.response = "" />

		<cfset local.eventInfo = application.beanFactory.getBean("event.#arguments.eventName#") />
		<cfset local.eventHandler = application.beanFactory.getBean(local.eventInfo.getBeanName()) />

		<cfinvoke component="#local.eventHandler#" method="#local.eventInfo.getMethodName()#" returnvariable="local.response" argumentcollection="#arguments.eventData#" />

		<cfreturn local.response />
	</cffunction>

</cfcomponent>

Defining Events as Beans - EventMaps.xml

To define our events, we create a bean for each one using the RemoteEventMap.cfc as the template for each one. The RemoteEventMap (code shown below) has two properties: beanName and methodName. These are used in the runEvent() method of the ServiceRunner (shown above) to obtain the properties needed for the CFINVOKE tag that executes the actual method we need.

<!DOCTYPE beans SYSTEM "ColdSpring.dtd"
[
   <!ENTITY appName "yourAppName">
   <!ENTITY appCFCMapping "&appName;.model">
   <!ENTITY eventCFCMap "utility.remoting.RemoteEventMap">
]>
<beans>
   <bean id="ServiceRunner" class="coldspring.aop.framework.ProxyFactoryBean">
      <property name="target">
         <bean class="utility.remoting.ServiceRunner" />
      </property>
      <property name="interceptorNames">
         <list>
            <value>metricsAdvisor</value>
         </list>
      </property>
   </bean>

   <bean id="event.getFacilities" class="&eventCFCMap;">
      <property name="beanName">
         <value>FacilityService</value>
      </property>
      <property name="methodName">
         <value>getHeldFacilities</value>
      </property>
   </bean>
</beans>

The Event Bean - RemoteEventMap.cfc

This is the simple RemoteEventMap that each event creates as a bean.

<cfcomponent output="false">

	<cffunction name="init" access="public" output="false" returntype="RemoteEventMap">
		<cfset variables.beanName = "" />
		<cfset variables.methodName = "" />

		<cfreturn this />
	</cffunction>

	<cffunction name="getBeanName" access="public" output="false" returntype="string">
		<cfreturn variables.beanName />
	</cffunction>

	<cffunction name="setBeanName" access="public" output="false" returntype="void">
		<cfargument name="beanName" type="string" required="true" />

		<cfset variables.beanName = arguments.BeanName />
	</cffunction>

	<cffunction name="getMethodName" access="public" output="false" returntype="string">
		<cfreturn variables.methodName />
	</cffunction>

	<cffunction name="setMethodName" access="public" output="false" returntype="void">
		<cfargument name="methodName" type="string" required="true" />

		<cfset variables.methodName = arguments.methodName />
	</cffunction>

</cfcomponent>

In Part II - which I will hopefully finish up tomorrow - I will show implementation examples of this pattern for ColdFusion and for Flex.

ColdSpring Low-Fat Double Inner-Bean Latte

I don’t know, when I was thinking about a name for the post, all the terms I was coming up with made me think of those coffee freaks at StarBucks ordering their custom cup o’ Joe.

Anyway, just wanted to share something that made my ColdSpring.xml file much cleaner and easier to manage/read. I use the AOP feature of the ColdSpring framework to add logging advice to my most heavily used components. This led to many, many, many beans in my config file as I had one for the gateway, one for the service and one for the proxy factory which wrapped around the service.

<bean id="VialDetailGateway" class="charm.model.request.item.vial.VialDetailGateway">
	<constructor-arg name="transfer">
		<bean factory-bean="transfer" factory-method="getTransfer" />
	</constructor-arg>
</bean>

<bean id="VialDetailTarget" class="charm.model.request.item.vial.VialDetailService">
	<constructor-arg name="transfer">
		<bean factory-bean="transfer" factory-method="getTransfer" />
	</constructor-arg>
	<constructor-arg name="VialDetailGateway">
		<ref bean="VialDetailGateway"/>
	</constructor-arg>
	<constructor-arg name="datasource">
		<bean factory-bean="transfer" factory-method="getDatasource" />
	</constructor-arg>
</bean>

<bean id="VialDetail" class="coldspring.aop.framework.ProxyFactoryBean">
       <property name="target">
		<ref bean="VialDetailTarget" />
       </property>
       <property name="interceptorNames">
		<list>
			<value>exceptionLoggingAdvisor</value>
		</list>
       </property>
</bean>

Then a few months ago, I was trolling the ColdSpring discussion boards and came across a post from Barney Boisvert where he mentions that he uses anonymous inner beans when creating the AOP proxy in order to prevent the creation of the actual service component.

It sounded like a good idea, so after implementing that, it reduced the amount of bean definitions in my config file by, you guessed it, 33%.

<bean id="VialDetailGateway" class="charm.model.request.item.vial.VialDetailGateway">
   <constructor-arg name="transfer">
      <bean factory-bean="transfer" factory-method="getTransfer" />
   </constructor-arg>
</bean>

<bean id="VialDetail" class="coldspring.aop.framework.ProxyFactoryBean">
   <property name="target">
      <bean class="charm.model.request.item.vial.VialDetailService">
         <constructor-arg name="transfer">
            <bean factory-bean="transfer" factory-method="getTransfer" />
         </constructor-arg>
         <constructor-arg name="VialDetailGateway">
            <ref bean="VialDetailGateway"/>
         </constructor-arg>
         <constructor-arg name="datasource">
            <bean factory-bean="transfer" factory-method="getDatasource" />
         </constructor-arg>
      </bean>
   </property>
   <property name="interceptorNames">
      <list>
         <value>exceptionLoggingAdvisor</value>
      </list>
   </property>
</bean>

Then it hit me today. I never directly access my gateway components, since there is a method in the service component that proxies each gateway method. If I don’t use the gateway beans, I thought, why on Earth don’t I just make them inner beans of the service definition?

In the end, I’ve reduced the amount of bean definitions by, you guessed right again, 66% and now just have one bean definition for each component. Nice and clean, just the way I like it.

<bean id="VialDetail" class="coldspring.aop.framework.ProxyFactoryBean">
   <property name="target">
   <bean class="charm.model.request.item.vial.VialDetailService">
         <constructor-arg name="transfer">
            <bean factory-bean="transfer" factory-method="getTransfer" />
         </constructor-arg>
         <constructor-arg name="VialDetailGateway">
            <bean class="charm.model.request.item.vial.VialDetailGateway">
               <constructor-arg name="transfer">
                  <bean factory-bean="transfer" factory-method="getTransfer" />
               </constructor-arg>
            </bean>
         </constructor-arg>
         <constructor-arg name="datasource">
            <bean factory-bean="transfer" factory-method="getDatasource" />
         </constructor-arg>
      </bean>
   </property>
   <property name="interceptorNames">
      <list>
         <value>exceptionLoggingAdvisor</value>
      </list>
   </property>
</bean>

Invoking ColdSpring beans with ajaxCFC

As a heavy user of Rob Gonda’s ajaxCFC library, I’ve incorporated it into almost every app I’ve written in the past two years. The only restriction that required me to write workarounds was the fact that you could only invoke ColdFusion Components directly. The thing is, I also love ColdSpring to manage dependencies and to implement my Aspect Oriented Programming components.

What I want is to be able to call my ColdSpring beans with ajaxCFC so that I can make my asynchronous calls, get serialized data back, and all the while utilizing the dependencies set up in my beans. Well, I finally got around to modifying Rob’s code to allow for this. I use the jQuery branch, so my solution currently only works for that implementation. I may try to work on the DWR version, but that’s unlikely because I don’t use it.

There are three changes to how you invoke ajaxCFC in order to work with ColdSpring beans.

The URL Attribute

Instead of the URL value being the path to your logic component, its value should be the path to the ajax.cfc component

url:'com/company/common/ajax/ajax.cfc'

The Bean Attribute

This property’s value will be the name of the ColdSpring bean you want to use.

bean: 'Facility'

The Factory Attribute

This property’s value will be the name of your ColdSpring bean factory.

factory:'application.beanFactory'

A Complete Invocation

Here’s a sample call stripped directly from one of my applications

$.AjaxCFC({
	url:'com/company/common/ajax/ajax.cfc',
	bean: 'Facility',
	factory:'application.beanFactory',
	method: 'getFacilities',
	data: { 'orderby':orderByField },
	useDefaultErrorHandler: false,
	success: function(results) {
		$("#facilitySelectContainer").html(results);
	},
	error: function(results) {
		Ext.MessageBox.alert('Error Notification', 'There was an error while loading the facilities. Please try again.')
	}
});

The Code

There are two files you need to replace.

  1. ajax.cfc
  2. jquery.AjaxCFC.js

Download ColdSpring-enabled ajaxCFC