Sun GlassFish Mobility Platform 1.1 Developer's Guide for Client Applications

Chapter 2 Building a Client Application

A Sun GlassFish Mobility Platform client application typically includes the following:

This chapter describes the basics of building a Sun GlassFish Mobility Platform client application. It contains the following sections:

This chapter does not explain how to develop a MIDlet, because this process varies depending upon what development tools you use.

Overview of the Mobile Client Business Object API

The Mobile Client Business Object (MCBO) API consists of the following Java classes:

See Chapter 4, Classes and Methods in the Mobile Client Business Object API Package for summaries of the fields and methods in these classes. The API documentation is also included in the Sun GlassFish Mobility Platform client bundle. In the directory where you unzipped the client bundle (see the Sun GlassFish Mobility Platform 1.1 Installation Guide for details), it is in the directory sgmp-client-1_1_01-fcs-b02/doc/mcbo/api.

The MCBO API packages provide a simple interface on top of a set of more complex packages, the com.synchronica APIs. At times an application may find it useful to call some of these APIs.

This chapter uses the Secure MusicDB sample application provided with Sun GlassFish Mobility Platform to demonstrate how to use the MCBO API. The client in this application communicates with an Enterprise Connector deployed in the gateway, which in turn communicates with a database using the Java Database Connectivity (JDBC) API.

The source code for the Secure MusicDB sample application is included in the Sun GlassFish Mobility Platform client bundle. In the directory where you unzipped the client bundle, it is in the subdirectory sgmp-client-1_1_01-fcs-b02/samples/secure-musicdb/src/mcbo. Extract the contents of the file securemusicdb-sources.jar to view the sources.

Use of security features in a Sun GlassFish Mobility Platform application is recommended, but it is not required. If you implement security, you can provide your own implementation of com.sun.mep.client.api.SecurityManager to replace com.sun.mep.client.api.DefaultSecurityManager or com.sun.mep.client.api.AESSecurityManager.

The Sun GlassFish Mobility Platform client bundle includes the source code for an additional sample client, for the Salesforce application. This client is more complex than the MusicDB client, and the code is organized differently. You can find it in the subdirectory sgmp-client-1_1_01-fcs-b02/samples/salesforce-ws/src/mcbo. Extract the contents of the file salesforce_ws-sources.jar to view the sources.

The Secure MusicDB and Salesforce sample clients can each communicate with a connector that is implemented using either the JAX-RS API or the Enterprise Connector Business Object (ECBO) API. The MCBO API client code for the applications is the same for both.

Overview of the JerseyMe API

The JerseyMe API allows a client application to access RESTful web services using Java ME. It is modelled after Jersey's client API for Java SE. The minimum platform requirements are CLDC 1.1 and MIDP 2.0.

Sun GlassFish Mobility Platform applications can use JerseyMe to access resources on the web.

JerseyMe supports caching using the file system on the device. Caching can be used to avoid re-fetching the same resource over and over and also to support an offline mode, in which resources are retrieved only from the local cache, even if they are stale.

The JerseyMe API contains the following classes and interface:

See Chapter 5, JerseyMe API Documentation for summaries of the JerseyMe API methods. The API documentation is also included in the Sun GlassFish Mobility Platform client bundle. In the directory where you unzipped the client bundle (see the Sun GlassFish Mobility Platform 1.1 Installation Guide for details), it is in the directory sgmp-client-1_1_01-fcs-b02/doc/JerseyMe/api/doc.

The MusicDB and Salesforce sample clients make only minor use of the JerseyMe API, but other applications are likely to find it very useful.

Extending the BusinessObject Class

To create a client application using the MCBO API, you need to create your own class that extends the com.sun.mep.client.api.BusinessObject class.

Typically, you begin by importing the packages the class needs. In the Secure MusicDB sample code, the Album class, defined in the file Album.java, begins by importing the following packages:

import com.sun.mep.client.api.BusinessObject;
import com.synchronica.commons.date.DateStringParser;
import com.synchronica.commons.date.Iso8601Converter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

You must implement bean properties for your data model. The only required getter and setter methods are setName and getName, which specify and retrieve the name of the object, and getExtension, which returns the file extension for your object.

In addition, you must implement the serialize and deserialize methods.

The Album class extends the BusinessObject class:

