RIA

  • submit to reddit

Getting Started with JavaFX

By Stephen Chin

17,506 Downloads · Refcard 56 of 151 (see them all)

Download
FREE PDF


The Essential JavaFX Cheat Sheet

JavaFX makes it easier to build better RIAs with graphics, animation, and media. Built on Java, this platform uses existing Java libraries and is capable of running in your browser, on your desktop, and on your phone. This DZone Refcard is ideal for the beginner, and will help you get started programming with JavaFX Script. It will also serve as a convenient reference once you have mastered the language. The instructions in this Refcard assume that you are using an IDE, but it is also possible to do everything from the command line as well.
HTML Preview
JavaFX

Getting Started with JavaFX

By Stephen Chin

About JavaFX

JavaFX is an exciting new platform for building Rich Internet Applications with graphics, animation, and media. It is built on Java technology, so it is interoperable with existing Java libraries, and is designed to be portable across different embedded devices including mobile phones and set-top boxes. This Refcard will help you get started programming with JavaFX Script and also serve as a convenient reference once you have mastered the language.

To get started, you will have to download the latest JavaFX SDK from the JavaFX website here: http://javafx.com/.

The instructions in the following tutorial assume that you are using an IDE, such as NetBeans. However, it is possible to do everything from the command line as well.

JFXPoetry, a si mple exa mple

To illustrate how easy it is to build an application that melds graphics, text, animation, and media, we will start with a simple tutorial. The goal will be to write an application that:

  • Loads and displays an image from the internet
  • Displays and animates a verse of poetry
  • Declaratively mixes in graphic effects
  • Plays media asynchronously

For the JFXPoetry theme, we will use “Pippa’s Song,” a wellknown excerpt from Robert Browning’s Pippa Passes.

Loading an Image on the Stage

Stage and Scene are the building blocks of almost every JavaFX program. A Stage can either be represented as a Frame for desktop applications, a rectangle for applets, or the entire screen for mobile devices. The visual content of a Stage is called a Scene, which contains a sequence of content Nodes that will be displayed in stacked order. The following program creates a basic Stage and Scene which is used to display an image:


var scene:Scene;
Stage {
  title: “Pippa’s Song by Robert Browning”
  scene: scene = Scene {
    content: [
      ImageView {
        image: bind Image {
	 height: scene.height
	 preserveRatio: true
	 url: “http://farm1.static.flickr.com/39/
	    121693644_75491b23b0.jpg”
        }
      }
    ]
  }
}

Notice that that JavaFX syntax makes it simple to express nested UI structures. The curly braces “{}” are used for object instantiation, and allow inline initialization of variables where the value follows the colon “:”. This is used to instantiate an ImageView with an Image inside that loads its content from the given URL. To ensure the image resizes with the window, we set preserveRatio to true and bind the Image. Binding is a very powerful facility in JavaFX that makes it easy to update values without heavyweight event handlers. Compiling and running this application will display a picture of a misty morning in Burns Lake, BC, Canada taken by Duane Conlon as shown in Figure 1.1 2

Figure 1.1 2

Figure 1: A JavaFX Stage containing an image loaded from the network

Displaying Text With Effects

Displaying text in JavaFX is as simple as instantiating a Text Node and setting the content to a String. There are many variables available on Text, but for this example we will set the font, fill color, and also add a Drop Shadow effect to make the text stand out on the background.


1 Creative Commons Attribution 2.0 License: http://creativecommons.org/licenses/by/2.0/

2 Duane Conlon’s Photostream: http://www.flickr.com/photos/duaneconlon/


