4.4. Running through a Complete Example

This section walks through an example that shows the BlazeDS remoting service in use. I use Apache Tomcat as the Servlet container and deploy a BlazeDS instance in it. From Chapter 2, you know how to deploy BlazeDS in Tomcat and many other mainstream Java application servers. For convenience, I also use Flex Builder as my IDE.

In this example, I take the energy consumption data for United States between the years 1949 and 2007 and depict that in a data grid and a time series line chart.

The data is accessible from a POJO service object called EnergyConsumptionDataService. The data itself manifests in an object-oriented format and is transferred as such. The consumption for individual data points for the time interval is encapsulated in an object called EnergyConsumption. The data for the entire time interval is a collection of such objects. The EnergyConsumption class has the following attributes:

  • year

  • fossilFuels

  • nuclearElectricPower

  • renewableEnergy

  • total

As a first step, I create a Flex project in Flex Builder and choose a J2EE server. To keep all the code in one place in a uniform manner I also choose to create a combined Java/Flex project using WTP (Web Tools Platform). WTP comes as a part of the Ecplise JEE version and you will benefit from installing it. Figure 4-5 shows the first screen where this initial project information is specified.

Figure 4.5. Figure 4-5

Next, I point the target runtime to my local Tomcat installation. The assumption is that Apache Tomcat is already configured to work with the Eclipse installation. In addition, one needs to specify the following:

  • Context Root

  • Content Folder

  • Flex WAR File

Flex Builder, by default, sets the project name as the Context Root value. The Flex WAR File variable is a legacy name, and for BlazeDS it points to the blazeds.war file. I chose to point to the blazeds.war archive file within my Tomcat installation. This isn't a requirement though. The war file could actually be anywhere in the file system. Figure 4-6 is a view of the screen where the context root, content folder, and war file path are specified.

Now you're ready to choose the MXML main application file name and the application URL. For now, you may just go with the defaults, which are already populated. See Figure 4-7 for details.

At this stage the project is set up in Flex Builder, and you are ready to add the code that will drive the example application. Let's build the service first.

Figure 4.6. Figure 4-6

Figure 4.7. Figure 4-7

4.4.1. Java-Based Data Service

The Java-based service is exposed through a remote method of the EnergyConsumptionDataService class. In our rudimentary example, that method is pretty much all that class has. The source for this service class is in Listing 4-2.

Example 4.2. Service That Returns the U.S. Energy Consumption Record from 1949 to 2007
package problazeds.ch04;