public class Album extends BusinessObject {

The code first declares a string constant and the bean properties:

private static final String DEFAULT_VALUE = "$$default$$";

String albumName;
/**
 * Album's artist.
 */
String artist;
/**
 * Date in which the album was published.
 */
Date datePublished;
/**
 * Album's rating from 1 to 5.
 */
int rating;

The Album class has two constructor methods, a no-argument version and one that takes the name of the album as an argument:

public Album() {
    super();
}

public Album(String name) {
    super(name);
}

The Album class does not implement its own versions of getName and setName, instead inheriting the versions in BusinessObject. It implements getExtension by specifying the suffix .alb as the file extension for Album objects:

public String getExtension() {
    return ".alb";
}

In addition, the class implements getter and setter methods for the String property artist, the java.util.Date property datePublished, and the int property rating:

public String getArtist() {
    return artist;
}
public Date getDatePublished() {
    return datePublished;
}
public int getRating() {
    return rating;
}
public void setArtist(String artist) {
    this.artist = artist;
}
public void setDatePublished(Date datePublished) {
    this.datePublished = datePublished;
}
public void setRating(int rating) {
    this.rating = rating;
}

The Album class implements the serialize method by creating a java.io.DataOutputStream from a java.io.ByteArrayOutputStream, writing the album data to the java.io.DataOutputStream, then returning the java.io.ByteArrayOutputStream converted to a ByteArray.

public byte[] serialize() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DataOutputStream dOut = new DataOutputStream(out);

    dOut.writeUTF(getName());
    dOut.writeUTF(artist != null ? artist : DEFAULT_VALUE);
    dOut.writeUTF(
        datePublished != null ? getSimplifiedDate(datePublished) : DEFAULT_VALUE);
    dOut.writeUTF(Integer.toString(rating));
    dOut.flush();
    
    System.err.println("Serializing album:");
    System.err.println("    Name: "  + getName());
    System.err.println("  Artist: "  + artist != null ? artist : DEFAULT_VALUE);
    System.err.println("    Date: "  + 
        datePublished != null ? getSimplifiedDate(datePublished) : DEFAULT_VALUE);
    System.err.println("  Rating: "  + Integer.toString(rating));
    
    return out.toByteArray();
}

The class implements the deserialize method by creating a java.io.DataInputStream from a java.io.ByteArrayInputStream passed as an argument, then reading the album data from the java.io.DataInputStream. It uses some utility methods from the com.synchronica API to handle date information.

public void deserialize(byte[] array) throws IOException {
    ByteArrayInputStream in = new ByteArrayInputStream(array);
    DataInputStream dIn = new DataInputStream(in);

    albumName = dIn.readUTF();
    artist = dIn.readUTF();
    if (artist.equals(DEFAULT_VALUE)) {
        artist = null;
    }

    DateStringParser dateParser = new Iso8601Converter();
    String date = dIn.readUTF();
    Calendar c = dateParser.stringToCalendar(date, TimeZone.getDefault());
    datePublished = date.equals(DEFAULT_VALUE) ? null : c.getTime();
    
    rating = Integer.parseInt(dIn.readUTF());
}

The Album class also contains a utility method, getSimplifiedDate, that converts the java.util.Date value to a String.

Using the Mobile Client Business Object API in a Java ME Application

A client application on a mobile device consists primarily of a Java ME MIDlet. The MIDlet implements the Graphical User Interface (GUI) for the application and also calls Mobile Client Business Object (MCBO) API methods to synchronize the BusinessObject data.

This section describes how to use the MCBO API in a MIDlet. It assumes that you are already familiar with the Java ME API. It does not describe how to create a Graphical User Interface (GUI) to display business objects and allow users to create or modify them. A good tool for creating a MIDlet is the NetBeans IDE with the Mobility Pack; for details, visit the NetBeans web site.

In the Secure MusicDB sample code, the SecureJdbcMIDlet.java file contains Java ME code and MCBO API code. The Java ME code creates the user interface that allows users to create, edit, and delete business objects. The MCBO API code stores and retrieves business object data on the client device and synchronizes client-side modifications with the data on the back end.

Typically, a MIDlet begins by importing the MCBO API and JerseyMe packages in addition to the Java ME packages:

import com.sun.mep.client.api.*;
import com.sun.jerseyme.api.client.Client;
import com.sun.jerseyme.api.client.WebResource;

A MIDlet uses the API to perform the following tasks:

Creating DefaultSecurityManager, SyncManager, and BusinessObjectStorage Objects

The first task for the Sun GlassFish Mobility Platform client code is to create the objects needed for synchronization and data manipulation:

You may also want to enable logging for debugging purposes by calling the SyncManager.enableLogging method. If logging is enabled, logging messages for the client code are written both to standard output and to a file on the device named meplog.txt.

You commonly perform these operations within a thread, as follows:

Thread t = new Thread(new Runnable() {
    public void run() {
        securityMgr = new DefaultSecurityManager("musicdb");
        securityMgr.setMaxValidationAttempts(3);
        syncMgr = new SyncManager(".alb", securityMgr);
        syncMgr.enableLogging(true);
        boStorage = syncMgr.getBusinessObjectStorage();
    }
});
t.run();

This code first instantiates a security manager and sets the maximum allowed number of validation attempts. If this maximum is exceeded, all Sun GlassFish Mobility Platform records on the device are erased. See Data Destruction for details.

The code then uses the form of the SyncManager constructor that takes two arguments, the file extension used for the business object and the security manager. In this case, the extension is the string ".alb", as specified by the getExtension method of the Album class. The code also turns on logging.

Once you enable security by specifying an implementation of SecurityManager in the SyncManager constructor, all of the data stored locally on the device will be encrypted and decrypted automatically. There are no further requirements on the client application to explicitly perform encryption or decryption of the data.

The code then calls the SyncManager.getBusinessObjectStorage factory method to instantiate the BusinessObjectStorage object. This object provides storage for Album objects on the mobile device's file system.

Establishing Login Credentials

To provide application-level authentication, a secure client application must use the security manager to create login credentials for the user. The MIDlet code provides an initial login screen that requires the user to create both a secret and a Personal Identification Number (PIN). Users do not need to remember the secret, but they must remember the PIN.

The MIDlet code calls the security manager's computeKey and setKey methods to create a key from the PIN entered by the user. It then calls the security manager's storeCredentials method to create credentials based on the secret.

byte[] key = securityMgr.computeKey(getInitialPinField().getString());
securityMgr.setKey(key);
securityMgr.storeCredentials(getSecretField().getString());

The getInitialPinField and getSecretField methods are UI methods that obtain the needed string values.

The secret and PIN provide security in addition to the username and password credentials required by the gateway in order to perform synchronization (as described in Setting User Credentials).

Working with Business Objects on the File System

The MIDlet code typically allows users to create new objects and to edit or delete existing objects in disconnected mode, using the mobile device's file system without being connected to a server. The code commonly uses a combination of BusinessObject and BusinessObjectStorage methods to perform the following tasks:

Typically, a user on a client device performs a number of operations on the client device in disconnected mode, then logs in to the server and synchronizes the data.

Retrieving Objects for Editing

To allow users to view existing objects, the code commonly displays a list of names returned by the BusinessObjectStorage.listBusinessObjectNames method. This method retrieves a list of the names of all the business objects that have the file extension specified by the SyncManager constructor method. For example, the SecureJdbcMIDlet code calls the following method before populating a form with a list of albums:

Vector v = boStorage.listBusinessObjectNames();

To display a selected album, the SecureJdbcMIDlet code instantiates an Album object, using a name argument that represents the filename stripped of its ".alb" extension. The code then calls the BusinessObjectStorage.readBusinessObject method to read the data for the selected album from the file system into the Album object.

Album a = new Album(selectedAlbum.substring(0, selectedAlbum.length()-4));
boStorage.readBusinessObject(a);

The SecureJdbcMIDlet code then calls the getter methods for Album objects to retrieve the selected album's property values and display them in a form for editing.

Deleting Objects

To allow users to delete a selected album, the SecureJdbcMIDlet code calls the BusinessObjectStorage.deleteBusinessObject method with a String argument, the name of the album:

boStorage.deleteBusinessObject(selectedAlbum);

Saving Objects

To save a newly created or edited album, the SecureJdbcMIDlet code calls its saveAlbum method. This method instantiates an Album object and then calls the methods that set the album's properties, using Java ME GUI code to retrieve the values. Finally, the saveAlbum method calls the BusinessObjectStorage.writeBusinessObject method to save the album to the file system:

Album a = new Album();
...
boStorage.writeBusinessObject(a);

Synchronizing Data with the Server

