refcards

  • submit to reddit

Getting Started with Spring-DM

By Craig Walls

16,699 Downloads · Refcard 57 of 151 (see them all)

Download
FREE PDF


The Essential Spring-DM Cheat Sheet

Spring is a framework that promotes development of loosely coupled/highly cohesive objects through dependency injection and interface-oriented design. Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This DZone Refcard shows you how to use Spring-DM to wire together OSGi services to build highly modular and dynamic applications. You may also enjoy the other Spring DZone Refcardz in our Collection: Spring Configuration and Spring Annotations.
HTML Preview
Getting Started with Spring-DM

Getting Started with Spring-DM

By Craig Walls

about spring-dm

Spring is a framework that promotes development of looselycoupled/ highly-cohesive objects through dependency injection and interface-oriented design. OSGi is a framework specification that promotes development of loosely-coupled/ highly-cohesive application modules through services and interface-oriented design. Seems like a match made in heaven! Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This reference card will be your resource for working with Spring- DM to wire together OSGi services and ultimately building modular applications.

You may be interested to know that Spring-DM is the basis for the SpringSource dm Server, a next-generation application server that embraces modularity through OSGi. What’s more, the upcoming OSGi R4.2 specification includes a component model known as the OSGi Blueprint Services that is heavily influenced by Spring-DM.

Introducing Spring-DM

The star player of Spring-DM is a bundle known as the Spring- DM extender. The Spring-DM extender watches for bundles to be installed and inspects them to see if they are Springenabled (that is, if they contain a Spring application context definition file). When it finds a Spring-enabled bundle, the extender will create a Spring application context for the bundle.

Spring Application Contexts

Spring-DM also provides a Spring configuration namespace that enables you to declare and publish Spring beans as OSGi services and to consume OSGi services as if they were just beans in a Spring application context. This declarative model effectively eliminates the need to work with the OSGi API directly.

Installing Spring-DM

One of the nice things about Spring-DM is that you do not need to include it in the classpath of your OSGi bundles or even reference it from those bundles. Installing Spring-DM involves two parts:

  1. Installing the Spring-DM and supporting bundles in your OSGi framework
  2. Adding the Spring-DM configuration namespace to your bundle’s Spring configuration XML files

You can download Spring-DM from
http://www.springframework.org/osgi. The distribution comes complete with everything you need to work with Spring- DM, including the Spring-DM extender bundle and all of its dependency bundles.

Installing the Spring-DM extender bundles

There are several means by which you can install bundles into an OSGi framework, depending on the OSGi framework and any add-ons or tools you may be using. But the most basic way is to use the “install” command that is available in most OSGi framework shells. For example, to install the Spring- DM extender bundle and the supporting Spring-DM bundles (assuming that you’ve unzipped the Spring-DM distribution in / spring-dm-1.2.0):


osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-core-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-extender-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-io-
   1.2.0.jar

Spring-DM depends on the Spring framework, so you’ll also need to install several other Spring bundles:

refcardzad


osgi> install file:///spring-dm-1.2.0/lib/spring-aop-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-context-
    2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-core-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-beans-2.5.6.A.jar

Finally, you’ll also need to install several other supporting bundles that Spring and Spring-DM depend on:


osgi> install file:///spring-dm-1.2.0/lib/com.springsource.net.
   sf.cglib-2.1.3.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.org.
   aopalliance-1.0.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   api-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   log4j-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   org.apache.commons.logging-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/log4j.osgi-1.2.15-
   SNAPSHOT.jar

Hot Tip