var text:Text;
Stage {
	  ...
	  ImageView {
        ...
	  },
	  text = Text {
		effect: DropShadow {}
		font: bind Font.font(“Serif”, FontWeight.BOLD,
					  scene.height / 12.5)
	    fill: Color.GOLDENROD
	    x: 10
	    y: bind scene.height / 6
	    content: “The year’s at the spring,\n”
				 “And day’s at the morn;\n”
				 “Morning’s at seven;\n”
				 “The hill-side’s dew-pearled;\n”
				 “The lark’s on the wing;\n”
				 “The snail’s on the thorn;\n”
				 “God’s in His heaven--\n”
				 “All’s right with the world!”
        }

Notice that rather than specifying the whole poem text on one line we have split it across several lines, which will automatically get concatenated. Also, we have used the bind operator to set both the font size and y offset, which will update their values automatically when the scene height changes. Figure 2 shows the updated example with text overlaid on the Image.

Figure 2

Figure 2: Updated example with a Text overlay

JavaFX offers a large set of graphics effects that you can easily apply to Nodes to create rich visual effects. Table 1 lists all the available effects you can choose from.

Table 1. Graphics effects available in JavaFX

Effect Description
Blend Blends two inputs together using a pre-defined BlendMode
Bloom Makes brighter portions of the Node appear to glow
BoxBlur Fast blur with a configurable quality threshold
ColorAdjust Per-pixel adjustments of hue, saturation, brightness, and contrast
DisplacementMap Shifts each pixel by the amount specified in a DisplacementMap
DropShadow Displays an offset shadow underneath the node
Flood Fills a rectangular region with the given Color
GaussianBlur Blurs the Node with a configurable radius
Glow Makes the Node appear to glow with a given intensity level
Identity Passes an image through to a chained effect
InnerShadow Draws a shadow on the inner edges of the Node
InvertMask Returns a mask that is the inverse of the input
Lighting Simulates a light source to give Nodes a 3D effect
MotionBlur Blurs the image at a given angle to create a motion effect
PerspectiveTransform Maps a Node to an arbitrary quadrilateral for a perspective effect
Reflection Displays an inverted view of the Node to create a reflected effect
SepiaTone Creates a sepia tone effect to mimic aged photographs
Shadow Similar to a DropShadow, but without the overlaid image

Animated Transitions

Animations in JavaFX can be accomplished either by setting up a Timeline from scratch, or using one of the pre-fabricated Transitions. To animate the Text rising onto the screen, we will use a TranslateTransition, which adjusts the position of a Node in a straight line for the specified duration:


var animation = TranslateTransition {
  duration: 24s
  node: text
  fromY: scene.height
  toY: 0
  interpolator: Interpolator.EASEOUT
}
animation.play();

By setting an interpolator of EASEOUT, the text will start at full speed and gradually deaccelerate as it approaches its destination. Animations and Transitions can also be configured to repeat, run at a specific rate, or reverse. To run the transition, all you need to do is call the play() function, which will animate the text as shown in Figure 3.

Figure 3

Figure 3: Animated Text Scrolling Into View

Table 2 lists all of the available transitions that are part of the JavaFX API. To get a feel for how the different transitions work, try adding a FadeTransition that will gradually fade the background in over a 5 second duration.

Table 2. Transitions Supported by JavaFX

Transition Description
FadeTransition Changes the opacity of a node over time
ParallelTransition Plays a sequence of transitions in parallel
PathTransition Animates nodes along a Shape or Path
PauseTransition Executes an action after the specified delay
RotateTransition Changes the rotation of a node over time
ScaleTransition Changes the size of a node over time
SequentialTransition Plays a sequence of transitions in series
TranslateTransition Changes the position of a node over time

Interacting With Controls

The JavaFX 1.2 release features a new library of skinnable controls written in pure JavaFX. Table 3 lists some of the new controls and what they can be used for.

Table 3. Controls Available in JavaFX 1.2

Control Description
Button Button that can contain graphics and text
CheckBox Selectable box that can be checked, unchecked, or undefined
Hyperlink HTML-like clickable text link
Label Text that can be associated with anther control
ListView Scrollable list that can contain text or Nodes
ProgressBar Progress bar that can show percentage complete or be indeterminate
RadioButton Selectable button that can belong to a group
ScrollBar Scroll control typically used for paging
Slider Draggable selector of a number or percent
TextBox Text input control

The simplest control to use is a Button, which can easily be scripted to play the animation sequence again from the beginning.


var button:Button;
Stage {
...
text = Text {
...
    },
    button = Button {
        translateX: bind (scene.width - button.width) / 2
        translateY: bind (scene.height - button.height) / 2
        text: “Play Again”
      visible: bind not animation.running
      action: function() {
        animation.playFromStart();
      }
    }
  ]

Ths bind operator is used to both hide the button while the animation is playing and also center the button in the window. Initially the button is invisible, but we added a new SequentialTransition that plays a FadeTransition to show the button after the translation is complete. Clicking the button shown in Figure 4 will hide it and play the animation from the beginning.

Figure 4

Figure 4: Button Control to Play the Animation Again

Panning With Layouts

JavaFX 1.2 comes with several new layouts that make it easy to design complex UIs. One of these is the ClipView, which we will use to support dragging of the poem text. ClipView takes a single Node as the input and allows the content to be panned using the mouse:


 content: [
...
    ClipView {
	 width: bind scene.width
	 height: bind scene.height
	 override var maxClipX = 0
	 node: text = Text {
...
     }
   }

To ensue the ClipView takes the full window, its width and height are bound to the scene. Also, we have overridden the maxClipX variable with a value of 0 to restrict panning to the vertical direction. The text can now be dragged using the mouse as shown in Figure 5.

Figure 5

Figure 5: Panning the Text using a ClipView

Table 4 lists all of the available layouts that come JavaFX comes with. HBox and VBox have been around since the 1.0 release, but all the other layouts are new in JavaFX 1.2.

Table 4. Layouts Available in JavaFX 1.2

Layout Description
HBox Lays out its contents in a single, horizontal row
VBox Lays out its contents in a single, vertical column
ClipView Clips its content Node to the bounds, optionally allowing panning
Flow Lays out its contents either vertically or horizontally with wrapping
Stack Layers its contents on top of each other from back to front
Tile Arranges its contents in a grid of evenly sized tiles

Finishing with Media

JavaFX has built-in media classes that make it very simple to play audio or video either from the local files or streaming off the network. To complete the example we will add in a public domain clip of Indigo Bunting birds chirping in the background. Adding in the audio is as simple as appending a MediaPlayer with autoPlay set to true that contains a Media object pointing to the URL.


MediaPlayer {
  autoPlay: true
  media: Media {
    source: “http://video.fws.gov/sounds/35indigobunting.mp3”
  }
}

In this example we are using an mp3 file, which is supported across platforms by JavaFX. Table 5 lists some of the common media formats supported by JavaFX, including all the crossplatform formats.

Table 5. Common Media Formats Supported by JavaFX

Type Platform Format File Extension
Audio Cross-platform MPEG-1 Audio Layer 3 mp3
Audio Cross-platform Waveform Audio Format wav
Audio Macintosh Advanced Audio Coding m4a, aac
Audio Macintosh Audio Interchange File Format aif, aiff
Video Platform Format File Extension
Video Cross-platform Flash Video flv, f4v
Video Cross-platform JavaFX Multimedia fxm
Video Windows Windows Media Video wmv, avi
Video Macintosh QuickTime mov
Video Macintosh MPEG-4 mp4

To try the completed example complete with animation and audio, you can click on the following url:

http://jfxtras.org/samples/jfxpoetry/JFXPoetry.jnlp

The full source code for this application is available on the JFXtras Samples website: http://jfxtras.org/portal/samples

Running on Mobile

To run the sample in the Mobile Emulator all you have to do is pass in the MOBILE profile to the javafxpackager program or switch the run mode in your IDE project properties. JavaFX Mobile applications are restricted to the Common Profile, which does not include all the features of desktop applications. The full list of restrictions is shown in Table 5.

Table 5. Functionality Not Available in the Common Profile

Class(es) Affected Variables and Methods
javafx.ext.swing.* All
javafx.reflect.* All
javafx.scene.Node effect, style
javafx.scene.Scene stylesheets
javafx.scene.effect.* All
javafx.scene.effect.light.* All
javafx.scene.shape.ShapeIntersect All
javafx.scene.shape.ShapeSubtract All
javafx.scene.text.Font autoKern, embolden, letterSpacing, ligatures, oblique, position
javafx.stage.AppletStageExtension All
javafx.util.FXEvaluator All
javafx.util.StringLocalizer All

Over 80% of the JavaFX API is represented in the Common Profile, so it is not hard to build applications that are portable. In this example we used a DropShadow on the text that, once removed, will let us run the example in the Mobile Emulator as shown in Figure 6.

Figure 6

Figure 6: JFXPoetry application running in the Mobile Emulator

Running as a Desktop Widget

You can deploy your application as a desktop widget using the WidgetFX open-source framework. Any JavaFX application can be converted to a widget by including the WidgetFX-API.jar and making some small updates to the code.

The Following code fragment highlights the code changes required:


var widget:Widget = Widget {
  resizable: false
  width: 500
  height: 375
  content: [
...
      height: widget.height
...
    font: bind Font.font(“Serif”, FontWeight.BOLD,
              widget.height / 12.5)
...
    y: bind widget.height / 6
...
  ]
}


...
    fromY: widget.height
...
widget;

The updates to the code include the following three changes:

  • Wrap your application in a Widget class. The Widget class extends javafx.scene.layout.Panel, which makes it easy to extend.
  • Set the initial widget width/height and modify references from scene to widget.
  • Return the widget at the end of the script.

To run the widget, simply change your project properties to run the application using Web Start Excecution. This will automatically create a JNLP file compatible with WidgetFX and launch the Widget Runner, which allows you to test your widget as shown in the Figure 7.

Figure 7

Figure 7: JFXPoetry running as a desktop widget

For more information about WidgetFX, including SDK download, documentation, and additional tutorials, check out the project website: http://widgetfx.org/

JavaFX Reference

Language Reference

JavaFX supports all the Java datatypes plus a new Duration type that simplifies writing animationed UIs.

Data Types:

DataType Java Equivalent Range Examples
Boolean boolean true or false true,false
Integer int -2147483648 to 2147483647 2009, 03731, 0x07d9
Number float 1.40×10 45 and 3.40×1038 3.14, 3e8, 1.380E-23
String String N/A “java’s”, ‘in”side”er’
Duration <None> -263 to 263-1 milliseconds 1h, 5m, 30s, 500ms
Character char 0 to 65535 0,20,32
Byte byte -128 to 127 -5, 0,5
Short short -32768 to 32767 -300, 0, 521
Long long -263 to 263-1 2009, 03731,0x07d9
Float float 1.40x10 45 and 3.40x1038 3.14, 3e8, 1.380E-23
Double double 4.94x10 324 and 1.80x10308 3.14, 3e8, 1.380E-123

JavaFX Characters cannot accept literals like ‘a’ or ‘0’, because they are treated as Strings. The primary way of getting Characters will be by calling a Java API that returns a char primitive, although you can create a new character by assigning a numeric constant

Operators:

The following table lists all the mathematical, conditional, and boolean operators along with their precedence (1 being the highest).

Operator Meaning Precedence Examples
++ Pre/post increment 1 ++i, i++
-- Pre/post decrement 1 --i, i--
not Boolean negation 2 not (cond)
* Multiply 3 2 * 5, 1h * 4
/ Divide 3 9 / 3, 1m / 3
mod Modulo 3 20 mod 3
+ Add 4 0 + 2, 1m + 20s
- Subtract (or negate) 4 (2) -2, 32 - 3, 1h - 5m
== Equal 5 value1 == value2, 4 == 4
!= Not equal 5 value1 != value2, 5 != 4
< Less than 5 value1 < value2, 4 < 5
<= Less than or equal 5 value1 <= value2, 5 <= 5
< Greater than 5 value1 > value2, 6 > 5
>= Greater than or equal 5 value1 >= value2, 6 >= 6
instanceof Is instance of class 6 node instanceof Text
as Typecast to class 6 node as Text
and Boolean and 7 cond1 and cond2
or Boolean or 8 cond1 or cond2
+= Add and assign 9 value += 5
-= Subtract and assign 9 value -= 3
*= Multiply and assign 9 value *= 2
/= Divide and assign 9 value /=4
= Assign 9 value = 7
  • Multiplication and division of two durations is allowed, but not meaningful
  • Underflows/Overflows will fail silently, producing inaccurate results
  • Divide by zero will throw a runtime exception

Sequences:

JavaFX sequences provide a powerful resizable and bindable list capability under a simple array-like syntax. All of the sequence operators (sizeof, reverse, indexof) have a relative precedence of 2.

Operation Syntax Examples
Construct

[x,y,z]
[y..z]
[y..<z]
[y..z step w]


var nums = [1, 2, 3, 4]; var letters = [“a”, “b”, “c”];
[1..5] = [1, 2, 3, 4, 5]
[1..>5] = [1, 2, 3, 4]
[1..9 step 2] = [1, 3, 5, 7, 9]

Size sizeof seq sizeof nums; // = 4
Index indexof variable

for(x in seq) {
indexof x;
}

Element seq[i] letters[2]; // = “c”
Slice

eq[x..y]
seq[x..<y]


nums[1..2]; // = [2, 3]
letters[0..<2]; // = [“a”, “b”]

Predicate seq[x|boolean] nums[n|n mod 2 == 0]; // = [2, 4]
Reverse reverse seq reverse letters; // = [“c”, “b”, “a”]
Insert

insert x into seq
insert x before seq[i]
insert x after seq[i]


insert 5 into nums; // = [1, 2, 3, 4, 5]
insert “gamma” before letters[2]; // = [“a”, “b”,
“gamma”, “c”]
insert “2.3” after nums[1]; // = [1, 2, 2.3, 3, 4]

Delete

delete seq[i]
delete seq[x..y]
delete x from seq
delete seq


delete letters[1]; // = [“a”, “c”]
delete nums[1..2]; // = [1, 4]
delete “c” from letters; // = [“a”, “b”]
delete letters; // = []

  • The javafx.util.Sequences class provides additional functions, which allow you to manipulate sequences, such as min, max, search, shuffle, and short.
  • Nested sequences are automatically flattened, so [[1,2], [3,4]] is equivalent to [1,2,3,4].
  • Sequences require commas after all elements except close braces; however it is recommended to always use commas
  • You can declare a sequence as a nativearray. This is an optimization so that arrays returned from a Java method don’t need to be converted to a sequence.

Access Modifiers:

The JavaFX access modifiers are based upon Java with the addition of extra variable-only modifiers.

Modifier Name Description
<Default> Script only access Only accessible within the same script file
package Package access Only accessible within the same package
protected Protected access Only accessible within the same package or by subclasses
public Public access Can be accessed anywhere
publicread

Read access
modifier

Var/def modifier to allow a variable to be read anywhere
public-init Init access modifier Var/def modifier to allow a variable to be initialized or read anywhere
  • Unlike Java the default permission in JavaFX is script-only rather than package.
  • The var/def access modifiers can be stacked with other modifiers, such as public-read protected

Expressions:

JavaFX supports many of the same expressions as Java, but adds in powerful inline functions and for loop extensions.

Expression Syntax Example
if

if (cond) expr1 else expr2
if (cond) then expr1 else expr2


if (grass.green) {
  grass.mow();
} else {
  grass.water();
}
var water = if (grass.color ==
BLACK) aLot else aLittle;

for

for (x in seq) expr
for (x in seq where cond) expr
for (x in seq, y in x) expr


var loans = for (b in borrowers
where b.pulse > 0)
{
  b.createLoan();
}
for (loan in loans) {
  loan.approve();
}

while while (bool) expr

while (swimming) {
  paddle();
  breathe();
}


try/catch/
finally


try {expr1} catch(exception)
{expr2} finally {expr3}


try {
  Bailout();
} catch(e:FinancialCrisis) {
  massiveBailout();
} finally {
  increaseTaxes();
}

function function(params):returnType{}

function(e:MouseEvent):Void {
     e.source.toFront();
}

Just like in Java programs:

  • continue can be used to skip a for or while loop iteration
  • break can be used to exit a for or while loop
  • return can be used to exite from a function event if inside a loop

Magic Variables:

JavaFX provides some built-in variables that can be accessed from any code running inside a script.

Name Description
__DIR__ Directory the current classfile is contained in
__FILE__ Full path to the current classfile
__PROFILE__ The current profile, which can be ‘desktop’ or ‘mobile’

API Reference

In the short span of a few pages you have already seen quite a bit of the JavaFX platform. Some other functionality that JavaFX offers includes:

Package Description
javafx.animation Animation and Interpolation
javafx.async Asynchronous Tasks and Futures
javafx.data.feed RSS/Atom Feed support
javafx.data.pull XML and JSON Pull Parsers
javafx.ext.swing Additional Swing-based Widgets
javafx.fxd Production Suite (FXD)
javafx.io Local Data Storage
javafx.reflect JavaFX Reflection Classes
javafx.chart Charting and Graphing
javafx.scene.media Media (Audio and Video) Playback
javafx.scene.shape Vector Shapes

An easy way to view and navigate the full JavaFX API is using the JFXplorer application. The following URL will launch it in as a web start application that you can use to start exploring the JavaFX API today:

http://jfxtras.org/samples/jfxplorer/JFXplorer.jnlp

Additional Resources

About The Author

Photo of Stephen Chin

Open-Source Developer and Agile Manager, Stephen Chin is founder of numerous opensource projects including WidgetFX and JFXtras and Senior Manager at Inovis in Emeryville, CA. He has been working with Java desktop and enterprise technologies for over a decade, and has a passion for improving development technologies and process. Stephen’s interest in Java technologies has lead him to start a Java and JavaFX focused blog and coauthor the upcoming Pro JavaFX Platform book together with Jim Weaver, Weiqi Gao, and Dean Iverson.

Stephen’s Blog:

http://steveonjava.com/

Jim Weaver’s JavaFX Learning Blog:

http://learnjavafx.typepad.com/

Recommended Book

ProJavaFX

Learn from bestselling JavaFX author Jim Weaver and expert JavaFX developers Weiqi Gao, Stephen Chin, and Dean Iverson to discover the highly anticipated JavaFX technology and platform that enables developers and designers to create RIAs that can run across diverse devices. Covering the JavaFX Script language, JavaFX Mobile, and development tools, Pro JavaFX™ Platform: Script, Desktop and Mobile RIA with Java™ Technology provides code examples that cover virtually every language and API feature.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Refcardz Cheat Sheet - Getting Started with Griffon

Get your free DZone Refcard on Getting Started with Griffon now!

0 replies - 7900 views - 07/19/10 by Lyndsey Clevesy in Announcements

Getting Started with Griffon

By Hamlet DArcy

7,318 Downloads · Refcard 107 of 151 (see them all)

Download
FREE PDF


The Essential Griffon Cheat Sheet

Griffon is a Grails-like application for rich desktop applications and is built on top of Groovy, Java, and Swing. Griffon embraces convention over configuration, automates many common development tasks, and features a large and growing plugin system. Griffon also features property binding for widgets and a broad and extensible event system. These combine to make Griffon an excellent choice for rich Internet applications. This DZone Refcard provides you with the essentials you need to get up and running with Griffon.
HTML Preview
Getting Started with Griffon

Getting Started with Griffon

By Hamlet D'Arcy

WHAT IS GRIFFON?

Griffon is a Grails like application framework for rich desktop applications and is built on top of Groovy, Java, and Swing. Griffon embraces convention over configuration, automates many common development tasks, and features a large and growing plugin system. Griffon also features property binding for widgets and a broad and extensible event system. These combine to make Griffon an excellent choice for rich Internet applications. You can write maintainable and well designed applications quickly without spending time on builds, deployment, or configuration tweaking. You also get a rocksolid, secure, and well-known platform in the JVM, and along with the productivity boost of a modern, dynamic language while retaining and using all your Java expertise.

FROM 0 TO DEPLOYED

Griffon is a full life-cycle framework: it automates not just creation and maintenance of applications, but also build and deployment tasks. We’ll cover Model-View-Controller next, but let’s start with creating, running, packaging, and deploying an app with Java WebStart, going from nothing to deployed in about 5 minutes time. We could deploy as an applet, Jar, or desktop installation as well, but WebStart is the most interesting for RIAs.

Prerequisites - You should have the Java Development Kit (JDK) version 1.5+ (Version 6 recommended).

Installing Griffon - Download the latest release from http://griffon.codehaus.org/. Simply extract the .zip file somewhere on your machine. Next, create an environment variable called GRIFFON_HOME, pointing to the directory you unzipped the package, and add GRIFFON_HOME/bin to your path. The Griffon website contains instructions on how to set environment variables if you need more specific guidance. If you’ve done everything correctly then you should be able to open a command prompt, enter “griffon help”, and see a help message from Griffon.


$ griffon help
Welcome to Griffon 0.3.1 - http://griffon.codehaus.org/
...

Griffon provides many commands to help you create and manage an application, and plugins may add more commands. “griffon help” will display all the available commands for your system.

griffon help Displays all the available commands for the Griffon installation
griffon <target> help Displays help for the specified target

Creating an Application – A full application stack is only a command away. Simply run “griffon create-app” and enter the name for the app when you are prompted.


$ griffon create-app
...
Application name not specified. Please enter:
Starter
...
Created Griffon Application at /home/hdarcy/dev/Starter
$ cd Starter

This step creates an entire project on your disk: standard directory layout, MVC groups, internationalization bundles, build scripts, IDE files, and more. The application is little more than a Hello World app at this point, but you can run it.

griffon create-app Creates a new Griffon application

Running the Application – Griffon apps are desktop applications that a user can install, Applet applications that run in a browser, and WebStart applications that run as Internet apps. Griffon hides the platform differences from you so any Griffon app you write can be deployed in any of these forms. To run the application on your desktop enter “griffon runapp”, and your Hello World style window will pop up shortly after the compile and packaging automatically finishes.

window1

It’s not much to look at yet, but pretty good considering we have written no code. You can also run the application using “griffon run-applet” or “griffon run-webstart”.

griffon run-app Compiles and runs the application as a desktop app
griffon run-applet Compiles and runs the application a browser Applet
griffon run-webstart Compiles and runs the application as a JNLP Webstart project

Signing the Application – The Java platform offers excellent security options, but the in past configuring these options was complex. This is an optional step, you do not need to sign applications, but you should, and Griffon handles all the hard work of managing digital signatures and signing Jar files for you with just two easy steps. First create your digital signature using the JDK’s keytool program (unless your company already has done this). We’ll call ours MyKey.


$ keytool -genkey -alias MyKey

You’ll be prompted to enter a password, as well as your name, company, and location. This creates the required Java key files in your home directory. Now we just need to tell our application about this key file. In a text editor, open the ./griffon-app/conf/Config.groovy configuration file. There are 5 entries that need to be changed in order to properly sign a WebStart application. In the environments.production. signingkey.params properties, add the following settings modified with your home directory and key name:


sigfile = ‘MyKey’
keystore = “/home/hdarcy/.keystore”
alias = ‘MyKey’

Then, under environments.production.griffon turn Jar packing off and specify your Internet deployment location.


jars {
	pack = false
}
webstart {
	codebase = ‘http://www.canoo.com/griffon/starter’
}

Finished. The Jars will all be signed the next time you package the app.

Hot Tip

Groovy property files are an improved version of Java property files. The old .properties file syntax of “key=value” can still be used if you want. However, properties are hierarchical and grouped, and the Groovy syntax makes these groupings more apparent. Plus, you can put any code you want in a property file and have it execute.

Packaging and Deployment – To package your application, run the “griffon package” target. This creates deployable files for Jar, Applet, and WebStart deployments. You’ll be prompted for your keystore password during the signature process. From here, just copy all the contents of your ./dist/webstart folder onto any webserver and your application is ready to launch over the Internet. You can see this sample deployed at http://canoo.com/griffon/starter. There is no need for a Java Servlet container, just copy the files and access the URL.

griffon package Packages the application into deployable bundles

SWING DONE RIGHT

Consistent Project Structure - Griffon projects follow a convention; all Griffon projects are meant to look the same. This consistency eases maintenance costs and promotes application best practices. The following table shows the project layout for a default project, and lists the contents of each folder.

Project Structure

./griffon-app/conf Build and runtime configuration data
./griffon-app/controllers Controller classes, orchestrate views and models
./griffon-app/i18n Message bundles for internationalization
./griffon-app/lifecycle Scripts to run on application events
./griffon-app/models Model classes
./griffon-app/resources Images, properties, and other resources
./griffon-app/views User interface view classes
./lib Jar files and libraries
./scripts Gant scripts, a Groovy wrapper around the Ant build tool
./src/main Other source files, with many JVM languages supported
./test Testing files, at both the integration and unit level

Hot Tip

When configuring version control for your project, do not check in these files: dist, staging, stacktrace. log, and the .iws file. Instead, add them to your VC’s ignore list.

Pervasive MVC – Model-View-Controller (MVC) is an often used design pattern that separates concerns in applications. An MVC pattern contains three essential elements: A View defines how your application looks. Buttons, Frames, and Widgets are all part of the view layer. A Controller defines how your application behaves. Querying the database, managing data, and coordinating user events are all part of the controller layer. The Model holds data and state required by both the controller and view. The state of buttons, the contents of text boxes, and dirty field tracking are all part of the model layer.

Hot Tip

A Griffon model is not a domain model, but an application model. As such, the Griffon model makes it easy for the controller and view to exchange data in a toolkit agnostic way. A domain model describes the conceptual entities in your software system. Consider the difference between an Employee object (a domain model) and an EmployeeTableModel (an application model).

Our starter application contains exactly one MVC triad: the main frame. Larger Griffon applications are made of many MVC triads, which are all defined in ./griffon-app/conf/Application.groovy. An MVC triad can be based around an entire window, a panel, or simply a widget. Beginners often create one MVC triad for each window in their application, but this is a mistake. MVC is a pattern you apply to components or bundles of components. The WeatherWidget sample application from the Griffon distribution illustrates this:

window2

In this window there are two visible MVC triads: The main frame WeatherWidget, which contains four SmallForecast MVC triads (one for each day of the week shown). Creating and reusing MVC triads is a key design and decomposition technique for building Griffon applications. Strive to build many, small, and reusable MVC triads within your application. This Griffon command will help you:

griffon create-mvc Creates a new MVC group: model, view, controller, and test

SIMPLE MVC

Griffon supports many view layer GUI toolkits through plugins: Swing (the default), Eclipse Standard Widget Toolkit (SWT), Pivot, Gtk, and even JavaFX. Using these toolkits is as easy as installing the appropriate plugin. For now, we’ll stay in Swing and start with an example. Following is a modified MVC Group from the first example, we’re adding a button and a simple counter to the screen. The view script adds a button and a label to the form, and the Controller simply updates a counter. The Model is used to communicate between the two:

model

ClickerView.groovy

application(title:’Clicker’) {
	gridLayout(rows: 2, cols: 1)
	label(text:bind {model.message})
	button(text: ‘Click Me’, actionPerformed: controller.&action)
}

ClickerController.groovy

class ClickerController {
	def model
	def counter = 0
	def action = {
	model.message = “Count: ${counter++}”
	}
}

ClickerModel.groovy

class ClickerModel {
	@groovy.beans.Bindable String message
}

The launched application looks like this once we click the button a few times:

clicker

View - The view script is Groovy and relies heavily on SwingBuilder, a Groovy convenience class for building Swing based UIs. As you can see, SwingBuilder is a terse and DSL-like script for writing widgets and configuration, which maps closely to the Swing API. In case you are not too familiar with Groovy, here is a quick summary of how this View script relates back to the JDK:

gridLayout(rows: 2,cols: 1) Applies the Java GridLayout to the current container. Parameters are named explicitly and map to the Java constructor or setter methods.
label(text:bind {model.message}) label() is a dynamic method and creates a JLabel in the current container. The text of the label is bound to a model property called message. Any updates to the model.message field will result in the label being updated. All of the event notification and listeners are handled for you.
button(text:’Click Me’, ...) button() is a dynamic method and creates a JButton in the current container. Setters may be invoked as named argument parameters.
actionPerformed: controller&action Creates and adds a Swing ActionListener to the component. This is the Groovy alternative to an anonymous inner class. When the button is clicked the controller is invoked.

Hot Tip

Laying out components in Swing forms is notoriously difficult using the GridBagLayout, which is exactly why MigLayout was created. It’s goal is to make complex layouts easy and normal layouts one-liners, and may of the Griffon team swears by it. Just install the miglayout plugin to get started.

Groovy adds a simplifying layer over the standard GUI toolkits, like Swing; however, GUI toolkits are usually large and complex. It is worthwhile to invest in one of the many Swing books available. Groovy in Action contains a thorough treatment of SwingBuilder, and the Oracle online documentation for Swing is excellent.

Controller – The controller simply updates a counter and tells the model that an update occurred. The model field is automatically injected into controllers by Griffon (as is the view, if you desire). The action field is just a closure (think Runnable) that writes a new message back to the model.

Model – The communication hub holds a simple String field marked @Bindable. This lets Griffon know that objects may bind to the property, and any time the property is updated then the correct PropertyChangeListeners will fire and observers will be notified. Those with a Swing background will understand that this simple annotation removes about 50 lines of boilerplate Swing code!

Advanced Data Binding – Binding widgets to a model is a requirement for modern GUI toolkits. But if you’ve worked with other tools you may be worried about too many events being posted and your application slowing down under a load of bound requests, a situation known as a “Bind Storm”. Griffon offers a flexible API to shelter you from this condition:

bind() Adds automatic event listeners and ties a component to a model
unbind() Removes the automatic listeners from a component
rebind() Reinstates the automatic listeners to a component

You don’t need to understand how binding works to write an application fast, but you may need to in order to write a fast application.

Hot Tip

Many Look & Feels exist to skin Swing apps into something more eye-pleasing. One of the best collections is Substance, available from http://substance.dev.java.net/. To install the Substance Look & Feels, run the following command: griffon install-plugin lookandfeel-substance

SERVICES

Many fields are automatically injected into your components by Griffon: Views receive an application instance, a model, and a controller, and Controllers receive a model and view. You can also create your own helper objects that will automatically be injected into your controllers by using Griffon services. A service is an object with a no-arg constructor, and they are discovered and injected based on naming conventions. To create a service use this Griffon command:

griffon create-service Creates a service class, prompting you to enter a package and a name. Also creates a unit test.

Here is our previous Clicker example refactored to use a service:

CounterService.groovy

class CounterService {
  def counter = 0
  def getNext() {
	 counter++
  }
}

ClickerController.groovy

class ClickerController {
	def model
	def counterService
	def action = {
		model.message = “Count: $counterService.next”
	}
}

Services are a key tool in decomposing large applications into manageable, independent pieces. Strive to move logic out of controllers and into reusable services. If you need more control over construction, then use the Spring or Guice plugins to provide full dependency injection frameworks.

Hot Tip

Mac and Linux users can easily chain commands together using the && operator. For example, to run a clean and package, run the command: “griffon clean && griffon package”. The 2nd command only runs if the 1st succeeds. This also works under Windows with Cygwin.

EVENTS

Custom Event Handing - Griffon has a rich, lightweight event system. For the most part, components in your application communicate via events and message passing rather than direct method calls. This means your controllers stay decoupled from one another but still communicate. Custom events and event handlers are wired together based on naming convention. Here is our controller that posts an event by interacting with the implicit “app” object and handles the event itself.


class ClickerController {
	def model
	def counterService
	def action = {
		app.event(“Click”, [counterService.next])
	}
	def onClick = { value ->
		doLater { model.message = “Count: $value” }
	}
}

Raise events using the GriffonApplication object named “app” and handle them by declaring an “on<EventName>” closure. Simple.

Application Life-Cycle Events - All Griffon applications have the same life-cycle, regardless of whether it is deployed as an applet, application, or webstart. As an application moves through the phases, you have the opportunity to cleanly execute any sort of acquiring or releasing resources you wish. Griffon provides an event system for you to both post and handle the events with custom code. Here’s the basics of the life-cycle:

life cycle

Initialize Application is created and configuration read. Good place to apply a new Look and Feel
Startup All MVC Groups from ./griffon-app/conf/Application.groovy marked as startup groups are instantiated
Ready All pending UI events have been processed and the main frame is about to be displayed
Shutdown The application is about to close
Stop Only available in Applet mode, called when destroy() is invoked by the container

To respond and handle any of the lifecycle events, such as BootstrapEnd, LoadPluginStart, NewInstance, or any of the many others, then add a handler in the file ./griffon-app/conf/Events.groovy. The name of the method should be “on<EventName>”. All of the available events are documented in the Griffon User Guide, and you may add your own custom events as well.

Extensible Build Scripting – The build of Griffon is completely scriptable; there is even a Griffon command to help you write build event extensions:

griffon create-script Creates a build script in the ./script directory, prompting you to enter a script name

The Griffon build is built on the Gant framework, a Groovy extension to Ant. The content of a build script is an event handler. There are build events for CompileStart, PackagingStart, RunAppEnd, and many more. To add pre or post processing to a build event then simply declare a closure in the script named “event<EventName>”. You can even add new build events if you need to, and the Griffon User Guide contains a complete reference of the built-in build events.

THREADING

The last example contained a method call to something called “doLater” with a closure as a parameter. This hints at one of the major concerns for the Griffon or Swing developer: threading. Swing is a single-threaded GUI toolkit, meaning there is a single thread called the Event Dispatch Thread (EDT) dedicated to refreshing and repainting the UI. If you perform a long computation on the EDT then your application will not repaint properly or may become sluggish. If you update the state of a UI widget from a thread other than the EDT then your widget may not paint or be updated correctly. As a Swing programmer you must remember two rules: all interactions with widgets must occur on the EDT and any other processing should occur off the EDT, and this rule holds true for other GUI toolkits as well. Groovy’s SwingBuilder object gives you three convenience methods to help you with this, and Griffon automatically imports these methods into your MVC groups.

doOutside { ... } Executes a block of code off the EDT.
edt { ... } Executes a block of code on the EDT. Similar to the JDK’s SwingUtilities.invokeAndWait.
doLater { ... } Executes a block of code on the EDT. Similar to the JDK’s SwingUtilities.invokeLater.

It is common for controller actions to start by reading a widget on the EDT, perform work off the EDT, and finally update the UI on the EDT. Here is a properly threaded version of our ClickerController.


class ClickerController {
	def model
	def counterService
	
	def action = {
	   model.busy = true
	   doOutside {
		  try {
		model.message = “Count: $counterService.next”
		} finally {
		  edt { model.busy = false }
		}
	 }
  }
}


The SwingBuilder methods are Swing specific, but Griffon offers a platform agnostic way to invoke them as well. If you are targeting SWT or some other toolkit then use the execOutside, execSync, and execAsync methods instead.

Hot Tip

It is worthwile to invest time understanding how Swing threading works by using the plenty of highquality documentation that exists on the Internet. Oracle’s Java Tutorial contains a section called “Concurrency in Swing” and other articles appear on the Sun Developer Network.

USING PLUGINS

The Griffon Plugin system is a key part of the framework. There are currently over 100 plugins listed in the public plugin repository, ranging from persistence providers like CouchDB and GSQL, rich components like Coverflow and GlazedLists, testing support like easyb and Spock, language support like Clojure and Scala, and many, many more. Plugins strive to make third party library integration a one or two line of code affair, and they are a great way to add features with a minimum of effort. As an example, consider how simple it is to generate Mac, Windows, and Linux installers with the Installer Plugin:


$ griffon install-plugin installer
$ griffon prepare-all-launchers
$ griffon create-all-launchers

Installing the plugin downloads the package from the public repository and installs it. The plugin adds several Griffon targets, and invoking these targets builds the packages. After running these commands you can see a Mac .app application, and Windows .exe installer, and several other formats all sitting in the ./installer folder.

Working effectively with plugins only requires mastering four Griffon targets:

griffon list-plugins Lists all the plugins available to install
griffon plugin-info <plugin name> Lists the documentation of the specified plugin
griffon install-plugin <plugin name> Downloads and installs the specified plugin. Also accepts a file or URL as an argument.
griffon uninstall-plugin <plugin name> Uninstalls the specified plugin.

Hot Tip

If you’d like to publish your own plugin to the repository then send an email to the Griffon mailing list: you’ll quickly be given the version control rights to execute a “griffon release-plugin”. Also, the next version of Griffon allows you to create your own plugin repository so your organization can have a private repo for non-open source plugins.

TESTING

Testing is a first class concern in Griffon. Many of the built in targets create unit test stubs for you and the quality related plugins are particularly rich. The core targets for testing are:

griffon test-app griffon test-app -unit Executes the tests in the project. When the -unit option is present, runs only the unit tests.
griffon create-unit-test Creates a new unit test.
griffon createintegration-test Creates a new integration test, in which the GriffonApplication object is available.

For additional testing options, install the easyb, FEST, and Spock plugins. Easyb is a Jolt award winning Behavior Driven Development library for Groovy, FEST is a UI testing library for Swing, and Spock is a rapidly growing testing tool in the Groovy community. There are many other code quality related plugins as well. The Clover and Cobertura plugins make code coverage statistics available, FindBugs and CodeNarc provide static code analysis, and JDepend and GMetrics offer structural and dependency analysis. Keeping the code clean is only a plugin install away.

Hot Tip

Command completion using the Tab key is available for Bash based command shells, like Linux, Mac, or Windows’ Cygwin. To enable completion, run the command “source $GRIFFON_HOME/bash/griffonauto- scripts”. You might just add this to execute as part of your login scripts.

IDE SUPPORT

Groovy enjoys very good IDE support; IntelliJ IDEA, NetBeans, and Eclipse all offer some level of Groovy support, and Griffon makes tooling easy by generating both Eclipse and IntelliJ IDEA projects files for every application. Currently, IntelliJ IDEA offers the best Groovy and Griffon support. Refactoring, Java-aware find usages, code completion, and many code intentions are supported. As for Griffon specific features, IDEA provides a project builder for new projects, a customized view that knows about MVC layouts, a Griffon target window to replace the need for the command line, support for unit and integration tests, and a UI to manage Griffon Plugins. Plus, you can generate an IDEA project from your Griffon sources in case you generated the project from the command line.

ON THE ROAD TO GRIFFON 1.0

The next version of Griffon will be 0.9, an API stable release on the road to 1.0. However, Griffon handles upgrades automatically and upgrades have always been painless. If you install version 0.3 and later upgrade to 0.9, then Griffon prompts you to run the upgrade scripts and convert the project. Upgrading should be seamless, any required changes are handled by the scripts supplied by the Griffon team or the plugin authors. If you’ve written your own plugins, take a look at the user mailing list to see if there are any required upgrade steps you need to provide to your users for a new release.

Hot Tip

In version 0.9, Griffon supports camelCase for targets. This means typing “griffon cApp” matches “create-app” and executes that target. If the camelCase input is ambiguous then Griffon will prompt you to select the intended target from a list.

MORE INFO

The best documentation for Griffon is the Griffon in Action book, currently available in early access form from the publisher’s website, if it hasn’t already been published. It extensively covers the material here, but also takes in depth looks at writing your own plugins, installing new look and feels, and managing the development versus production environments. Otherwise, the Griffon User Guide and mailing list are free to use, and the mailing list in particular is quite responsive. For more info on rich clients in Swing, I recommend the book Filthy Rich Swing Clients.

For learning by example, the Griffon download package contains several examples, and the code for all examples in this Refcard are available at: http://github.com/HamletDRC/ GriffonRefcard. Lastly, you can follow all the latest Griffon news by following @theaviary on Twitter. Happy Developing!

About The Authors

Photo of author Hamlet D'Arcy

Hamlet D'Arcy

Hamlet D'Arcy has been writing software for over a decade, and has spent considerable time coding in Groovy, Java, and C++. He's passionate about learning new languages and different ways to think about problems, and recently he's been discovering the joys of both F# and Scheme. He's a committer on several open source projects including Groovy and JConch, and is a contributor on a few others (including Griffon and the IDEA Groovy Plugin). He blogs regularly at http://hamletdarcy.blogspot.com, tweets as HamletDRC, and can be contacted at hamletdrc@gmail.com.

Recommended Book

Griffon in Action

Griffon in Action is a comprehensive tutorial written for Java developers who want a more productive approach to UI development. In this book, readers will immediately dive into Griffon. After a Griffon orientation and a quick Groovy tutorial, they'll start building examples that explore Griffon's high productivity approach to Swing development. The book covers declarative view development, like the one provided by JavaFX Script, as well as the structure, architecture and life cycle of Java 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.

New Silverlight and Expression Blend DZone Refcard

0 replies - 13021 views - 03/29/10 by Lyndsey Clevesy in Announcements

Getting Started with Silverlight and Expression Blend

By Victor Gaudioso

11,445 Downloads · Refcard 92 of 151 (see them all)

Download
FREE PDF


The Essential Expression Blend Cheat Sheet

Silverlight is a cross-browser, cross-platform plug-in for your browser that installs in seconds. It allows for developers and designers to create Rich Internet Applications and deliver them through the web . This DZone Refcard will provide an introduction to Silverlight 4 and Expression Blend, an application that is used to develop Silverlight applications. Also included is an introduction to some of the cool new features offered by the newest version of Silverlight 4, and a step by step guide through the development of your first Silverlight application.
HTML Preview
Getting Started with Silverlight and Expression Blend

Getting Started with Silverlight and Expression Blend

By Victor Gaudioso

INTRODUCTION

Today there is a lot of buzz around a relatively new platform in the world of Rich Internet Application (RIA) development called Silverlight. Even with all of the buzz going around there are many who do not really know or understand what Silverlight is or what it can do. This DZone Refcard will put that mystery to rest along with providing an introduction to Blend, an application that is used to develop Silverlight applications. Also included is an introduction to some of the cool new features offered by the newest version of Silverlight 4, and a step by step guide through the development of your first Silverlight application.

WHAT IS SILVERLIGHT?

Silverlight is a cross browser, cross platform plug-in for your browser that installs in seconds. It also allows for developers to designers to develop Rich Internet Applications (RIA) and deliver them through the web and now even Out of Browser (OOB) experiences.

The Silverlight plug-in installs in seconds and is free to users.

Silverlight applications leverage the .NET Framework which allow for rapid development and provide backend support. Silverlight offers support for delivery of high quality audio and video. Since the release of Silverlight 3 Silverlight offers rich, stutter-free, fullscreen experiences. Below is a list of video features offered with Silverlight:

  • True HD playback in fullscreen.
  • Support for a number of 3rd party video codecs. Further video can be decoded outside of the runtime and rendered in Silverlight thus extending format support beyond native codecs.
  • Smooth Streaming - Smooth streaming automatically detects CPU and bandwidth conditions and can seamlessly switch to lower or higher quality versions of the same video thus allowing for delivery of non-stuttering video even if the CPU or bandwidth conditions change during a live streaming session.
  • Built in Digital Rights Management (DRM) - Silverlight DRM provided by PlayReady Content Protection allows you to protect your video using AES encryption or Windows Media DRM.
  • Format Choice - Silverlight supports VC-1/MMA and since the release of Silverlight 3 support for MPEG-4.

Silverlight allows for rapid RIA development by making use of the improved designer/developer workflow. Because Silverlight UserControls make use of a front-end XML based language called XAML (pronounced ZAMEL) and a codebehind C# (Visual Basic can also be used) the developers can now work on the back end code-behind files while the designers can, at the same time work on the front-end XAML pages. This allows for the designer and developers to work on the same set of files at the same time thus making for more rapid application development.

Silverlight offers Out Of Browser (OOB) experiences. OOB support is offered since Silverlight 3 without any further downloads of the Silverlight runtime or the need to write applications any differently. There are new features in Silverlight 4 that make OOB development even more exciting. We will talk more about that in the new features of Silverlight 4 section.

Silverlight has improved performance by doing this such as application library caching. Now parts of the .NET Framework are cached on the client machine thus reducing the size of your applications. Further applications now communicate with the server via Binary XML thus increasing the speed by which data is exchanged.

Silverlight now has enhanced data support. This allows for features such as Element to Element DataBinding. In the past Silverlight only allowed Binding between UI elements and data objects. Now UI elements can bind directly to properties on other UI elements. For instance a Slider can now bind to properties of other UI elements such as the Volume property of a MediaElement, this allows for more interactive, user-friendly interactions.

NEW FEATURES OF SILVERLIGHT 4

At the Professional Developers Conference (PDC) 2009 in Los Angeles, CA Microsoft released Silverlight 4 Beta. Currently Silverlight 4 is still in the Beta phase with the release date expected to be in late March of 2010 and possibly to coincide with the Microsoft MIX conference in Las Vegas March 15-17. The Silverlight 4 Beta version can be download and installed from the Silverlight.net website located here:

http://silverlight.net/getstarted/silverlight-4-beta/

There are still some features that have not been released but below you will find a list of the new features that have been released in the Beta version:

  • Printing - Silverlight 4 now offers support for printing documents that are on the screen as well as virtual print which allows for printing that is independent of what is showing on the users screen.
  • Tooling support for Visual Studio 2010 (the other tool for development of Silverlight applications)- now Visual Studio will now have features that were formerly exclusive to Blend. This includes but is not limited to: Drag and Drop data binding, integration with Blend styling resources, and an editable design surface.
  • New Controls - Silverlight 4 now offers new controls such as the RichTexBox that allows for images, other controls and hyperlinks.
  • Managed Extensibility Framework (MEF) - a framework that allows for large scale composite Silverlight applications.
  • Right-to-left support - this allows for controls to align their content from right-to-left instead of the default leftto-right.
  • Improved RIA Services and WCF support - this allows for more powerful n-tier data driven applications.
  • Enhanced data binding support
  • Intellisence with support for XAML, C# and VB.
  • Webcam and microphone API (Application Programming Interface) - this allows the developer to incorporate video and audio from the client machine without the inclusion of any third party dlls or plug-ins.
  • Fully Trusted Applications - now it is easy to set properties on your Silverlight applications so that they can be ran as fully trusted applications on client machines.
  • Support for the Google Chrome browser. Mouse Wheel support - now developers have access to the Mouse Wheel to allow for effortless scrolling though long documents or content controls.
  • Right-click support - now developers have access to the right-click mouse event. This allows developers to develop applications that easily respond to right-clicks from their users. This will allow for such features as Context Menus in your Silverlight applications.
  • Performance optimizations means that Silverlight 4 applications can run up to 200% faster than applications developed in Silverlight 3.
  • Multi-touch support - Silverlight 4 applications have the ability to respond to gestures and touch interactions such as pinch to shrink.
  • Multicast networking allows for cheap smooth streaming.
  • Content protection for H.264 media through Silverlight DRM.

Below is a list of Silverlight 4 features that apply to Out Of Browser (OOB) applications:

  • The ability to place HTML into your Silverlight applications.
  • This allows you to add content from the web such as charts, email, and social serves such as Facebook, Linked-In, twitter, and MySpace.
  • Support for Windows settings - this allows you to set the Startup Position of you Silverlight applications, set the size and choose a Windows Chrome.
  • Offline DRM - This allows you to play protected content such as video. Content can be downloaded from the web and imediately enjoyed on your OOB Silverlight applications.
  • “Toast” support - Toast Windows are popup windows that appear on the Taskbar and allow you to provide messages from your OOB Silverlight application. A common Toast window would be the Online Status of your application.

Below is a list of Silverlight 4 features that apply to Out Of Browser (OOB) Trusted applications:

  • Networking Improvements - Silverlight 4 Trusted OOB applications now have cross-domain access without a security policy file.
  • The COM API - This API allows you to Run and control other programs right from your trusted Silverlight applications such as Word, Excel, as well as other Microsoft Office applications. Further, you can request and send email using Outlook from you Silverlight applications.
  • Read and write capability - you can now read and write files to the User's file library. This includes the MyDocuments, MyPictures, and MyVideos folders.
  • A new user interface for requesting additional privileges outside of the Silverlight sandbox.

Now that you know what Silverlight is let's move ahead and examine the main tool by which you develop Silverlight applications.

WHAT IS BLEND?

There are two programs developed by Microsoft for developing Silverlight applications. They are Blend and Visual Studio. Visual Studio has been around for many years now and is the main tool for writing Silverlight code-behind. Because it is not new and not specific to Silverlight we will only mention it here. Blend, on the other hand is a tool that was developed by Microsoft specifically for developing Silverlight (and Silverlight's big brother WPF) applications. While Visual Studio is most often used to write Silverlight code-behind Blend can handle to task as well. So, that means an entire application can be developed with Blend alone.

Blend 3, released in July 2009 is an application developed by Microsoft (using WPF) specifically for developing Silverlight applications in a visual manner. Objects can be dragged from the toolbar on the artboard (analogous to a State in Flash). Properties for objects on the artboard can be set in the properties panel.

Further you can create Storyboard animations in Blend using Blend's Timeline in Blend's animation mode (as opposed to Blend's Design mode). Once you have created a Storyboard animation you can then preview that animation right inside of Blend. This allows you to perfect your animations before you even build and deploy your Silverlight applications. When you create a Storyboard you move a playhead out to a specific time on your Timeline, say for example 5 seconds. You then manipulate objects on your artboard. When you run the animations the manipulations you created on the artboard will occur over the timespan you set with your played, 5 seconds in our example. These Storyboards that you create are written in XAML by Blend. They then become resources that you can fire in code-behind or by Storyboard Behaviors (pre-defined Storyboard actions written in Code and dragged onto objects in Blend).

You can also use the Visual State Manager (VSM) to create Visual States in Blend using the States panel. These Visual States make use of Storyboards to control the Visual States. You then hook up these States to user actions by dragging Behaviors (pre-defined actions written in code-behind)onto objects on the Artboard or Blend's Objects and Timeline panel (a panel that provides a textual representation of objects in your Visual Tree). You can also fire these Visual States from code-behind in both Blend and Visual Studio.

When you develop visually in Blend code is written for you in the XAML file of the UserControl. This XAML can be written by hand in both Blend and Visual Studio but this can be both time consuming and laborious. Further, it would be nearly impossible to create some objects by hand such as a very complex Path object. For this type of development Blend is essential.

Most often the designer works in Blend doing things visually while the developer works in Visual Studio doing things in code-behind. This workflow is fuzzy and can overlap with some designers jumping into Visual Studio at times and some developers using Blend at times.

The tools in Blend are much like those that designers are used to from working with popular design programs such as Adobe's Photoshop, Illustrator and Fireworks. A designer can create vector graphics right inside of Blend or use tools like Expression Design to create the graphics and move them into Blend. Further, Photoshop and Illustrator files can be directly imported into Blend via the importer interface.

Blend now includes a Data panel where data can be imported from Silverlight data objects created in Visual Studio, from XML or from Sample Data that is shipped with Blend. Blend also includes an interface for doing complex DataBinding.

While coding is usually done in Visual Studio Blend does have an editor for code. The editor now even includes Intellisense which attempts to figure out what you are trying to do in code and then tries to auto-complete the code for you. Intellisense is also available for coding XAML in Blend as well.

Blend also has panels for: all of the files in the application, called the Projects panel; all of the Resources available to the application, called the Projects panel; We will go over all of the panels in Blend in the Blend IDE Refcard.

WHAT CAN BE DONE IN BLEND?

Now that you know what Silverlight is and what Blend is I think it is time that we create your first Silverlight application and I show you what we can do. In this example I am going to go over only what to do, not why or how we are doing it. We will go over the why's and how's in later Refcardz; this example is merely meant to show you that you can easily and quickly do some very cool things with Blend in Silverlight. With that, open Blend and let's get started.

  • 1) In Blend's menu click File>New Project
  • 2) In the New Project dialog box select Silverlight as the Project Type, Silverlight 3 Application for the Template, name the project MyFirstSLApp, select Visual C# for the language and click OK like I am doing in Figure 1-1.

New Project dialog

Figure 1-1: Create a new Silverlight project named MyFristSLApp.

Textblock tool

Figure 1-2: The TextBlock tool.

  • 3) Next double-click the TextBlock tool in the toolbar(shown in Figure 1-2).
  • 4) This will put a TextBlock in the upper left corner of your artboard with the text selected (see Figure 1-3).