Once users have created or modified objects on the client using BusinessObjectStorage methods, they can use SyncManager methods to synchronize the modified data with the server. Synchronization includes the following tasks:

Setting User Credentials

The gateway requires username/password authentication for secure access. Before performing a synchronization, the MIDlet must call the SyncManager.setCredentials method, which takes three arguments: the username, the password, and the HTTP/S URL of the gateway. In SecureJdbcMIDlet.java, the arguments are supplied by three GUI methods, as follows:

syncMgr.setCredentials(
        getUserName().getString(),
        getPassword().getString(),
        getSyncServer().getString());

These methods obtain input from the user and return TextField values.

The initial creation of users is a Sun GlassFish Mobility Platform administrative task, described in the Sun GlassFish Mobility Platform 1.1 Administration Guide

Performing Synchronization

Once user credentials are established, synchronization can take place. The SecureJdbcMIDlet code calls the SyncManager.sync method, which takes a SyncType argument. In this case, the code calls a method that returns a SyncType value:

syncMgr.sync(getSelectedSyncType());

The getSelectedSyncType method in turn uses the value returned by a GUI method, getSyncType.

Retrieving Synchronization Results

After a successful synchronization, you can retrieve and display information about the synchronization results. The SecureJdbcMIDlet code retrieves the results using the SyncManager.getSyncResults method, which returns a SyncResults value:

SyncResults results = syncMgr.getSyncResults();

It then displays the results in a GUI form by calling SyncResults methods. These methods can return either the number of items changed or a list of the actual business objects that were changed. The SecureJdbcMIDlet code displays only the number of items changed.

Developing Client Applications for the BlackBerry Using NetBeans IDE

This guide cannot describe how to develop client applications for every possible device using every possible development tool. This section, however, describes how to develop a client application for one of the most commonly used devices, the BlackBerry, using one of the most commonly used development tools, NetBeans IDE. It contains the following sections:

Prerequisites

Before you can develop a client application for the Blackberry using NetBeans IDE, you must install the following software on a Microsoft Windows system:


Note –

You must have a BlackBerry Developer Community account in order to download the BlackBerry software. If you do not have an account, follow the instructions on the website to obtain one.


ProcedureTo Configure BlackBerry JDE v4.2.1

  1. Click Start->All Programs->Research In Motion->BlackBerry JDE 4.2.1->JDE.

  2. Click Edit->Preferences.

  3. Click the Simulator tab and perform these steps:

    1. Select the 8800-JDE Profile from the pull-down menu.

    2. Select the Launch simulator checkbox.

    3. Select the Launch Mobile Data Service (MDS) with Simulator checkbox.

  4. Click the MDS Simulator Tab. Make sure that the MDS Simulator directory location is pointing to the v4.1.4 MDS directory you installed. For example:

    C:\Program Files\Research In Motion\BlackBerry Email and MDS Services Simulators 4.1.4\MDS
  5. Click OK.

    You can leave the JDE running, because you may need it later on.

