Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Tools & Methods

  • submit to reddit

Application Performance Testing: From Conception to Gravestone

0 replies - 1285 views - 12/05/11 by Brandon Nokes in Whitepapers

Why Load Testing From The Cloud Doesn't Work

0 replies - 1242 views - 12/05/11 by Brandon Nokes in Whitepapers

Web Load Testing is Good Business

0 replies - 1292 views - 12/05/11 by Brandon Nokes in Whitepapers

Eclipse Tools for Spring

The SpringSource Tool Suite

By Gordon Dickens

13,800 Downloads · Refcard 147 of 151 (see them all)

Download
FREE PDF


The Essential SpringSource Tool Suite Cheat Sheet

This cheat sheet covers the SpringSource Tool Suite (STS), an Eclipse-based IDE that includes many useful Spring developer plugins out of the box. These tools include visual editors, project validators, and a Spring dashboard. The suite can be used for development in Spring Roo, Groovy, Grails, Gradle, Spring tcServer, and Spring Insight. This Refcard will walk you through installation, configuration, validation, Bean navigation, Spring Aspect Oriented Programming, and analysis. Whether youre new to Spring development or a veteran on the framework, you need to get your hands on this card.
HTML Preview
Eclipse Tools for Spring: The SpringSource Tool Suite

Eclipse Tools for Spring:The SpringSource Tool Suite

By Gordon Dickens, Chariot Solutions

ABOUT SPRINGSOURCE TOOL SUITE

SpringSource Tool Suite (STS) is an Eclipse-based IDE with pre-installed plugins that provides valuable features for Spring developers. In addition to support for the core Spring framework, STS also provides visual editors, project validators, and Spring Dashboard for other projects such as Spring Roo, Grails, Groovy, Gradle, tcServer, and Spring Insight.

The main plugin for STS is Spring IDE, which provides the fundamental Spring tooling features. STS comes preconfigured with many other plugins such as M2Eclipse for Maven, Web Tools Platform (WTP), Data Tools Platform (DTP), and AspectJ Development Tools (AJDT) and JUnit tooling.

Why use STS?

  • Content aware XML Spring Bean editing and refactoring
  • Content-aware Spring shortcuts for Java classes
  • Visualizers for graphical configuration editing
  • Validators for project configuration
  • Dashboard
  • Spring tcServer and Insight
Getting STS

STS is available from SpringSource: http://www.springsource.com/developer/sts

STS version numbers are different than the Eclipse versions. When choosing versions from the Spring site, go the current version of STS to see the supported Eclipse versions.

When installing STS from the native installer, it prompts you to install optional products such as Spring Roo, Apache Maven, and tcServer Developer edition. If these features are already installed and configured, uncheck these products.

Already have Eclipse?

If you already have Eclipse 3.6, download the STS plugin as follows:

  1. Before installing STS, ensure you have the current JDK installed.
  2. Download the bookmarks file from: http://dist.springsource.com/release/TOOLS/composite/e3.6/bookmarks.xml.
  3. In Eclipse, select Preferences -> Install/Update -> Available Update Sites.
  4. Click the “Import…” button, select the downloaded “bookmarks. xml”, and click “Open” to finish the import.

If you are using another version of Eclipse, find installation instructions here: http://www.springsource.com/products/eclipsedownloads.

Manage the plugin sites from Help > Install New Software… Clicking the “Available Sites” link shows the currently configured plugin sites.

The Dashboard

When you start STS, one of the first things you will see is the Spring Dashboard. At the bottom of this view are two tabs: Dashboard and Extensions. The Dashboard tab contains five sections:

  1. Create – Spring, Java, Grails & Groovy Projects
  2. Updates – Update information for STS
  3. Tutorials – Spring, Security, Web, Web Flow, WS
  4. Help & Docs – Forums, JIRA, STS New & Noteworthy
  5. Feeds - RSS announcements from Spring and Spring Blog posts

The Extensions tab contains two tabs:

  1. Extensions tab provides options for installing Roo, Groovy, Grails, and other useful extensions such as Google (GWT & GAE), CloudFoundry, DataNucleus, EGit, FindBugs, PMD, and more.
  2. The Find Updates tab checks for extension updates.

Hot Tip

To Manage the Dashboard: Preferences > Spring > Dashboard Add Spring blogs like: http://gordondickens.com/wordpress/feed/

PROJECT CONFIGURATION

To take advantage of Spring tooling features, add the Spring Project Nature to each project. Then you can view the project in Spring Project Explorer and define bean config files and config sets.

If you’re using Maven, you can configure this in your pom.xml file using the maven-eclipse-plugin:



<build>
...
  <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.8</version>
	<configuration>
	  <downloadSources>true</downloadSources>
	  <downloadJavadocs>true</downloadJavadocs>
	  <wtpversion>1.5</wtpversion>
	  <additionalBuildcommands>
		<buildCommand>
		  <name>org.springframework.ide.eclipse.core.springbuilder</
name>
		</buildCommand>
	  </additionalBuildcommands>
	  
	  <additionalProjectnatures>
		<projectnature>
		  org.springframework.ide.eclipse.core.springnature
		</projectnature>
	  </additionalProjectnatures>
	</configuration>
  </plugin>
...
</build>



Once the Maven Eclipse plugin is installed, you can generate the Eclipse project files from the command prompt with:


mvn eclipse:eclipse

Hot Tip

A project configured with Spring Project Nature will have an “S” over the project, bean config files and directory icons containing bean config files.
Spring Perspective

The Spring Perspective is an Eclipse perspective displaying views such as Spring Explorer and other standard Eclipse views: Servers, Spring Explorer, Task List, Outline, Console, Markers, and Progress. This is a convenient layout that can be customized to your liking.

Spring Explorer View

This view provides the ability to see the Bean Config files within Spring projects. Here you can view the beans graph visualizer, create bean config files, define Bean Config sets, define new beans, validate beans, and openf MVC request mappings.

Bean Config files are XML files defining beans and bean relationships within a project. If you are using a project and don’t remember where the Bean Config files are located, open Spring Explorer. Within Spring Explorer, right-click a config file and choose from several options:

  • Open Dependency Graph - the visualizer for bean relationships. This is the same as the “Bean Graph” tab available in the bean editor.
  • New Bean Definition - provides a dialog for entering bean definitions.
  • RequestMapping - opens a view for MVC applications showing all the request mappings configured in this file. Validate - validates the bean configuration file based on the Spring Bean
  • Validate - will validate the bean configuration file based on the Spring Bean validation configuration settings in preferences.
  • Properties - opens project beans, validation, config set dialog. In this dialog we have the option to scan for more configuration files with the “Scan” Button.
Window 1
Project Explorer View

This view provides you with the ability to look at the project by its component types such as Spring Elements, Bean Config Files, Bean Config Sets, Web Service components, Java Resources, and more.

Window 2

Once you have added Spring Project Nature to your project, you can create or mark bean config files.

Creating a Spring config file – From Package Explorer, click the directory for the XML file and choose:

File > New > Spring Bean Configuration File