public class EnergyConsumptionDataService
{
    public List getEnergyConsumptionData() throws RuntimeException {

        List list = new ArrayList();
        Connection c = null;

        try {
            c = HSQLDBConnectionHelper.getConnection();
            Statement s = c.createStatement();

ResultSet rs = s.executeQuery("SELECT * FROM energy_consumption ORDER
              BY year");
            while (rs.next()) {
                list.add(new EnergyConsumption(rs.getInt("year"),
                        rs.getDouble("fossil_fuels"),
                        rs.getDouble("nuclear_electric_power"),
                        rs.getDouble("renewable_energy"),
                        rs.getDouble("total")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            HSQLDBConnectionHelper.close(c);
        }
        return list;

    }

}

As you browse through the getEnergyConsumptionData method code, you will notice that all the persistence and data-access-related heavy lifting is done by the HSQLDBConnectionHelper class. This application cuts out the complexity induced by full-blown relational databases and instead uses the lightweight embedded HSQL database as the data store. HSQL DB's four main advantages, which come handy here are:

  • It can be embedded and can run within the same JVM as the application.

  • It has a low footprint and needs little or no administration.

  • It can link to CSV and text files on the file system and allow you to interact with it as you do with the relational tables, fairly effortlessly. The data for this example resides in a CSV file.

  • You can use the good old SQL and the JDBC semantics to interact with HSQL DB

You can learn more about HSQL DB at http://hsqldb.org.

The HSQLDBConnectionHelper class sets up and interacts with the HSQLDB instance. It creates a singleton instance of the class, configures it. and sets up a connection. The bulk of all these activities, other than the JDBC driver class loading and the specification of the database URL, gets done in the static getConnection method, which looks like this:

public static Connection getConnection() throws SQLException {
        if (singletonInstance == null) {
            singletonInstance = new HSQLDBConnectionHelper();
        }
        try {
            Connection conn = DriverManager.getConnection(singletonInstance.url);
            final StringBuilder createTable = new StringBuilder();
            createTable.append("CREATE TEXT TABLE energy_consumption (");
            createTable.append("year INT PRIMARY KEY, fossil_fuels DOUBLE,");
            createTable.append("nuclear_electric_power DOUBLE, renewable_energy DOUBLE,
              total DOUBLE)");

final StringBuilder linkTable = new StringBuilder();
            linkTable.append("SET TABLE energy_consumption SOURCE ");
            linkTable.append(""us_energy_data.csv");
            linkTable.append(";ignore_first=true;all_quoted=true"");

            conn.setAutoCommit(true);
            conn.createStatement().execute(createTable.toString());
            conn.createStatement().execute(linkTable.toString());
            return conn;
        } catch (SQLException e) {
            throw e;
        }
    }

This class also defines a close method for graceful cleanup. The service returns a collection of EnergyConsumption objects. The EnergyConsumption class is depicted in a class diagram in Figure 4-8.

Figure 4.8. Figure 4-8

That is all as far as our service goes. The service is configured in remoting-service.xml as follows:

<service id="remoting-service"
    class="flex.messaging.services.RemotingService">

    <adapters>
        <adapter-definition id="java-object" class="flex.messaging.
          services.remoting.adapters.JavaAdapter"default="true"/>
    </adapters>

    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>


    <destination id="energyConsumptionData">
        <properties>
            <source>problazeds.ch04.EnergyConsumptionDataService</source>
        </properties>
    </destination>

</service>

This service is called from a simple Flex application, which you will learn about next.

4.4.2. Client-Side Flex Code

The Flex application is aggregated together in a single MXML file. This is not ideal for a real-life example but seems functional enough for this example. In addition to this application file, there is the class that represents the client-side counterpart of the EnergyConsumption object. Listing 4-3 lists the code for the main MXML application.

Example 4.3. ProBlazeDSCh04.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">
    <mx:RemoteObject id="srv1" destination="energyConsumptionData"/>
      <mx:Button label="Get Data"
        click="srv1.getEnergyConsumptionData()"/>

      <mx:DataGrid dataProvider="{srv1.getEnergyConsumptionData.
        lastResult}"
        width="100%" height="100%"/>

      <mx:Panel title="Line Chart">
        <mx:LineChart id="myChart"
            dataProvider="{srv1.getEnergyConsumptionData.lastResult}"
            showDataTips="true">

            <mx:horizontalAxis>
               <mx:CategoryAxis
                dataProvider="{srv1.getEnergyConsumptionData.
                  lastResult}"
                categoryField="year"/>
            </mx:horizontalAxis>
            <mx:series>
               <mx:LineSeries
                yField="fossilFuels"
                displayName="Fossil Fuels"/>
               <mx:LineSeries
                   yField="nuclearElectricPower"
                   displayName="Nuclear Electric Power"/>
               <mx:LineSeries
                   yField="renewableEnergy"
                   displayName="Renewable Energy"/>
               <mx:LineSeries
                   yField="total"
                   displayName="Total"/>
            </mx:series>
        </mx:LineChart>
     <mx:Legend dataProvider="{myChart}"/>
  </mx:Panel>

</mx:Application>

The illustration of the service, client, and the configuration covers all aspects of the example.

The code for this simple example is available for download. You may want to modify it, play with it, and experimentally explore how things work.

Now that you know all the essentials of remoting between Flex and POJOs, you may want to start exploring the ways and means of customizing and extending the code beyond the standard mechanism.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.81.201