Getting Started Tutorial

This document is a short but effective tutorial on how to write your own servlets for Tynamo™-CDC. Below are steps that describe the entire process, from downloading the tools, to accessing your servlet or servlets from an HTTP client. More details can be found in the Building a Web Server document.

Table of Steps

  1. Pre-Setup
  2. Download Tynamo™
  3. Write Servlets
  4. Update the Build Configuration
  5. Build Using Ant
  6. Update the Servlet Configuration
  7. Additional Configuration
  8. Transfer to Your Device
  9. Invoke the Web Server
  10. Enjoy Your Servlets!

0. Pre-Setup

Before beginning this sequence of steps, it is important to have all the necessary tools and utilities installed. Thus, this step "0" is here to provide instruction on this initial setup, if needed.

There is one tool, besides the JDK and device SDK, that the build process uses. This is the Ant utility from The Jakarta Project. As of this writing, the latest version of this tool is Ant 1.6.1. Ant also requires the Jakarta Commons/Net library for deployment using FTP.

Briefly, Ant needs the ANT_HOME and JAVA_HOME environment variables set correctly, and the bin subdirectory of the Ant installation added to the path. As well, the commons-net.jar (it may be named commons-net-1.1.0.jar or something similar) library needs to be placed into Ant's lib/ subdirectory.


1. Download Tynamo™

Download the latest version of Tynamo™ from tynamo.qindesign.com. (This is the current homepage.) The easiest way to install the package is to create a directory, such as 'tynamo-cdc-1.0', and unzip the file into this location.

[Top]


2. Write Servlets

This step demonstrates how to write a simple servlet. There is much literature on this subject, for example in the Documentation section of the Servlets home page, so a relatively small example is presented here. Please remember, however, that Tynamo™ complies with the Servlet 2.2 specification, and not 2.3 or above.

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple servlet that shows information about the server.
 *
 * @author Shawn Silverman
 */
public class ServerInfoServlet extends HttpServlet {
    /**
     * Process a GET request.
     *
     * @param req the request object
     * @param resp the response object
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        // Set up the response

        resp.setContentType("text/html");
        ServletOutputStream out = resp.getOutputStream();

        out.print("<html><head><title>Server Info Servlet</title>");
        out.print("<style>body{font-family: Verdana,sans-serif}</style></head><body>");
        out.print("<h1>Server Information</h1>");
        out.print("<p>This servlet shows information about the server.</p>");

        // Get the servlet context

        ServletContext context = getServletContext();

        out.print("<table border=\"0\">");

        // Server info

        out.print("<tr><td>Server is</td><td><strong>");
        out.print(context.getServerInfo());
        out.print("</strong></td></tr>");

        // Server uptime

        out.print("<tr><td>Server uptime is</td><td>");
        Long startTime = (Long)getServletContext().getAttribute(
                "com.qindesign.http.startTime");
        if (startTime != null) {
            out.print("<strong>");
            printElapsedTime(out, System.currentTimeMillis() - startTime.longValue());
            out.print("</strong>");
        } else {
            out.print("&lt;unknown&gt;");
        }
        out.print("</td></tr>");

        out.print("<tr><td bgcolor=\"Gray\" height=\"2\" colspan=\"2\"></td></tr>");

        // Attribute names

        out.print("<tr valign=\"top\"><td>Context attributes:</td><td>");
        Enumeration e = context.getAttributeNames();
        if (e.hasMoreElements()) {
            out.print("<ul style=\"margin-left: 1.5em\">");
            do {
                String name = (String)e.nextElement();
                out.print("<li><code>");
                out.print(name);
                out.print('=');
                out.print(String.valueOf(context.getAttribute(name)));
                out.print("</code></li>");
            } while (e.hasMoreElements());
            out.print("</ul>");
        } else {
            out.print("&lt;none&gt;");
        }
        out.print("</td></tr>");

        out.print("</table>");

        // Print a footer with the current time

        out.print("<hr /><address>This page was generated on <strong>");
        out.print(new Date().toString());
        out.print("</strong>.</address>");

        out.print("</body></html>");
    }

    /**
     * Prints the elapsed time in "d'd', HH:mm:ss" format.
     *
     * @param out the output stream
     * @param time the elapsed time, in ms
     */
    private static void printElapsedTime(ServletOutputStream out, long time)
        throws IOException
    {
        // Days

        out.print(time / (1000*60*60*24));
        time %= 1000*60*60*24;
        out.print("d, ");

        // Hours

        long l = time / (1000*60*60);
        if (l < 10) out.write('0');
        out.print(l);
        time %= 1000*60*60;

        out.write(':');

        // Minutes

        l = time / (1000*60);
        if (l < 10) out.write('0');
        out.print(l);
        time %= 1000*60;

        out.write(':');

        // Seconds

        l = time / 1000;
        if (l < 10) out.write('0');
        out.print(time / 1000);
    }
}