Locating Spring config files - from Spring Explorer view, right-click the project:

Properties > Spring > Beans Support “Scan” button the directory for the XML file and choose: File > New > Spring Bean Configuration File

Hot Tip

Bean config files will appear with the “S” over the directory and file.
Bean Config Sets

Bean config sets allow you to group bean config files together. Using Config Sets provides the ability to validate beans and bean relationships defined within multiple bean config files. Validation also provides suggestions via content assist when editing.

This feature is particularly useful when you have infrastructure beans such as dataSource defined within a test config file and the application’s entity, services, etc defined in a common bean config file that is the same for all deployment platforms. You do not have the ability to assign config sets to any components or tests. This is unnecessary as STS performs cross-file validation on all config sets.

If the bean config files within a config set do not define all referenced beans, mark a config set by checking the “Is incomplete” checkbox. If checked, the BeansConfigValidator doesn’t complain about missing bean references within this config set.

Spring MVC Request Mappings

Spring MVC is very powerful and easy to configure using annotations. The MVC Request Mappings view displays the request mappings for an MVC project. In Spring Explorer, right-click an MVC project, config file, or config set and select RequestMappings to see the URL details in a tabular view. If it is not an MVC application, this view is empty. The view provides the following details:

  • Resource URL
  • Resource Method: GET, POST, etc.
  • Handler Method
  • JavaDoc

Within the view, Double click on line to go to the code.

Windows 3

STARTING A PROJECT FROM SCRATCH

Spring Project

This option is extremely bare bones and only creates a basic Java project with src directory and Spring Project Nature added. No Spring dependency jars or other structures are configured. It is recommended to use the Spring Template Projects instead.

See the Spring Dashboard for quick links to create Spring, Groovy, Grails, and Spring Roo projects.

Spring Template Project

From the File > New menu, you can create a Spring project using the predefined templates from SpringSource. These templates provide a convenient starting point for different Spring projects.

The projects created from these templates are configured as Maven projects with the necessary project (JAR) dependencies.

Note: Many of the templates may require manual updating of project configuration. Updating configuration is often in two main areas: version dependencies in pom.xml and bean config file namespaces for the latest project versions.

BEAN CONFIGURATION

Bean Editing

The bean editor in STS provides features beyond a standard XML editor. In the java editor, you are already familiar with content assist. Spring adds content assist when typing in bean declarations. For example, in the bean config editor (and throughout Eclipse), you can use camel case when typing bean names. This provides the ability to enter the class name without having to know the full package or spelling of the bean.

For example:

If you want to configure JmsTemplate, type <bean class=“JT”/> and press CTRL-Space after the “T” to get a long list of beans matching J and T. Narrow by <bean class=“JmT”/> then press CTRL-Space after the “T” to get a shorter list where you can choose JmsTemplate. The complete package and classname is entered for you.

When configuring properties of a bean, content assist provides you with the available properties that you can set in the XML config.

<bean id=“jmsTemplate” class=“…JmsTemplate”> <property name=“”/> </bean>

By hitting CTRL-Space within the quotes of the property name, you are prompted with all of the properties available to set.

Spring also provides XML templates to quickly insert config within the xml files. For example, on a blank line in the bean config editor, type “bean” and press CTRL-Space.

Windows 4

Choose Bean - Inserts a Bean Tag and below shows the example of what will be inserted into the code:

<bean id=”id” class=”class”>

</bean>

Hot Tip

View, add or modify XML bean templates in Preferences > Spring > Beans Support > XML Templates
Windows 5
Bean Editor Tabs

A series of Tabs will display at the bottom of the editor based on the content of the XML namespaces used. Overview tabs for specific namespaces include JDBC, Spring Integration, Spring Batch and Web Flow.

Windows 6
  • Source – The XML editor
  • Namespaces - Choose namespaces to include/exclude in the configuration file, without the risk of typos.
  • Configure the namespace discovery in Preferences > Spring > Beans Support > Namespaces
  • Overview - General overview of the beans within a bean definition file. A tree hierarchy shows the beans, nested beans and bean properties.
  • Namespace specific tabs – provide bean information for namespaces we have selected. Such as: context, jee, tx, etc.

Beans Graph – Display’s graphical representation of beans (see Visualizers below)

Hot Tip

<Configure the namespace discovery by selecting Preferences > Spring > Beans Support > Namespaces.

VALIDATION

Spring project validation rules are available in Preferences > Spring > Project Validators section.

Spring Validator

There is only one option to verify Spring is in the classpath. This validator is disabled by default. There are three categories: Bean validation, STS validation, and Spring validation.

Bean Validation

There are 15 rules available, most enabled by default. These rules validate bean names, aliases, deprecation, @Required annotation, constructor injection, and Autowired annotation types (@Autowired, @Resource, @EJB).

Bean Rule Description
Required Property Validates @Required annotation
Annotation-based
Auto wiring
Validates @Autowired, @Resource and @EJB annotations
Bean Alias Validates alias names associated with bean
Bean Class Validates a bean class
Bean Constructor
Argument
Validates non-abstract bean’s constructor arguments
Bean Definition Holder Validates Root bean’s name and aliases
Bean Definition Validates a bean’s definition
Bean Deprecation Validates init, destroy and setters are not deprecated
Bean Factory Validates a factory beans and factory methods
Bean Init and Destroy
Method
Validates non-factory beans init and destroy method
Bean Method Override Validates bean method override
Bean Property Validates bean’s property accessor method is in bean class
Bean Reference Validates bean references depends-on attribute, a value holder or collection type
XML Parsing Problems Validates XML file is parseaable
XSD Tool Annotation Validates attributes based on schema
STS Validator

The eight STS validator options are project-wide validation rules.
These validators are disabled by default.

STS Rule Description
Driver Manager Data Source Validates the project does not use this class
Bean Inheritance Recommends bean inheritance for simplification
Import Elements at Top Recommends imports before other bean definitions
Parent Beans not Abstract Validates that parent beans are not abstract
Too Many Beans Validates too many beans in file – approx. 80 beans
Unnecessary Ref Check for ref elements and recommends ref attribute instead. <property … ref=””/> instead of <property …><ref bean=””/></property>
Dedicated Namespace Syntax Checks for cases where dedicated namespaces can be used

Once enabled, from Package Explorer view, R-Click on the project and select validate.

STS Validation errors will be displayed in the Markers and Problems views.

Once corrected actions are made, you may need to remove the validation markers. R-Click on project > Spring Tools > Remove Validation Markers and then validate again.

Bean Refactoring

The Bean Config editor provides the ability to refactor bean definitions. In the editor, right-click on a bean definition, select “Refactor…” and you will see three options:

  • Refactor Property Element – Nested ref and value tags.
  • Move Bean Element (class)… - Move class to another package.
  • Rename Bean Element (id, class, property name)…- Rename bean id, can search for literal string references and similarly named classes.

BEAN NAVIGATION & ANALYSIS

Within STS, you can quickly open a bean or view bean cross references or bean outline from the Eclipse Search and Navigate menu options.