Default textblock

Figure 1-3: A default TextBlock.

  • 5) Next start typing “Hello World”. Because your TextBlock is already highlighted this will now become the Text of your TextBlock.
  • 6) Next go to the Properties panel and find the Text bucket and change the font to 20pt like I am doing in Figure 1-4.

Font dialog

Figure 1-4: Change the front to 20.

  • 7) Now click the V key to get your Selection tool (the first tool on the top of the toolbar). Click and drag your TextBlock to the center of the artboard like I have done in Figure 1-5.

The art board

Figure 1-5: Drag your TextBlock to the center of the artboard.

  • 8) Now right-click the TextBlock and left-click Path>Convert to Path like I am doing in Figure 1-6.

Text to path

Figure 1-6: Convert the TextBlock to a Path.

  • 9) Now right-click the TextBlock in the Objects and Timeline panel and right-click Path>Release Compound Path like I am doing in Figure 1-7

Release the Compound Path

Figure 1-7: Release the Compound Path.

Now you will notice that each of your letters is now its very own Path. Now we can manipulate each individual letter of “Hello World”. Let's do that now.

  • 1) Click V to select the Selection tool and click a draw a line around all of the letters to select them all like I am doing in Figure 1-8.

Select all letters

Figure 1-8: Select all letters.

  • 2) Now with all of the letters selected click and drag them off the right of the artboard like I have done in Figure 1-9.