Use tools to help install bundles Installing bundles using the “install” command should work with almost any OSGi framework, but it is also quite a manual process. Pax Runner (http:// paxrunner.ops4j.org) is an OSGi framework launcher that takes a lot of the tedium out of installing bundles. Just use Pax Runner’s “spring dm” profile: % pax-run.sh --profiles=spring.dm

The Spring-DM configuration namespace

Schema URI:

http://www.springframework.org/schema/osgi

Schema XSD:

http://www.springframework.org/schema/osgi/spring-osgi.xsd

When it comes to declaring services and service consumers in Spring-DM, you’ll use Spring-DM’s core namespace. To do that, you’ll need to include the namespace in the XML file.


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xmlns:osgi=”http://www.springframework.org/schema/osgi”
	xsi:schemaLocation=”http://www.springframework.org/
schema/beans
	    http://www.springframework.org/schema/beans/
spring-beans.xsd
		   http://www.springframework.org/schema/osgi
		     http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
...
</beans>

Spring’s “beans” namespace is the default namespace, but if you know that most or all of the elements in the Spring configuration file will be from the Spring-DM namespace, you can make it the default namespace:

spring beans

Publishing Services

To demonstrate Spring-DM’s capabilities, we’re going to create a few OSGi services that translate English text into some other language. All of these services will implement the following Translator interface:


package com.habuma.translator;
public interface Translator
   {
String translate(String text);
}

The first service we’ll work with is one that translates English into Pig Latin. It’s implementation looks something like this:


package com.habuma.translator.piglatin;
import com.habuma.translator.Translator;
public class PigLatinTranslator implements Translator {
	private final String VOWELS = “AEIOUaeiou”;
	public String translate(String text) {
	  // actual implementation left out for brevity
	}
}

If we were working with basic OSGi (that is, without Spring- DM), we’d publish this service to the OSGi service registry using the OSGi API, perhaps in a bundle activator’s start() method:


public void start(BundleContext context) throws Exception {
	context.registerService(Translator.class.getName(),
				new PigLatinTranslator(), null);
}

Although the native OSGi approach will work fine, it requires us to work programmatically with the OSGi API. Instead, we’ll publish services declaratively using Spring-DM. The first step: Create a Spring context definition file that declares the PigLatinTranslator as a Spring bean:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
		  http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean id=”pigLatinTranslator”
    class=”com.habuma.translator.piglatin.PigLatinTranslator” />
</beans>

Hot Tip

Overriding the context configuration location By default, the Spring-DM extender looks for all XML files located in a bundle’s META-INF/spring folder and assumes that they’re all Spring context definition files that are to be used to create a Spring application context for the bundle; however, if you’d like to put your context definition files elsewhere in the bundle, use the Spring-Context: header in the META-INF/ MANIFEST.MF file.
For example, if you’d rather place your Spring configuration files in a directory called “spring-config” at the root of the bundle, add the following entry to your bundle’s manifest: Spring-Context: spring-config/*.xml

This Spring context file can be named anything, but it should be placed in the Pig Latin translator bundle’s META-INF/ spring directory. When the bundle is started in an OSGi framework, the Spring-DM extender will look for Spring context configuration files in that directory and use them to create a Spring application context for the bundle.

Publishing a simple OSGi service

By itself the Spring context we’ve created only creates a bean in the Spring application context. It’s not yet an OSGi service. To publish it as an OSGi service, we’ll create another Spring context definition file that uses the Spring-DM namespace:


<<?xml version=”1.0” encoding=”UTF-8”?>
<<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/
spring-beans.xsd
			  http://www.springframework.org/schema/osgi
				http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
   <<service ref=”pigLatinTranslator”
	  interface=”com.habuma.translator.Translator” />
<</beans:beans>

Hot Tip

Don’t mix your Spring and OSGi contexts Although you can certainly define all of your bundle’s Spring beans and OSGi services in a single Spring context definition file, it’s best to keep them in separate files (all in META-INF/spring). By keeping the OSGi-specific declarations out of the normal Spring context definition, you’ll be able to use the OSGi-free context to do non-OSGi integration tests of your beans.

This new Spring context file uses Spring-DM’s element to publish the bean whose ID is “pigLatinTranslator” in the OSGi service registry. The ref attribute refers to the Spring bean in the other context definition file. The interface attribute identifies the interface under which the service will be available in the OSGi service registry.

Publishing a service under multiple interfaces

Let’s suppose that the PigLatinTranslator class were to implement another interface, perhaps one called TextProcessor. And let’s say that we want to publish the service under both the Translator interface and the TextProcessor interface. In that case, you can use the element to identify the interfaces for the service:


<service ref=”pigLatinTranslator”>
  <interfaces>
    <beans:value>com.habuma.translator.Translator</beans:value>
    <beans:value>com.habuma.text.TextProcessor</beans:value>
  </interfaces>
</service>

Auto-selecting service interfaces

Instead of explicitly specifying the interfaces for a service, you can also let Spring-DM figure out which interfaces to use by specifying the auto-export attribute:


<service ref=”pigLatinTranslator”
       auto-export=”interfaces” />

By setting auto-export to “interfaces”, it tells Spring-DM to publish the service under all interfaces that the implementation class implements. You can also set auto-export to “all-classes” to publish the service under all interfaces and classes for the service or “class-hierarchy.”

Publishing a service with properties

It’s also possible to publish a service with properties to qualify that service. These properties can later be used to help refine the selection of services available to a consumer. For example, let’s say that we want to qualify Translator services by the language that they translate to:


<rvice ref=”pigLatinTranslator”
      interface=”com.habuma.translator.Translator”>
<service-properties>
   <beans:entry key=”translator.language” value=”Pig Latin” />
 </service-properties>
</service>

The <service-properties> element can contain one or more <entry> elements from the “beans” namespace. In this case, we’ve added a property named “translator.language” with a value of “Pig Latin”. Later, we’ll use this property to help select this particular service from among a selection of services that all implement Translator.

Consuming Services

Now that we’ve seen how to publish a service in the OSGi service registry, let’s look at how we can use Spring-DM to consume that service. To get started, we’ll create a simple client class:


package com.habuma.translator.client;
import java.util.List;
import com.habuma.translator.Translator;
public class TranslatorClient {
  private static String TEXT = “Be very very quiet. I’m hunting
rabbits!”;
  public void go() {
     System.out.println(“ TRANSLATED: “ +
        translator.translate(TEXT));
  }
  private Translator translator;
  public void setTranslator(Translator translator) {
    this.translator = translator;
  }
}

TranslatorClient is a simple POJO that is injected with a Translator and uses that Translator in its go() method to translate some text. We’ll declare it as a Spring bean like this:


<?xml version=”1.0” encoding=”UTF-8”?>
		<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean class=”com.habuma.translator.client.TranslatorClient”
     init-method=”go”>
   <property name=”translator” ref=”translator” />
  </bean>
</beans>

As with the service’s Spring context declaration, the name of this Spring context definition can be named anything, but it should be placed in the client bundle’s META-INF/spring folder so that the Spring-DM extender will find it.

The bean is declared with the init-method attribute set to call the go() method when the bean is created. And we use the <property> element to inject the bean’s translator property with a reference to a bean whose ID is “translator”.

The big question here is: Where does the “translator” bean come from?

Simple service consumption

Spring-DM’s <reference> element mirrors the <service> element. Rather than publishing a service, however, <reference> retrieves a service from the OSGi service registry. The simplest way to consume a Translator service is as follows:


<reference id=”translator”
interface=”com.habuma.translator.Translator” />

When the Spring-DM extender creates a Spring context for the client bundle, it will create a bean with an ID of “translator” that is a proxy to the service it finds in the service registry. With that id attribute and interface, it is quite suitable for wiring into the client bean’s translator property.

Setting a service timeout

In a dynamic environment like OSGi, services can come and go. When the client bundle starts up, there may not be a Translator service available for consumption. If it’s not available, then Spring-DM will wait up to 5 minutes for the service to become available before giving up and throwing an exception.

But it’s possible to override the default timeout using the <reference> element’s timeout attribute. For example, to set the timeout to 1 minute instead of 5 minutes:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	timeout=”60000” />

Notice that the timeout attribute is specified in milliseconds, so 60000 indicates 60 seconds or 1 minute.

Optional service references

Another way to deal with the dynamic nature of OSGi services is to specify that a service reference is optional. By default, the cardinality of a reference to a service is “1..1”, meaning that the service must be found within the timeout period or else an exception will be thrown. But you can specify an optional reference by setting the cardinality to “0..1”:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	cardinality=”0..1” />

Filtering services

Imagine that we have two or more Translator services published in the OSGi service registry. Let’s say that in addition to the Pig Latin translator there’s also another Translator service that translates text into Elmer Fudd speak. How can we ensure that our client gets the Pig Latin service when another implementations may be available?

Earlier, we saw how to set a property on a service when it’s published. Now we’ll use that property to filter the selection of services found on the consumer side:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	filter=”(translator.language=Pig Latin)” />

The filter attribute lets us specify properties that will help refine the selection of matching services. In this case, we’re only interested in a service that has its “translator.language” property set to “Pig Latin”.

Consuming multiple services

But why choose? What if we wanted to consume all matching services? Instead of pin-pointing a specific service, we can use Spring-DM’s <list> element to consume a collection of matching services:


<list id=”translators”
	interface=”com.habuma.translator.Translator” />

The Spring-DM extender will create a list of matching services that can be injected into a client bean collection property such as this one:


private List<Translator> translators;
public void setTranslators(List<Translator> translators) {
  this.translators = translators;
}

Optionally, you can use Spring-DM’s <set> element to create a set of matching services:


<set id=”translators”
   interface=”com.habuma.translator.Translator” />

The <list> and <set> elements share many of the same attributes with <reference>. For example, to consume a set of all Translator services filtered by a specific property:


<set id=”translators”
interface=”com.habuma.translator.Translator”
filter=”(translator.language=Elmer Fudd)” />

Testing Bundles

Hopefully, you’re in the habit of writing unit tests for your code. If so, that practice should extend to the code that is contained within your OSGi bundles. Because Spring-DM encourages POJO-based OSGi development, you can continue to write unit-tests for the classes that define and consume OSGi services just like you would for any other non-OSGi code.

But it’s also important to write tests that exercise your OSGi services as they’ll be used when deployed in an OSGi container. To accommodate in-OSGi integration testing of bundles, Spring-DM provides AbstractConfigurableBundleCreatorTests, a JUnit 3 base test class from which you can write your bundle tests.

What’s fascinating is how tests based on AbstractConfigurableBundleCreatorTests work. When the test is run, it starts up an OSGi framework implementation (Equinox by default) and installs one or more bundles into the framework. Finally, it wraps itself in an on-the-fly bundle and installs itself into the OSGi framework so that it can test bundles as an insider.

Writing a basic OSGi test

To illustrate, let’s write a simple test that loads our Translator interface bundle and the Pig Latin implementation bundle:


package com.habuma.translator.test;
import org.osgi.framework.ServiceReference;
import org.springframework.osgi.test.
AbstractConfigurableBundleCreatorTests;


import com.habuma.translator.Translator;
public class PigLatinTranslatorBundleTest
      extends AbstractConfigurableBundleCreatorTests {
  @Override
  protected String[] getTestBundlesNames() {
     return new String[] {
		“com.habuma.translator, interface, 1.0.0”,
		“com.habuma.translator, pig-latin, 1.0.0”
      };
  }
  public void testOsgiPlatformStarts() {
    assertNotNull(bundleContext);
  }
}

The getTestBundleNames() method returns an array of Strings where each entry represents a bundle that should be installed into the OSGi framework for the test. The format of each entry is a comma-separated set of values that identify the bundle by its Maven group ID, artifact ID, and version number.

So far, our test has a single test method, testOsgiPlatformStarts(). All this method does is test that the OSGi framework has started by asserting that bundleContext (inherited from AbstractConfigurableBundleCreatorTests) is not null.

Testing OSGi service references

A more interesting test we could write is one that uses the bundle context to lookup a reference to the Translator service and assert that it meets our expectations:


public void testServiceReferenceExists() {
  ServiceReference serviceReference =
    bundleContext.getServiceReference(Translator.class.
getName());
	assertNotNull(serviceReference);
	assertEquals(“Pig Latin”,
       serviceReference.getProperty(“translator.language”));
}

Here we retrieve a ServiceReference from the bundle context and assert that it isn’t null. This means that some implementation of the Translator service has been published in the OSGi service registry. Then, it examines the properties of the service reference and asserts that the “translator.language” property has been set to “Pig Latin”, as we’d expect from how we published the service earlier.

Testing OSGi services

One more thing we could test is that the Translator service does what we’d expect it to do. Certainly, this kind of test usually belongs in a unit test. But it’s still good to throw a smoke test its way to make sure that we’re getting the service we’re expecting.

We could use the ServiceReference to lookup the service. But, we can avoid any additional work with the OSGi API by having the Translator service wired directly into our test class. First, let’s add a Translator property and setter method to our test class


private Translator translator;
public void setTranslator(Translator translator) {
  this.translator = translator;
}

When the test is run, Spring will attempt to autowire the property with a bean from its own Spring application context. But we haven’t defined a Spring application context for the test yet. Let’s do that now:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
   xsi:schemaLocation=”http://www.springframework.org/schema/
beans
      http://www.springframework.org/schema/beans/spring-beans.
xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd”>
  <reference id=”translator”
    interface=”com.habuma.translator.Translator” />
</beans:beans>

You’ll recognize that this Spring context definition looks a lot like the one we created for the service consumer. In fact, our test class will ultimately be a consumer of the Translator service. We just have one more thing to do before we can test the service—we’ll need to override the getConfigLocations() method to tell the test where it can find the context definition file:


@Override
protected String[] getConfigLocations() {
   return new String[] { “bundle-test-context.xml” };
}

Now we can write our test method:


public void testTranslatorService() {
	assertNotNull(translator);
	assertEquals(“id-DAY is-thAY ork-wAY”,
       translator.translate(“Did this work”));
}

This method assumes that by the time it is invoked, the translator property has been set. It first asserts that it is not null and then throws a simple test String at it to test that the service does what we expect.

Changing the tested OSGi framework

By default, Spring-DM tests are run within Equinox. But you can change them to run within another OSGi framework implementation such as Apache Felix or Knopflerfish by overriding the getConfigLocations() method. For example, to run the test within Apache Felix:


@Override
  protected String getPlatformName() {
    return Platforms.FELIX;
}

Or for Knoplerfish:


@Override
protected String getPlatformName() {
  return Platforms.KNOPFLERFISH;
}

Providing a Custom Manifest

When a Spring-DM test gets wrapped up in an on-the-fly bundle, a manifest will be automatically generated for it. But if you’d like to provide a custom manifest. To provide a custom manifest for the on-the-fly bundle, all you need to do is override the getManifestLocation(). For example:


protected String getManifestLocation() {
  return “classpath:com.habuma.translator.Translator.MF”;
}

Be aware, however, that if you provide a custom manifest, you must include a few things in that manifest to make Spring-DM testing work. First, you’ll need to specify a bundle activator:


Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator

And you’ll need to import JUnit and Spring-DM packages:


Import-Package: junit.framework,
  org.osgi.framework,
  org.apache.commons.logging,
  org.springframework.util,
  org.springframework.osgi.service,
  org.springframework.osgi.util,
  org.springframework.osgi.test,
  org.springframework.context

References

Example Source Code:

http://www.habuma.com/refcard/spring-dm/translator.zip

Spring-DM Homepage:

http://www.springframework.org/osgi

OSGi Alliance:

http://www.osgi.org

Modular Java on Twitter:

http://twitter.com/modularjava

Craig’s Modular Java Blog:

http://www.modularjava.com

Craig’s Spring Blog:

http://www.springinaction.com

56 76

About The Author

Photo of Craig Walls

Craig Walls

is a Texas-based software developer with more than 15 years experience working the telecommunication, financial, retail, education, and software industries. He’s a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring and OSGi on his blog. When he’s not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, and two dogs.

Craig’s Publications:

  • Modular Java: Creating Flexible Applications with OSGi and Spring, 2009
  • Spring in Action, 2nd Edition, 2007
  • XDoclet in Action, 2003

Craig’s Blog: http://www.springinaction.com

Recommended Book

Spring in action

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Recommended Book

ModularJava

Modular Java is filled with tips and tricks that will make you a more proficient OSGi and Spring-DM developer. Equipped with the know-how gained from this book, you’ll be able to develop applications that are more robust and agile.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Agile Adoption

Reducing Cost

By Gemba Systems

17,905 Downloads · Refcard 54 of 151 (see them all)

Download
FREE PDF


The Essential Agile Adoption Cheat Sheet

Adopting Agile methods in your projects is easier than you think. This DZone Refcard series focuses on building software faster, better, and cheaper. This Refcard in particular teaches you four practical strategies for reducing the cost of software development. Learn how specific Agile methods like evolutionary design, refactoring and automated testing will help you reduce costs and eliminate risks. Other topics covered include how to adopt Agile practices successfully, as well as what’s next in Agile and a wealth of references. You’ll also enjoy Agile Adoption: Decreasing Time to Market, the first Refcard in this Agile Adoption series.
HTML Preview
JavaServer Faces 2.0

Agile Adoption: Reducing Cost

By Gemba Systems

About this agile adoption refcard

Faster, better, cheaper. That’s what we must do to survive. The Time to Market Refcard (a companion in this series) addresses faster, the Quality Refcard addresses better, and this Refcard addresses cheaper. This is about building the system for less.

Some of the costs of software development are associated with man hours needed to build the system, others with cost of maintenance over time, and yet others include hardware as well as software platform costs. Practices that educe any or all of these costs without sacrificing quality reduce the overall cost of the system.

Then there is the Pareto principle – a.k.a. the 80/20 rule. This rule suggests that roughly 20% of the software system is used 80% of the time. This is also backed up by research that is even more dramatic [figure with usage]. Practices that help the team build only what is needed in a prioritized manner reduce the cost and still deliver the most important business value to the customer (the part she uses).

Figure 1 Practices that help reduce the cost of building software.

reducecost

You will be able to use this Refcard to get 50,000 ft view of what will be involved to reduce the cost of developing your systems.

Four Strategies to reduce cost

Software development is complex and often very complicated. It is HARD. This is not some new revelation, in fact Fred Brooks in the well known paper, “No Silver Bullet.”, states:

The essence of a software entity is a construct of interlocking concepts ...

I believe the hard part of building software to be the specification, design, and testing of this conceptual construct, not the labor of representing it and testing the fidelity of the representation.

There are four major strategies that can help you reduce the cost of building and maintaining your software

Maintain the Theory of the Code

Brain

One way to look at software development is ‘theory building’. That is, programs are theories – models of the world mapped onto software – in the head of the individuals of the development team. Great teams have a shared understanding of how the software system represents the world. Therefore they know where to modify the code when a requirement change occurs, they know exactly where to go hunting for a bug that has been found, and they communicate well with each other about the world and the software.

Conversely, a team that does not have a shared ‘theory’ make communication mistakes all the time. The customer may say something that the business analyst misunderstands because she has a different world view. She may, in turn, have a different understanding than the developers, so the software ends up addressing a different problem or, after several trials, errors and frustrations, the right problem but very awkwardly. Software where the theory of the team does not match, or even worse, the theory is now lost because the original software team is long-gone, is very expensive to maintain.

Building a shared theory of the world-to-software-mapping is a human process that is best done face-to-face by trial and error and with significant time.

Build Less

It has been shown that we build many more features than are actually used. In fact, we can see in Figure 2, only about 20% of functionality we build is used often or always. More than 60% of all functionality built in software is rarely or never used!

Building

One way to reduce the cost of software is to find a way not to build the unused functionality. There are several Agile practices that help you get to that point.

Pie Chart

Functionality Usage

Figure 2: Most functionality built is never used.

Pay Less for Bug Fixes

Typically, anywhere between 60%-90% of software cost goes into the maintenance phase. That is, most of our money goes into keeping the software alive and useful for our clients after the initial build. Practices that help us reduce the cost of software maintenance will significantly affect the overall cost of the software product or system.

Figure 3

Figure 3: Maintain the theory of the code helps reducing the cost of making design changes and fixing bugs. Building less enables better understanding and helps to understand the theory of the code for a change because there is less to change

Pay Less for Changes

The only thing constant in today’s software market is change. If we can embrace change, plan for it, and reduce its cost

when it eventually happens we can make significant savings. One of the strongest points of Agile development is that its practices enable you to roll with the punches and change your software as the business world changes.

Hand with money

The four strategies above: maintain the theory of the code, build less, paying less for maintenance and being able to react to change are not independent.

The practices

Evolutionary Design

Four Icons

Evolutionary Design

Evolutionary Design

Book Evolutionary design is the simple design practice done continuously. Start off with a simple design and change that design only when a new requirement cannot be met by the existing design.
Dollar Evolutionary design reduces the cost by focusing on always building less. This, in turn, directly affects the cost of change drastically.
Cubes You are on a development team practicing automated developer tests, refactoring, and simple design. That’s it, because this is one of those things that is applicable to all types of development projects. The context is especially a match if the technology used technologies is new to a large part of the team.

Simple Design

Evolutionary Design

Book If a decision between coding a design for today’s requirements and a general design to accommodate for tomorrow’s requirements needs to be made, the former is a simple design. Simple design meets the requirements for the current iteration and no more.
Dollar Simple design reduces cost because you build less code to meet the requirements and you maintain less code afterwards. Simple designs are easier to build, understand, and maintain.
Cubes Simple design should only be used when your team also is writing automated developer tests and refactoring. A simple design is fine as long as you can change it to meet future requirements.

Refactoring

Diagram1

Book The practice of Refactoring code changes the structure (i.e., the design) of the code while maintaining its behavioe.
Dollar Costs are reduced because continuous refactoring keeps the design from degrading over time, ensuring that the code is easy to understand, maintain, and change.
Cubes You are on a development team that is practicing automated developer tests. You are currently working on a requirement that is not well-supported by the current design. Or you may have just completed a task (with its tests of course) and want to change the design for a cleaner solution before checking in your code to the source repository.

Automated Developer Tests

Icons

Book Automated developer tests are a set of tests that are written and maintained by developers to reduce the cost of finding and fixing defects—thereby improving code quality—and to enable the change of the design as requirements are addressed incrementally.
Dollar Automated developer tests reduce the cost of software development by creating a safety-net of tests that catch bugs early and enabling the incremental change of design. Beware, however, that automated developer tests take time to build and require discipline.
Cubes You are on a development team that has decided to adopt iterations and simple design and will need to evolve your design as new requirements are taken into consideration. Or you are on a distributed team. The lack of both face-to-face communication and constant feedback is causing an increase in bugs and a slowdown in development.

Evocative Document

Brain Small

Book Evocative documents are documents that evoke memories, conversations, and situations that are shared by those who wrote the document. They are more meaningful and representative of a team’s understanding of the system than traditional documents.
Dollar Evocative documents help by accurately representing the team’s internal model of the software and allowing that model to be handed down from master to apprentice. The better understanding of the system over time also reduces the maintenance cost of the system over time because appropriate changes reduce the deterioration of the software.
Cubes Current documentation isn’t working – as a document is passed from one person to another much of the context and value is lost, and as a result, the maintenance team’s understanding of the codebase constantly deteriorates. This is resulting in the calcification of your software system.

Automated Acceptance Tests

Diagram and icons

Book Automated acceptance tests are tests written at the beginning of the iteration that answer the question: “what will this requirement look like when it is done?”. This means that you start with failing tests at the beginning of each iteration and a requirement is only done when that test passes.
Dollar This practice builds a regression suite of tests in an incremental manner and catches errors, miscommunications, and ambiguities very early on. This, in turn, reduces the amount of work that is thrown away and therefore enables building less. The tests also catch bugs and act as a safety-net during change.
Cubes You are on a development project with an onsite customer who is willing and able to participate more fully as part of the development team. Your team is also willing to make difficult changes to any existing code. You are willing to pay the price of a steep learning curve.

The remaining practices also help reduce the cost of software development. Because of the limited size of the refcard, we will only summarize them below.

img1 A backlog is a prioritized list of requirements that enable a team to build less by making sure they always work on the most important items first and help the team understand the theory of the code when used as an evocative document that shows a larger picture of the system.
img2 An iteration is a time-box where the team builds what is on the backlog and is a potential release and therefore enables building less.
img3 The done state is a definition agreed upon by the entire team of what constitutes the completion of a requirement. The closer the done state is to deployable software, the better it is because it forces the team to resolve all hidden issues early and thus reduces cost.
img4 The cross-functional team is one that has the necessary expertise among its members to take a requirement from its initial concept to a fully deployed and tested piece of software within one iteration. A requirement can be taken off of the backlog, elaborated and developed, tested, deployed.
img5 A self-organizing team is in charge of its own fate. Management gives the team goals to achieve and the team members are responsible for driving towards those goals and achieving them. A self-organizing team recognizes and responds to changes in their environment and in their knowledge as they learn. A self-organizing team is frequently a cross functional team as well.
img6 The Retrospective is a meeting held at the end of a major cycle - iteration or release - to gather and analyze data about that cycle and decide on future actions to improve the team’s environment and process. A retrospective is about evaluating the people, their interactions, and the tools they use.
img7 Continuous integration reduces the total time it takes to build a software system by catching errors early and often. Errors caught early cost significantly less to fix when caught later. It leverages both automated acceptance tests and automated developer tests to give frequent feedback to the team and to pay a much smaller price for fixing a defect.
img8 A user story is an evocative document for requirements. A user story is a very high level description of the requirement to be built –it usually fits on a 3 x 5 index card – and is a “promise for a conversation” later between the person carrying out the Customer Part of Team practice and the implementers.

How to adopt Agile practices successfully

To successfully adopt Agile practices let’s start by answering the question “which ones first?” Once we have a general idea of how to choose the first practices there are other considerations.

Become “Well-Oiled” First

One way to look at software development is to see it as problem solving for business. When considering a problem to solve there are two fundamental actions that must be taken:

  • Solving the right problem. This is IT/Business alignment.
  • Solving the problem right. This is technical expertise.

Intuitively it would seem that we must focus on solving the right problem first because, no matter how well we execute our solution to the problem, if it is the wrong problem then our solution is worthless. This, unfortunately, is the wrong way to go. Research shows in Figure 3, that focusing on alignment first is actually more costly and less effective than doing nothing. It also shows that being “well-oiled”, that is focusing on technical ability first, is much more effective and a good stepping-stone to reaching the state where both issues are addressed.

Figure 3.2

Figure 4: The Alignment Trap (from Avoiding the Alignment Trap in Information Technology, Shpilberg, D. et al, MIT Sloan Management Review, Fall 20078.)

This is supported anecdotally by increasing reports of failed Agile projects that do not deliver on promised results. They adopt many of the soft practices such as Iteration, but steer away from the technically difficult practices such as Automated Developer Tests, Refactoring, and Done State. They never reach the “well-oiled” state.

So the lesson here is make sure that on your journey to adopt Agile practices that improve time to market (or any other business value for that matter), your team will need to become “well-oiled” to see significant, sustained improvement. And that means you should plan on adopting the difficult technical practices for sustainability.

Know What You Don’t Know

The Dreyfus Model of Skill Acquisition, is a useful way to look at how we learn skills – such as learning Agile practices necessary to reduce cost. It is not the only model of learning, but it is consistent, has been effective, and works well for our purposes. This model states that there are levels that one goes through as they learn a skill and that your level for different skills can and will be different. Depending on the level you are at, you have different needs and abilities. An understanding of this model is not crucial to learning a skill; after all, we’ve been learning long before this model existed. However, being aware of this model can help us and our team(s) learn effectively.

So let’s take a closer look at the different skill levels in the Dreyfus Model:

Pyramid

Figure 5: The Dreyfus Model for skill acquisition. One starts as a novice and through ecperience and learning advances towards expertise.

How can the Dreyfus Model help in an organization that is adopting agile methods? First, we must realize that this model is per skill, so we are not competent in everything. Secondly, if agile is new to us, which it probably is, then we are novices or advanced beginners; we need to search for rules and not break them until we have enough experience under our belts. Moreover, since everything really does depend on context, and we are not qualified to deal with context as novices and advanced beginners, we had better get access to some people who are experts or at least proficient to help guide us in choosing the right agile practices for our particular context. Finally, we’d better find it in ourselves to be humble and know what we don’t know to keep from derailing the possible benefits of this new method. And we need to be patient with ourselves and with our colleagues. Learning new skills will take time, and that is OK.

Choosing a Practice to Adopt

Choosing a practice comes down to finding the highest value practice that will fit into your context. Figure 1 will guide you in determining which practices are most effective in decreasing your time to market and will also give you an understanding of the dependencies. The other parts in this section, How to Adopt Agile Practices Successfully?, discuss other ideas that can help you refine your choices. Armed with this information:

figure 5

Figure 5: Steps for choosing and implementing practices.

What Next?

This Refcard is a quick introduction to Agile practices that can help you reduce the cost of building and maintaining your software and an introduction of how you to choose the practices for your organizational context. It is only a starting point. If you choose to embark on an Agile adoption initiative, your next step is to educate yourself and get as much help as you can afford. Books and user groups are a beginning. If you can, find an expert to join your team(s). Remember, if you are new to Agile, then you are a novice or advanced beginner and are not capable of making an informed decision about tailoring practices to your context.

References

Column 1

Column 2

Column 3

Column 4

Column 5

Column 6

Column 7

Column 8

Column 9

Column 10

Column 11

Column 12

Column 13

Column 14

Astels, David. 2003. Test-driven development: a practical guide. Upper Saddle River, NJ: Prentice Hall. x x
Avery, Christopher, Teamwork is an Individual Skill, San Francisco: Berrett-Koehler Publishers, Inc., 2001 x
Bain, Scott L., 2008, Emergent Design, Boston, MA: Pearson Education x x x x
Beck, Kent. 2003. Test-driven development by example. Boston, MA: Pearson Education. x x
Beck, K. and Andres, C., Extreme Programming Explained: Embrace Change (second edition), Boston: Addison-Wesley, 2005 x x x x x x x x
Cockburn, A., Agile Software Development: The Cooperative Game (2nd Edition), Addison-Wesley Professional, 2006. x
Cohn, M., Agile Estimating and Planning, Prentice Hall, 2005. x x
Crispin, L. and Gregory, J., Agile Testing: A Practical Guide for Testers and Agile Teams x
Derby, E., and Larson, D., Agile Retrospectives: Making Good Teams Great, Raliegh: Pragmatic Bookshelf, 2006. x x
Duvall, Paul, Matyas, Steve, and Glover, Andrew. (2006). Continuous Integration: Improving Software Quality and Reducing Risk. Boston: Addison-Wesley. x
Elssamadisy, A., Agile Adoption Patterns: A Roadmap to Organizational Success, Boston: Pearson Education, 2008 x x x x x x x x x x x x x x
Feathers, Michael. 2005. Working effectively with legacy code. Upper Saddle River, NJ: Prentice Hall. x x
Jeffries, Ron. “Running Tested Features.” http://www.xprogramming.com/xpmag/jatRtsMetric.htm x
Jeffries, Ron. 2004. Extreme programming adventures in C#. Redmond, WA: Microsoft Press. x x
Kerth, N., Project Retropsectives: A Handbook for Team Reviews, NY: Dorset House Publishing Company, 2001. x
Kerievsky, Joshua. “Don’t Just Break Software, Make Software.” http://www.industriallogic.com/papers/storytest.pdf x
Larman, C., Agile and Iterative Development: A Manager’s Guide, Boston: Addison-Wesley, 2004 x x
Larman, C., and Vodde, B., Scaling Lean and Agile Development, Boston: Addison-Wesley, 2009 x x x
Massol, Vincent. 2004. Junit in action. Greenwich, CT: Manning Publications. x x
Meszaros, XUnit Test Patterns: Refactoring Test Code, Boston: Addison-Wesley, 2007 x x
Mugridge, R., and W. Cunningham. 2005. Fit for Developing Software: Framework for Integrated Tests. Upper Saddle River, NJ: Pearson Education. x
Poppendieck, M., and Poppendieck, T., Implementing Lean Software Development, Addison-Wesley Professional, 2006. x
Rainsberger, J.B. 2004. Junit recipes: Practical methods for programmer testing. Greenwich, CT: Manning Publications. x x
Schwaber, K., and Beedle, M., Agile Software Development with Scrum, Upper Saddle River, New Jersey: Prentice Hall, 2001. x x x x
Senge, P., The Fifth Discipline: The Art and Practice of The Learning Organization, NY: Currency 2006. x
Surowiecki, J., The Wisdom of Crowds, NY: Anchor, 2005. x

About Gemba Systems

Gemba Systems is comprised of a group of seasoned practitioners who are experts at Lean & Agile Development as well as crafting effective learning experiences. Whether the method is Scrum, Extreme Programming, Lean Development or others - Gemba Systems helps individuals and teams to learn and adopt better product development practices. Gemba Systems has taught better development techniques - including lean thinking, Scrum and Agile Methods - to thousands of developers in dozens of companies around the globe. To learn more visit http://us.gembasystems.com/

Recommended Book

Maven

Agile Adoption Patterns will help you whether you’re planning your first agile project, trying to improve your next project, or evangelizing agility throughout your organization. This actionable advice is designed to work with any agile method, from XP and Scrum to Crystal Clear and Lean. The practical insights will make you more effective in any agile project role: as leader, developer, architect, or customer.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Flex Mobile Development

Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

9,696 Downloads · Refcard 146 of 151 (see them all)

Download
FREE PDF


The Essential Flex Mobile Cheat Sheet

The Flex Mobile Development cheat sheet will walk you through the easiest process yet for developing and deploying cross-platform applications on multiple devices and platforms with the richness that you expect out of an Adobe creative tool. You can now develop mobile ActionScript and Flex applications for Google Android, Apple iOS, and BlackBerry Tablet OS with the same ease and quality as on desktop platforms, and with most of the same code! Get a rundown of the new Flash Builder 4.5s mobile app capabilities through a series of sections on app creation, mobile packaging, testing, and debugging.
HTML Preview
Flex Mobile Development: Build Apps for Android, iOS, and BlackBerry Tablet OS

Flex Mobile Development:Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

Adobe® Flash® Builder™ is an integrated development environment (IDE) based on the Eclipse platform. Available for Windows and Mac, it is used for creating Flex and Flash applications accessible via a web browser with Flash Player or as standalone apps.

Because it is based on the Eclipse platform (version 3.6.1), it can be installed as a standalone IDE or as a plug-in within another Eclipse installation.

You can run this version along with previous versions (Flash Builder 4 or Flash Builder 3) without any problems.

This version comes in two flavors: standard or premium. Each flavor is also available as Flash Builder 4.5 for PHP, which has all the features of Flash Builder plus Zend Studio 8.1 and a number of plug-ins that integrate these two IDEs.

Flash Builder Premium provides the following features in addition to those included with the standard version:

  • Network Monitor
  • Memory Profiler
  • HP QuickTest Professional and FlexUnit integration
  • Command-line support for automated build processes
  • ColdFusion Builder (an Eclipse-based IDE for ColdFusion application developers)

You can download Flash Builder 4.5 from here and Flash Builder 4.5 for PHP from here. Select the installer for the version you are interested in and for your operating system. The same installer can be used for installing the standalone version or the plug-in version.

Each version offers a 60-day trial period. Every time you start the product during the trial period you will see a reminder that enables you to buy the product or enter the serial number if you’ve already bought it.

To enable support for BlackBerry Tablet OS development you’ll have to download an Eclipse plug-in from RIM. Once installed in Flash Builder 4.5, this plug-in will enable a new platform target.

What’s new in Flash Builder 4.5

Here is a high level view of what is new in this release:

Support for mobile development. Flex 4.5 version marks the extension of the Flex framework to mobile development. Flash Builder 4.5 includes several mobile-specific features, including new project types, desktop simulation and design view, and support for packaging projects as native installers for Android, iOS, and BlackBerry Tablet OS.

Improved productivity. Code templates, quick assist, code hinting for metadata, and an improved profiler.

Expanded PHP support. Flash Builder for PHP integrates Zend Studio with Flash Builder:

  • New wizards for creating Flex and PHP projects for desktop or mobile.
  • Integrated debugging for PHP and Flex.

Flash Builder 4.5, Flex 4.5, and the screen metaphor

While it is possible to create mobile applications using pure ActionScript and Flash Builder 4.5, developing mobile apps using the Flex 4.5 framework, with its support for the screen metaphor, provides a substantial productivity boost.

There is almost always enough resolution and area on a desktop computer to fit all the information you want on the screen. By using hierarchical menus and pop-up windows you can fit even more content. Compared to this, a smartphone screen feels (almost) like a postage stamp. Besides screen size, pixel density plays an important role. The Nexus One, for example, has a resolution of 480 x 800 pixels and 254 pixels per inch. This means that you have to enlarge the text roughly two to four times to make it appear similar to the app running on a desktop or laptop screen. Thus you end up with less space to display information.

Window 1

Using the screen metaphor you can split the information and the UI of your application among multiple screens. For example, consider the MAX Companion 2010 app, which shows conference session information. When you want to see details for a particular session (see the images above) another screen is presented. When you return to the previous screen, the session list is shown again.

Elegant as it might be, writing an app using the screen metaphor is not rocket science. However, there are some issues to be considered, such as:

  • Memory management – pushing dozens of screens can consume all the memory available on the device
  • Transitions from one screen to another – nice effects will help you create an application like a professional UX Designer
  • Passing data from one screen to another – you need some way of exchanging data between screens
  • Preserving application state – when the OS closes your app, you’ll want to save its state to restore when it reopens
  • Integration with hardware buttons – you press the Back button of the device, for example, to navigate to the previous screen

The Flex framework has built-in support for the screen metaphor so you don’t have to reinvent the wheel as you address these issues

Supported mobile platforms

The June 2011 release of Flash Builder 4.5 and the Flex 4.5 SDK support Android, iOS, and BlackBerry Tablet OS. The initial launch (in May 2011) supported Flex development for Android only, although you could still develop pure ActionScript apps for all three platforms (Android, iOS, and BlackBerry Tablet OS).Applications created in Flash Builder run differently depending on the target platform:

  • On Android and BlackBerry Tablet OS the APK or BAR files are run using the Adobe AIR runtime installed on the devices. PlayBook devices (running BlackBerry Tablet OS) come with Adobe AIR pre-installed. Some Android devices have Adobe AIR pre-installed, while others don’t. If AIR is not installed already, you will be prompted to install it from the Android Market the first time an AIR application is opened.
  • On iOS, the application is cross-compiled to a native IPA file together with the Adobe AIR runtime.

FLASH BUILDER 4.5 MOBILE PROJECT TYPES

When you choose File > New in Flash Builder 4.5, you will see two new mobile applications project types to choose from: ActionScript Mobile Project and Flex Mobile Project.

In Flash Builder for PHP you’ll see those two types plus one more for creating a Flex Mobile and PHP project.

CREATING A FLEX MOBILE PROJECT

To use the Flex framework to create a mobile app:

  1. 1choose File > New > Flex Mobile Project. In the first page of the wizard, specify the project name.
  2. Window 2
  3. In the second page of the wizard, choose the target platforms. In the following image, BlackBerry Tablet OS and Google Android are selected; in the June 2011 release you can also select iOS. You can also use the Permissions tab on this page to set additional mobile application permissions for Android and BlackBerry Tablet OS. In the Application Template tab you’ll see three options: Blank, View-Based Application, and Tabbed Application. If you want Flex support for the screen metaphor, choose either View-Based Application or Tabbed Application. The Tabbed Application option is preferable if your application has lots of screens and you want to use a tab group at the bottom of the page to group these screens.

    if you choose Blank, you can use Flex components but you will have to handle events such as device orientation changes or pressing the Back button on an Android device yourself.

    When creating a Flex mobile and PHP project with Flash Builder 4.5 for PHP (File > New > Flex Mobile and PHP Project), the process is quite similar except you also set up a PHP project at the same time:
Window3

  • The second screen is for setting up the Flex project
  • The third screen is for setting up mobile specific settings

You can watch my video tutorial on this topic. Creating an ActionScript mobile project is similar to the Flex one.

Understanding Flex mobile View and ViewNavigator class

If you choose to use View-Based Application or Tabbed Application, it is important to understand the following classes: View, ViewNavigator, ViewNavigatorApplication, and TabbedViewNavigatorApplication.

The top application class will be ViewNavigatorApplication or TabbedViewNavigatorApplication depending on the Application Template you used when creating the project. You create your application user interface by extending the View class. Basically each screen of your application will be represented by a component that extends the View class. To create a new screen, choose File > New > MXML Component and then set the spark.components.View class as the class to base the component on.

The View class has two important properties: data and navigator. You use the navigator property (which refers to an instance of the ViewNavigator class) to control the screens. When you want to push a new view to the screen, you call navigator.pushView(new-viewclass- name). When you want to return to the previous view, you call navigator.popView(). When you want to jump to the first view you call navigator.popToFirstView().If you don’t want to have the View destroyed, you can set the destructionPolicy attribute of the View tag to “never”.

To pass data from the current View to the next one, simply set the second argument of the pushView() method to the data you want to pass; for example, navigator.pushView(view-class-name, dataToBeUsed); There are some applications that need to preserve their entire state when they are closed by the OS. To do this, just set the persistNavigatorState attribute in your main application file to true. This is a neat feature that allows you to support (with almost no effort) scenarios in which the user has navigated several screens into the application when the application gets closed (for example if the user switched to a new application or decided to close the app); when the application opens again, the user will see the same screen as in the previous session.

There are also events you can listen for in each View:

  • viewActivate (FlexEvent.VIEW_ACTIVATE) – Dispatched when the current view has been activated.
  • viewDeactivate (FlexEvent.VIEW_DEACTIVATE) – Dispatched when the current view has been deactivated.
  • removing (FlexEvent.REMOVING) – Dispatched when the screen is about to be removed in response to a screen change. If you call preventDefault() you can cancel the screen change. This event is triggered before the FlexEvent.VIEW_DEACTIVATE event.

TESTING AND DEBUGGING MOBILE PROJECTS

One of the most powerful features of Flash Builder 4.5 is its ability to run mobile projects right from the IDE. If you have a physical device you can deploy the app and debug on the device from Flash Builder

If you don’t have a device you can use the Flash Builder simulator to test the app. In either case, you start by choosing Run > Running Configuration or Run > Debug Configurations.

To add a new configuration, select the Mobile Application entry (or Mobile (PHP) Application if the project type is Flex Mobile and PHP) and then click the top-left icon to add a new configuration. Select the project that you want to create the configuration for and then select the Target Platform (Android, iOS, or BlackBerry Tablet OS).

Window4

For the Launch Method, select On Desktop if you want to run the app on the desktop simulator or select On Device if you want to deploy the app to the device. The simulator is quick and easy to use. Using the second option—On Device—is less straightforward; depending on the target platform you will need certificates, provisioning files, debug tokens, and so on. For both options you can run the application with or without debugging support.

PACKAGING A MOBILE PROJECT AS A MOBILE APP

Flash Builder 4.5 supports packaging your mobile projects (ActionScript or Flex) as native applications that is, as an APK for Android, an IPA for iOS, or a BAR for BlackBerry Tablet OS.

To access this feature, select the project for which you want to create the native app, choose File > Export, and select Flash Builder > Release Build.

Window5

Follow the directions on screen for the rest of the process, which is different for each supported target (Android, BlackBerry Tablet OS, or iOS).

Packaging mobile apps for Android

To package a mobile app for Android, right-click the project name in the Package Explorer view and select Export > Flash Builder > Release Build. On the first page of the wizard make sure you select the Google Android platform and select Signed Package For Each Target Platform.

Window6

On the second page of the wizard in the Digital Signature section, click Create to begin creating a self-signed certificate. Type the publisher name, organizational unit, organizational name, and country. Select 2040-RSA for the type, set the password, and specify the location and the file name for the certificate. When you click OK, Flash Builder will create the certificate. When you complete the wizard by clicking Finish, Flash Builder will create the APK file. By default, the APK file is created inside the root of your project. You can upload this file to the Android Market.

Window7

Every time you want to release an update for your application, first increase the versionNumber in your application descriptor file and then use the same workflow to create the APK. This time, however, instead of creating a new certificate, just select the one you created earlier.

Packaging mobile apps for BlackBerry Tablet OS

There are two main steps you have to complete to package AIR projects for BlackBerry Tablet OS:

  • Request permission from RIM to sign BlackBerry Tablet OS apps and get the CSJ registration files.
  • Configure Flash Builder for signing PlayBook apps and sign your application.

The credit card is required only for verification purpose. Once you finish this registration you will receive a confirmation email. Then, you should receive by email a number of CSI and CSJ files within 24 hours. Save all these files in the same folder. (Note that the number part of the filename is different for each registration). If you forget the PIN or if you want to sign from another computer, you can submit another request.

Package the project for PlayBook

Once you have the files from RIM, you are ready to use Flash Builder 4.5 to sign mobile ActionScript and Flex projects. Begin by opening the Preferences dialog box (choose Window > Preferences). Then expand the Flash Builder entry on the left side and choose Target Platforms > BlackBerry Tablet OS > Signing.

The top section is for providing a developer certificate for signing the code. To create one, click Create Certificate. Pay attention to what password you set and what value you set for the Publisher–this value must be the same as the one you provided when requesting permission to sign PlayBook apps. When you click OK in the Create Developer Certificate dialog box, a new certificate will be generated. Now, add this certificate by clicking the Select Certificate button.

Window8

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate.

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate. To save the configuration, click OK.

Window9

After you’ve registered your certificates with the BlackBerry Signing Authority you should receive an email confirmation. The next step is to open the application descriptor file for your project in Flash Builder and make sure you set a version number for <versionNumber>. Each time you export a release build you’ll have to increase this number. Next, open the blackberry-tablet. xml file and make sure that the value for the <publisher> node is the same as the one you set for the company value when you registered for signing PlayBook apps and when you generated the developer certificate. Then right-click the project name in the Package Explorer view and select Export.

In the wizard that opens, select Flash Builder > Release Build and click Next. In the second page of the wizard make sure you select BlackBerry Tablet OS in the Target Platforms section. By default the BAR file will be created in the root folder of the project you are exporting. If you want to use a different path, type a new Export To Folder value. You also need to select Export And Sign A Platform-specific Application Package. Click Next.

Window10

In the third page of the wizard select Enable Digital Signing on the Digital Signature tab. This option will use the certificates (Developer and RIM) you set earlier. Finally, click Finish.

Window11

After a few seconds you should have a new BAR file. If you encounter any errors, see BlackBerry’s page on application signing errors for additional information.

You can submit the BAR file to the BlackBerry App World portal (if you have registered as a vendor) via https://appworld.blackberry. com/isvportal/.

Packaging mobile apps for iOS

To package applications for testing and debugging on iOS devices or for deployment to the Apple App Store you will need to enroll in the Apple Developer Program (fees apply). For more information on the Apple Developer Program and to create an account, visit Apple’s Developer Program Enrollment page.

Once registered, you will need to login to the iOS Provisioning Portal and complete the following tasks:

  • Generate a development certificate
  • Register any devices to which you wish to deploy applications during development
  • Define an App ID for the application you are developing
  • Create a development provisioning profile

You will also use the iOS Provisioning Portal to distribute your application via the App Store. That part of the process is not covered in this article; instead refer to Apple’s documentation. The development certificate (in P12 format) and the provisioning profile are required before you can package your application for iOS in Flash Builder.

Generate a development certificate

Follow the guide on the iOS Provisioning Portal to generate your development certificate. This guide assumes you are using a Mac OS based computer, but it is possible to generate the certificate using Windows; details are available in the Adobe AIR documentation.

Convert the developer certificate into a P12 format

To use the certificate with Flash Builder, you must convert into P12 format. Instructions on how to do this are provided in the Adobe AIR documentation on signing AIR applications.

Store the P12 (.p12) file on your computer; you will need to use it with Flash Builder later.

Register devices to which you wish to deploy applications during development

You must specify any devices on which you intend to run or debug the application in the provisioning profile used to package the application; as such, you must register the devices on the iOS Provisioning Portal.

To register a device you need its Unique Device Identifier (UDID). To get this, connect your device to your computer and launch iTunes. In iTunes, select your device in the Devices section and navigate to the Summary tab. Click the Serial Number label to reveal the Identifier field and the 40 character UDID. Press Command/CTRL+C to copy the UDID to your clipboard.

Define an App ID for the application you are developing

Each application that you wish to deploy must have an App ID, which comprises a Bundle Seed ID (also called the App ID Prefix) and a Bundle Identifier (also called the App ID Suffix). Follow the guide on the iOS Provisioning Portal to create your

App ID.
Note that the Bundle Identifier must be the same as the value of the <id> attribute in your application’s app.xml descriptor file. For example, if you create a Bundle Identifier as “com.adobe. myApp”, then your app.xml file must contain the following:

<!-- A universally unique application identifier. Must be unique across all AIR applications. Using a reverse DNSstyle name as the id is recommended. Required. --> <id>com.adobe.myApp</id> You can use a wildcard in the Bundle Identifier to create a provisioning profile that is valid for a number of applications; for example a provisioning profile with a Bundle Identifier specified as “com.adobe.*” can be used with applications with an id of “com.adobe.myApp” and “com.adobe.myOtherApp”. Also note that once created, you cannot remove an App ID from the iOS Provisioning Portal.

Create a development provisioning profile

The final step you need to complete using the iOS Provisioning Portal is to create an iOS Development Provisioning Profile. You will define a profile name, specify the certificate you created, select an App ID, and choose the device or devices the application can be deployed to. More information on creating a Provisioning Profile can be found in the guide on Apple’s site. Download the provisioning file to your computer; you will need to use it with Flash Builder later.

Specify build packaging information for the project in Flash Builder

Before you are ready to deploy an application to an Apple iOS device you need to specify the information required to package the application as an IPA file.

In the Package Explorer view in Flash Builder, right-click your project and select Properties. In the Properties dialog box, select ActionScript Build Packaging > Apple iOS (for an ActionScript project) or Flex Build Packaging > Apple iOS (for a Flex project). In the Digital Signature tab, specify the previously saved P12 certificate file and the provisioning file for your project. Click Apply and then click OK.

When you want to create an IPA file simply right-click the project name in the Package Explorer view and select Export > Flash Builder > Release build. Follow the steps in the wizard to create your IPA file.

CONCLUSIONS

If you want to learn more about mobile development for Android, iOS, and PlayBook using Adobe AIR, Flash Builder, and Flex I encourage you to check these resources:

  • Adobe Mobile and Devices Development Center
  • Creating Flex Mobile Apps with Flash Builder for PHP tutorial
  • Great list of resources for designing and skinning mobile applications

About The Authors

Mihai Corlan

Mihai Corlan is a world wide developer evangelist at Adobe focusing on Flex, AIR, Flash Builder, and Flex, and HTML. Before that he worked with Flex Builder as a computer scientist. Prior to joining Adobe, Mihai was a senior web developer with InterAKT Online (acquired by Adobe in 2006), where he built web applications, frameworks, desktop software, and RIAs. Since 2008 he’s been writing about RIAs and mobile development at http:// corlan.org

You can follow him on Twitter http://twitter.com/mcorlan

Recommended Book

Continuous Delivery

Adobe Flex: Training from the Source was written by a team of authors with practical experience as consultants, mentors and developers of courseware, this book/CD uses project-based tutorials, and is designed to teach beginning Flex developers the details of building and architecting real-world rich internet applications using Flash Builder incorporating MXML and ActionScript 3.0.Flex 4.5 features, such as new enhancements to the Spark architecture and component set. It will also show you how to take advantage of the improvements to core Flex infrastructure for large application development.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Have you started using Spring Dynamic Modules yet?

Get started now! Download the latest DZone Refcard: Getting Started with Spring-DM. 

0 replies - 5272 views - 06/08/09 by Lyndsey Clevesy in Announcements

Reduce Your Software Developement Costs Now!

Are your software development costs breaking the bank? Click here for a solution!

0 replies - 4760 views - 05/18/09 by Lyndsey Clevesy in Announcements