Finding Spring Beans

From Search > Beans, you can conduct a wildcard search for beans by name, class, property name, beans referencing, and child beans.

Navigate > Open Spring Bean displays a search box where you can search for class names using camel-case.

Beans Quick Cross References

Within the bean config editor, select Navigate > Beans Quick Cross References to show the beans cross references for the current bean file. From here, you can jump to the bean declaration.

Note:

  • Beans Cross References view is for Spring
  • Cross References view is for AspectJ
Beans Quick Outline

Within the bean config editor, select Navigate > Beans Quick Outline to display an outline list of all bean declarations and property settings. You can search for a specific bean by ID and click a bean to see its definition.

Beans Cross References View

This view shows cross references based on the open file. By default, this view is empty until you click the “Link with Editor” in the title bar of the view (gold arrows).

Windows 7

SPRING ASPECT ORIENTED PROGRAMMING (AOP)

Spring AOP support in STS is extends the installed AspectJ Development Tools (AJDT) plug-in.

Spring Aspects Tooling

Spring AOP support in STS extends the installed AspectJ Development Tools (AJDT) plug-in.

Right-click on a project. Under Spring Tools, there is an option to enable Spring Aspects Tooling. This enables AJDT weaving features within a project.

With this setting, AJDT weaves itself into JDT with features:

  • TD-aware reconciling/eager parsing
  • TD-aware content assist
  • TD-aware type hierarchies
  • Search for aspect elements using standard Java search and Open Java type

Source: http://wiki.eclipse.org/JDT_weaving_features

AOP Event Trace

The AOP Event Trace view provides log-like detail during a project build. The view logs information about the Spring IDE’s internal AOP model creation.

To enable this feature:

  • Add spring-aspects.jar to the project.
  • Right-click project > Spring Tools > Enable Spring Aspects Tooling.
  • Select Preferences > AspectJ Compiler > Other > Check Verbose & Pointcut matching timers.
Windows 9
Spring Pointcut Matches

From the Search menu, we can use Spring AOP Pointcut expressions and test pointcuts such as:

execution(void set*(*))

bean(transactionManager)

Windows 8

VISUALIZERS

STS provides the ability to graphically view and edit Spring configuration. The five visualizers are beans, Spring Integration, Spring Batch, Web Flow, and Aspects.

Beans Graph

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

Within a Bean Config file, the tab “Beans Graph” displays beans within the file.

Windows 10

From Project Explorer, expand the project under Spring Elements, right-click the Config Set name, and choose “Open Dependency Graph”.

Windows 11

Set preferences for Beans Graph in Preferences > Spring > Beans Support

  • Display Inner Beans
  • Display Infrastructure Beans
  • Display Extended Content (Autowired beans)

This feature is enabled by default in Preferences > Spring> Beans Support > Editor > Enable embedded graph pages.

Integration Graph

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

This visualizer is editable using the tool pallet on the left. The tool pallet only shows tools based on the namespaces included in the XML file.

Windows 12
Batch Graph

When using Spring Batch, you see the batch-graph tab in the beans config editor. This visualizer is editable.

Windows 13
Web Flow Graph

Spring Web Flow provides you with the ability to design Stateful page flows. The bean config editor provides the ability to edit the flows in XML or visually from the flow-graph tab.

Windows 14
Aspect Visualization

To see visualize Spring AOP aspects, select Preferences > Visualizer under Visualizers and then check Spring AOP Provider. You can also do this from the Visualizer view by clicking the down arrow in the view’s title bar and choosing preferences.

In the view tools, select the “Hide Unaffected Bars” to show only the classes affected by aspects.

Note: You do not need to enable Spring aspects tooling for this feature to work.

Windows 15

About The Authors

Gordon Dickens

Gordon Dickens is an instructor/mentor/consultant for Chariot Solutions (chariotsolutions.com) with experience in the IT consulting for over 15 years. Gordon’s background includes presenting at conferences and user groups on Spring, Groovy & Grails, with experience developing Spring, Hibernate, Grails, Roo and OSGi applications. Gordon blogs at technophile.gordondickens.com and actively tweets open source tips at (twitter.com/gdickens). Gordon is a contributor to Spring Roo in Action manning.com/rimple and very active in the Spring Framework, Roo, Spring Integration and Spring Batch projects. He currently teaches Maven and Spring as a Certified Spring Instructor by SpringSource.

Recommended Book

Spring Roo in Action Book

Roo is a lightweight Java development tool that works within existing processes, to rapidly produce high-quality, 100% Java code. Roo enforces correct coding practices and patterns and instantly integrates not only with Spring, but also with virtually every mainstream Java technology.

Roo in Action is unique book that teaches how to code Java in Roo, with a particular focus on Spring-based applications. It starts by getting into the Roo mindset, along with a quick-and-dirty guide to setting up Roo effectively. Through hands-on examples, readers will learn how Roo creates well-formed application structures and supports best practices and tools.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Continuous Delivery

Patterns and Antipatterns in the Software Lifecycle

By Paul M. Duvall

19,646 Downloads · Refcard 145 of 151 (see them all)

Download
FREE PDF


The Essential Continuous Delivery Cheat Sheet

This Continuous Delivery cheat sheet from DZone is loaded with over 40 different patterns and antipatterns for configuration management, continuous integration (CI), infrastructure, incremental development, and deployment. Continuous Delivery: Patterns and Antipatterns in the Software Lifecycle encourages you to follow the mantra: "Release early and often." The key is for software production teams to minimize the time it takes to go from idea to usable software by using agile techniques and automating the entire software delivery system: build, deploy, test, release.
HTML Preview
Continuous Delivery Patterns and Antipatterns in the Software Lifecycle

Continuous DeliveryPatterns and Antipatterns in the Software Lifecycle

By Paul M. Duvall

ABOUT CONTINUOUS DELIVERY

With Continuous Delivery (CD), teams continuously deliver new versions of software to production by decreasing the cycle time between an idea and usable software through the automation of the entire delivery system: build, deployment, test, and release. CD is enabled through the Deployment Pipeline, which encompasses a collection of patterns described in this Refcard.

CD is concerned with “…how all the moving parts fit together: configuration management, automated testing, continuous integration and deployment, data management, environment management, and release management.” (1)

THE DEPLOYMENT PIPELINE

Figure 1

The purpose of the deployment pipeline is threefold:

  • Visibility: All aspects of the delivery system - building, deploying, testing, and releasing – are visible to all team members promoting collaboration.
  • Feedback: Team members learn of problems as soon as they occur so that issues are fixed as soon as possible.
  • Continually Deploy: Through a fully automated process, you can deploy and release any version of the software to any environment. (1)

In the Deployment Pipeline diagram above, all of the patterns are shown in context. There are some patterns that span multiple stages of the pipeline, so I chose the stage where it’s most predominately used.