Move letters

Figure 1-9: Move the letters off to the right of the artboard.

Now we can make a Storyboard that will make the letters fly into the screen.

  • 3) First click F6 to go into Blend's Animation mode.
  • 4) Click the New Storyboard button like I am doing in Figure 1-10.

Click the New Storyboard button

Figure 1-10: Click the New Storyboard button.

  • 5) When the Create Storyboard Resource dialog box appears name the Storyboard SlideInLetters and click OK like I am doing in Figure 1-11.

Name the new Storyboard

Figure 1-11: Name the new Storyboard SlideInLetters.

  • 6) Notice how the artboard has a red line around it and a Timeline appears next to the Objects and Timeline panel to indicate you are recording.
  • 7) Move your playhead out to one second like I have done in Figure 1-12.

Move your playhead

Figure 1-12: Move your playhead out to one second.

  • 8) Now select the last letter and move it out to the artboard like I am doing in Figure 1-13.

Move last letter

Figure 1-13: Move the last letter “d” to the artboard.

  • 9) Now move your playhead out to 2 seconds and move the next letter, “r” onto the artboard next to the last letter, “d” like I am doing in Figure 1-14.

Move second last letter

Figure 1-14: With the playhead at 2 seconds move in your second to last letter.

  • 10) Keep repeating this for every letter, that is move the playhead out one more second and move the next letter onto the artboard.