Save this code as ServerInfoServlet.java in a directory named src underneath the Tynamo™ installation.

[Top]


3. Update the Build Configuration

Open the build.properties file in the root of your Tynamo™ installation. The first thing you need to do is change the src.paths property to point to the root of your servlet source code. For example, if you have a directory named src underneath /projects/myapp, then change src.paths to read:

src.paths=/projects/myapp/src

Note: if you use backslashes (\) as the file separator, then you must use them in pairs (eg. src.paths=C:\\Projects\\myapp\\src). This applies to all of the build properties.

Personally, I like to place a src/ directory underneath the root of the Tynamo™ installation. If you have done this, then src.paths should read something like:

src.paths=/tynamo-cdc-1.0/src

(This assumes that the Tynamo™ installation resides at /tynamo-cdc-1.0.)

After this, add an Ant-style list of source files to the src.files property. For the example above, this would read:

src.files=ServerInfoServlet.java

Finally, set the correct path to the platform API. For example, the classes for the EJC platform are located in a location that looks like:

cdc.classes=/path/to/ejc-1.0.2/stubs/lib

Note that by default, a jar named myclasses.jar will be created that contains all classes compiled in this step. To use a different name, set the target.jar property:

target.jar=myservlets.jar

More src.files Examples

If, say, you have more than one source file in the package com.entity.myapp, then src.files would read as:

src.files=com/entity/myapp/*.java

You can even include more than one subpackage by doing this:

src.files=com/entity/myapp/**/*.java

Please consult the Ant documentation for more details about specifying files.

[Top]


4. Build Using Ant

Build the servlets using Ant. In many cases, all you need to do is execute the ant command from the commandline in the same place as your Tynamo™ installation. Ant will automatically look for the included build.xml file, use your new build configuration, and then proceed to build the appropriate files.

[Top]


5. Update the Servlet Configuration

Open the servlets.props file in the device/bin/ directory of your Tynamo™ installation. You must provide a mapping, a classname, and any initialization arguments for each servlet. Further details can be found in the Servlet Configuration Properties document. For our example, one possibility for these settings is:

ServerInfo.mapping=/servlet/ServerInfo
ServerInfo.class=ServerInfoServlet

We have just indicated to the web server that any request for the path /servlet/ServerInfo will access our example servlet. Also, it is worthwhile to note that this class does not exist inside of a package, so the full classname is just the classname itself: ServerInfoServlet as oppsed to com.widgets.ServerInfoServlet.

It is also worth mentioning that smaller servlets.props files take less time to load. Removing unnecessary lines will cause the server to start faster.

[Top]


6. Additional Configuration

For additional web server configuration, you are referred to the Server Configuration Properties and MIME Types documents.

Note that some of the configuration properties refer to http-root and logs directories. When transferring files to your device, create these directories also.

[Top]


7. Transfer to Your Device

Simply use an FTP client to transfer the entire contents of the device/ subdirectory to your device.

There is a convenience script in device/bin/, called WebServer, that can be used to invoke the web server on the device itself. Other than modifying the absolute paths in this file, all other files should remain as they are.

It is recommended to have some sort of dedicated user, 'web' for example, in whose account all the files are stored. Inside this user's home directory, create these subdirectories:

  • bin for the the above-mentioned binaries and configurations,
  • http-root for any static content such as HTML files, and
  • logs to store the transfer logs and any server messages.

Alternatively, the server can be deployed using Ant.

Example Command-Line FTP Session

What follows is a sample FTP session that transfers the server to your device. It is assumed that the FTP command was invoked from the root of your distribution.

ftp device_address
username            Log in as 'username'
password            Password is 'password'
bin                 Change the transfer mode to binary
mkdir web           Create a root location for the webserver
cd web
mkdir bin           Create directories necessary for the webserver
mkdir http-root
mkdir logs
cd bin              Change to the 'bin' directory
lcd device/bin      Change to the 'bin' directory on the local machine
prompt off          Suppress prompting for each file
mput *              Transfer all files in this directory
cd ../http-root     Transfer all web pages and images
lcd ../http-root
mput *
quit                End the session

[Top]


8. Invoke the Web Server

Log on to your device, navigate to the location of the files transferred in the previous step, and run the program. You can do this in one of two ways: by calling the WebServer script with the command source WebServer, or by running the program directly.

[Top]


9. Enjoy Your Servlets!

Use a web browser or some other HTTP client and connect to your CDC web server:

http://{device address}/servlet/ServerInfo

Enjoy!!

[Top]