BENEFITS

  • Empowering Teams: Because the deployment pipeline is a pull system, testers, developers, operations, and others can self service the application version into an environment of their choice.
  • Reducing Errors: Ensuring the correct version, configuration, database schema, etc. are applied the same way every time through automation.
  • Lowering Stress: Through push-button releases to production and Rehearsing Deployments, a release becomes commonplace without the typical stress.
  • Deployment Flexibility: Instantiate a new environment or configuration by making a few changes to the automated delivery system.
  • Practice makes Perfect: Through the deployment pipeline, the final deployment into production is being rehearsed every single time the software is deployed to any target environments. (1)

CONFIGURATION MANAGEMENT

Configuration Management is “the process by which all artifacts relevant to your project, and the relationships between them, are stored, retrieved, uniquely identified, and modified”. (1)

Note: Each pattern is cited with a number in parentheses that corresponds to the source in the References section.

Configurable Third-Party Software (1)

Pattern Evaluate and use third-party software that can be easily configured, deployed, and automated.
Anti-patterns Procuring software that cannot be externally configured. Software without an API or commandline interface that forces teams to use the GUI only.

Configuration Catalog (1)

Pattern Maintain a catalog of all options for each application, how to change these options and storage locations for each application. Automatically create this catalog as part of the build process.
Anti-patterns Configuration options are not documented. The catalog of applications and other assets is “tribal knowledge”.

Mainline (3)

Pattern Minimize merging and keep the number of active code lines manageable by developing on a mainline.
Anti-patterns Multiple branches per project.

Merge Daily (1)

Pattern Changes committed to the mainline are applied to each branch on at least a daily basis.
Anti-patterns Merging every iteration once a week or less often than once a day.

Protected Configuration (5) ,(1)

Pattern Store configuration information in secure remotely accessible locations such as a database, directory, or registry.
Anti-patterns Open text passwords and/or single machine or share.

Repository (3) , (1)

Pattern All source files - executable code, configuration, host environment, and data - are committed to a versioncontrol repository.
Anti-patterns Some files are checked in, others, such as environment configuration or data changes, are not. Binaries – that can be recreated through the build and deployment process – are checked in.

Short-Lived Branches (1)

Pattern Branches must be short lived – ideally less than a few days and never more than an iteration.
Anti-patterns Branches that last more than an iteration. Branches by product feature that live past a release.

Single Command Environment (1)

Pattern Check out the project’s version-control repository and run a single command to build and deploy the application to any accessible environment, including the local development.
Anti-patterns Forcing the developer to define and configure environment variables. Making the developer install numerous tools in order for the build/deployment to work.

Single Path to Production (1)

Pattern Configuration management of the entire system - source, configuration, environment and data. Any change can be tied back to a single revision in the version-control system.
Anti-patterns Parts of system are not versioned. Inability to get back to a previously configured software system.

CONTINUOUS INTEGRATION (CI)

Build Threshold (5)

Pattern Fail a build when a project rule is violated – such as architectural breaches, slow tests, and coding standard violations.
Anti-patterns Manual code reviews. Learning of code quality issues later in the development cycle.

Commit Often (6)

Pattern Each team member checks in regularly to trunk - at least once a day but preferably after each task to trigger the CI system.
Anti-patterns Source files are committed less frequently than daily due to the number of changes from the developer.

Continuous Feedback (6)

Pattern Send automated feedback from CI system to all Cross-Functional Team members.
Anti-patterns Notifications are not sent; notifications are ignored; CI system spams everyone with information they cannot use.

Continuous Integration (6)

Pattern Building and testing software with every change committed to a project’s version control repository.
Anti-patterns Scheduled builds, nightly builds, building periodically, building exclusively on developer’s machines, not building at all.

Stop the Line (5) , (1) , (4), (12)

Pattern Fix software delivery errors as soon as they occur; stop the line. No one checks in on a broken build as the fix becomes the highest priority.
Anti-patterns Builds stay broken for long periods of time, thus preventing developers from checking out functioning code.

Independent Build (6)

Pattern Write build scripts that are decoupled from IDEs. These build scripts are executed by a CI system so that software is built at every change.
Anti-patterns Automated build relies on IDE settings. Builds are unable to be run from the command line.

Visible Dashboards

Pattern Provide large visible displays that aggregate information from your delivery system to provide highquality feedback to the Cross-Functional Team in real time.
Anti-patterns Email-only alerts or not publicizing the feedback to the entire team.

TESTING

Automate Tests

Pattern Automate the verification and validation of software to include unit, component, capacity, functional, and deployment tests
Anti-patterns Manual testing of units, components, deployment, and other types of tests.

Unit- Automating tests without any dependencies.

Component- Automating tests with dependencies to other components and heavyweight dependencies such as the database or file system.

Deployment- Automating tests to verify the deployment and configuration were successful. Sometimes referred to as a “smoke tests”.

Functional- Automating tests to verify the behavior of the software from a user’s perspective.

Capacity- Automating load and performance testing in nearproduction conditions.

Isolate Test Data (1)

Pattern Use transactions for database-dependent tests (e.g.,component tests) and roll back the transaction when done. Use a small subset of data to effectively test behavior.
Anti-patterns Using a copy of production data for Commit Stage tests. Running tests against a shared database.

Parallel Tests (1)

Pattern Run multiple tests in parallel across hardware instances to decrease the time in running tests.
Anti-patterns Anti-patterns Running tests on one machine or instance. Running dependent tests that cannot be run in parallel.

Stub Systems (1)

Pattern Use stubs to simulate external systems to reduce deployment complexity.
Anti-patterns Manually installing and configuring interdependent systems for Commit Stage build and deployment.

DEPLOYMENT PIPELINE

Pattern A deployment pipeline is an automated implementation of your application’s build, deploy, test, and release process.
Anti-patterns Deployments require human intervention (other than approval or clicking a button). Deployments are not production ready.

Value-Stream Map (4)

Pattern Create a map illustrating the process from check in to the version-control system to the software release to identify process bottlenecks.
Anti-patterns Separately defined processes and views of the checkin to release process.

BUILD AND DEPLOYMENT SCRIPTING

Dependency Management (5)

Pattern Centralize all dependent libraries to reduce bloat, classpath problems, and repetition of the same dependent libraries and transitive dependencies from project to project.
Anti-patterns Multiple copies of the same binary dependencies in each and every project. Redefining the same information for each project. Classpath hell!

Common Language (1)

Pattern As a team, agree upon a common scripting language - such as Perl, Ruby, or Python - so that any team member can apply changes to the Single Delivery System.
Anti-patterns Each team uses a different language making it difficult for anyone to modify the delivery system reducing cross-functional team effectiveness.

Externalize Configuration (5)

Pattern Changes between environments are captured as configuration information. All variable values are externalized from the application configuration into build/deployment-time properties.
Anti-patterns Hardcoding values inside the source code or per target environment.

Fail Fast (6)

Pattern Fail the build as soon as possible. Design scripts so that processes that commonly fail run first. These processes should be run as part of the Commit Stage.
Anti-patterns Common build mistakes are not uncovered until late in the deployment process.

Fast Builds (6)

Pattern The Commit Build provides feedback on common build problems as quickly as possible - usually in under 10 minutes.
Anti-patterns Throwing everything into the commit stage process, such as running every type of automated static analysis tool or running load tests such that feedback is delayed.

