Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex, ColdFusion

Adobe Flex: Article

Advanced Ant for Adobe Flex Projects

How to use Ant to automate HTML wrappers creation and more

Why Ant?

Typically, Flex developers use Flex Builder IDE, but Adobe also offers free Flex SDK, and  you should know how to build your applications without Flex Builder, and here’s why:
•    There is no simple way to share all your project settings (including absolute source paths) with another user.
•    If your project consists of many subprojects (some library projects, server side J2EE code) you may need to build each project in different IDEs, in a specific order.
•    At the time of this writing, there is no Flex Builder for Linux and only beta version for Macs exists. What about cross-platform?
•    And finally, Flex Builder costs money.

If you came from the Java world you knew the answer: projects could be built with Apache Ant tool. But if you used to be a Flash developer, you entirely depended on Flash IDE, binary .fla files and nightmare  builds. If you never had a chance using Ant, read the article from Farata Systems blog Intro to Building and Deploying Flex Applications with Ant.

Now with Adobe Flex SDK and Apache Ant you can easily formalize the way your projects are  built and deployed, and this can be done by any member of your team. Just type ant in the command window  and your build process is taken care off! Well, not that easy, you have to make sure that your build script is correct, the source code files are in place and compile without errors, et all.

On the other hand, Ant build gives your colleagues a possibility of customizing application view (via CSS), some data (with external mx:Model or mx:XML) and i18n (through resource bundles). Having your  build file, a person responsible for building your project can make all these changes by himself. No more developer's headaches with changing border color or font size.

Also, Ant builds are very useful for implementing Continuous Integration, Unit Testing and other development methodologies.

A Sample project

Download the source code of the sample project . This application  just contains a login form and log authentication data to XPanel, an open source trace component from Farata Systems. The project directory structure is very simple:
/
----- src // our source files
----- lib // our libs
----- src // libs with sources
----- swc // binary libs – not used  in my sample project

Our build  will also include debug and release directories  – for debug and release versions.

Ant Build Basics

Now we want create a cross-platform build file for our test project, which will only include the  path to Flex SDK. Our build will be based on these artifacts:

•    mxmlc.jar – a cross-platform compiler for Flex and ActionScript projects.
•    flex-config.xml – a special compilation configuration file as an easy way to externalize compilation settings.
•    html-wrappers – a set of templates for representing your application in World Wide Web.

You can find  more information about Ant at Apache Ant website. And don't forget to go through the article  on Ant best practices.

Flex mxmlc compiler can accept arguments both from command line and a special flex-config.xml file (feel free to rename it as you like). And you can combine both methods. And don't forget about compiler options precedence! So you can find base flex-config.xml at {flex.sdk.home}/frameworks/ flex-config.xml. We will modify it for our build (including the source and library paths). Why not modify original flex-config.xml in its location? Because you use SDK's flex-config.xml in many projects. And remember, other people may need to run your build script on their computers, which have unmodified flex-config.xml in Flex SDK directory.

Flex config is more readable than command-line parameters, it allows comments and is more structured.

Compiling

Let's create simple compile macro which we will use in build:

    <!-- = = = = = = = = = = = = = = = = =
          macrodef: mxmlc.compile          
         = = = = = = = = = = = = = = = = = -->
    <macrodef name="mxmlc.compile">
        <attribute name="in" />
        <attribute name="out" />
        <attribute
            name="config"
            default="${flex.config.xml}" />
        <attribute
            name="additional"
            default="" />
        <sequential>
            <java
                jar="${mxmlc.jar}"
                fork="true"
                maxmemory="512m"
                failonerror="true">
                <arg value="+flexlib=${flex.sdk.dir}/frameworks"/>
                <arg value="[email protected]{config}"/>
                <arg value="[email protected]{out}"/>
                <arg line="@{additional}"/>
                <arg value="@{in}" />
            </java>
        </sequential>
    </macrodef>

Note the  flexlib variable. We will use ${flexlib} in flex-config.xml as a pointer to Flex SDK install to resolve mxmlc executable directory which will point to our project root. If we skip it,  you may run into issues with locating embed fonts, and we have to explicitly point at *.ser file and lose the cross-platform nature of the build process. With ${flexlib}, *.ser will include automatically for each platform.

Creating an HTML wrapper

Now we need to take care of  html wrappers (Flex Builder create them for you, but we are preparing the build that can create them for us automatically). Flex 2 SDK contains a number of  wrapper templates in {flex.sdk.home}/resources/html-templates: one with client side Flash Player detection, another with no player detection,  and the third type is with Flash Player Express Install feature. Each  of these templates has two modifications: with History Manager support and without it. You can choose one of these six templates or create your own. In our build we’lll choose express-installation-with-history (see the wrapper.dir property in our build.xml).

Each template is a set of necessary files with index.template.html as target html. index.template.html contains a number of variables (${title} , ${version_major}, ${version_minor}, ${version_revision}, ${width}, ${height}, ${application}, ${bgcolor}, ${swf}), which need to be replaced with desired values. And finally we'll rename the index.template.html.

