Using the Flash Builder 4 Data Centric Features with Parsley (and other frameworks)

I have blogged about the new data-centric features in Flash Builder 4 here and here. One question people often ask me is: “Can I use this feature if I use a Framework (Cairngorm, Mate, Parsley, Spring ActionScript, Swiz, etc)?”

The answer is yes: The classes generated by Flash Builder (Value Objects and Service Stubs) are standard building blocks that are part of most RIA design patterns, regardless of whether or not you use a framework.

The way you leverage these classes in your application may differ slightly depending on the framework you are using. For example, each framework may have a different approach to configure service endpoints or to instantiate generated service stubs.

To demonstrate this, I built a version of my “Contacts” application (also known as InSync) using the Flash Builder 4 data-centric features and the Parsley Framework.

[Read more...]

Flex 4 Sample Application using a Java Back-End, BlazeDS 4 and Flash Builder 4 Data Wizards

I put together a new Test Drive environment to allow you to explore the development of Flex 4 applications with a Java back-end using the new “Data-Centric Development” features of Flash Builder 4. These features include service introspection, value object and service stub generation, etc. This Test Drive is still work in progress: it currently consists of a single application called InSync (a complete Flex 4 rewrite of my contact management sample application), but I think it’s already valuable to understand the impact of the new Flash Builder 4 data features. Insync also demonstrates some of the new features of Flex 4: skinning, skinnable components, layout managers, etc.

Watch the video below to get familiar with the Test Drive environment and the sample application:

Installation Instructions

  1. Download flex-java-testdrive.zip, and unzip the file in your root directory.
  2. Open a Command Window or Shell, navigate to /flex-java-testdrive/tomcat/bin, and start Tomcat (for instance: catalina run).
  3. Open a browser and access http://localhost:8400/testdrive/InSync/InSync.html.

Importing the projects in Flash Builder 4

  1. In Flash Builder 4, click File > Import > General > Existing Projects into Workspace.
  2. Specify flex-java-testdrive/projects as the root directory and click finish.
  3. Explore the projects: InSync is the Flex project and java-testdrive is the Java project for the server-side classes.

In the InSync project, the classes in the services and valueObjects packages have been generated automatically by Flash Builder 4. My next blog post will show you how to generate these classes based on existing Java services deployed in BlazeDS.

NOTE: Because BlazeDS 4 hasn’t yet been released, this version of the Test Drive uses a nightly build of BlazeDS 4.

Building the Server-Side of the "Tour de Flex" Real-Time Dashboard

Greg Wilson and Damien Mandrioli are also blogging about the new Tour de Flex real time dashboard today. Greg is the inspiration behind everything “Tour de Flex”, including the idea of the dashboard. He has the story behind the genesis of this project on his blog. Damien (from IBM/ILOG) did a fantastic job at building the client-side of the dashboard using the very cool ILOG Elixir components, and he walks you through the details on his blog.

My contribution to the project is the “real-time messaging” infrastructure. I provide the details below.

First the overall workflow…

The reason we are combining PHP and Java in this workflow is mostly historical. In the initial version of Tour de Flex, there was no Java involved: Greg was persisting loaded samples data (sample id and timestamp) directly from his PHP page. We later added LiveCycle Data Services to the picture to support the data push requirement of the dashboard, and we took the opportunity to move some code (such as the database persistence) from PHP to Java. Note that we are using LCDS for the performance and scalability of its high-end channels, but the application could also be deployed on BlazeDS.

A more straightforward architecture would be for the client to communicate directly with LCDS. For example, the client could invoke a remote object that would directly publish the loaded sample data (sample id and geolocation of the client) to the message destination. Alternatively, the client could use a Producer object to directly publish the message to the destination. Because some logic (such as geolocating the IP address and persisting the data) has to be executed at the server-side before routing the messages to the subscribed clients, you would have to write a custom message adapter if you used this approach.

We will probably streamline the workflow with one of these two approaches in the future, but in the meantime here is the source code for the servlet (logging and non-essential code removed for brevity):

package com.adobe.tdf;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;

import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;

public class TDFServlet extends HttpServlet {

	// Unique clientID for the message service
	private String clientID = UUIDUtils.createUUID();

	// The geocoding service
	protected LookupService lookupService;

	// A DAO to store sample requests in a database
	protected SampleRequestDAO dao = new SampleRequestDAO();

	// The LCDS message broker
	protected MessageBroker messageBroker;