Scripted Deployment (5)

Pattern All deployment processes are written in a script, checked in to the version-control system, and run as part of the Single Delivery System.
Anti-patterns Deployment documentation is used instead of automation. Manual deployments or partially manual deployments. Using GUI to perform a deployment.

Unified Deployment (5)

Pattern The same deployment script is used for each deployment. The Protected Configuration – per environment - is variable but managed.
Anti-patterns Different deployment script for each target environment or even for a specific machine. Manual configuration after deployment for each target environment.

DEPLOYING AND RELEASING APPLICATIONS

Binary Integrity (5)

Pattern Build your binaries once, while deploying the binaries to multiple target environments, as necessary.
Anti-patterns Software is built in every stage of the deployment pipeline.

Canary Release

Pattern Release software to production for a small subset of users (e.g. , 10%) to get feedback prior to a complete rollout.
Anti-patterns Software is released to all users at once.

Blue-Green Deployments (1)

Pattern Deploy software to a non-production environment (call it blue) while production continues to run. Once it’s deployed and “warmed up”, switch production (green) to non-production and blue to green simultaneously.
Anti-patterns Production is taken down while the new release is applied to production instance(s).
Figure 2

Dark Launching (11)

Pattern Launch a new application or features when it affects the least amount of users.
Anti-patterns Software is deployed regardless of number of active users.

Rollback Release (5)

Pattern Provide an automated single command rollback of changes after an unsuccessful deployment.
Anti-patterns Manually undoing changes applied in a recent deployment. Shutting down production instances while changes are undone.

Self-Service Deployment (1)

Pattern Any Cross-Functional Team member selects the version and environment to deploy the latest working software.
Anti-patterns Deployments released to team are at specified intervals by the “Build Team”. Testing can only be performed in a shared state without isolation from others.

INFRASTRUCTURE AND ENVIRONMENTS

Automate Provisioning (1)

Pattern Automate the process of configuring your environment to include networks, external services, and infrastructure.
Anti-patterns Anti-patterns Configured instances are “works of art” requiring team members to perform partially or fully manual steps to provision them.

Behavior-Driven Monitoring (1)

Pattern Automate tests to verify the behavior of the infrastructure. Continually run these tests to provide near real-time alerting.
Anti-patterns No real-time alerting or monitoring. System configuration is written without tests.

Immune System (9)

Pattern Deploy software one instance at a time while conducting Behavior-Driven Monitoring. If an error is detected during the incremental deployment, a Rollback Release is initiated to revert changes.
Anti-patterns Non-incremental deployments without monitoring.

Lockdown Environments (1)

Pattern Lock down shared environments from unauthorized external and internal usage, including operations staff. All changes are versioned and applied through automation.
Anti-patterns The “Wild West”: any authorized user can access shared environments and apply manual configuration c hanges, putting the environment in an unknown state leading to deployment errors.

Production-Like Environments (1)

Pattern Target environments are as similar to production as possible.
Anti-patterns Environments are “production like” only weeks or days before a release. Environments are manually configured and controlled.

Transient Environments

Pattern Utilizing the Automate Provisioning, Scripted Deployment and Scripted Database patterns, any environment should be capable of terminating and launching at will.
Anti-patterns Environments are fixed to “DEV, QA” or other predetermined environments.

DATA

Database Sandbox (7)

Pattern Create a lightweight version of your database – using the Isolate Test Data pattern. Each developer uses this lightweight DML to populate his local database sandboxes to expedite test execution.
Anti-patterns Shared database. Developers and testers are unable to make data changes without it potentially adversely affecting other team members immediately.

Decouple Database (1)

Pattern Ensure your application is backward and forward compatible with your database so you can deploy each independently
Anti-patterns Application code data are not capable of being deployed separately.

Database Upgrade (7)

Pattern Use scripts to apply incremental changes in each target environment to a database schema and data.
Anti-patterns Manually applying database and data changes in each target environment.

Scripted Database (7)

Pattern Script all database actions as part of the build process.
Anti-patterns Using data export/import to apply data changes. Manually applying schema and data changes to the database.

INCREMENTAL DEVELOPMENT

Branch by Abstraction (2)

Pattern Instead of using version-control branches, create an abstraction layer that handles both an old and new implementation. Remove the old implementation.
Anti-patterns Branching using the version-control system leading to branch proliferation and difficult merging. Feature branching.

Toggle Features (10)

Pattern Deploy new features or services to production but limit access dynamically for testing purposes.
Anti-patterns Waiting until a feature is fully complete before committing the source code.

COLLABORATION

Delivery Retrospective (1)

Pattern For each iteration, hold a retrospective meeting where everybody on the Cross-Functional Team discusses how to improve the delivery process for the next iteration.
Anti-patterns Waiting until an error occurs during a deployment for Dev and Ops to collaborate. Having Dev and Ops work separately.

Cross-Functional Teams (1)

Pattern Everybody is responsible for the delivery process. Any person on the Cross-Functional Team can modify any part of the delivery system.
Anti-patterns Siloed teams: Development, Testing, and Operations have their own scripts and processes and are not part of the same team.

Amazon.com has an interesting take on this approach. They call it “You build it, you run it”. Developers take the software they’ve written all the way to production.

Root-Cause Analysis (1)

Pattern Learn the root cause of a delivery problem by asking “why” of each answer and symptom until discovering the root cause.
Anti-patterns Accepting the symptom as the root cause of the problem.

TOOLS

This is meant to be an illustrative list, not an exhaustive list, to give you an idea of the types of tools and some of the vendors that help to enable effective Continuous Delivery. The Java, .NET and Ruby platforms are represented. The tools that span categories have been assigned to the most appropriate category or duplicated when necessary.

Category Example Software Tools
Configuration Management Subversion (SVN), git, Perforce, PassPack, PasswordSafe, ESCAPE, ConfigGen
Continuous Integration Bamboo, Jenkins, AntHill Pro, Go, TeamCity, TFS 2010, Electric Commander. Supporting tools: , Doxygen, Grand, GraphViz, JavaDoc, NDoc, SchemaSpy, UmlGraph, CheckStyle, Clover, Cobertura, FindBugs, FxCop, JavaNCSS, JDepend, PMD, Sonar, Simian
Testing Twist , AntUnit, Cucumber, DbUnit, webrat, easyb, Fitnesse, JMeter, JUnit, NBehave, SoapUI, Selenium, RSpec, SauceLabs
Deployment Pipeline Go, AntHill Pro
Build and Deployment Scripting Ant, AntContrib, NAnt, MSBuild, Buildr, Gant, Gradle, make, Maven, Rake, Java Secure Channel, ControlTier, Altiris, Capistrano, Fabric, Func
Infrastructure and Environments AWS EC2, AWS S3, Windows Azure, Google App Engine, AWS Elastic Beanstalk, Heroku, Capistrano, Cobbler, BMC Bladelogic, CFEngine, IBM Tivoli Provisioning Manager, Puppet, Chef, Bcfg2, AWS Cloud Formation, Windows Azure AppFabric, rPath, JEOS, BoxGrinder, CLIP, Eucalyptus, AppLogic, CloudKick, CloudWatch, Nagios, Zabbix, Zenoss
Data Hibernate, MySQL, Liquibase, Oracle, PostgreSQL, SQL Server, SimpleDB, SQL Azure, Ant, MongoDB, dbdeploy
Components and Dependencies Ivy, Archiva, Nexus, Artifactory, Bundler
Collaboration Mingle, Greenhopper, JIRA

