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
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
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...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
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...