	// The LCDS messaging destination where real time sample requests information is pushed
	protected String destination;

	public void init() throws ServletException {

		ServletConfig config = getServletConfig();
		destination = config.getInitParameter("messaging.destination.name");
		String path = config.getInitParameter("geocoding.database.path");
		try {
			// Load the geocoding database in init() to make sure we load it only once
			lookupService = new LookupService(path, LookupService.GEOIP_MEMORY_CACHE);
		} catch (IOException e) {
			// We swallow the exception here. If the database is not available, the feed
			// will still work but won't provide the location info.
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		if (messageBroker == null)
		{
			messageBroker = MessageBroker.getMessageBroker(null);
		}

		SampleRequest sampleRequest = new SampleRequest();

		try {
			sampleRequest.setSampleId(Integer.parseInt(request.getParameter("sampleId")));
		} catch (Exception e) {
			String message = "A valid sampleId is required to process this request";
			throw new RuntimeException(message);
		}

		sampleRequest.setTimestamp(new Date());

		String ipAddress = request.getParameter("ipAddress");

		// Geolocate the IP address and add the info to the message
		if (lookupService != null && ipAddress != null)
		{
	                Location location = lookupService.getLocation(ipAddress);
			if (location != null)
			{
				sampleRequest.setLatitude(location.latitude);
				sampleRequest.setLongitude(location.longitude);
				sampleRequest.setCountry(location.countryCode);
				sampleRequest.setCity(location.city);
			}
		}

		try {
			dao.create(sampleRequest, ipAddress);
		} catch (RuntimeException e) {

		}

		String subtopic = request.getParameter("subtopic");
		if (subtopic == null) subtopic = "flex";

		// Publish the message to specified destination and subtopic.
		AsyncMessage msg = new AsyncMessage();
		msg.setDestination(destination);
		msg.setHeader("DSSubtopic", subtopic);
		msg.setClientId(clientID);
		msg.setMessageId(UUIDUtils.createUUID());
		msg.setTimestamp(System.currentTimeMillis());
		msg.setBody(sampleRequest);
		messageBroker.routeMessageToService(msg, null);

		PrintWriter out = response.getWriter();
	        out.println("<html><body>ok</body></html>");

	}

}

The servlet is responsible for three things:

  1. Geolocate the IP address of the client requesting the sample. We currently use the MaxMind Geolocation API. The API is straightforward and the results seem pretty accurate.
  2. Save the information about the loaded sample in a database. We keep track of historical data to be able to support future data visualization projects.
  3. Publish the data about the loaded sample to a message destination. The servlet uses the Message Service Java API to directly push messages to the Flex destination (lines 97 to 104). Note that the same API exists for ColdFusion, so CF developers could use a CF page instead of this servlet to push messages to the client.

Channels

The messaging destination is set up to support different communication channels: RTMP, long polling, and regular polling. The client-side developer can decide which channel to use to communicate with the server. For example, if you wanted to use RTMP as the primary channel, fall back to long polling if the RTMP connection fails, and fall back to regular polling if the long polling connection fails you could set up your client-side ChannelSet as follows:

<mx:ChannelSet id="channelSet">
	<mx:RTMPChannel id="rtmp" url="rtmp://hostname:2037"/>
	<mx:AMFChannel url="http://hostname/context/messagebroker/amflongpolling"/>
	<mx:AMFChannel url="http://hostname/context/messagebroker/amfpolling"/>
</mx:ChannelSet>

New Update to the Spring BlazeDS Integration Test Drive

I made some additional changes to the Spring BlazeDS Integration (RC1) Test Drive:

  • The Test Drive now includes an annotation-based configuration sample (the Company Manager sample). Spring annotations such as @Service, @RemotingDestination, @Autowired, @RemotingInclude, and @RemotingExclude make it really easy to configure your beans and make them available through Remoting. As an example, here is the source code for the CompanyDAO class:

    package flex.spring.samples.company;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.sql.DataSource;
    
    import org.springframework.flex.remoting.RemotingDestination;
    import org.springframework.flex.remoting.RemotingExclude;
    import org.springframework.flex.remoting.RemotingInclude;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
    import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
    import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
    
    import flex.spring.samples.industry.IIndustryDAO;
    
    @Service("companyService")
    @RemotingDestination(channels={"my-amf"})
    public class CompanyDAO implements ICompanyDAO {
    
    	private final SimpleJdbcTemplate template;
    	private final SimpleJdbcInsert insertCompany;
    