ProcedureTo Configure NetBeans IDE for BlackBerry Application Development

  1. Start a text editor and copy the following text into an empty file.


    Note –

    If you installed BlackBerry JDE in a non-default location (for example, not on the C:\ drive), edit the contents of the home property setting for the platform element.

    Make sure that the contents of the preverifycmd property setting for the platform element all appear on one line of the file. The contents are broken up here for readability only.


    <?xml version='1.0'?>
    <!DOCTYPE platform PUBLIC '-//NetBeans//DTD J2ME PlatformDefinition 1.0//EN' 
              'http://www.netbeans.org/dtds/j2me-platformdefinition-1_0.dtd'>
    <platform name="BlackBerry_JDE_421" 
              home="C:\Program Files\Research In Motion\BlackBerry JDE 4.2.1" 
              type="CUSTOM" 
              displayname="BlackBerry JDE 421" 
              srcpath="" 
              docpath="${platform.home}/docs/api," 
              preverifycmd="&quot;{platformhome}{/}bin{/}preverify&quot; 
                            {classpath|-classpath &quot;{classpath}&quot;} 
                            -d &quot;{destdir}&quot; &quot;{srcdir}&quot;" 
              runcmd="cmd /C &quot;cd /D {platformhome}{/}simulator&amp;{device}&quot;" 
              debugcmd="cmd /C &quot;cd /D {platformhome}{/}bin&amp;jdwp&quot;">
        <device name="8800" description="8800">
            <optional name="JSR75" version="1.0" 
                      displayname="File Connection and PIM Optional Packages" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <optional name="MMAPI" version="1.0" 
                      displayname="Mobile Media API" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <configuration name="CLDC" version="1.1" 
                           displayname="Connected Limited Device Configuration" 
                           classpath="${platform.home}/lib/net_rim_api.jar" 
                           dependencies="" default="true"/>
            <optional name="OBEX" version="1.0" 
                      displayname="Object Exchange APIs" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <optional name="JSR82" version="1.0" 
                      displayname="Java APIs for Bluetooth Wireless Technology" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <optional name="WMA" version="1.1" 
                      displayname="Wireless Messaging API" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <optional name="JSR179" version="1.0" 
                      displayname="Location Based APIs" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <optional name="JSR177" version="1.0" 
                      displayname="Security and Trust Services APIs" 
                      classpath="${platform.home}/lib/net_rim_api.jar" 
                      dependencies="" default="true"/>
            <profile name="MIDP" version="2.0" 
                     displayname="Mobile Information Device Profile" 
                     classpath="${platform.home}/lib/net_rim_api.jar" 
                     dependencies="" default="true"/>
        </device>
    </platform>
  2. Save the file, giving it the name BlackBerry_JDE_421.xml.

  3. Copy the file to the following location in your home directory under C:\Documents and Settings:

    .netbeans\6.5\config\Services\Platforms\org-netbeans-api-java-Platform
  4. If NetBeans IDE is running, stop it.

    You will be prompted to start (or restart) NetBeans IDE in the next task, To Import the SecureMusicDB Sources into NetBeans IDE as a BlackBerry Project.

Next Steps

After you start NetBeans IDE, The Blackberry JDE will appear in the list of platforms when you choose Java Platforms from the Tools menu.

ProcedureTo Import the SecureMusicDB Sources into NetBeans IDE as a BlackBerry Project