REFERENCES

  1. Jez Humble and David Farley, “Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation”, Addison Wesley Professional, 2010

  2. Paul Hammant and www.continuousdelivery.com

  3. Stephen P. Berczuk and Brad Appleton, “Software Configuration Management Patterns.”, Addison Wesley Professional, 2003

  4. Mary and Tom Poppendieck, “Leading Lean Software Development”, Addison Wesley, 2009

  5. Paul M. Duvall, “Continuous integration. Patterns and Antipatterns”, DZone refcard #84, 2010 http://bit.ly/l8rfVS

  6. Paul M. Duvall, “Continuous integration. Improving Software Quality and Reducing Risk”, Addison Wesley, 2007

  7. Scott W. Ambler and Pramodkumar J. Saladage, “Refactoring Databases. Evolutionary Database Design”, Addison Wesley, 2006.

  8. Paul M. Duvall, IBM developerWorks series “Automation for the people” http://ibm.co/iwwvPX

  9. IMVU: http://bit.ly/jhqP5f

  10. Martin Fowler and Facebook: http://on.fb.me/miBrOM

  11. Facebook Engineering: http://on.fb.me/miBrOM

  12. Paul Julius, Enterprise Continuous Integration Maturity Model, http://bit.ly/m7h5vC

About The Authors

Paul Duvall

