Sunday, 28 February 2010

ColdFusion Head First Design Patterns: Observer

Continuing in this design patterns series taken from Head First Design Patterns, is a ColdFusion implementation of the Observer Pattern.

Interfaces

Subject.cfc

<cfinterface>
  <cffunction access="public" returntype="void" name="registerObserver">
    <cfargument required="true" type="Observer" name="o">
  </cffunction>

  <cffunction access="public" returntype="void" name="removeObserver">
    <cfargument required="true" type="Observer" name="o">
  </cffunction>
  
  <cffunction access="public" returntype="void" name="notifyObservers">
  </cffunction>
</cfinterface>

Observer.cfc

<cfinterface>
  <cffunction access="public" returntype="void" name="update">
    <cfargument required="true" type="numeric" name="temperature">
    <cfargument required="true" type="numeric" name="humidity">
    <cfargument required="true" type="numeric" name="pressure">        
  </cffunction>
</cfinterface>

DisplayElement.cfc

<cfinterface>
  <cffunction access="public" returntype="void" name="display">
  </cffunction>
</cfinterface>

Subject Implementation

WeatherData.cfc

<cfcomponent implements="Subject" output="false">

  <cffunction access="public" returntype="Subject" name="init">
    <cfset VARIABLES.observers = arrayNew(1)>
    
    <cfreturn THIS>
  </cffunction> 

  <cffunction access="public" returntype="void" name="registerObserver">
    <cfargument required="yes" type="Observer" name="o" />
    
    <cfset arrayAppend(VARIABLES.observers, ARGUMENTS.o)>
  </cffunction>

  <cffunction access="public" returntype="void" name="removeObserver">
    <cfargument required="yes" type="Observer" name="o" />
    
    <cfset arrayDelete(VARIABLES.observers, ARGUMENTS.o)>    
  </cffunction>

  <cffunction access="public" returntype="void" name="notifyObservers">
    <cfset var LOCAL = {}>
  
    <cfloop index="LOCAL.o" array="#VARIABLES.observers#">
      <cfset LOCAL.o.update(VARIABLES.temperature, VARIABLES.humidity, VARIABLES.pressure)>
    </cfloop>
  </cffunction>
  
  <cffunction access="public" returntype="void" name="measurementsChanged">
    <cfset notifyObservers()>
  </cffunction>
  
  <cffunction access="public" returntype="void" name="setMeasurements">
    <cfargument required="yes" type="numeric" name="temperature" />
    <cfargument required="yes" type="numeric" name="humidity" />
    <cfargument required="yes" type="numeric" name="pressure" />
    
    <cfset VARIABLES.temperature = ARGUMENTS.temperature>
    <cfset VARIABLES.humidity = ARGUMENTS.humidity>
    <cfset VARIABLES.pressure = ARGUMENTS.pressure>
    <cfset measurementsChanged()>
  </cffunction>
</cfcomponent>

Display Elements

CurrentConditionsDisplay.cfc

<cfcomponent implements="Observer, DisplayElement" output="true">

  <cffunction access="public" returntype="CurrentConditionsDisplay" name="init">
    <cfargument required="true" type="WeatherData" name="weatherData">
    
    <cfset VARIABLES.weatherData = ARGUMENTS.weatherData>
    <cfset VARIABLES.weatherData.registerObserver(THIS)>
    
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="void" name="update">
    <cfargument required="true" type="numeric" name="temperature">
    <cfargument required="true" type="numeric" name="humidity">
    <cfargument required="true" type="numeric" name="pressure">
    
    <cfset VARIABLES.temperature = ARGUMENTS.temperature>
    <cfset VARIABLES.humidity = ARGUMENTS.humidity>
    <cfset display()>
  </cffunction>

  <cffunction access="public" returntype="void" name="display">
    <cfoutput>
      Current conditions: #VARIABLES.temperature#F degrees and #VARIABLES.humidity#% humidity
      <br />
    </cfoutput>
  </cffunction>
</cfcomponent>

HeatIndexDisplay.cfc