To build and run a SecureMusicDB project for the BlackBerry from sources in NetBeans IDE, follow these steps.

  1. To obtain the Sun GlassFish Mobility Platform client library bundle, go to the following URL: http://www.sun.com/software/products/mep/get.jsp.

  2. Click Download, provide the requested information, then click Log In and Continue.

  3. Download the sgmp-client-1_1_01-fcs-b02.zip bundle.

  4. Unzip the bundle in a location of your choosing (for example, under C:\).

  5. Unzip the source files for the SecureMusicDB project.

    1. Navigate to the directory C:\sgmp-client-1_1_01-fcs-b02\samples\secure-musicdb\src\mcbo.

    2. Extract the files from the securemusicdb-sources.jar file to the C:\sgmp-client-1_1_01-fcs-b02\samples\secure-musicdb\src\mcbo directory.

      You could use WinZip or the jar xvf command, for example, to extract the files.

    3. Remove the META-INF directory and its contents (the file MANIFEST.MF).

  6. Start NetBeans IDE.

    The first time you start NetBeans IDE, you are prompted to install some updates. Install them.

  7. In NetBeans IDE, follow these steps to create a Java ME Project and import the secure-musicdb sources.

    1. From the File menu, select New Project.

      The Choose Project screen appears.

    2. Click Java ME, then click Mobile Project with Existing MIDP Sources.

    3. Click Next.

      The Specify MIDP Sources Screen appears.

    4. In the Sources Location field, specify the location of the secure-musicdb sources you extracted. For example, if you unzipped the bundle to the C:\ directory, specify the following:

      C:\sgmp-client-1_1_01-fcs-b02\samples\secure-musicdb\src\mcbo

      Leave the JAD/Manifest Location field empty.

    5. Click Next.

      The Name and Location Screen appears.

    6. Type a name for the Project or keep the default name.

    7. Click Next.

      The Default Platform Selection Screen appears.

    8. Set the Emulator Platform to “BlackBerry JDE 421” and verify that the Device is 8800.

    9. Click Finish.

      The project appears in the Projects pane.

  8. To specify the MIDlet and icon to be used, follow these steps.

    1. Right-click the project and select Properties.

    2. Click the Application Descriptor node.

    3. Click the MIDlets tab.

    4. If the SecureJdbcMIDlet appears, click Edit. If it does not, click Add.

      In the Add MIDlet dialog, the MIDlet name and class, SecureJdbcMIDlet and sample.SecureJdbcMIDlet, are already filled in.

    5. For the MIDlet Icon, select /Clear_Note_32.png from the menu (it is the only choice). If no menu appears, type the value in the field.

    6. Click OK, then click OK in the properties dialog.

  9. To add the files mep_client_api.jar and jerseyme_api.jar to the supported Libraries & Resources, follow these steps.

    1. Right-click the project and select Properties.

    2. Click Libraries & Resources under Build.

    3. Click Add Jar/Zip.

    4. Browse to the lib\BlackBerry directory to add mep_client_api.jar.

      For example, if you unzipped the bundle to the C:\ directory, the file name would be C:\sgmp-client-1_1_01-fcs-b02\lib\BlackBerry\mep_client_api.jar.

    5. From the same location, add jerseyme_api.jar.

    6. Click OK.

    7. Click the Files tab (next to the Projects tab) and open the project.properties file under the nbproject directory.

    8. Edit the file.reference.mep_client_api.jar property to contain the fully qualified path name of the mep_client_api.jar file.

      For a BlackBerry project, the pathname must be absolute, not relative.

      For example, if you unzipped the bundle to the C:\ directory, edit the property definition to look like this:

      file.reference.mep_client_api.jar=C:/sgmp-client-1_1_01-fcs-b02/lib/BlackBerry/mep_client_api.jar

      Use forward slashes (/) instead of the usual Windows file separator.

    9. Edit the file.reference.jerseyme_api.jar property to contain the fully qualified path name of the jerseyme_api.jar file.

      For example, if you unzipped the bundle to the C:\ directory, edit the property definition to look like this:

      file.reference.jerseyme_api.jar=C:/sgmp-client-1_1_01-fcs-b02/lib/BlackBerry/jerseyme_api.jar
    10. Edit the file.reference.src-mcbo property to contain the fully qualified path name of the project sources.

      For example, if you unzipped the bundle to the C:\ directory, edit the property definition to look like this:

      file.reference.src-mcbo=C:/sgmp-client-1_1_01-fcs-b02/samples/secure-musicdb/src/mcbo
  10. Click the Files tab and open the project's build.xml file.

  11. Add the following code fragment immediately before the </project> tag at the end of the file:

        <target name="do-preprocess">
            <fail unless="libs.ant-contrib.classpath">
         Classpath to Ant Contrib library (libs.ant-contrib.classpath property) is not set.
            </fail>
            <taskdef resource="net/sf/antcontrib/antlib.xml">
                <classpath>
                    <pathelement path="${libs.ant-contrib.classpath}"/>
                </classpath>
            </taskdef>
            <available file="${platform.home}/bin/rapc.exe" property="do.rapc"/>
            <if>
                <isset property="do.rapc"/>
                <then>
                    <property name="jpda.port" value="8000"/>
                    <path id="antlib.classpath">
                        <fileset dir="${user.dir}/mobility8/modules/ext/" 
                                 includes="ant-contrib-1.0b3.jar"/>
                    </path>
                    <mkdir dir="${dist.dir}"/>
                    <path id="src-files">
                        <fileset dir="${src.dir}" includes="**/*.*"/>
                    </path>
                    <property name="srcs" value="${toString:src-files}"/>
                    <for list="${srcs}" param="file" delimiter=";" trim="true">
                        <sequential>
                            <echo message="@{file}${line.separator}" 
                                  file="${src.dir}/${name}_build.files" append="true"/>
                        </sequential>
                    </for>
                    <touch file="${dist.dir}/${dist.jar}"/>
                    <nb-overrideproperty name="buildsystem.baton" 
                                         value="${preprocessed.dir}"/>
                </then>
                <else>
                    <nb-overrideproperty name="buildsystem.baton" value="${src.dir}"/>
                    <antcall target="${name}-impl.do-preprocess"/>
                </else>
            </if>
        </target>
        <target name="do-compile">
            <if>
                <isset property="do.rapc"/>
                <then>
                    <antcall target="create-jad"/>
                    <antcall target="update-jad"/>
                    <copy file="${dist.dir}/${dist.jad}" toDir="${src.dir}"/>
                    <exec dir="${src.dir}" 
                          executable="${platform.home}/bin/rapc.exe" failonerror="true">
                        <arg value="-quiet"/>
                        <arg value="import=${platform.bootclasspath};${libs.classpath}"/>
                        <arg value="codename=${name}"/>
                        <arg value="-midlet"/>
                        <arg value="jad=${dist.jad}"/>
                        <arg value="@${name}_build.files"/>
                    </exec>
                    <delete file="${basedir}/${src.dir}/${name}_build.files"/>
                    <copy file="${name}.alx" todir="${dist.dir}"/>
                    <nb-overrideproperty name="buildsystem.baton" 
                                         value="${build.classes.dir}"/>
                </then>
                <else>
                    <nb-overrideproperty name="buildsystem.baton" 
                                         value="${preprocessed.dir}"/>
                    <antcall target="${name}-impl.do-compile"/>
                </else>
            </if>
        </target>
        <target name="pre-obfuscate">
            <nb-overrideproperty name="buildsystem.baton" value="${build.classes.dir}"/>
        </target>
        <target name="post-jar" if="do.rapc">
            <move todir="${dist.dir}">
                <fileset dir="${src.dir}">
                    <include name="**/${name}*.*"/>
                </fileset>
            </move>
            <copy todir="${platform.home}/simulator" verbose="true">
                <fileset dir="${dist.dir}">
                    <include name="**/${name}*.*"/>
                </fileset>
            </copy>
        </target>
        <target name="post-clean">
            <delete failonerror="false" includeemptydirs="true">
                <fileset dir="${platform.home}/simulator">
                    <include name="**/${name}*.*"/>
                </fileset>
                <fileset dir="${dist.dir}">
                    <include name="**/*.*"/>
                </fileset>
                <fileset dir="${src.dir}">
                    <include name="**/${name}*.*"/>
                </fileset>
            </delete>
        </target>
  12. Create an .alx file for this project.

    1. Click the Files tab.

    2. Right-click your project and select New->Other.

    3. In the Choose File Type screen, click Other, then click Empty File.

    4. Click Next.

    5. In the Name and Location screen, give the file the same name as your project, with the extension .alx.

      For example, if bb-secure-musicdb is the project name, name the file bb-secure-musicdb.alx.

    6. Click Finish.

      The empty file opens.

    7. Copy and paste the following text into the file, replacing myProject with your project name, and including any vendor and copyright information needed for your application.

      <loader version="1.0">
          <application id="myProject">
              <name>
                  myProject
              </name>
              <description/>
              <version>
                  1.0
              </version>
              <vendor>
              </vendor>
              <copyright>
              </copyright>
              <fileset Java="1.3">
                  <directory/>
                  <files>
                      myProject.cod
                  </files>
              </fileset>
              <application id="mep_client_api">
                  <name/>
                  <description/>
                  <version>
                      1.0
                  </version>
                  <vendor>
                      Sun Microsystems Inc.
                  </vendor>
                  <copyright>
                      Copyright (c) 2009 Sun Microsystems Inc.
                  </copyright>
                  <fileset Java="1.3">
                      <directory/>
                      <files>
                          mep_client_api.cod
                      </files>
                      <files>
                          jerseyme_api.cod
                      </files>
                  </fileset>
              </application>
          </application>
      </loader>
    8. Save and close the file.

  13. Copy the files mep_client_api.cod and jerseyme_api.cod from the directory C:\sgmp-client-1_1_01-fcs-b02\lib\BlackBerry to the simulator directory of the BlackBerry JDE (for example, C:\Program Files\Research In Motion\BlackBerry JDE 4.2.1\simulator).

  14. Click the Projects tab, then right-click your secure-musicdb project and select Clean & Build.

    If a message that begins error while reading original manifest appears, you can ignore it.

  15. Right-click your secure-musicdb project and select Run.

    The BlackBerry Device Simulator appears.


    Note –

    When you select Run, NetBeans IDE automatically loads the application on the Simulator using the .jad and .jar files (not the .cod file). If you want to load the application from the .cod file created, use the File->Load Java Program option in the Simulator.


  16. Launch the SecureJdbcMIDlet application and perform a Sync.

    The icon for the application is a musical note.


    Note –

    The MDS must be running for the client to perform syncs. If you started the JDE, MDS should get launched automatically. Otherwise, start MDS manually as follows: From the Windows Start menu, choose All Programs->Research in Motion->BlackBerry Email and MDS Services Simulators 4.1.4->MDS.