Paul M. Duvall is the CTO of Stelligent, (http://stelligent. com/) a company that helps organizations with Continuous Integration and Delivery, Cloud Migrations and Elastic Operations. Paul is the author of many books including the Jolt-award winning book Continuous Integration: Improving Software Quality and Reducing Risk (http://amzn.to/cibook) and the recently published Startup@Cloud: 33 tips for running your company using cloud-based software (http://amzn.to/startupatcloud). He is passionate about the cloud and automation and blogs at http://devopscloud.com/.

Recommended Book

Continuous Delivery
Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation

The book has two themes: automation and collaboration. Delivering software of any complexity involves people with a bunch of skills: testers, developers, and sysadmin / operations personnel. The last group of people often gets left out of the process of delivering software until the end, and even testers are often not as heavily involved in the development process as they should be.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Flash Builder 4.5 for PHP

Adobe/Zend Tools for the PHP Professional

By Marco Tabini

3,231 Downloads · Refcard 96 of 151 (see them all)

Download
FREE PDF


The Essential Flash Builder 4.5 for PHP: Adobe/Zend Tools for the PHP Professional Cheat Sheet

"Flash Builder 4.5 for PHP, Adobe/Zend Tools for the PHP Professional is a DZone Refcard that covers tools used by professional web developers to develop applications with slick, Flex UIs and powerful, battle-tested backends coded in PHP. Adobes new Eclipse-based IDE, Flash Builder 4.5 for PHP, was co-developed by Adobe and Zend Technologies. Its one of the more interesting cross-platform integrations in a long time. This Refcard will show you how to profit from this marriage of tools created by the leaders in the RIA and PHP development arenas."
HTML Preview
Getting Started With Integrating PHP and Flex

Adobe® Flash® BuilderTM 4.5 for PHP: Adobe/Zend Tools for the PHP Professional

By Marco Tabini

WHAT IS FLEX?

Flex is an open-source framework developed and distributed by Adobe Systems. It is based on the Adobe® Flash Platform and primarily provides a streamlined approach to the development of Rich Internet Applications.

Flex eliminates many of the designer-oriented features of Flash in favor of establishing a development environment that caters more to programmers. As such, you will find that Flex encompasses many of the concepts that you are already familiar with if you have developed front-end systems using JavaScript or, indeed, most other GUI programming environment, allowing you to take advantage of the underlying Flash infrastructure without having to worry about concepts like timelines, assets, and so on.

Flex is multi-platform—this means that, with some exceptions, you can run a Flex application on any platform that supports Adobe Flash Player. If your users run on Windows, OS X or Linux and their browsers have a recent version of the Flash Player plug-in installed, they will also be able to run your Flex applications without a problem.

Because Flex is open source, there is no cost associated with creating and distribution applications that are based on it.

Hot Tip

You can download Adobe Flex SDK for free directly from the Adobe website at http://www.adobe.com/products/flex/

What is Adobe AIR?

The Adobe Integrated Runtime (Adobe AIR) is a companion technology to the Flex framework that extends the functionality provided by the latter into desktop application development. With AIR, you can build Flex applications that can be deployed as native applications on your user's machines, thus gaining all the advantages of running in a desktop environment.

Like Flex, AIR is also cross-platform, which means that you can write your code once and immediately deploy it across multiple operating systems. Because they run natively rather than in a web browser, AIR applications also gain access to functionality that is usually restricted by the Flash Player's security model, such as local file manipulation, unrestricted access to the network, and so forth.

What is Adobe Flash Builder?

Flash Builder 4 is Adobe's IDE for developing Flex and AIR applications. Although Flash Builder 4 is not required in order to compile or run a Flex-based application, it significantly simplifies the process of Flex development by providing an integrated environment that includes code intelligence, real-time analysis, compilation support, live debugging and much more.

Flash Builder 4 is based on the open-source Eclipse IDE and can either be downloaded as a standalone product or as a plug-in for the latter. Like Eclipse, Flash Builder 4 is also crossplatform and runs on both Windows and OS X.

Hot Tip

You can download a 60-day trial of Flash Builder 4 from the Adobe website at http://www.adobe.com/products/flex/

BUILDING APPLICATIONS WITH FLASH® BUILDER™ 4 AND PHP

Even though Flex is based on Flash, you don’t need to be proficient in the latter in order to use the former.

Flex uses a language called ActionScript3 (AS3), which is itself derived from the ECMAScript standard. ECMAScript is the same basic definition on which JavaScript is based—therefore, if you have any familiarity with browser programming, it's likely that you will find your bearings in AS3 very quickly.

Flex applications are based on the concept of component. A component defines a container of behaviors and, optionally, of a user interface representation. Components can be visual or non-visual, depending on whether the provide an interface of some kind (like a button) or just functionality of some kind (like a library for connecting to a remote server).

The visual structure of a component can be easily defined using MXML, Adobe’s specialized brand of XML. Other than the use of specific namespaces, MXML is nothing more than well-formed XML code; by nesting multiple components, you can create complex GUIs without ever writing a line of code.

Creating Flex Applications

Flash® Builder 4 makes creating new applications as easy as following the steps of its New Application Wizard. Simple select New Flex® Project from the File menu, then choose a name and type for your application. If you intend to write code that will be executed inside a browser, choose "Web" for your application type; if, on the other hand, you want to build a desktop application, choose "Desktop" instead.

You newly-created Flex project will contain a component that represents the application's main entry point:


<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Declarations>
</fx:Declarations>
</s:Application>

From here on, you can add more components to your application simply by typing the MXML code that represents them in the appropriate order. However, Flash Builder 4's strength resides in its visual layout editor, which allows you to arrange and wire the different components that make up your user interface using a WYSIWYG approach. For example, you can add a DataGrid object to show the contents of a data structure and then a button to fetch the data–all enclosed in a VGroup object to provide the overall layout:

Flex’s powerful layout capabilities, like the rest of the framework, are also designed to be developer-friendly and are almost entirely based on standard CSS, with a few exceptions designed to make automated positioning easier.

Useful Flex Components

Flex provides a rich ecosystem of components that can be easily expanded to meet your needs. While many of its components are designed to closely mimic their HTML cousins, there are also a number that provide unique functionality. For example:

  • AdvancedDataGrid and DataGrid: display tabular data in a rich, editable environment.
  • DateChooser and DateField: simplify the process of choosing and formatting date values.
  • NumericStepper: allows the user to increment and decrement a numeric value.
  • RichEditableText: allows you to create a rich text editor with support for several formatting options (e.g.: italic, bold, etc.).
  • VideoDisplay/VideoPlayer: provide fully-featured and completely skinnable video players that can be embedded directly in your application.
  • HSlider/VSliders:allows the user to select a value by sliding a selector across a horizontal or vertical range.
  • HGroup/VGroup: automatically arrange their content horizontally or vertically. Combine to easily create complex layouts.
  • Accordion/TabNavigator: allow multiple content panels to stack and be displayed one at a time.
  • MenuBar/TabBar: add a menu or tab bar to your component.
  • Flex Charting: adds powerful charting abilities to your applications.

Hot Tip

While Flex Charting and AdvancedDataGrid were only available in the Professional version of Flex Builder 3, they are now included in all versions of Flash Builder 4.

Connecting to PHP with AMF Introspection

One of the most interesting features of Flex is that it is designed to provide powerful data connectivity capabilities in a variety of formats and protocols, including XML, SOAP, JSON and Adobe’s own AMF. In fact, in most cases you will be able to use Flash Builder 4 to connect your Flex application to a PHP backend without having to write a single line of code in either!

In order to use Flash Builder 4's PHP-aware functionality through AMF, you need to have direct access to the root directory of a copy of your site—either through a network share or on your local computer. To get started, select Connect to Data/Service… from the Data menu, then choose PHP from the list of available connectors. Flash Builder 4 will ask you to confirm that your project type is set to PHP, then specify both the location of your site's server root and its URL:

At this point, you can click "Validate Configuration" to make Flash Builder 4 run a simple test to determine whether it can access your site as expected, then OK to complete the set up process.

Now, Flash Builder 4 will ask you to choose a PHP class that will provide the entry point to which your Flex application will connect. If your code is not encapsulated in classes, you could create some simple stubs for the purpose of providing services to your Flash Builder 4 code. The wizard will automatically fill in the defaults for you based on the name of the PHP file that you select.

Hot Tip

In order for this system to work, it is important that the class you want to import be stored in a file of the same name [e.g.: Index inside index.php]. Otherwise, Zend_AMF will be unable to find it.

At this point, if you website does not include a copy of Zend_AMF, a Zend Framework module that Flash Builder 4 uses to marshal data, remote procedure calls and error management, you will be asked to download and install a copy. This is required because Flash Builder 4 makes use of Action Message Format (AMF), a protocol that PHP does not support by default.

Hot Tip

Your application does not need to use Zend Framework in order to take advantage of AMF—Flash Builder 4 will only use Zend_AMF in order to communicate with your server, independently of the rest of your code.

Flash Builder 4 will introspect your code and discover which methods the service makes available:

Once you click Finish, the wizard will create a series of classes inside your project that provide all the necessary functionality required to connect to your project and execute your web service.

Hot Tip

Remember that it is your responsibility to provide a security layer where required—for example, by passing a secure key to the service as appropriate.

Establishing Data Connections

Your application is now capable of connecting to the PHP backend, but the data that the latter provides is not yet wired to any of the controls.

Luckily, this, too, is something that can be done without writing a line of code. You can, instead, use the Data/Services panel, visible in the bottom tray of the Flash Builder 4 window, where all the remote data services defined in your application are visible:

All you need to do in order to connect the data returned by a service call to any of your components is to simply drag it from the Data/Services panel to the component. Flash Builder 4 will ask you whether you intend to create a new call, or use an existing one. In the former case, you will first need to specify the type of data returned by the remote service call, because the data connection wizard has no way of determining it by means of static analysis of your code.

Flash Builder 4 can, however, auto-detect the data type returned by a service call by making a call to it, or you can specify it by hand. Where a sample service call will have no adverse effects on your PHP backend, allowing the wizard to determine the return type automatically is usually sufficient and produces all the infrastructure required to handle the data on the Flex side.

Hot Tip

In order for your data to be used in a Flex application, it must conform to all the appropriate AS3 rules—for example, you cannont return objects with properties whose names are reserved AS3 keywords like protected or private, even if those are perfectly acceptable in PHP

Your Flex application now has access to all the data returned by your service. If, for example, you drag a service on to a DataGrid component, the latter will be automatically populated with all the appropriate data columns—all you need to do is remove those you don’t want displayed and rename the header of the others to the proper human-readable format:

Your application is now fully functional—if you execute it, you will see that the data service is automatically called as soon as the DataGrid object finishes loading. If the call is successful, the data is immediately loaded and displayed.

If you prefer to add a manual method of refreshing the information, you can simply drag the appropriate data call on to the button—this will create all the code needed so that, when the user clicks on it at runtime, the service will be called again and all the data automatically updated.

Differences between PHP and AS3 Data

While much of the data types are interchangeable between AS3 and PHP, there are some notable differences.

  • Integer values in PHP can either be 32- or 64-bit long, whereas, in AS3, they are always 64 bits. Therefore, you must be prepared for the fact that a numeric value passed from AS3 to PHP may be represented as a float even if it is, in fact, just a large integer.

  • String values in AS3 are always Unicode-compliant. It is up to you to ensure Unicode compliance on the PHP side.

  • Array values in AS3 can only have contiguous numeric keys starting at zero. If your PHP arrays have string keys or non-contiguous numeric keys, they will be represented as objects in AS3.

    You should avoid passing objects into AS3 that contain members whose keys are reserved keywords, as handling them will be inconvenient—and many of Flash Builder 4's facilities will refuse to work with them.

Under most circumstances, these issues are unlikely to affect your application because both AS3 and PHP have a significant amount of flexibility.

CONNECTING TO WEB SERVICES

SOAP

AMF is not your only choice when it comes to external connectivity from Flash Builder 4—almost exactly the same functionality can just as easily be used to connect to an XML web service powered by SOAP.

You can start the process by selecting Connect To Data/ Service… from the Data menu and then choosing WSDL as the service type. This will bring up a dialog box that asks you to provide the URL of the service's WSDL specification:

Like before, Flash Builder 4 will fetch the WSDL file from the server and introspect it, extracting all the available remote procedure calls. You will then be able to drag and drop the data into your application like before.

Accessing XML Services

Of course, SOAP is not the only way of retrieving XML data from a remote location. Flash Builder 4 provides facilities for introspecting a remote URL that simply returns a flat XML document and extracting information from it.

Once again, you will need to click on Connect To Data/ Service… from the Data menu and, this time, choose XML as the service type. Flash Builder 4 will ask you to provide the URL of the service you wish to access, invoke it and create a stub class in AS3 to encapsulate the data:

The resulting data provider will become available in the Data/ Services panel of Flash Builder 4's GUI, from where you can connect it to your components like before.

Hot Tip

Be mindful of the fact that, when manipulation raw XML, Flash Builder 4 has no way of determining whether your service provides data in a consistent format. Therefore, you should ensure that this is the case, or your service call may unexpectedly fail at runtime.

JSON and XML

JSON (JavaScript Object Notation) has rapidly become a very popular choice for web service development because of its simplicity, lightweight format and ease of use in a number of languages.

While PHP has had built-in support for JSON since version 5.2.0, AS3 does not have any facilities for manipulating JSON data. Luckily, Flex provides a number of different ways for using JSON.

To start, you will need a PHP script that takes zero or more parameters either through a GET or POST HTTP transaction and outputs JSON-formatted data. For example:


<?php
function getTimeline($user) {
	$data = json_decode(
		file_get_contents("
			http://api.twitter.com/1/statuses/user_timeline.
			json?screen_name=" . urlencode($user)));
	
	foreach($data as $v) {
		unset($v->user->protected);
	}
	return $data;
}
echo json_encode(getTimeline($_GET['user']));

The simplest way of connecting to this service consists of once again using the Data/Service Connector wizard to access arbitrary HTTP-based web services. Choosing "HTTP" from the Connect To Data/Service… menu will result in this dialog, where Flash Builder 4 asks for the URL of the service and its parameters:

Once you provide the correct information and click on Finish, the wizard will once again create all the infrastructure required to run your service and make it available as before. The HTTP Data/Service Connection wizard also supports XML data.

DEPLOYING YOUR APPLICATION

In most cases, you will want to develop your application in Debug mode. This causes the Flex compiler to add all sorts of useful information that can be used to debugger to help you address any issues that may occur within your application.

However, when it comes time to deploy your application for production, you will want to switch to a Release build so that you can end up with the most compact and efficient codebase possible. You can do so by selecting Export Release Build... from the Build menu.

Exporting a Release build causes a new directory, called binrelease, which contains a number of different files:

Most of these files play a support role to your application—in fact, the only one you will normally interact with is the host HTML file that contains the code required to display your application.

Hot Tip

You can change the template used to generate your host HTML file by editing the html-template/index.template. html file in your application's root directory.

Passing Data to Your Flex Application

It is sometimes useful to pass data, like request parameters, to your Flex application as it is being initialized on the client browser.

This can be accomplished by introducing a special parameter in the HTML code that causes the application to be embedded in the web page. In reality, Flex provides a series of convenient wrappers that make the job even easier; if you look inside your HTML template, you will find a portion of code that looks like:


var flashvars = {};
...
swfobject.embedSWF(
		"Fle.swf", "flashContent",
		"100%", "100%",
		swfVersionStr, xiSwfUrlStr,
		flashvars, params, attributes);

All you need to do is change the content of flashVars to suit your need—that same data will be made available inside the application as the FlexGlobals.topLevelApplication.parameters object, where you can peruse it as needed.

Understanding the Security Model for Flash

When running in the browser, Flash employs a very strict security model that places your code in a sandbox through which all network and disk activities are regulated.

Hot Tip

For more information about the Flash security model, read the "Security" section under "Application architecture" in the Flash Builder help online at http//help.adobe.com/en_US/Flex/4.0/UsingSDK/

The sandbox is turned off during debugging—therefore, you don't normally become aware of it until you run your code in production mode and find out that your application cannot access any of its remote data.

Flash supports a number of different sandboxes, depending on what kind of data your application needs to deal with. Most of the time, you will want to use the local-with-networking sandbox, which allows your application to access remote locations, but denies all access to local files.

By default, the sandbox model prevents an application from accessing any resources outside of its own domain, unless that domain specifically grants access with a crossdomain.xml file. Therefore, it is important to remember that you may not be able to access information across different domains.

Hot Tip

Adobe AIR applications usually run in the local-trusted sandbox and, therefore, are not subject to connectivity restrictions.

Documenting Your Code with ASDoc

While much of the functionality provided by Flex can be accessed without writing significant amounts of AS3 code, it is entirely possible to address extremely complex tasks entirely within the Flex runtime — systems as complex as encryption engines and image compression libraries have been built in pure AS3 and are used in production every day (in fact, the entire Flex framework itself is built in AS3 as well).

Through a featured called ASDoc, Flash Builder 4 allows you to write inline comments that can be used to document your entire codebase. The syntax used by ASDoc is very similar to the PHPDoc syntax that is commonly used to comment PHP code; for example:


/**
* Performs some important function
*
* @param event The event dispatched to this method
*/
protected function handler(event:FlexEvent):void
{
	// Do something
}

Flash Builder 4 will automatically scan your code and add any information you write as part of your ASDoc blocks to its code intelligence features; these, in turn, will display the information as you use your code, providing you with a handy dynamic reference for your classes and methods:

About The Author

Marco Tabini

Marco Tabini is the co-founder, with Arbi Arzoumani, of php|architect, the world's largest PHP magazine in the English language, currently distributed in over 145 countries. He is also the co-founder, with Keith Casey, of Blue Parabola, LLC, a consulting firm that specializes in information architecture, code and security auditing, large-scale deployments and optimization.

An accomplished author on the subject of PHP and the business of web development, Marco is also a frequent speaker at PHP and OSS conferences throughout the world.

Recommended Book

Flash Builder 4 and Flex 4

Create desktop applications that behave identically on Windows, Mac OS X, and Linux with Adobe's new Flash Builder 4 platform and this in-depth guide. The book's tutorials and explanations walk you step-by-step through Flash Builder’s new, faster tools; the new framework for generating code; how to connect to popular application servers; upgrading from Flex 3; and much more.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Daily Dose: LinkedIn Goes Public!

LinkedIn, the popular social networking site for professionals, is going public! Selling at $45 per share, the 7.84 million shares total to an amazing $352.8 million. Originally, LinkedIn had considered offering the shares at $32-$35 per share. Soon,...

0 replies - 21446 views - 05/18/11 by Katie Mckinsey in Daily Dose

Scripps Networks finds a fit Case Study

0 replies - 3122 views - 05/18/11 by Brandon Nokes in Whitepapers