When you have completed your Timeline should look like what I have in Figure 1-15.

Storyboard Timeline

Figure 1-15: Your Storyboard Timeline should look like this.

Now that we have created the Storyboard you can close it by clicking the Close Storyboard button like I am doing in Figure 1-16. Then Click F6 to exit the animation mode.

Close the Storyboard

Figure 1-16: Close the Storyboard.

Now all we need to do it to trigger the Storyboards to start when the application loads. To do this we are going to use a Behavior.

  • 1) Click the Asset Library, then click the Behaviors tab, and find the ControlStoryboardAction Behavior like I am doing in Figure 1-17.

Close the Storyboard

Figure 1-17: Find the ControlStoryboardAction Behavior.

  • 2) Click and drag that behavior and drop it onto the [UserControl] in the Objects and Timeline panel like I am doing in Figure 1-18.

Objects and Timeline panel

Figure 1-18: Drag the Behavior onto the [UserControl] in the Objects and Timeline panel.

  • 3) In the Properties panel find the Tigger bucket and change the EventName property to Loaded like I am doing in Figure 1-19.

Properties panel

Figure 1-19: Change the EventName to Loaded.

  • 4) Next located the Common Properties bucket and change the Storyboard property dropdown to the name of our Storyboard, “SlideInLetters” like I am doing in Figure 1-20.

