Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

Model-Driven Development with ColdFusion and UML

Generating Code from Class Diagrams

The sign of an experienced developer is solid design. Novices edit examples they find on the Net, journeymen figure out how to code something as they do it, but craftsmen plan their work. Starting out, this can look like wasted time, but if your app is any good, your customer will want to expand it. Then, if you need some help, you'll have to explain all that intuitive code to ten people, all of whom you are paying by the hour. Diagrams would be nice then, right?

Many development organizations are moving toward more structured development cycles, involving formal documentation standards, to ensure that code is maintainable after the developer moves away from the project. For these organizations, the challenge is to balance the demand for rapid development with the requirement for clear, solid design and analysis documents.

For developers, it is annoying to go through the trouble of writing all of those class, property, method, and argument names only to have to do it again in the database and in the code. Wouldn't it be great to do that once and then fill in the details -- kind of sketch out the application - so that the model would drive the development and get developers enthusiastic about the whole process? In this article I'll illustrate how to do this by taking a UML class diagram and using it to generate ColdFusion code. From this simple starting point, one could go on to create stubs for complex CFCs, tables, stored procedures, unit tests and even simple CRUD GUIs.

A Picture Is Worth a Thousand Words
To start, we need to find a diagramming tool that is capable of exporting its diagrams in a text format. UML tools generally seem to be using XMI (XML Metadata Interchange) to handle this, and Gentleware's Poseidon Community Edition comes to our rescue as a capable, free editor. The downside is that XMI is pretty verbose. Diagram two or three classes and you're already clocking hundreds of lines of text. The upside is that it's XML, and with ColdFusion's XML functions for parsing and searching, we'll be able to tackle this with ease... after we figure out the format of that huge file. Now that we have a tool to edit our diagrams and save them to text, we can plan our application. We're writing a tool to generate code from diagrams, so let's start by diagramming. That way we'll have something to generate at the end of this article. We know that we'll have to do at least four things: parse the XMI; create a model of our results that is easy to manipulate; generate code based on the model; and, finally, do something with the generated code (write to a file, execute, etc.). These things are likely to be complicated enough that they will involve a set of functions, so, on our diagram, we'll create four classes to start with: XMI_Parser, Generator, Model, and Writer.

Parsing the XML
First we'll have to get our tool to export an XMI version of our diagram. In Poseidon, this is as simple as File->Export Project to XMI. Open up the diagram you created earlier and export it to XMI, then open it in a text editor or an XML editor. You will see, as you browse through the file, that there is a lot of layout markup that is irrelevant to us: We're only interested in 17 of this file's 660 lines! The XML will get more and more complex as we add functions, attributes and new datatypes. We will need to find the information that is relevant to our application design, then extract and simplify it to make it easier to work with for the rest of the project. (see Figure 1) This requires a function that wraps a series of XPath queries by way of ColdFusion's xmlSearch. We'll put that on our diagram as a public function in the XMI_Parser class as "createModelFromFile," which will take a string called fileName (the path to the XMI file) and return a Model object. Poseidon shows this as "+createModelFromFile(fileName:string):Model." For our purposes, we start by identifying classes used in the diagram:

    <cfscript>
      xmlDoc = xmlparse('OpenModel.xmi');
      classes = xmlsearch(xmlDoc,"//UML:Class[@xmi.id]");
      classesLen = arrayLen(classes);
      for(i=1;i lte classesLen;i=i+1){
        thisClass = classes[i];
        //now loop down into properties, methods and arguments
      }
    </cfscript>

Deconstructing the XPath Query
Our XPath query for classes looks through the whole XML document for all elements of type UML:Class that have an xmi.id element ("[@xml.id]]"), regardless of their position in the document ("//"), and returns an array of ColdFusion XML objects that match. Listing 1 shows the XML element describing our XMI_Parser class at this point in the design.
We can see that we are interested in elements of type UML:Class that contain elements of type UML:Attribute and UML:Operation. UML:Operation elements also contain UML:Parameters, some of which are input (kind="in") and some of which are output (kind="return"). The subelements refer to other Classes or Datatypes for their type info: <UML:DataType xmi.idref = '1'/>. Somewhere in our diagram there is a Class or Datatype that has xmi.id = '1' to match this reference. These IDs are assigned by the tool to track the entities being diagrammed. When we want to determine an element's type (e.g, string, date, etc.), we can do an XPath query to look it up:

thisMethodReturnsDataType = xmlsearch(xmlDoc,"//*[@xmi.id='#thisMethod.returnParam_XMI_IDREF#']");

Creating the Model
You can see now what we have to do. We are going to loop over the results of the classes XPath query, building a ColdFusion structure as we go that simplifies and abstracts the XML we are reading. For each Class, we will loop over the nested Attributes (properties for us), then the Operations (functions for us). For each Operation, we will loop over its Parameters (arguments). At the end of the day, we have a ColdFusion structure that looks like this:

COMPONENTNAME e.g."XMI_Parser"[
   name [string]
   displayname [string]
   hint [string]

    PROPERTIES[
      PROPERTYNAME[
        name [string]
        type [string]
        required [BOOLEAN]
        displayname [string]
        hint [string]
        default [string]
      ]
    ]
    FUNCTIONS[
      FUNCTIONNAME[
        string name [string]
        access [string]
        returntype [string]
        roles [string]
        hint [string]
        output [BOOLEAN]
        ARGUMENTS[
          ARGUMENTNAME[
            name [string]
            type [string]
            required [BOOLEAN
            default [string]
            hint [string]
          ]
        ]
      ]
    ]
]

To ensure that we have a consistent interface to this data structure, we'll add functions to our Model class to add or remove information. Let's update our diagram with: addComponent, deleteComponent, addProperty, deleteProperty, addMethod, deleteMethod, addArgument, and deleteArgument. We'll also add functions called getModel (to return our populated struct), serialize (in case we want to save our struct to a file for later use), and deserialize (to populate a Model from a previously saved state), as well as a private property called componentStruct to keep track of everything as we go.


More Stories By Chip Temm

Over the past decade, Chip Temm moved from North America to Europe and on to Africa where his company anthroLogik solutions provided analysis and development services organizations across seven timezones. He is currently back in Washington, DC where "remote development" means working from home and "wildlife" means raccoon.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture was Octoblu, a cross-protocol Internet of Things (IoT) mesh network platform, acquired by Citrix. Prior to co-founding Octoblu, Chris was founder of Nodester, an open-source Node.JS PaaS which was acquired by AppFog and ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...