Getting started with OCAP, Part 2: Writing applications for the OCAP RI

Cross-compiling Java code

Get a taste of what's possible with the OpenCable Application Platform in this article, the second in a three-part series. Author Jonathan Knudsen demonstrates how to create applications, called Xlets, for OCAP devices and run them on a desktop computer using the OCAP RI.

Jonathan Knudsen, Developer and Writer

Photo of Jonathan KnudsenJonathan Knudsen is the author of several books and more than a hundred articles about Java technology and mobile robots. He is the husband of the most glorious woman to walk the Earth, the father of four amazing children, a decent piano player, and the scourge of many Bonsai trees. When Jonathan grows up, he wants to be a cowboy. For more information, see http://jonathanknudsen.com/.



05 April 2010 (First published 09 March 2010)

Also available in Chinese Japanese

18 Mar 2010: By author request, changed all instances of hostapps.properties to hostapp.properties.

Part 1 of this series introduced you to the OpenCable Application Platform (OCAP) — a platform for interactive cable TV applications — and the OCAP Reference Implementation (RI). You learned that OCAP's structure is based on three specifications that are part of standard Java ME technology:

  • The Connected Device Configuration (CDC) describes a JVM and a set of fundamental APIs.
  • The Foundation Profile (FP) provides additional APIs.
  • The Personal Basis Profile (PBP) specifies graphics functionality.

In terms of Java, Standard Edition (Java SE), the CDC/FP/PBP stack is more or less equivalent to the Java Development Kit (JDK) 1.4.2. Don't take this too literally, though — it's just an approximation to help you understand the CDC/FP/PBP stack.

In Part 1, you ran a couple of the demo applications that are bundled with the RI. In this article, you'll learn how to create applications of your own that you can run on the RI and on other OCAP devices. You'll start at the command line and progress to using the OCAP plug-in for Eclipse.

Cross-compiling

In general terms, building OCAP applications is an example of cross-compiling, which simply means that you build on one platform with the intention of running on another. The concept of cross-compiling is easy to understand with respect to small platforms such as mobile phones. You don't build a mobile phone application on the phone itself. Typically, you use a desktop computer (the host) to create an application that will run on the mobile phone (the target). Similarly, you can use a Java SE development environment on a desktop computer to build an application that runs on the OCAP platform.

Here is where things get a little tricky. The OCAP RI you downloaded in Part 1 also runs on your desktop computer, but it's really a simulator. The OCAP RI makes your computer pretend to be a set-top box.

Regardless, if you build an OCAP application, it should run on any OCAP platform, either a real set-top box or a simulator like the OCAP RI.


Building character at the command line