Change Properties

Figure 1-20: Change the Storyboard property to the Storyboard we created earlier.

Now hit F4 to run the application and you will see a browser open and run our SlideInLetters Storyboard. See Figure 1-21.

Silverlight application running in browser

Figure 1-21: Our Silverlight application running in a browser.

You can see my application here:
http://windowspresentationfoundation.com/RefCardSamples/RefCard1/

SUMMARY

This DZone Refcard provided a brief introduction to SIlverlight 4 and how Blend is used to develop Silverlight applications. You should now have the building blocks you need to grow as a Silverlight developer. For further information on Microsoft Silverlight and Expression Blend please visit the following sites: Silverlight.net, Learn Expression Blend, Download Silverlight and Download Expression Blend.

About The Authors

Victor Gaudioso

Victor Gaudioso is a Windows Presentation Foundation (WPF), Silverlight, Windows 7, Microsoft Surface, and Windows & Mobile software developer. He has worked on some of the most cutting-edge WPF, Silverlight and Surface applications that have been developed to date, including the Surface Winebar CES demo and Surface Air Hockey with simulated physics. Victor was also part of the team that launched the Silverlight Entertainment Tonight Emmy Mini- Site; one of the first professional grade Silverlight applications created. The ET mini-site made live streaming video directly from the red carpet available to the site's visitors. In his spare time, Victor has authored several books on WPF and Silverlight which have become required reading in many courses on interactive web media development. In addition Victor has recorded Silverlight Starter Kits for Microsoft that teach those new to Silverlight how to develop rich internet applications. Victor also has many free video tutorials on his personal blog located at victorgaudioso.wordpress.com. You can follow Victor on twitter @victorgaudioso

Recommended Book

Expression Blend 4

Foundation Expression Blend 4 with Silverlight 4 takes you through your first steps in creating Rich Internet Applications (RIAs) using the latest release of Microsoft's technology. Silverlight 4 enables you to rapidly develop compelling, cross-platform RIAs using the extensive .NET 4 libraries, the powerful, design friendly Blend 4 Integrated Development Environment, and an enhanced workflow that allows designers and developers to work on the same set of files at the same time.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Getting Started with LiveCycle Data Services ES

By Michael Slinn

6,922 Downloads · Refcard 73 of 151 (see them all)

Download
FREE PDF


The Essential LiveCycle Data Services ES Cheat Sheet

Adobe LiveCycle Data Services ES is a high-performance, scalable, and flexible framework that streamlines the development of Rich Internet Applications using the Flash Platform. LCDS facilitates the creation of client-server applications and supports a rich set of features to create real-time and near-real time solutions, including support for occasionally connected AIR clients. This DZone Refcard covers installation, channels and endpoints, Java to ActionScript Type Mapping, ActionScript to Java Type mapping, Eclipse Projects, and even shows you how to get started with your first project in LCDS.
HTML Preview
Getting Started with LiveCycle Data Services ES

Getting Started with LiveCycle Data Services ES

By Michael Slinn

ABOUT ABOUT LIVECYCLE DS

Adobe® LiveCycle® Data Services ES (LCDS) is a high-performance, scalable, and flexible framework that streamlines the development of Rich Internet Applications (RIAs) using the Flash Platform.

LCDS facilitates the creation of client-server applications and supports a rich set of features to create real-time and near real-time solutions, included support for occasionally connected AIR clients. LCDS provides numerous options for remote procedure calls, proxy support, lazy loading and server push, including publish/subscribe messaging, data synchronization, data paging and conflict resolution.

LCDS supports Java EE web applications. Versions are available for Windows, Linux, AIX, HP_UX and Solaris. LCDS v2.6.1 is not officially supported under Mac O/S X, however the v3.0 beta does provide support for Mac.

This Refcard briefly mentions the major features, discusses a few key concepts and shows how to get started with LCDS. The book entitled 'Flex Data Services, Hibernate and Eclipse' contains much more information, complete code examples, and the LCDS version of the free software tool mentioned in this Refcard.

ADOBE_lifecycle

Installation

You can download the current version of LCDS from http://www.adobe.com/products/livecycle/dataservices/. You need to sign in with your Adobe ID to get the download. IDs are free, so register if you need one. The download page displays a serial number which you need to save in order to install the product.

Unlike BlazeDS, LCDS has an installation script. By default, LCDS installs into C:\Program Files\Adobe\lcds on Windows.

Channels and Endpoints