Next Steps

To remove the application from the Simulator, delete the .jad, .jar, and .cod files from the Simulator directory within the JDE and execute the three erase options in the JDE under File->Erase Simulator File.

ProcedureTo Create a New BlackBerry Project to Use the MCBO API

To create a new NetBeans IDE project that uses the MCBO API, follow these steps.

  1. In NetBeans IDE, choose New Project from the File menu.

  2. Choose Project Screen.

  3. Click Java ME->MIDP Application.

  4. Click Next.

  5. In the Name and Location screen:

    1. Type a name for the project or keep the default name.

    2. Select Set as Main Project.

    3. Select Create Hello MIDlet.

    4. Click Next.

  6. In the Default Platform Selection Screen:

    1. Specify BlackBerryJDE421 as the Emulator Platform.

    2. Specify 8800 as the Device.

    3. Click Finish.

  7. Add the mep_client_api.jar and jerseyme_api.jar files to your Libraries & Resources for this project in order to call and have access to the MCBO API.

    1. If you have not done so before, go to http://www.sun.com/software/products/mep/get.jsp and download the sgmp-client-1_1_01-fcs-b02.zip bundle.

    2. Unzip the sgmp-client-1_1_01-fcs-b02.zip bundle (for example, under C:\).

    3. In NetBeans IDE, right-click the project and select Properties.

    4. Click Libraries & Resources.

    5. Click Add Jar/Zip.

    6. Browse to the location of the unzipped bundle above the lib directory to add mep_client_api.jar.

      For example, if you unzipped the bundle to the C:\ directory, the file name would be C:\sgmp-client-1_1_01-fcs-b02\lib\BlackBerry\mep_client_api.jar.

    7. From the same location, add jerseyme_api.jar.

    8. Click OK.

    9. Click the Files Tab (next to the Projects tab) and open the project.properties file under the nbproject directory.

    10. Edit the file.reference.mep_client_api.jar property to contain the fully qualified path name of the mep_client_api.jar file.

      For a BlackBerry project, the pathname must be absolute, not relative.

      For example, if you unzipped the bundle to the C:\ directory, edit the property setting to look like this:

      file.reference.mep_client_api.jar=C:/sgmp-client-1_1_01-fcs-b02/lib/BlackBerry/mep_client_api.jar

      Use forward slashes (/) instead of the usual Windows file separator.

    11. Edit the file.reference.jerseyme_api.jar property to contain the fully qualified path name of the jerseyme_api.jar file.

      For example, if you unzipped the bundle to the C:\ directory, edit the property setting to look like this:

      file.reference.jerseyme_api.jar=C:/sgmp-client-1_1_01-fcs-b02/lib/BlackBerry/jerseyme_api.jar
    12. Click the Files Tab and open the project's build.xml file. Immediately before the </project>tag at the end of the file, add the same code fragment you added in Step 11 of To Import the SecureMusicDB Sources into NetBeans IDE as a BlackBerry Project.

  8. Create an .alx file for this project:

    1. Click the Files tab.

    2. Right-click your project and select New->Other.

    3. In the Choose File Type screen, click Other, then click Empty File.

    4. Click Next.

    5. Give the file the same name as your project name, with the .alx extension.

    6. Click Finish.

    7. Copy and paste into the file the content from Step g under Step 12 of To Import the SecureMusicDB Sources into NetBeans IDE as a BlackBerry Project, replacing myProject with your project name.

    8. Save and close the file.

  9. Copy the files mep_client_api.cod and jerseyme_api.cod from the directory C:\sgmp-client-1_1_01-fcs-b02\lib\BlackBerry to the simulator directory of the BlackBerry JDE (for example, C:\Program Files\Research In Motion\BlackBerry JDE 4.2.1\simulator).

  10. Click the Projects tab, then right-click your project and select Clean & Build.

  11. Right-click your project and select Run.

    The BlackBerry Device Simulator appears.


    Note –

    When you select Run, NetBeans IDE automatically loads the application on the Simulator using the .jad and .jar files (not the .cod file). To load the application from the .cod file created, use the Load Java Program option in the Simulator.


  12. Launch the MIDlet application.

Next Steps

At this point, you have a boilerplate application that says Hello World. You can now add code to implement and call the MCBO API classes and methods, and you can edit the MIDlet code to provide a user interface and to perform synchronizations.