Let’s review two ways to create a wrapper. The first approach is based on Ant's  expandproperties task:

    <!-- - - - - - - - - - - - - - - - - -
          target: copy.wrapper                      
         - - - - - - - - - - - - - - - - - -->
    <target name="copy.wrapper">
        <copy todir="${build.dir}">
            <fileset dir="${wrapper.dir}">
                <exclude name="**/index.template.html" />
            </fileset>
        </copy>
        <copy file="${wrapper.dir}/index.template.html" tofile="${output.html}"
                                                                                                              encoding="utf-8">
            <filterchain>
                <expandproperties />
            </filterchain>
        </copy>
    </target>

The target from the build script above is the simplest way of creating a wrapper (don't forget to define properties with the same names as in index.template.html). But it is reasonable for simple projects with one html file.

Using Ant task ReplaceRegExp

Now we want to create the debug and release versions with different html titles. A real-world project can contain many different htmls and you need more flexible solution - let's create one!

We'll find all occurrences of ${something} tokens in index.template.html and replace them with the real values. In my opinion, the  replaceregexp task is the best solution for it. This task goes  through the template file and replaces the occurrence of a given regular expression with supplied substitution pattern. We won't use all the power of regular expressions but only some basics (you can learn more about regular expressions in from Flex documentation).

Our target variables (${something}) contains tree regexp metacharacters: $, { and }. We need escape them with \. Don't forget about global replacement and corresponding ReplaceRegExp flags:

            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{width\}"
                replace="@{width}"/>

Including copying templates from {flex.sdk.home}/resources/html-templates our make.wrapper macro will look in the following way:

    <!-- = = = = = = = = = = = = = = = = =
          macrodef: make.wrapper          
         = = = = = = = = = = = = = = = = = -->
    <macrodef name="make.wrapper">
        <attribute name="width" default="100%" />
        <attribute name="height" default="100%" />
        <attribute name="title" default="" />
        <attribute name="version.major" default="9" />
        <attribute name="version.minor" default="0" />
        <attribute name="version.revision" default="0" />
        <attribute name="application" default="" />
        <attribute name="swf" default="" />
        <attribute name="bgcolor" default="#869ca7" />
        <attribute name="wrapper.dir" />
        <attribute name="output.dir" />
        <attribute name="output.html" />
        <sequential>
            <copy todir="@{output.dir}">
                <fileset dir="@{wrapper.dir}">
                    <exclude name="**/index.template.html" />
                </fileset>
            </copy>
            <copy
                file="@{wrapper.dir}/index.template.html"
                tofile="@{output.html}" />
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{width\}"
                replace="@{width}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{height\}"
                replace="@{height}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{title\}"
                replace="@{title}"
                encoding="utf-8"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{version_major\}"
                replace="@{version.major}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{version_minor\}"
                replace="@{version.minor}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{version_revision\}"
                replace="@{version.revision}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{application\}"
                replace="@{application}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{bgcolor\}"
                replace="@{bgcolor}"/>
            <replaceregexp
                file="@{output.html}"
                flags="gs"
                match="\$\{swf\}"
                replace="@{swf}"/>
        </sequential>
    </macrodef>

Please note how we replaced the  html title. Don't forget about encoding for non-Latin symbols, if needed. We explicitly set it to utf-8.

The Finishing Touches

You can examine full build.xml by downloading sample project (link), which consists of the following  targets:

•    build -  The main public target. Preforms entire build.
•    Clear - Clears build directory before the build.
•    init -  Set build directories before the build.
•    compile.release, compile.debug -  Compiles application.
•    make.release.wrapper, make.debug.wrapper -  Creates html wrappers.

You can run targets separately from command line or from Eclipse Ant view.

Also look at the file local.properties in the project root of the sample applications. It contains commented out flex.sdk.dir property:
#flex.sdk.dir = C:\\Program Files\\Adobe\\flex_sdk_2\\

Uncomment it and replace with directory that points at your Flex framework install. You should not  store local.properties in your version control system, because it contains only the values applicable to your PC.

A complete version of the Ant build file is included in the sample application. Re-read this  article while peeking at this build.xml file - isn't  studying of someone else's  source code the best way to learn?

Summary

In this short article I’ve highlighted some important elements of Ant build process, and automating creation of HTML wrappers. Hopefully you found some not-so-obvious advises on using Ant in your Flex application. Good luck with your Ant builds!
 

More Stories By Konstantin Kovalev

Konstantin Kovalev "aka Constantiner" is an independent contractor presently working for Farata Systems. He is professional Flex developer and former Flash developer. Konstantin is active participant of Russian Flex community and creator of Russian blog resource www.riapriority.com dedicated to RIAs and Flash platform. Konstantin lives in St.Petersburg, Russia.

Comments (1)

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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
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...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
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...
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...