Data moves between client and server in a manner prescribed by the data services configuration. Both the client and the server must be configured in a compatible manner. Adobe provides samples of five XML files that are parsed by Flex Builder and the server-side Data Services runtime at startup. You must modify some or all of these files in order to configure the data services transport for each project. The configuration files define client channels ('pipes'), server endpoints (the URL and properties) and destinations.

A client channel formats and translates messages into a network-specific form and delivers them to an endpoint on the server; channels define message formats, network protocols and network behaviors. An endpoint unmarshals messages in a protocol-specific manner. A destination is the server-side object or service that the endpoint connects to. Destinations are defined by channels and adapters; adapters connect directly with the server object or service. The LCDS message broker routes requests arriving at endpoints to the appropriate service destination.

The following diagram illustrates how client channels, server endpoints and destinations are related.

diagram1

The message broker uses the last token of the URL to route the incoming request to the appropriate service for handling. The preceding diagram shows two endpoints, with routing tokens amf and amfstreaming. Endpoints are URLs that are responded to by the LCDS message broker.

An example of a server endpoint is http://localhost:8080/test/messagebroker/amf. The message broker uses the last token of the URL to route the incoming request to the appropriate service for handling. The preceding diagram shows two endpoints, with routing tokens amf and amfstreaming. The message broker is normally configured to pass requests arriving at these endpoints to services that handle remote procedure calls (RPCs) and streaming, respectively.

LCDS scales to orders of magnitude more clients per CPU than BlazeDS because it offers NIO-based server endpoints in addition to the servlet-based endpoints that BlazeDS offers. You can take a web application developed using BlazeDS and get much greater throughput simply by installing LCDS in place of BlazeDS, and editing services-config.xml to use NIO endpoints.

At a minimum, client channels must have an id, a class and an endpoint. The id allows the channel to be referenced. The class defines the scope of the channel's potential behavior. The endpoint defines the URL for a remote client to access the channel. Channels have default properties, which can be overridden. The available properties vary for each class of channel. The client-side channel classes are all defined in the mx.messaging.channels ActionScript package. The server-side endpoint classes are all defined in the flex.messaging.endpoints Java package.

The following server-side endpoints are all implemented using servlet-based blocking I/O, requiring one thread per connection. This table has many entries '" defining a channel gets really confusing when all the options are considered. The free Flex Data Services Channel Designer described next, is intended to clarify the options and write the XML for the channels that your application needs.

Servlet-based endpoints and their client channels
Binary AMF data AMFChannel / AMFEndpoint Used for RPC when default properties are not overridden; used for messaging and data management service when polling properties are configured. Transmits data in the binary AMF format. Usually uses the http protocol.
SecureAMFChannel / SecureAMFEndpoint Secure subclasses of AMFChannel / AMFEndpoint. Uses the https protocol.
StreamingAMFChannel / StreamingAMFEndpoint Uses the HTTP 1.1 'chunked' server push model instead of polling for data from the server. An internal HTTP connection to the server is held open so the server can stream data to the client with little overhead. Cannot be compressed or proxied.
SecureStreamingAMFChannel / SecureStreamingAMFEndpoint Subclasses of StreamingAMFChannel / StreamingAMFEndpoint which use the https protocol.
Plain Text data (AMFX - an XML Format) HTTPChannel / HTTPEndpoint Like AMFChannel, but transmits data in plain text. Not recommended for production sites.
SecureHTTPChannel / SecureHTTPEndpoint Like HTTPChannel / AMFEndpoint but uses https protocol.
Plain Text data (AMFX - an XML Format) StreamingHTTPChannel / StreamingHTTPEndpoint Like StreamingAMFChannel / StreamingAMFEndpoint but transmits data in plain text instead of the binary AMF format. Not recommended for production sites.

All of the above servlet-based endpoints have Java NIO-based counterparts, as shown in the next table. The RTMP protocol is also NIO-based. All of the NIO-based server endpoints support many threads per connection because they do not use blocking I/O calls. Unlike HTTP-based protocols, RTMP is full-duplex, requiring half as many channels for two-way traffic. RTMP also immediately informs the server of client disconnects, allowing the server to release resources without waiting for the client to time out. BlazeDS does not support NIO-based server endpoints, just LCDS.

Notice that server endpoints might be implemented using NIO or blocking I/O, however the client channel is the same regardless of the type of server endpoint '" with the exception that RTMP channels must use matching RTMP endpoints.

NIO-based server-side endpoints and their client channels
Binary AMF data AMFChannel / NIOAMFEndpoint Used for RPC when default properties are not overridden; used for messaging and data management service when properties are configured. Transmits data in the binary AMF format. Usually uses the http protocol.
SecureAMFChannel / SecureNIOAMFEndpoint Secure subclasses of AMFChannel / NIOAMFEndpoint. Uses the https protocol.
StreamingAMFChannel / StreamingNIOAMFEndpoint Uses the HTTP 1.1 'chunked' server push model instead of polling for data from the server. An internal HTTP connection to the server is held open so the server can stream data to the client with little overhead. Cannot be compressed or proxied.
SecureStreamingAMFChannel / SecureStreamingNIOAMFEndpoint Subclass of StreamingAMFChannel which uses the https protocol.
RTMPChannel / RTMPEndpoint Used for messaging; does not route well. Uses the rtmp protocol, which provides best support for real-time applications.
SecureRTMPChannel / SecureRTMPEndpoint Used for secure messaging; does not route well. Uses the rtmps protocol.
Plain Text data (AMFX - an XML Format) HTTPChannel / NIOHTTPEndpoint Like AMFChannel / NIOAMFEndpoint, but transmits data in plain text. Not recommended for production sites.
SecureHTTPChannel / SecureNIOHTTPEndpoint Like HTTPChannel but uses https protocol.
StreamingHTTPChannel / StreamingNIOHTTPEndpoint Like StreamingAMFChannel but transmits data in plain text instead of the binary AMF format. Not recommended for production sites.
SecureStreamingHTTPChannel / SecureStreamingNIOHTTPEndpoint Like SecureStreamingAMFChannel / SecureStreamingNIOAMFEndpoint, but transmits data in plain text.

Channel Sets

Channel definitions are combined into channel sets, and these are assigned to destinations; default channel sets can also be defined for each service class and the overall web application. The service classes common to BlazeDS and LCDS are RemotingService, MessageService and HTTPProxyService. LCDS adds the DataService. Channel sets provide for graceful and transparent fallback should a channel not be available for a specific client. Each time a client connects to a destination on a server, the destination's channels are tried, in the order listed in the channels element. Should the first channel specify a protocol or endpoint that is not available, or fails during usage, the other channels are tried in sequence.

If the destination specifies a channels element, only those channels are tried when a client connects to that destination. Service classes can each have their own default channel set, defined by the service's default-channels element; if specified, those channels are tried in sequence if the service has not specified a channels element. An application-level default channel set may be specified in the top-level default-channels element, and its channels are tried in sequence if the service class and the destination do not specify default-channels or channels elements, respectively.

For example, messaging applications need an ongoing dialog, such as provided by polling and streaming protocols. All of the channel types described in the previous section could work, if they were suitably configured. For the sake of this example, let us assume that a messaging application needs a secure transport. One might opt to support the following channel set. This ChannelSet falls back from a secure RTMP channel to a secure NIO streaming channel, then a secure streaming AMF channel, then to a secure AMF channel with polling enabled to work around network components such as web server connectors, HTTP proxies, or reverse proxies that could buffer chunked responses incorrectly. Recall that a channel also defines an associated server endpoint; the table shows the channel and endpoint classes for each channel in the channel set.

SecureRTMPChannel / SecureRTMPEndpoint Provides best performance; guarantees the order of messages; scales well. RTMP is bidirectional, so half as many channels are required compared to HTTPbased channels. RTMP also immediately notifies the server when a client disconnects, so resources can be released. Firewalls or proxies might block RTMP.
SecureStreamingAMFChannel / SecureStreamingNIOAMFEndpoint Good performance; scales well; difficult to configure if you want to use the same port as HTTP. Nonstandard ports might cause firewall or proxies to block it.
SecureStreamingAMFChannel / SecureStreamingAMFEndpoint Routes well; good performance; does not scale well.
SecureAMFChannel / SecureAMFEndpoint configured for piggybacking Routes well; moderate performance; does not scale well.

Channel Designer

LCDS provides sample channel and endpoint definitions for common configurations in
{LCDS}/resources/config/services-config.xml.

The free Flex Data Services Channel Designer provided with the book is a handy tool for visually designing client channels and server endpoints. The Channel Designer is intended to clarify the options and write the XML for the channels that your application needs.

Java to ActionScript Type Mapping

Data exchanged between Flex client and Java server must be converted between the ActionScript representation and the Java representation. Regardless of the transport protocol used, the same rules are used for the data conversion. The following two tables describe the general rules for the conversions.

Java Type ActionScript (AMF3/AMFX)
java.lang.String String
java.lang.Boolean Boolean
java.lang.Integer java.lang.Short java.lang.Byte int
java.lang.Double java.lang.Long java.lang.Float Number
java.util.Calendar java.util.Date Date
java.lang.Character java.lang.Character[] String
java.lang.Byte[] ByteArray
java.util.Collection java.util.Collection ArrayCollection
java.lang.Object[] Array
java.util.Map java.util.Dictionary Object
java.lang.Object Typed Object
null null

ActionScript to Java Type Mappings

ActionScript type (AMF3) Java Interface Supported Java type binding
Array (dense) java.util.List java.util.Collection, Object[ ] (native array) If the type is an interface, it is mapped to the following interface implementations
  • List becomes ArrayList
  • SortedSet becomes TreeSet
  • Set becomes HashSet
  • Collection becomes
    ArrayList
A new instance of a custom Collection implementation is bound to that type.
Array (sparse) java.util.Map java.util.Collection, native array
String containing 'true' or 'false' java.lang.Boolean Boolean, boolean, String
flash.utils.ByteArray byte []
flash.utils. IExternalizable java. io.Externalizable
Date java.util.Date (formatted for Coordinated Universal Time (UTC)) java.util.Date, java. util.Calendar, java.sql. Timestamp, java.sql.Time, java.sql.Date
int/uint java.lang.Integer java.lang.Byte, java. lang.Double, java.lang. Float, java.lang.Long, java.lang.Short, java. math.BigDecimal, String, primitive types of byte, double, float, long, and short
null null primitives
Number java.lang.Double java.lang.Byte, java.lang. Double, java.lang.Float, java.lang.Long, java. lang.Short, java.math. BigDecimal, String, 0 (zero) if null is sent, primitive types of byte, double, float, long, and short
Object (generic) java.util.Map If a Map interface is specified, Flex Data Services creates a new java. util.HashMap for java.util.Map and a new java.util.TreeMap for java.util. SortedMap.
String java.lang.String java.lang.String, java. lang.Boolean, java.lang. Number
typed Object typed Object when you use [RemoteClass] typed Object
undefined null null for Object, default values for primitives
XML org.w3c.dom.Document org.w3c.dom.Document