    	private IIndustryDAO industryDAO;
    
    	private final ParameterizedRowMapper<Company> rowMapper = new ParameterizedRowMapper<Company>(){
    		public Company mapRow(ResultSet rs, int rowNum) throws SQLException {
    			Company company = new Company();
    			company.setId(rs.getInt("id"));
    			company.setName(rs.getString("name"));
    			company.setAddress(rs.getString("address"));
    			company.setCity(rs.getString("city"));
    			company.setState(rs.getString("state"));
    			company.setZip(rs.getString("zip"));
    			company.setPhone(rs.getString("phone"));
    			company.setIndustry(industryDAO.findById(rs.getInt("industry_id")));
    			return company;
    		}
    	};
    
    	@Autowired
    	public CompanyDAO(DataSource dataSource, IIndustryDAO industryDAO) {
    		template = new SimpleJdbcTemplate(dataSource);
    		insertCompany = new SimpleJdbcInsert(dataSource).withTableName("COMPANY").usingGeneratedKeyColumns("ID");
    		this.industryDAO = industryDAO;
    	}
    
    	@RemotingInclude
    	public Company findById(int id) {
    		return template.queryForObject("SELECT * FROM company WHERE id=?", rowMapper, id);
    	}
    
    	@RemotingInclude
    	public List<Company> findAll() {
    		return template.query("SELECT * FROM company ORDER BY name", rowMapper);
    	}
    
    	@RemotingInclude
    	public List<Company> findByName(String name) {
    		return template.query("SELECT * FROM company WHERE UPPER(name) LIKE ? ORDER BY name",
    				rowMapper,
    				"%" + name.toUpperCase() + "%");
    	}
    
    	@RemotingInclude
    	public Company create(Company company) {
    		Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("name", company.getName());
            parameters.put("address", company.getAddress());
            parameters.put("city", company.getCity());
            parameters.put("state", company.getState());
            parameters.put("zip", company.getZip());
            parameters.put("phone", company.getPhone());
            parameters.put("industry_id", company.getIndustry().getId());
            Number id = insertCompany.executeAndReturnKey(parameters);
    		company.setId(id.intValue());
    		return company;
    	}
    
    	@RemotingInclude
    	public boolean update(Company company) {
            int count = template.update("UPDATE company SET name=?, address=?, city=?, state=?, zip=?, phone=?, industry_id=? WHERE id=?",
    				company.getName(),
    				company.getAddress(),
    				company.getCity(),
    				company.getState(),
    				company.getZip(),
    				company.getPhone(),
    				company.getIndustry().getId(),
    				company.getId());
    		return (count == 1);
    	}
    
    	@RemotingExclude
    	public boolean remove(Company company) {
    		int count = template.update("DELETE FROM company WHERE id=?", company.getId());
    		return (count == 1);
    	}
    
    }
    

  • The Test Drive is now using the M3 build of Spring 3 (as opposed to M2 in the previous builds of the Test Drive).
  • I modified the configuration of the long polling channel to support more persistent connections per domain based on the browser capabilities.
  • And of course compared to the M2 build, this version of the Test Drive includes a number of Messaging samples.

    Using the Messaging integration, setting up a destination can be as easy as:

    <flex:message-destination id="chat" />
    

    And here is how you configure a destination mapped to a JMS topic:

    <flex:jms-message-destination id="jms-chat" jms-destination="chatTopic" />
    

Installation Instructions:

  1. Download the Spring / Flex TestDrive here: http://coenraets.org/downloads/spring-flex-testdrive-RC1v2.zip
  2. Unzip it in your root directory
  3. Navigate to /spring-flex-testdrive/tomcat/bin and start Tomcat (for instance: catalina run)
  4. Open a browser and access http://localhost:8080
  5. Follow the instructions

Speaking at the New England Java User Group on Thursday (May 14th)

I will be joined by Mark Fisher from SpringSource and we will talk about Flex, Spring, BlazeDS and the integration of these technologies. Spring BlazeDS integration RC1 was released last week. One of the key features in RC1 is the integration of the Message service, and Mark is the lead developer on that feature.

I hope to see you there if you live in the greater Boston area.

Thu, May 14 6:00pm
Sun Microsystems – 1 Network Way, Burlington, MA
NEJUG Link

New Test Drive for Spring BlazeDS Integration RC1

UPDATE: An updated version of this Test Drive is available here

SpringSource just released the RC1 build for the Spring / BlazeDS integration project. The key new feature in RC1 is the integration of the BlazeDS Message Service.

I updated my Spring BlazeDS Integration Test Drive to showcase the messaging integration.

In addition to Remoting and Security samples, the Test Drive now includes the following Messaging samples:

  • Chat: Messaging basics
  • Simple Data Push: A simple data push example
  • Traderdesktop: A more sophisticated data push example showing how to use subtopics
  • JMS Chat: A chat application using a JMS topic and exchanging messages with a Swing-based client
  • Collaboration: An example showing how to use messaging to remotely drive another client’s application

Installation Instructions:

  1. Download the Spring / Flex TestDrive here: http://coenraets.org/downloads/spring-flex-testdrive-RC1.zip
  2. Unzip it in your root directory
  3. Navigate to /spring-flex-testdrive/tomcat/bin and start Tomcat (for instance: catalina run)
  4. Open a browser and access http://localhost:8080
  5. Follow the instructions

As always, I’d love to hear your feedback and your ideas to improve this Test Drive.

I will probably have another version next week with a couple of additional samples and more documentation for the Message Service, but I already wanted to make this version available to allow you to experiment RC1 samples.

Christophe

Externalizing Service Configuration using BlazeDS and LCDS

A typical source of confusion when developers start working with RemoteObject or other BlazeDS/LCDS related classes is where and most importantly *when* the configuration of your services is being read.

The question often arises after an application stops working when you move it to another server. This is one of the most frequently asked questions related to BlazeDS and LCDS, so I figured I would answer it here. There is nothing really new in this post, but hopefully this will be a good point of reference.

When you create a new BlazeDS or LCDS project in Flex Builder, you are typically told to select J2EE as the “Application Server Type” and then check “use remote object access service”. This adds a compiler argument pointing to the location of your services-config.xml. If you check the Flex Compiler properties of your Flex Builder project, you’ll see something like this:

-services “c:\blazeds\tomcat\webapps\samples\WEB-INF\flex\services-config.xml”

When you then compile your application, the required values of services-config.xml are baked into the SWF. In other words, services-config.xml is read at compile time and not at runtime as you may have thought intuitively. To abstract things a little bit, you can use tokens such as {server.name}, {server.port}, and {context.root} in services-config.xml. However, {context.root} is still substituted at compile time, while {server.name} and {server.port} are replaced at runtime using the server name and port number of the server the SWF was loaded from (which is why you can’t use these tokens for AIR applications).

[Read more...]

Spring / BlazeDS Integration on Adobe TV

In this new Adobe TV episode, I demonstrate how to build Flex applications that connect to a Spring back-end using the new Spring / BlazeDS Integration project.

If you are interested in this integration, make sure you check out the Spring / BlazeDS Integration page on the SpringSource web site and the new Spring / BlazeDS Integration Test Drive.

Sample application using the Swiz Framework and BlazeDS

There have been a lot of discussions around Flex Frameworks lately. Tony Hillerson has an interesting series here: 1 2 3 4 5 6

A relative newcomer on the list is Swiz, the work of Chris Scott. I figured I would give it a try, and create a Swiz version of the inSync application that I often use to try out and demonstrate different features and techniques in Flex and Adobe AIR. This is not an endorsement of Swiz over other frameworks. I simply wanted to share the sample application I built as part of my own research as a (neutral like a Swiss) Evangelist.

View the source code.

[Read more...]

New Spring/BlazeDS Integration Test Drive

UPDATE: I posted a new version of the Test Drive for the M2 build of the Spring / BlazeDS integration project here. Please use that version.

SpringSource recently announced the Spring / BlazeDS Integration project. You can read more about the project and download the bits at http://www.springsource.org/spring-flex.

To help developers get started with the integration, I put together a new “Spring / BlazeDS Test Drive”. This Test Drive consists of a minimal version of Tomcat with BlazeDS and the “Spring / BlazeDS integration” preconfigured and ready to use. It also includes a series of samples running “out-of-the-box” that should allow you to get up and running integrating Flex (and Adobe AIR) with Spring in minutes.

Installation Instructions:

  1. Download the Spring / Flex TestDrive here: http://coenraets.org/downloads/spring-flex-testdrive.zip
  2. Unzip it in your root directory
  3. Navigate to /spring-flex-testdrive/tomcat/bin and start Tomcat (for instance: catalina run)
  4. Open a browser and access http://localhost:8080
  5. Follow the instructions

As always, I’d would love to hear your feedback and your ideas to improve this Test Drive.

Christophe