<cfcomponent implements="Observer, DisplayElement" output="true">

  <cffunction access="public" returntype="HeatIndexDisplay" name="init">
    <cfargument required="true" type="WeatherData" name="weatherData">
    
    <cfset VARIABLES.weatherData = ARGUMENTS.weatherData>
    <cfset VARIABLES.weatherData.registerObserver(THIS)>
    
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="void" name="update">
    <cfargument required="true" type="numeric" name="temperature">
    <cfargument required="true" type="numeric" name="humidity">
    <cfargument required="true" type="numeric" name="pressure">
    
    <cfset VARIABLES.temperature = ARGUMENTS.temperature>
    <cfset VARIABLES.humidity = ARGUMENTS.humidity>
    <cfset VARIABLES.heatIndex = computeHeatIndex(VARIABLES.temperature, VARIABLES.humidity)>
    <cfset display()>
  </cffunction>

  <cffunction access="public" returntype="void" name="display">
    <cfoutput>
      Heat index is #VARIABLES.heatIndex#
      <br />
    </cfoutput>
  </cffunction>

  <cffunction access="private" returntype="numeric" name="computeHeatIndex">
    <cfargument required="true" type="numeric" name="t">
    <cfargument required="true" type="numeric" name="rh">

    <cfset var LOCAL = {}>
    <cfset LOCAL.index = ((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) +
            (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) +
            (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +
            (0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 *  
            (rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +
            (0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) +     
            0.000000000843296 * (t * t * rh * rh * rh)) -
            (0.0000000000481975 * (t * t * t * rh * rh * rh)))>
  
    <cfreturn LOCAL.index>
  </cffunction> 
</cfcomponent>

Test Page

WeatherStation.cfm

<cfset weatherData = createObject("component", "WeatherData").init()>

<cfset currentDisplay = createObject("component", "CurrentConditionsDisplay").init(weatherData)>
<cfset heatDisplay = createObject("component", "HeatIndexDisplay").init(weatherData)>

<cfset weatherData.setMeasurements(80, 65, 30.4)>
<cfset weatherData.setMeasurements(82, 70, 29.2)>
<cfset weatherData.setMeasurements(78, 90, 29.2)>

Source Code

Saturday, 27 February 2010

Maven GWT WAR & Glassfish skeleton project

Another skeleton project implementing the same functionality as this previous post, a Google Web Toolkit front-end, with an embedded Derby database, accessed using the Java Persistence API; but this time running on an embedded Glassfish 3 instance and making use of EJB3.1 features.

Here is the projects POM:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.adrianwalker.maven.skeleton.war.gwt.glassfish</groupId>
  <artifactId>maven-war-gwt-glassfish-skeleton</artifactId>
  <packaging>war</packaging>
  <version>0.1.0</version>
  <name>Maven WAR-GWT-Glassfish Skeleton</name>

  <description>
    Skeleton project for creating a GWT WAR running on Glassfish, with a Derby
    database accessed through JPA.

    Usage: mvn clean install embedded-glassfish:run
  </description>

  <url>http://www.adrianwalker.org</url>

  <organization>
    <name>adrianwalker.org</name>
    <url>http://www.adrianwalker.org</url>
  </organization>

  <developers>
    <developer>
      <name>Adrian Walker</name>
      <email>ady.walker@gmail.com</email>
      <organization>adrianwalker.org</organization>
      <organizationUrl>http://www.adrianwalker.org</organizationUrl>
    </developer>
  </developers>

  <repositories>
    <repository>
      <id>java.net</id>
      <url>http://download.java.net/maven/2</url>
    </repository>

    <repository>
      <id>codehaus.org</id>
      <url>http://repository.codehaus.org</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>java.net</id>
      <url>http://download.java.net/maven/glassfish</url>
    </pluginRepository>
  </pluginRepositories>

  <properties>
    <gwt.version>2.0.2</gwt.version>
  </properties>

  <build>
    <outputDirectory>war/WEB-INF/classes</outputDirectory>

    <finalName>message</finalName>

    <resources>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <includes>
          <include>META-INF/persistence.xml</include>
        </includes>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <configuration>
          <filesets>
            <fileset>
              <directory>war</directory>
              <includes>
                <include>**/*</include>
              </includes>
            </fileset>
          </filesets>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>gwt-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.glassfish</groupId>
        <artifactId>maven-embedded-glassfish-plugin</artifactId>
        <configuration>
          <app>${project.build.directory}/${build.finalName}.war</app>
          <instanceRoot>${project.build.directory}/glassfish</instanceRoot>
          <contextRoot>${build.finalName}</contextRoot>
          <configFile>${basedir}/src/test/resources/config/domain.xml</configFile>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.glassfish.extras</groupId>
      <artifactId>glassfish-embedded-all</artifactId>
      <version>3.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-servlet</artifactId>
      <version>${gwt.version}</version>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
      <version>${gwt.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jxr-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </reporting>
</project>

The embedded Glassfish server is configured using a domain.xml taken from a fresh install of Glassfish 3, located \src\test\resources\config\domain.xml and referenced from the embedded Glassfish Maven plugin configuration element in the pom.xml

The default domain.xml has been amended to include jdbc-resource and jdbc-datasource entries for the web applications database. The domain.xml below shows the amendments, with the rest of the file removed for brevity:

domain.xml

<domain log-root="${com.sun.aas.instanceRoot}/logs" application-root="${com.sun.aas.instanceRoot}/applications" version="10.0">

  ...

  <resources>

    ...

    <jdbc-resource pool-name="MessagePool" jndi-name="jdbc/message" />

    ...

    <jdbc-connection-pool name="MessagePool" datasource-classname="org.apache.derby.jdbc.EmbeddedDataSource" res-type="javax.sql.DataSource">
      <property name="databaseName" value="target/database/message" />
      <property name="connectionAttributes" value=";create=true" />
    </jdbc-connection-pool>
  </resources>
  <servers>
    <server name="server" config-ref="server-config">

      ...

      <resource-ref ref="jdbc/message" />
    </server>
  </servers>

  ...

</domain>

The configured datasource is referenced in the projects persistence.xml, which uses EclipseLink to implement the JPA.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="messagePersistenceUnit" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/message</jta-data-source>
    <class>org.adrianwalker.maven.skeleton.jpa.entity.MessageEntity</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Run the project with 'mvn clean install embedded-glassfish:run' and point your brower at http://localhost:8080/message/.

Source Code

Monday, 22 February 2010

ColdFusion Head First Design Patterns: Singleton

Everyone's favorite, The Singleton Pattern, is probably the most overused and least well implemented design pattern.

There are at least seven different variations on the singleton implementation in Java, some are detailed in Head First Design Patterns, some are documented in Joshua Bloch's awesome book Effective Java, and some I've found along the way on the web.

Not all of the variations can be implemented in ColdFusion, but lets list them and pick the best one to code in CFML.

None of them can be implemented in ColdFusion, but lets list them and see why.

Lazily created Singleton with static factory method

Introduced as the first singleton example in Head First Design Patterns. It isn't thread safe.

public final class Singleton {

  private static Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (null == instance) {
      instance = new Singleton();
    }

    return instance;
  }
}

Synchronized lazily created Singleton with static factory method

Introduced as the second example in Head First, it is thread safe but uses a computationally expensive synchronized method.

public final class Singleton {

  private static Singleton instance;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    if (null == instance) {
      instance = new Singleton();
    }

    return instance;
  }
}

Eagerly created Singleton with static factory method

Detailed as an alternative to synchronizing the getInstance() method in Head First, and presented as a possible implementation in Joshua Bloch's Effective Java. Bloch goes on to note that this implementation and the following implementation can not be made serializable by just adding implements Serializable. All instance fields would need to be declared transient and a readResolve() method provided.

public final class Singleton {

  private static final Singleton INSTANCE = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return INSTANCE;
  }
}

Eagerly created Singleton with public final field

Presented by Bloch as an alternative to the above implementation, it's main advantage is that the class definition clearly shows it is a singleton.

public final class Singleton {

public static final Singleton INSTANCE = new Singleton();

  private Singleton() {
  }
}

Double checked locking

The third and final example in Head First, only synchronizes the first time through the getInstance() method. This implementation of the singleton makes use of the volatile keyword. In Java versions 1.4 and earlier, volatile could allow improper synchonization, this implementation is not portable to older JVMs.

public final class Singleton {

  private volatile static Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (null == instance) {
      synchronized (Singleton.class) {
        if (null == instance) {
          instance = new Singleton();
        }
      }
    }

    return instance;
  }
}

The solution of Bill Pugh

The solution of Bill Pugh uses a nested class to be as lazy as possible, is thread safe without using synchronized or volatile, and is usable with all JVM versions.

public final class Singleton {

  private Singleton() {
  }

  private static class SingletonHolder {

    private static final Singleton INSTANCE = new Singleton();
  }

  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
  }
}

Enum Type

Since version 1.5, Java has had support for enums. The final implementation in Effective Java uses an enumerated type with one element. This is equivalent to the public final field implementation but takes care of serialization automatically, and guarantees only a single instance.

public enum Singleton {

  INSTANCE;
}

From Effective Java:

"a single-element enum type is the best way to implement a singleton."

ColdFusion

ColdFusion doesn't support enum types or nested CFCs, so those are out straight away.

Lazily created Singleton with factory method

A lazily created Singleton fails to be initialized because the component can't see its own private constructor.

LazyFactoryMethod/Singleton.cfc

<cfcomponent output="false" >

  <cffunction access="private" returntype="Singleton" name="init">
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="Singleton" name="getInstance">
    <cfif NOT isDefined("VARIABLES.INSTANCE")>
      <cfset VARIABLES.INSTANCE = createObject("component", "Singleton").init()>
    </cfif>
  
    <cfreturn VARIABLES.INSTANCE>  
  </cffunction>
  
</cfcomponent>

Eagerly created Singleton with factory method

An eagerly created Singleton with a factory method goes in to a self referential loop and fills up the stack.

EagerFactoryMethod/Singleton.cfc

<cfcomponent output="false" >

  <cfset VARIABLES.INSTANCE = createObject("component", "Singleton").init()>

  <cffunction access="private" returntype="Singleton" name="init">
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="Singleton" name="getInstance">
    <cfreturn VARIABLES.INSTANCE>  
  </cffunction>
  
</cfcomponent>

Eagerly created Singleton with a public field

Same as with the previous eagerly created Singleton, a java.lang.StackOverflowError is thrown on instantiation.

EagerField/Singleton.cfc

<cfcomponent output="false" >

  <cfset THIS.INSTANCE = createObject("component", "Singleton").init()>

  <cffunction access="private" returntype="Singleton" name="init">
    <cfreturn THIS>
  </cffunction>

</cfcomponent>

So ColdFusion can't create real singletons, how bad does that suck?

Source Code

Thursday, 18 February 2010

ColdFusion Head First Design Patterns: Strategy

Following on from my previous post on a ColdFusion implementation of the Head First Design Patterns web MVC Pattern is a ColdFusion implementation of the Strategy Pattern.

The Strategy Pattern is probably the most useful pattern, to quote the Head First book:

"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

Abstract Duck

Duck.cfc

<cfcomponent output="true">

  <cffunction access="public" returntype="void" name="display">    
  </cffunction>
  
  <cffunction access="public" returntype="void" name="performFly">
    <cfset VARIABLES.flyBehaviour.fly()>    
  </cffunction>
  
  <cffunction access="public" returntype="void" name="performQuack">
    <cfset VARIABLES.quackBehaviour.quack()>    
  </cffunction>

  <cffunction access="public" returntype="void" name="swim">
    <cfoutput>All ducks float, even decoys!<br/></cfoutput>    
  </cffunction>

  <cffunction access="public" returntype="void" name="setFlyBehaviour">
    <cfargument required="true" type="FlyBehaviour" name="flyBehaviour">
    <cfset VARIABLES.flyBehaviour = ARGUMENTS.flyBehaviour>
  </cffunction>

  <cffunction access="public" returntype="void" name="setQuackBehaviour">
    <cfargument required="true" type="QuackBehaviour" name="quackBehaviour">
    <cfset VARIABLES.quackBehaviour = ARGUMENTS.quackBehaviour>
  </cffunction>
    
</cfcomponent>

Quack Strategies

Quack.cfc

<cfcomponent implements="QuackBehaviour" output="true">

  <cffunction access="public" returntype="Quack" name="init">
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="void" name="quack">
    <cfoutput>Quack<br/></cfoutput>  
  </cffunction>
  
</cfcomponent>

Fly Strategies

FlyWithWings.cfc

<cfcomponent implements="FlyBehaviour" output="true">
  
  <cffunction access="public" returntype="FlyWithWings" name="init">
    <cfreturn THIS>
  </cffunction>   
  
  <cffunction access="public" returntype="void" name="fly">
    <cfoutput>I'm flying!<br/></cfoutput>
  </cffunction>
  
</cfcomponent>

FlyNoWay.cfc

<cfcomponent implements="FlyBehaviour" output="true">
  
  <cffunction access="public" returntype="FlyNoWay" name="init">
    <cfreturn THIS>
  </cffunction>
  
  <cffunction access="public" returntype="void" name="fly">
    <cfoutput>I can't fly<br/></cfoutput>
  </cffunction>
  
</cfcomponent>

FlyRocketPowered.cfc

<cfcomponent implements="FlyBehaviour" output="true">
  
  <cffunction access="public" returntype="FlyRocketPowered" name="init">
    <cfreturn THIS>
  </cffunction>  
  
  <cffunction access="public" returntype="void" name="fly">
    <cfoutput>I'm flying with a rocket!<br/></cfoutput>
  </cffunction>
  
</cfcomponent>

Duck Implementations

MallardDuck.cfc

<cfcomponent extends="Duck" output="true">

  <cffunction access="public" returntype="MallardDuck" name="init">
    <cfset VARIABLES.flyBehaviour = createObject("component", "FlyWithWings").init()>
    <cfset VARIABLES.quackBehaviour = createObject("component", "Quack").init()>
    <cfreturn THIS>
  </cffunction>
  
  <cffunction access="public" returntype="void" name="display">
    <cfoutput>I'm a real Mallard duck<br/></cfoutput>
  </cffunction>
   
</cfcomponent>

ModelDuck.cfc

<cfcomponent extends="Duck" output="true">

  <cffunction access="public" returntype="ModelDuck" name="init">
    <cfset VARIABLES.flyBehaviour = createObject("component", "FlyNoWay").init()>
    <cfset VARIABLES.quackBehaviour = createObject("component", "Quack").init()>
    <cfreturn THIS>
  </cffunction>
  
  <cffunction access="public" returntype="void" name="display">
    <cfoutput>I'm a model duck<br/></cfoutput>
  </cffunction>
   
</cfcomponent>

Test Page

MiniDuckSimulator.cfm

<cfset mallard = createObject("component", "MallardDuck").init()>
<cfset mallard.performQuack()>
<cfset mallard.performFly()>

<cfset model = createObject("component", "ModelDuck").init()>
<cfset model.performFly()>
<cfset model.setFlyBehaviour(createObject("component", "FlyRocketPowered").init())>
<cfset model.performFly()>

Source Code

Tuesday, 16 February 2010

ColdFusion Head First Design Patterns: MVC

Head First Design Patterns is a pretty good book, with loads of good code examples in Java and not nearly as dry as GoF. It's even got a fit bird on the front cover. Careful though, looks like she's rocking an itchy twunt.

Source code for the book is available here.

For this post I've taken the web application MVC code written in Java/Servlets/JSP and re-coded it in CFML.

Model

BeatModel.cfc

<cfcomponent output="false">

  <cfset VARIABLES.bpm = 90>

  <cffunction returntype="BeatModel" name="init">
    <cfreturn this>
  </cffunction>

  <cffunction returntype="void" name="on">
    <cfset setBPM(90)>
  </cffunction>

  <cffunction returntype="void" name="off">
    <cfset setBPM(0)>
  </cffunction>

  <cffunction returntype="void" name="setBPM">
    <cfargument required="yes" type="numeric" name="bpm" />

    <cfset VARIABLES.bpm = ARGUMENTS.bpm>
  </cffunction>

  <cffunction returntype="numeric" name="getBPM">
    <cfreturn VARIABLES.bpm>
  </cffunction>
  
</cfcomponent>

View

DJView.cfm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>DJ View</title>
  </head>
 <body>
    <h1>DJ View</h1> 
    Beats per minute = <cfoutput>#APPLICATION.beatModel.getBPM()#</cfoutput>    
    <br />
    <hr />
    <br />    
    <form method="post" action="DJView.cfc">
      BPM: <input type="text" name="bpm" value="<cfoutput>#APPLICATION.beatModel.getBPM()#</cfoutput>" />
       
      <input type="submit" name="set" value="set" />
      <br />
      <input type="submit" name="decrease" value="<<" />
      <input type="submit" name="increase" value=">>" />
      <br />
      <input type="submit" name="on" value="on" />
      <input type="submit" name="off" value="off" />
    </form>
  </body>  
</html>

Controller

DJView.cfc

<cfcomponent output="false">

  <cfif NOT isDefined("FORM.bpm")>
    <cfset FORM.bpm = APPLICATION.beatModel.getBPM()>
  </cfif>
  
  <cfif isDefined("FORM.set")>
    <cfset APPLICATION.beatModel.setBPM(trim(FORM.bpm))>
  </cfif>
  
  <cfif isDefined("FORM.decrease")>
    <cfset APPLICATION.beatModel.setBPM(APPLICATION.beatModel.getBPM() - 1)>
  </cfif>
 
  <cfif isDefined("FORM.increase")>
    <cfset APPLICATION.beatModel.setBPM(APPLICATION.beatModel.getBPM() + 1)>
  </cfif>
 
  <cfif isDefined("FORM.on")>
    <cfset APPLICATION.beatModel.on()>
  </cfif>

  <cfif isDefined("FORM.off")>
    <cfset APPLICATION.beatModel.off()>
  </cfif>

  <cflocation url="DJView.cfm">

</cfcomponent>

Initialization

Application.cfc

<cfcomponent output="false">

  <cfset THIS.Name = "Head First MVC" />
   
  <cffunction access="public" returntype="void" name="onApplicationStart">
    <cfset APPLICATION.beatModel = createObject("component", "BeatModel").init()>
  </cffunction>
  
</cfcomponent>

Source Code

SQL NULL Rage

Just don’t allow nulls in your relational database tables, just don’t do it. No. No, not even then, no. No. NO.

Null, it doesn’t mean empty string, it doesn’t mean zero, it doesn’t mean missing relationship, it means undefined, it is a mark for missing data. Why would you want to store a mark indicating that data isn’t there instead of just not storing anything?

At what point does using null become overuse? When a couple of columns in a row contain nulls? When most of them contain nulls? When all of them contain nulls and foreign key columns contain nulls? Why don’t you just fill your entire database to capacity with nulls because you expect it to contain real data at some point in the future?

Yeah that's right, because that would be stupid, wouldn’t it?

E. F. Codd, the daddy of the relational model, suggests in his The Relational Model for Database Management Version 2 (go buy it here) that the null mark should be further refined into two marks, one for information that is applicable but absent (A-marks) and another for inapplicable information (I-marks).

He goes on to recommend that A-marks not be allowed in foreign key columns:

"I strongly recommend that database administrators or users consider very carefully the question of whether to permit or prohibit A-marks in foreign-key columns, and also that they document how and why that decision was made."

Codd then gives us two rules for all databases, the first, don’t allow either mark for a primary key and don’t allow I-marks for foreign keys. And the second rule, don’t have foreign keys point to stuff that’s not there:

"There are two integrity rules that apply to every relational database

  1. Type E, entity integrity. No component of a primary key is allowed to have a missing value of any type. No component of a foreign key is allowed to have an I-marked value (missing-and-inapplicable).
  2. Type R, referential integrity. For each distinct, unmarked foreign-key value in a relational database, there must exist in the database an equal value of a primary key from the same domain. If the foreign key is composite, those components that are themselves foreign keys and un-marked must exist in the database as components of at least one primary-key value drawn from the same domain."

This is all good for maintaining referential integrity, but for me, it doesn’t really address the issues. The quad-value logic seems to me to make the problem worse. How do I do arithmetic and aggregation on these two kinds of null mark? How would these two marks eventually manifest themselves in the code? Would I treat them differently? Why do I even care what kind of null it is, I just don’t want nulls to bite me on the arse later.

We should treat null marks as seriously in all columns as Codd proposes we treat them in relation defining columns. Why not keep partitioning the data until we get rid of the nulls? Normalizing to 5th and 6th normal form if we have to!

Much smarter people than me have thought about this and if you are at all bothered in relational database design then check out The Third Manifesto. Especially this PDF, Missing info without nulls.

From the Missing info without nulls abstract:

""The Third Manifesto", by C.J. Date and Hugh Darwen (3rd edition, Addison-Wesley, 2005), contains a categorical proscription against support for anything like SQL’s NULL, in its blueprint for relational database language design."

Sounds good to me.

Monday, 8 February 2010

Java, JDBC & SOAP on Windows Mobile 2003 Pocket PC

Symbol MC50

Check it out! The Symbol MC50 looks smart enough to divide by zero and tough enough to club a seal to death with! Here is how to program it!

This post is about getting Java running on Pocket PC, setting up an Apache Derby embedded database, and using kSOAP 2 to communicate with a web service.

ActiveSync

First off you're going to need to use ActiveSync to create a guest partnership between your Pocket PC and your development machine. If your running Windows XP, get ActiveSync v4.5 from here.

Java ME

Sun and Microsoft don't do a JVM for Pocket PC/Windows Mobile 2003, so a 3rd party JVM is the way to go. There are a few options but I'm having a punt on WebSphere Everyplace Micro Environment (WEME).

You can grab a trial version of WebSphere Everyplace Micro Environment Personal Profile 1.0 for Windows Mobile 2003 from here, or here

Run the EXE file contained in the downloaded WEME ZIP to install the JRE onto your local machine and onto the Pocket PC via ActiveSync.

Java ME JDBC

To use JDBC on the Pocket PC with WEME you will need The JDBC Optional Package for CDC-Based J2ME Applications. The source code is available for download here, or is available as a Maven build at the bottom of this page.

The JDBC optional package Maven build produces a 'jdbc-cdc-1.0.jar' JAR file. Copy the JAR to the Pocket PC JRE folder:

\Program Files\J9\PPRO10\lib\jclPPro10\ext

Web Service

Next knock out a quick SOAP web service for the Pocket PC to access. Below is a simple ColdFusion component which has a getStockPrice method that returns a price for a given stock name:

<cfcomponent namespace="http://www.example.org/stock">

  <cffunction access="remote" returnType="numeric" name="getStockPrice">
    <cfargument required="true" type="string" name="stockName" >
  
    <cfset var stockPrice = -1>
    
    <cfswitch expression="#Trim(ARGUMENTS.stockName)#">      
      <cfcase value="IBM">
        <cfset stockPrice = 123.91>
      </cfcase>

      <cfcase value="MSFT">
        <cfset stockPrice = 28.25>
      </cfcase>

      <cfcase value="ADBE">
        <cfset stockPrice = 32.74>
      </cfcase>

      <cfcase value="ORCL">
        <cfset stockPrice = 23.43>
      </cfcase>      
    </cfswitch>
  
    <cfreturn stockPrice>
  </cffunction>
  
</cfcomponent>

Java Application

The Java application to access the stock web service is built with Maven, and has the following POM file:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.adrianwalker.pocketpc</groupId>
  <artifactId>pocketpc-derby-ksoap2</artifactId>
  <packaging>jar</packaging>
  <version>0.1.0</version>
  <name>Pocket PC Derby kSOAP2</name>

  <description>
    Pocket PC Derby kSOAP2 example.
  </description>

  <repositories>
    <repository>
      <id>codehaus.org</id>
      <url>http://repository.codehaus.org</url>
    </repository>
    <!--
     ksoap2 isn't in any maven repoository, 
     so I'm distributing it with the project
    -->
    <repository>
      <id>project</id>
      <url>file://${basedir}/lib</url>
    </repository>
  </repositories>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.3</source>
          <target>1.3</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>fat</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>src/main/assembly/fat.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
          <execution>
            <id>distribution</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>src/main/assembly/distribution.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>

    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*</exclude>
        </excludes>
      </resource>
    </resources>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
      <version>10.2.2.0</version>
    </dependency>

    <!--
    Included in project lib directory
    -->
    <dependency>
      <groupId>org.ksoap2</groupId>
      <artifactId>ksoap2-j2me-core</artifactId>
      <version>2.1.2</version>
    </dependency>
    
    <!--
      To emulate javax.microedition classes for testing,
      NOT to be deployed with the application
    -->
    <dependency>
      <groupId>org.microemu</groupId>
      <artifactId>microemulator</artifactId>
      <version>2.0.4</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <configuration>
          <threshold>low</threshold>
          <effort>max</effort>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>

The build contains 2 Maven assembly descriptors. The first creates a fat jar which contains the project classes and all of required dependency classes. The second creates a directory distribution containing the fat jar and lnk file needed to run the application on the Pocket PC.

Pocket PC link files have a maximum command string length of 255 characters, listing seperate jars as java classpath arguments would exceed this length, hence the need for a single fat jar file.

I coudn't find kSOAP 2 in any maven repositories so I've included it with project source code in the /lib directory. In a real project you will probably want to install the jar into you local/company repository.

The microemulator dependency allows you to run the application from a desktop PC for testing, but is excluded from the distribution that will go on the Pocket PC.

The application itself is a simple AWT frame with a drop down list of stock names, a text field for the stock price and two buttons. The first button retrieves the stock price from the web service, and the second saves the value in the stock value field to the Derby database. When a stock name is selected, the application queries the database to see if it contains a row for that stock:

The main class, Stock.java, is an AWT frame which makes calls to a controller class.

Stock.java

package org.adrianwalker.pocketpc.stock;

import java.awt.event.WindowEvent;

public final class Stock extends java.awt.Frame {

  private static final String TITLE = "Pocket PC Example";
  private StockController stockController;

  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        Stock stock = new Stock();
        stock.setVisible(true);
      }
    });
  }

  public Stock() {
    setTitle(TITLE);

    initComponents();
    initListeners();

    stockNameChoice.add("IBM");
    stockNameChoice.add("MSFT");
    stockNameChoice.add("ADBE");
    stockNameChoice.add("ORCL");

    try {
      stockController = new StockController();
    } catch (Throwable t) {
      stockPriceField.setText("Error");
    }
  }

  // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    stockNameLabel = new java.awt.Label();
    stockNameChoice = new java.awt.Choice();
    stockPriceLabel = new java.awt.Label();
    stockPriceField = new java.awt.TextField();
    getStockPriceButton = new java.awt.Button();
    saveStockPriceButton = new java.awt.Button();

    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        exitForm(evt);
      }
    });
    setLayout(new java.awt.GridBagLayout());

    stockNameLabel.setText("Stock Name:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(stockNameLabel, gridBagConstraints);

    stockNameChoice.addItemListener(new java.awt.event.ItemListener() {
      public void itemStateChanged(java.awt.event.ItemEvent evt) {
        stockNameChoiceItemStateChanged(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(stockNameChoice, gridBagConstraints);

    stockPriceLabel.setText("Stock Value:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(stockPriceLabel, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(stockPriceField, gridBagConstraints);

    getStockPriceButton.setLabel("Get Stock Value");
    getStockPriceButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        getStockPriceButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(getStockPriceButton, gridBagConstraints);

    saveStockPriceButton.setLabel("Save Stock Value");
    saveStockPriceButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        saveStockPriceButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    add(saveStockPriceButton, gridBagConstraints);

    pack();
  }// </editor-fold>                        

    private void exitForm(java.awt.event.WindowEvent evt) {                          
      try {
        stockController.close();
      } catch (Throwable t) {
        // ignore shutdown error
      } finally {
        dispose();
        System.exit(0);
      }
    }                         

    private void stockNameChoiceItemStateChanged(java.awt.event.ItemEvent evt) {                                                 
      String name = stockNameChoice.getItem(stockNameChoice.getSelectedIndex());
      double price;
      try {
        price = stockController.getDatbaseStockPrice(name);
      } catch (Throwable t) {
        stockPriceField.setText("Error");
        return;
      }

      if (price == -1) {
        stockPriceField.setText("Unknown");
      } else {
        stockPriceField.setText(String.valueOf(price));
      }
    }                                                

    private void getStockPriceButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                    
      String name = stockNameChoice.getItem(stockNameChoice.getSelectedIndex());
      double price;
      try {
        price = stockController.getWebserviceStockPrice(name);
      } catch (Throwable t) {
        stockPriceField.setText("Error");
        return;
      }

      if (price == -1) {
        stockPriceField.setText("Unknown");
      } else {
        stockPriceField.setText(String.valueOf(price));
      }
    }                                                   

    private void saveStockPriceButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                     

      String name = stockNameChoice.getItem(stockNameChoice.getSelectedIndex());
      double price;
      try {
        price = Double.parseDouble(stockPriceField.getText());
        stockController.saveStock(name, price);
      } catch (Throwable t) {
        stockPriceField.setText("Error");
        return;
      }
    }                                                    

  // Variables declaration - do not modify                     
  private java.awt.Button getStockPriceButton;
  private java.awt.Button saveStockPriceButton;
  private java.awt.Choice stockNameChoice;
  private java.awt.Label stockNameLabel;
  private java.awt.TextField stockPriceField;
  private java.awt.Label stockPriceLabel;
  // End of variables declaration                   

  private void initListeners() {
    addWindowListener(new java.awt.event.WindowAdapter() {

      public void windowIconified(WindowEvent evt) {
        exitForm(evt);
      }
    });
  }
}

Two useful things to note about this code are:

  1. When you close a Java frame on the Pocket PC the program does not fire the window closing event, but instead is actually minimised. To exit the application you must listen for the window iconified event and use that to exit the application.
  2. You must call dispose() on the frame when exiting, otherwise the memory the application was using it not released, even when System.exit(0) is called.

StockController.java contains some Derby configuration settings and the web service end point URL which you will probaly want to change before deploying to the Pocket PC. The actual database and web service logic is delegated to 2 other classes, DatabaseController.java and WebServiceController.java.

StockController.java

package org.adrianwalker.pocketpc.stock;

import org.adrianwalker.pocketpc.stock.database.DatabaseController;
import org.adrianwalker.pocketpc.stock.webservice.WebServiceController;

public final class StockController {

  private static final String DATABASE_NAME = "\\StockDB";
  private static final String ENDPOINT = "http://localhost:8500/pocketpc-web-service/Stock.cfc";
  private static final String NAMESPACE = "http://www.example.org/stock";

  // default 1000, minimum 40
  private static final String PAGE_CACHE_SIZE = "40";
  // values: 4096 (default), 8192, 16384, or 32768
  private static final String PAGE_SIZE = "4096";
  private static final String ROW_LOCKING = "false";
  private final DatabaseController databaseController;
  private final WebServiceController webServiceController;

  public StockController() throws Exception {

    System.setProperty("derby.storage.pageCacheSize", PAGE_CACHE_SIZE);
    System.setProperty("derby.storage.pageSize", PAGE_SIZE);
    System.setProperty("derby.storage.rowLocking", ROW_LOCKING);

    databaseController = new DatabaseController(DATABASE_NAME);
    webServiceController = new WebServiceController(ENDPOINT, NAMESPACE);
  }

  public void close() throws Exception {
    try {
      webServiceController.close();
    } finally {
      try {
        databaseController.close();
      } catch (Exception e) {
        // ignore shutdown error
      }
    }
  }

  public double getWebserviceStockPrice(final String name) throws Exception {
    return webServiceController.getStockPrice(name);
  }

  public double getDatbaseStockPrice(final String name) throws Exception {
    return databaseController.readStockPrice(name);
  }

  public void saveStock(final String name, final double price) throws Exception {

    if (price < 0) {
      throw new IllegalArgumentException("Price must be positive");
    }

    if (databaseController.readStockPrice(name) == -1) {
      databaseController.createStock(name, price);
    } else {
      databaseController.updateStock(name, price);
    }
  }
}

WebServiceController.java

package org.adrianwalker.pocketpc.stock.webservice;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;

public final class WebServiceController {

  private static final String STOCK_PRICE_METHOD = "getStockPrice";
  private final String endpoint;
  private final String namespace;
  private final HttpTransport httpTransport;

  public WebServiceController(final String endpoint, final String namespace) {
    this.endpoint = endpoint;
    this.namespace = namespace;
    this.httpTransport = new HttpTransport(this.endpoint);
  }

  public double getStockPrice(final String stockName) throws Exception {
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
    SoapObject request = new SoapObject(this.namespace, STOCK_PRICE_METHOD);
    envelope.setOutputSoapObject(request);
    request.addProperty("stockName", new SoapPrimitive(this.namespace, "string", stockName));
    httpTransport.call("", envelope);
    SoapObject body = (SoapObject) envelope.bodyIn;

    SoapPrimitive stockPrice = (SoapPrimitive) body.getProperty("getStockPriceReturn");

    return Double.parseDouble(stockPrice.toString());
  }

  public void close() {
    httpTransport.reset();
  }
}

DatabaseController.java

package org.adrianwalker.pocketpc.stock.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.derby.jdbc.EmbeddedSimpleDataSource;

public final class DatabaseController {

  private static final String CREATE_DATABASE = "create";
  private static final String DATABASE_SHUTDOWN = "shutdown";
  private static final String CREATE_TABLE =
          "CREATE TABLE APP.STOCK ( " +
          "ID    BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY PRIMARY KEY," +
          "NAME  VARCHAR(10) NOT NULL UNIQUE," +
          "PRICE DOUBLE NOT NULL" +
          ")";
  private static final String INSERT_STOCK =
          "INSERT INTO APP.STOCK(NAME, PRICE) " +
          "VALUES(?,?)";
  private static final String SELECT_STOCK_PRICE =
          "SELECT PRICE " +
          "FROM APP.STOCK " +
          "WHERE NAME = ?";
  private static final String UPDATE_STOCK_PRICE =
          "UPDATE APP.STOCK " +
          "SET PRICE = ? " +
          "WHERE NAME = ?";
  private static final String DROP_TABLE =
          "DROP TABLE APP.STOCK";
  private EmbeddedSimpleDataSource dataSource;
  private Connection connection;
  private PreparedStatement insertStock;
  private PreparedStatement selectStockPrice;
  private PreparedStatement updateStockPrice;

  public DatabaseController(final String databaseName) throws SQLException {
    createDataSource(databaseName);
    createConnection();

    if (!tableExists()) {
      createTable();
    }

    createPreparedStatements();
  }

  private void createDataSource(final String databaseName) {
    this.dataSource = new EmbeddedSimpleDataSource();
    this.dataSource.setDatabaseName(databaseName);
    this.dataSource.setCreateDatabase(CREATE_DATABASE);
  }

  private void createConnection() throws SQLException {
    this.connection = dataSource.getConnection();
  }

  private void createPreparedStatements() throws SQLException {
    this.insertStock = connection.prepareStatement(INSERT_STOCK);
    this.selectStockPrice = connection.prepareStatement(SELECT_STOCK_PRICE);
    this.updateStockPrice = connection.prepareStatement(UPDATE_STOCK_PRICE);
  }

  private boolean tableExists() throws SQLException {
    ResultSet tables = connection.getMetaData().getTables(null, "APP", "STOCK", new String[]{"TABLE"});
    return tables.next();
  }

  public void createTable() throws SQLException {
    Statement statement = connection.createStatement();
    try {
      statement.execute(CREATE_TABLE);
    } catch (SQLException se) {
      se.printStackTrace();
    } finally {
      statement.close();
    }
  }

  public void dropTable() throws SQLException {
    Statement statement = connection.createStatement();
    try {
      statement.execute(DROP_TABLE);
    } catch (SQLException se) {
      se.printStackTrace();
    } finally {
      statement.close();
    }
  }

  public double readStockPrice(final String name) throws SQLException {
    this.selectStockPrice.setString(1, name);

    double price = -1;
    ResultSet resultSet = selectStockPrice.executeQuery();
    try {
      while (resultSet.next()) {
        price = resultSet.getDouble(1);
        return price;
      }
    } finally {
      resultSet.close();
    }

    return price;
  }

  public void createStock(final String name, final double price) throws SQLException {
    this.insertStock.setString(1, name);
    this.insertStock.setDouble(2, price);
    this.insertStock.execute();
  }

  public void updateStock(final String name, final double price) throws SQLException {
    this.updateStockPrice.setDouble(1, price);
    this.updateStockPrice.setString(2, name);
    this.updateStockPrice.execute();
  }

  public void close() throws SQLException {
    try {
      this.insertStock.close();
      this.selectStockPrice.close();
      this.updateStockPrice.close();
    } finally {
      try {
        this.connection.close();
      } finally {
        this.dataSource.setShutdownDatabase(DATABASE_SHUTDOWN);
        this.dataSource.getConnection();
      }
    }
  }
}

Build & Deploy

Build the project like an regular Maven build, 'mvn clean install', making sure your web service is available to pass all the unit tests.

The build should create a directory distribution in:

target\pocketpc-derby-ksoap2-0.1.0-distribution.dir

Copy the contents of this directory to the Pocket PC via ActiveSync to the directory:

\Program Files\Java\

Once the files have copied you can run the stock link file to run the app:

\Program Files\Java\pocketpc-derby-ksoap2-0.1.0\stock.lnk

Source Code

AJAX Reference 2

Another quick reference to achieve the same thing as this post but this time using <cfajaxproxy>.

time.cfm

<cfajaxproxy cfc="Time" jsclassname="Time">

<html>
  <head>
    <script src="js/time.js" type="text/javascript"></script>
  </head>
  <body>
    <form name="myForm">
      Name: <input id="username" type="text" onkeyup="getTime();" />
      Time: <input id="time" type="text" />
    </form>
  </body>
</html>

Time.cfc

<cfcomponent output="false">    
  <cffunction access="remote" name="getTime" returntype="string" returnformat="json">
    <cfreturn timeFormat(now())>
  </cffunction> 
</cfcomponent>

time.js

function getTime() {
  var time = new Time();
  time.setCallbackHandler(getTimeSuccess);
  time.setErrorHandler(getTimeError);
  return time.getTime();
}

function getTimeSuccess(result) {
 document.myForm.time.value = result;
}

function getTimeError(code, message) {
  alert(code + " - " + message);
}

Binding to display controls

Binding data returned from an ajax proxy to UI widgets is worth a mention:

data.cfm

<cfajaxproxy cfc="Data" jsclassname="Data">

<html>
  <head>
  </head>
  <body>
    <cfform>
      <cfgrid format="html"
              name="myGrid"
              pagesize=10
              sort=true
              bind="cfc:Data.getData({cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
              selectMode="row">

        <cfgridcolumn name="Id" display=true header="Id"/>
        <cfgridcolumn name="Description" display=true header="Description"/>
      </cfgrid>
    </cfform>
  </body>
</html>

Data.cfc

<cfcomponent output="false">

  <!---
  Create some mock data
  ---> 
  <cfset data = createData()>

  <cffunction name="createData" access="private" returntype="query">   
   <cfset var data = queryNew("Id, Description", "Integer, VarChar")>
   <cfset var i = 0>
   
   <cfset queryAddRow(data, 1000)>
    <cfloop index="i" from="1" to="1000">
      <cfset querySetCell(data, "Id", i, i)>
      <cfset querySetCell(data, "Description", "Item #i#", i)>
    </cfloop>
    
    <cfreturn data>  
  </cffunction>

  <cffunction name="getData" access="remote" returntype="struct" returnformat="json">
    <cfargument name="page">
    <cfargument name="pageSize">
    <cfargument name="gridSortColumn">
    <cfargument name="gridStartDirection">
    
    <cfset var qryData = ''>

    <!---
    Query data
    --->
    <cfquery name="qryData" dbtype="query">
      SELECT
        Id,
        Description
      FROM
        data

      <cfif ARGUMENTS.gridSortColumn NEQ "">
        ORDER BY
          #ARGUMENTS.gridSortColumn#
      </cfif>

      <cfif ARGUMENTS.gridStartDirection NEQ "">
        #ARGUMENTS.gridStartDirection#
      </cfif>
    </cfquery>

    <cfreturn queryConvertForGrid(qryData, ARGUMENTS.page, ARGUMENTS.pageSize)>
  </cffunction>
</cfcomponent>

Source Code