Parents usually tell their kids that anything unpleasant is good for building character. Keep that in mind as you work your way through building an OCAP application using command-line tools. You will certainly learn a lot about exactly how the process works. Even if you choose to use Eclipse to build OCAP applications (we'll learn this later in the article), working through the steps at the command line will give you a deep understanding of what Eclipse handles for you.

Build structure of the OCAP implementation

A note on terminology

The OCAP code itself can be built for a large variety of platforms, including real devices. In addition, you can build the OCAP code so that it runs on the RI platform, which is a layer that simulates an OCAP device on a Windows or Linux desktop computer. The OCAP implementation plus the RI platform is the OCAP RI.

Although you haven't yet downloaded the full source of the OCAP RI, the binary OCAP RI you installed in Part 1 has a similar directory structure. Knowing this structure will help you locate important files and directories.

One important location is OCAPROOT, which is the root of the OCAP implementation source code. It is the root of a fairly complex tree that can support building on different hosts for multiple targets. For example, you could build the OCAP implementation on a Linux computer for a specific kind of set-top box. Alternately, you might build on Windows for the OCAP RI platform.

The actual value of OCAPROOT depends on where you installed the OCAP RI binaries. If you used the default installation location, the value is /CableLabs/tru2way/ocap-ri/ocap. (Although Windows traditionally uses a backslash as a path separator, I will use forward slashes in this article for consistency.)

When you build the OCAP implementation, the results go into the ${OCAPROOT}/bin directory. Specifically, they are placed in a subdirectory whose name reflects the target platform. The target platform is represented by OCAPTC. The results of the build go in ${OCAPROOT}/bin/${OCAPTC}.

For example, when you build the Windows OCAP stack, OCAPTC is CableLabs/simulator/Win32/debug.

Finding what you need in the OCAP build

A successful build of the OCAP implementation produces Java class files as well as native libraries. For the purposes of building OCAP applications, all you really need to care about are the class files that define the platform.

The OCAP Java platform is packaged in two JAR files:

  • ${OCAPROOT}/bin/${OCAPTC}/env/cvm/lib/basis.jar is the CDC/FP/PBP stack.
  • ${OCAPROOT}/bin/${OCAPTC}/env/sys/ocap-classes.jar contains all the Java classes of the OCAP implementation.

A few lines of code

Before you can use the JAR files to create an OCAP application, you need some source code to build. Save the code in Listing 1 as src/HelloOcap.java (or download it):

Listing 1. Some source code to build
import javax.tv.xlet.Xlet; 
import javax.tv.xlet.XletContext; 
import javax.tv.xlet.XletStateChangeException;

import org.havi.ui.HScene; 
import org.havi.ui.HSceneFactory;

import java.awt.*;
import java.awt.event.*;

import java.util.Vector;
import java.util.Random;

public class HelloOCAP implements Xlet {
  private HScene mScene;
  private HelloOCAPUI mContent;
  
  public void initXlet(XletContext ctx) throws XletStateChangeException {
    System.out.println("HelloOCAP initXlet");
    HSceneFactory factory = HSceneFactory.getInstance();
    mScene = factory.getDefaultHScene();
    
    mContent = new HelloOCAPUI();
    mContent.setVisible(true);
    
    mScene.setLayout(new BorderLayout());
    mScene.add(mContent, BorderLayout.CENTER);
    
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension d = toolkit.getScreenSize();
    
    mScene.setLocation(0, 0);
    mScene.setSize(d.width, d.height);
    mScene.validate();
  }
  
  public void startXlet() throws XletStateChangeException {
    mScene.setVisible(true);
  }
  
  public void pauseXlet() {
  }
  
  public void destroyXlet(boolean forced) throws XletStateChangeException {
  }
}

class HelloOCAPUI extends Container {
  private boolean mInitialized;
  private Font mFont;
  private int mX, mY;
  
  public HelloOCAPUI() {
    mInitialized = false;
    mFont = null;
    mX = mY = -1;
  }
  
  public void paint(Graphics g) {
    String s = "Hello, OCAP!";

    if (mInitialized == false) {
      mFont = new Font("Serif", Font.PLAIN, 96);
      int w = getWidth();
      int h = getHeight();
      FontMetrics fm = g.getFontMetrics(mFont);
      int sw = fm.stringWidth(s);
      int sh = fm.getHeight();
      int sd = fm.getDescent();
      mX = (w - sw) / 2;
      mY = (h + sh) / 2 - sd;
      mInitialized = true;
    }
    
    g.setFont(mFont);
    g.setColor(Color.blue);
    g.drawString("Hello, OCAP!", mX, mY);
  }
}

In Listing 1, the code in initXlet() sets up a display for the application, using a helper class called HelloOCAPUI. Most of HelloOCAPUI addresses the problem of centering text on the screen.

Building the source code

You can build HelloOcap.java with a rather long command line, but if you plan on doing this frequently, you'll want a script (also called batch file on Windows).

Listing 2 has one example of a script to build the HelloOCAPUI.java source file. Save this as build.bat at the same level as the src directory. The last line — the one with javac — is very long, so here it is split onto multiple lines for clarity:

Listing 2. A build script
@echo off

set JAVA_HOME=C:/Progra~1/Java/jdk1.6.0_16

set OCAPROOT=/CableLabs/tru2way/ocap-ri/ocap set OCAPTC=CableLabs/simulator/Win32/debug

set OCAP_ENV=%OCAPROOT%/bin/%OCAPTC%/env

if not exist bin mkdir bin

%JAVA_HOME%/bin/javac
    -source 1.4
    -target 1.4
    -bootclasspath %OCAP_ENV%/cvm/lib/btclasses.zip;
                   %OCAP_ENV%/cvm/lib/basis.jar;
                   %OCAP_ENV%/sys/ocap-classes.jar
    src/*.java
    -d bin

If your JDK or OCAP RI are located in different directories, you'll have to adjust the script accordingly.

Installing your application

The next step is to convince the OCAP RI to run your application. To do this, first copy the class files you just generated into the OCAP RI directory structure. Then supply a hostapp.properties file by saving the contents of Listing 3 as bin/hostapp.properties at the same level as the src directory:

Listing 3. hostapp.properties
app.0.application_identifier=0x000000015205 app.0.application_control_code=AUTOSTART 
app.0.visibility=VISIBLE
app.0.priority=220
app.0.base_directory=/syscwd/usr/HelloOCAP 
app.0.application_name=HelloOCAP 
app.0.initial_class_name=HelloOCAP

Lastly, Listing 4 is a script that copies the class files and the hostapp.properties file to a directory in the OCAP RI. Save this script as install.bat at the same level as the src directory.

Listing 4. install.bat
@echo off

set OCAPROOT=/CableLabs/tru2way/ocap-ri/ocap 
set OCAPTC=CableLabs/simulator/Win32/debug

set OCAP_ENV=%OCAPROOT%/bin/%OCAPTC%/env

if not exist %OCAP_ENV%/usr/HelloOCAP mkdir %OCAP_ENV%/usr/HelloOCAP

xcopy /s /y bin/* %OCAP_ENV%/usr/HelloOCAP

In Listing 4, OCAP_ENV is equivalent to /syscwd in hostapp.properties. All the script does is copy files into a usr subdirectory.

The final step

The final step — an important one — is to point the OCAP RI to the hostapp.properties file you just created. To do this, edit the mpeenv.ini file. Remember from Part 1 that mpeenv.ini is located in $OCAPROOT/bin/$OCAPTC/env, or /CableLabs/tru2way/ocap-ri/ocap/bin/CableLabs/simulator/Win32/debug/env if you used the default location when you installed the OCAP RI.

The classpath should be defined near the top of the file. Just add the usr/HelloOCAP directory to the front, as shown in Listing 5. Again, the very long line is split here for readability.

Listing 5. Changing the classpath definition
VMOPT.0=-Djava.class.path=/syscwd/usr/HelloOCAP;
                          /syscwd/sys/ocap-classes.jar;
                          /syscwd/sys/ocap-rez.jar;
                          /syscwd/sys/support.jar;
                          /syscwd/qa/ocap-test.jar;
                          /syscwd/qa/support-test.jar;
                          /syscwd;
                          /syscwd/usr;
                          /syscwd/apps/eas

Next time you launch the OCAP RI, you'll be rewarded by seeing the application code do its thing, as shown in Figure 1:

Figure 1. Hello, OCAP!
Screen shot of the OCAP RI with Hello, OCAP! displayed on the application screen

Using the Eclipse plug-in

Messing around with scripts and command lines is not fun for everyone. Fortunately, the OCAP RI project offers an excellent alternative — an Eclipse plug-in, which takes care of many of the gritty details and allows you to concentrate on writing application code.

The OCAP RI project calls the plug-in <tru2way> Workbench (TWB). Installing TWB is a matter of first installing Eclipse, then telling Eclipse where to find TWB, then telling TWB where to find the OCAP RI.

Installing and running Eclipse

A specific version of Eclipse, Eclipse for Java Developers 3.4.2 Ganymede SR2, is recommended for use with TWB. The Eclipse download is a zip file (approximately 85MB). To install Eclipse, just unzip the file. I placed it at C:/eclipse.

Launch Eclipse by running c:/eclipse/eclipse.exe. Eclipse asks you where you want to place a workspace, which is simply a location where Eclipse will save settings and files. I chose c:/eclipse-workspace, but you can choose whatever location you want.

Installing TWB

Once Eclipse is up and running, choose Help > Software Updates... from the menu. Click on the Available Software tab. Click Add Site... and enter the following URL:

http://ri.opencable.com/sdk/updates/eclipse.3.4.2/stable/latest/

When you click OK, Eclipse consults the OpenCable Web site, finds TWB, and displays it in the list, as you can see in Figure 2:

Figure 2. Adding TWB
Screen shot of adding TWB in the Software Updates and Add-ons window

Check tru2way Workbench Feature and then click Install.... Eclipse thinks for a while, downloads TWB, and then (as shown in Figure 3) asks you to confirm the installation:

Figure 3. Confirm TWB installation
Screen shot showing confirmation of the TWB installation

Click Next >. Review the license agreement, choose I accept the terms of the license agreement, and click Finish. Eclipse finishes installing TWB and asks if you want to restart Eclipse. This is a good idea, so click Yes.

Registering the OCAP RI

You are almost ready to start building OCAP applications. The next step is to tell Eclipse about the OCAP RI so it can be used for running applications. This is the same OCAP RI that you downloaded and installed in Part 1 of this series. Eclipse will install applications into the OCAP RI and launch it for you.

From the Eclipse menu, choose Window > Preferences. In the list on the left side, choose RI Bundle Registry. Click New... and find a file called RIBundleManifest.xml.

If you installed the OCAP RI in its default location, you'll find the file at c:\CableLabs\tru2way\ocap-ri\twb_support\RIBundleManifest.xml. Once you locate the file, click Open and then OK.

Restore mpeenv.ini

Finally, if you followed along with the first section of this article, you need to reverse your change to the classpath in mpeenv.ini. Remove /syscwd/usr/HelloOCAP from the front of the classpath definition in mpeenv.ini.

Create a new project

At long last, all the pieces are in place for you to create a new OCAP application using Eclipse.

Begin by creating the new project. Choose File > New > Project... from the Eclipse menu. Now open the OCAP item and select New OCAP Project. Click Next >.

Enter HelloOCAP for the Project name. Click Next >. Select Hello World Template and click Finish.

Eclipse sets up the entire project, including an Xlet class named org.ocapproject.xlet.HelloWorld. All you have to do is set things up for the OCAP RI.

Create a service configuration

Choose Run > Package Services > Open Services Dialog... from the Eclipse menu. In essence, you will be setting up the fields that go in a hostapp.properties file.

In the list on the left, select Xlet Service Configurations and click the new icon, shown in Figure 4:

Figure 4. The new icon
Example of the new icon

Fill out the values to match the example in Table 1:

Table 1. Creating a service configuration
ValuesEntries
Application NameHelloOCAP
Application ID0x5025
Organization ID0x1
Control CodeAutostart
VisibilityVisible
TypeUnbound
Base DirectoryC:/eclipse-workspace/HelloOCAP/bin
Note that you might have a different path to the project if you chose a different location for your Eclipse workspace.
Xlet Classorg.ocapproject.xlet.HelloWorld

After filling out the fields, click Apply, then Package.

Create a run configuration

The final step is to tell Eclipse that you want to use the service configuration (which is kind of like a hostapp.properties file) that you just created. The way to do this is called a run configuration.

Choose Run > Run Configurations from the Eclipse menu. Select OCAP Simulation and click on the new icon.

Use Hello-1-run-configuration for the Name. Click Unbound Xlets, then Add.... In the drop-down box, choose the service configuration you just created, HelloOCAP-service-configuration.

Click Apply, then Run. The OCAP RI will pop up and, after a while, a simple "Hello World!" will appear on the screen.

To stop the OCAP RI correctly, choose TWB > Stop Emulator from the Eclipse menu.

Understanding the development cycle

To understand the development cycle, you will make a change in the source code and run the changed Xlet on the OCAP RI.

If you're still looking at Eclipse's welcome screen, click on the workbench icon, shown in Figure 5:

Figure 5. Eclipse's workbench icon
Example of Eclipse's workbench icon

In the HelloOCAP project, expand src, then expand org.ocapproject.xlet. Double-click on HelloWorld.java to open it in the source editor.

Make some changes in the source. (One simple change is to modify the definition of HELLOWORLD_STR.) Save the file and choose Run > Run History > HelloOCAP-run-configuration from the Eclipse menu. Eclipse takes care of rebuilding the project, packaging it correctly, and launching the OCAP RI. You will see your changes right away.

Using the debugger

Eclipse allows you to set breakpoints, step through code, examine variables, and do other useful stuff. Making this happen is just a matter of creating a debug profile instead of a run profile, and the process is nearly identical.

Choose Run > Debug Configurations from the Eclipse menu. You will see the run configuration you already created is in the list on the left. Select OCAP Simulation and click on the new icon.

Use HelloOCAP-debug-configuration for the Name. Click Unbound Xlets, then Add.... In the dropdown box, choose the service configuration you just created, HelloOCAP-service-configuration.

Click Apply, then Close.

Before you run, create a breakpoint in the source code so you can see debugging in action. Suppose you want to debug the user interface creation in HelloWorld. Scroll the code editor to line 198, the first line of the initGUI() method. In the dark gray gutter to the left of the text area, double-click to create a breakpoint. It looks like a little blue circle, as you can see in Figure 6:

Figure 6. Setting a breakpoint
Example of setting a breakpoint

Now fire up the debugger. Choose Run > Debug Configurations again, select HelloOCAP-debug-configuration, and click Debug. The OCAP RI launches, the debugger hits your breakpoint, and Eclipse asks if you want to open up the Debugger perspective. You do, so check Remember my decision and click Yes.

The debugger shows a list of all the running threads, an area where you can examine variables, and another area where you can step through source code. Use the buttons in the toolbar to step through code, into code, or continue running.

For more information on how to work with Eclipse and the debugger, consult the Eclipse documentation.

When you're finished playing, shut down the OCAP RI as before by using TWB > Stop Emulator.


Conclusion to Part 2

This article explained how to create your own applications for OCAP devices and run them on a desktop computer using the OCAP RI. Although it's possible to accomplish this task at a command line, a plug-in for Eclipse makes the process much easier. Using Eclipse, you can also take advantage of excellent debugging facilities.

You now have a taste of what is possible with OCAP and the tools you need to create whatever you wish. OCAP's foundations in CDC/FP/PBP mean that you have a rich palette of APIs to use in building your applications. Go on and do something wonderful! And be sure to tune in to Part 3 for a deep dive into the OCAP RI source code.


Download

DescriptionNameSize
Source code for the sample applicationj-ocap2.zip3KB

Resources

Learn

Get products and technologies

  • OCAP RI: The OCAP RI project, hosted on java.net, is the place to go to download the binary installer or the Eclipse plug-in, or to learn how to get the source code.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Java technology on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=472527
ArticleTitle=Getting started with OCAP, Part 2: Writing applications for the OCAP RI
publish-date=04052010