Eclipse Projects

Eclipse WST is used to develop LCDS server-side projects. You can create integrated Flex / Java Eclipse projects or separate Flex and Java projects. Integrated projects are much easier to work with. Use the Flex Builder plugin with Eclipse Ganymede SR2 for best results. This project also requires Tomcat 6 to be installed. You can use the version of Tomcat provided with LCDS, but that has been tweaked to make the demo programs work. Just so there is no magic, download a fresh copy of Tomcat 6 core '" we will refer to the directory that you place Tomcat into as {CATALINA_HOME}.

The following diagram shows how client-side Flex ActionScript and MXML source code are built into a SWF with an HTML wrapper, and then deployed to a Tomcat instance. The server-side Java code is compiled into a staging area called WebContent, which is also deployed to the Tomcat instance.

Eclipse_diagram

With an integrated Flex/Java project you can debug both client and server simultaneously. It is cool to see the client and server debug stacks next to each other.

You can start make a combined Flex / Java Eclipse project as follows:

  1. In Eclipse, press Control / Command N to open the New Wizard.
  2. Open the Flex Builder folder, select Flex Project and press the Next > button.
  3. Give your project a name and change the Application server type to J2EE. Uncheck Use remote object access service. Leave the other options at their default settings. Press the Next > button.
  4. Select Apache Tomcat 6.0 as the value for the Target runtime. Change the Context root to a single short word. Leave the other options at their default settings. Press the Finish button.
  5. Copy {LCDS}/tomcat/webapps/lcds/WEB-INF/web.xml to WebContent/WEB-INF.
  6. Copy {LCDS}/resources/lib/* to WebContent/WEB-INF/lib
  7. Ensure that Publish module contexts to separate XML files is selected.
  8. Select the Servers tab at the bottom of the screen and double-click on the server you just created.
  9. Ensure that Publish module contexts to separate XML files is selected.

(Optional) If you are not using dynamically defined channels and destinations and are instead defining them in the WEB-INF/flex XML files:

  1. Copy {LCDS}/resources/config/* to WebContent/WEB-INF/flex and edit as required. You may also want to include these files so that you can customize the LCDS configuration.
  2. Add a Flex Compiler argument pointing at the XML file. To do this, open the Properties / Flex Compiler dialog and add the following to Additional compiler arguments:

-services ../WebContent/WEB-INF/flex/services-config.xml

Sample Project

I made a Flex Builder project using the source code for the Data Management Service (DMS) Test Drive sample program provided with LCDS, and added all the dependencies. You should be able to import this project into Eclipse Ganymede SR2 with the Flex Builder Plugin and compile it without any editing. To import the DMS Test Drive Eclipse project:

  1. Start Eclipse
  2. Select File / Import' / General / Existing Projects into Workspace
  3. Browse to the directory where you unzipped the Test Drive project into.
  4. Press TAB and notice that the project is now listed and selected.
  5. Click on the Finish button.

The LCDS libraries were not written using Java generics. I converted as much of the Java source code as possible to use generics. Subclasses of the LCDS types could not be genericized, so I added the @SuppressWarnings('unchecked') annotation where required. I also added @Override where required. No other changes were made to Adobe's source code other than cleaning up some formatting issues and removing unused cruft. I simplified the data services configuration files in WebContent/WEB-INF/flex so that undefined references for the other sample programs delivered with LCDS were removed.

Before you can run the project, the web application must be associated with a Tomcat instance. To do that, open the Servers panel at the bottom of the Java EE perspective and right-click on a Tomcat instance. Select the Add and RemoveProjects' menu item, then press the Add All >> button.

Next you need to start the HSQLDB database. For Windows, double-click on {LCDS}/sampledb/startdb.bat; for Linux and Mac, double-click on {LCDS}/sampledb/startdb.sh.

You can now start the web application by clicking on the server instance and then clicking on bug icon at the right side of the Servers panel. By default, the web application is automatically built and deployed prior to starting Tomcat. Point your browser to http://localhost:8080/dmsTestdrive/dmsTestdrive.html in two different web browser windows. Here is what you should see:

data_chart

If you have problems, increase LCDS logging verbosity by editing WebContent/WEB-INF/flex/services-config.xml and changing the level from 'Warn' to 'Debug' in the following line, then restart the server:


<target class='flex.messaging.log.ConsoleTarget' level='Warn'>

If you really need more logging verbosity, add the following filter pattern and restart the server:

<pattern>*</pattern>

Click on the Get Data button in each browser window. Double-click on a cell in one browser, change a value and notice that the value is propagated to the application running in the other browser. Because this simple application has no form validation, an error will be thrown if you enter a non-numeric value into a cell.

How the program works

The LCDS configuration is usually the best place to start when you want to understand how a program built with LCDS works. WebContent/WEB-INF/flex/services-config.xml defines a channel called my-rtmp, and within the channel definition, an endpoint that uses the RTMP protocol to push messages between client and server:


<channel-definition id='my-rtmp' class='mx.messaging.channels.RTMPChannel'>
	<endpoint url='rtmp://{server.name}:2037' class='flex.messaging.endpoints.RTMPEndpoint'/>
	<properties>
<idle-timeout-minutes>20
	</properties>
</channel-definition>

The data-management-config.xml file contains the following definition for the default channels by which the client and server communicate using data management services:

<default-channels> <channel ref='my-rtmp' /> </default-channels>

The same configuration file also defines a destination called inventory.


<destination id='inventory'>
    <properties>
        <use-transactions>false
        <source>flex.samples.product.ProductAssembler
        <scope>application
        <metadata>
           <identity property='productId'/>
        </metadata>
        <network>
           <paging enabled='false' pageSize='10' />
        </network>
   </properties>
</destination>

The destination's source property identifies the server-side class that implements CRUD operations. Several default properties are implied, including auto-sync-enabled (set true), which automatically propagates changes between client and server in both directions.

The public methods found in ProductAssembler.java are:


public Collection fill(List fillArgs);
public Object getItem(Map identity);
public void createItem(Object item);
public void updateItem(Object newVersion, Object prevVersion, List changes);
public void deleteItem(Object item);

LCDS creates ActionScript equivalents for each of the public methods in ProductAssembler. When called from ActionScript, the fill() method populates a client-side Flex ArrayCollection with data items from the server. The server-side fill() method calls ProductService.getProduct(), which runs a JDBC query and the result is returned to the client. ProductService references ConnectionHelper to make the JDBC connections, and throws DAOException if a problem occurs. The other methods in ProductAssembler.java are not used by this simple application, because it does not fully implement all CRUD functionality.

Shifting our attention to the Flex client for a moment, the following line in dmsTestdrive.mxml specifies that the inventory destination should be used by a DataService called ds to transport CRUD data by the following line:

<mx:DataService id='ds' destination='inventory' />

The next line defines an ArrayCollection called products to act as a client-side data buffer for the data streaming between client and server:


<mx:ArrayCollection id='products' />

The next line defines an anonymous ActionScript variable of type Product. The variable is anonymous because its value is unimportant. The side effect of this line is that the ActionScript to Java mapping of the Product classes defined in Product.as and Product.java is incorporated into the Flex program:


<local:Product />

The data streaming between client and server is of type Product. On the client, Product is defined as follows:


package {
    [Managed]
    [RemoteClass(alias='flex.samples.product.Product')]
    public class Product {
	    public var productId:int;
		public var name:String;
		public var description:String;
		public var image:String;
		public var category:String;
		public var price:Number;
		public var qtyInStock:int;
	}
}

LiveCycle DS supports the concept of managed classes for projects that must transmit complex trees of hierarchical data between subscribed clients and a server. The [Managed] class-level annotation signifies that the entire object graph should not be retransmitted to all subscribers when a property of a subordinate object in the graph changes value. Instead, the responsibility for keeping the remote object in sync is the responsibility of the subordinate class. In this case, all of the public properties are primitives, so [Managed] is not really doing anything in this regard. The annotation is required for

Data Management Services to manage the data. The [RemoteClass] class-level annotation provides strong typing information for serialization and deserialization operations. Without the annotation, LCDS does not have knowledge of the public properties of the class, and the update() method would throw an error. The mapped Java class has the same public properties as the equivalent ActionScript class.

There is one more important line in dmsTestdrive.mxml, which defines the Flex client's button as follows:


<mx:Button label='Get Data' click='ds.fill(products)' />

The click handler, defined inline in ActionScript, causes the client-side version of the fill() method to be invoked when the user clicks on the button. The ArrayCollection called products is passed to the fill() method so it can be used as a data transfer buffer. This method call is forwarded to the server, where it is executed by the Java version of the fill() method, defined in ProductAssembler. When the server returns the data to the Flex client, the DataGrid is automatically updated by the ArrayCollection because of data binding, denoted by curly braces:


<mx:DataGrid dataProvider='{products}' editable='true' width='100%' height='100%'>

You can see this in action by placing breakpoints on update() method in ProductService.java.

Licensing

LCDS is available under several licenses, including a free license. The software provided is the same for all licenses. The LCDS Trial Developer License is a non-expiring trial for development on one or more CPUs. This version lets developers create RIAs with rich data services capabilities. If your application requires more than one CPU with two cores for production deployment, or if you want licenses for Q/A and staging, contact your Adobe sales representative or channel partner to purchase the appropriate runtime license. The LCDS Single-CPU License lets you run an application in a commercial, production environment on a single machine with one CPU with up to two cores. This version is ideal for use in small to medium-scale production applications and proof-of-concept projects.

Q/A and staging server licenses are available separately and are not free.

About The Author

Photo of author Mike Slinn

Mike Slinn

Mike Slinn is a software contractor specializing in Adobe Flex and Java. With over three decades of hands-on experience, Mike focuses on value creation, including technology, methodology and business drivers. He has provided litigation support for contractual and patent disputes and US Federal court has recognized him as a software expert. A graduate of Carleton University in Ottawa, Canada, Mike received a B. Eng. in Electronics in 1979 and became P. Eng. in B.C. in 1983. Mike has lived in Silicon Valley since 1996, and now resides in Half Moon Bay, CA with his wife and their ever-demanding parrot.

Recommended Book

Flex Data Services, Hibernate and Eclipse

Flex Data Services, Hibernate and Eclipse is intended for experienced architects and programmers who would like to design and implement non-trivial applications using the Adobe Flash Platform using a Java EE back end. This book explains how to design, build and test the Flex Data Services and the server-side Java stack of an application built with the Adobe Flash Platform.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Are you using JavaFX yet?

Are you using JavaFX yet? You should be! Click here to check out our latest Refcard on Getting Started with JavaFX. 

0 replies - 5911 views - 06/02/09 by Lyndsey Clevesy in Announcements