The Generic Connection Framework
The Generic Connection framework is introduced in J2ME's CLDC to reflect the requirements of small-footprint networking and file I/O for a broad range of mobile devices.
To meet the small-footprint requirement, the Generic Connection framework generalizes the functionality of J2SE's network and file I/O classes from J2SE's java.io and jave.net packages. It is a precise functional subset of J2SE classes, but much smaller in size. These J2ME classes and interfaces are all included in a single package, javax.microedition.io.
To meet the extendibility and flexibility requirement, the Generic Connection framework uses a set of related abstractions for different forms of communications, represented by seven connection interfaces: Connection, ContentConnection, DatagramConnection, InputConnection, OutputConnection, StreamConnection, and StreamConnectionNotifier.
The Generic Connection framework supports the following basic forms of communications. All the connections are created by one common method, Connector.open():
HTTP:
Connector.open("http://www.webyu.com");
Sockets:
Connector.open("socket://localhost:80");
Datagrams:
Connector.open("datagram://http://www.webyu.com:9000");
Serial Port:
Connector.open("comm:0;baudrate=9600");
File:
Connector.open("file:/foo.dat");
This flexible design makes adding a new form of communication much easier without causing major structural changes to the class libraries.
Figure 9.1 shows the hierarchical relationships between these connection interfaces.
Connection Interfaces
As shown in Figure 9.1, Connection is the base interface, the root of the connection interface hierarchy. All the other connection interfaces derive from Connection. StreamConnection derives from InputConnection and OutputConnection. It defines both the input and output capabilities for a stream connection. ContentConnection derives from StreamConnection. It adds three methods for MIME data handling to the input and output methods in StreamConnection. Finally, HttpConnection derives from ContentConnection.
The HttpConnection is not part of the Generic Connection framework. Instead, it is defined in the MIDP specification that is targeted at cellular phones and two-way pagers. HttpConnection contains methods and constants specifically to support the HTTP 1.1 protocol. The HttpConnection interface must be implemented by all MIDP implementations, which means the HttpConnection will be a concrete class in the actual MIDP implementations. The http communication capability is expected to be available on all MIDP devices.
Figure 9.1 The connection interface hierarchy.
Why are these connections defined as interfaces instead of concrete classes? Because the Generic Connection framework specifies only the basic framework of how these connection interfaces should be implemented. The actual implementations are left to individual device manufacturers' profile implementations (MIDP or PDAP). As discussed in the previous section, individual device manufacturers may be interested in implementing only a subset of these connection interfaces based on the capabilities of their devices. The documentation of each manufacturer's J2ME MIDP SDK should indicate which connection interfaces are implemented and which are not.
Creating Network Connections
So far we have talked about the different kinds of connections. You may wonder how the connections are created and how to use them.
The Connector class is the core of the Generic Connection framework, because all connections are created by the static open() method in the Connector class. Different types of communication are created from the same method. The connection type can be file I/O, serial port communication, datagram connection, or an HTTP connection, depending on the string parameter passed to the method. Such a design makes the J2ME implementation more extensible and flexible in supporting new devices and product.
The method's signature is as follows:
Connection open(String connect_string)
The connect_string has a format of {protocol}:[{target}][{params}], which is similar to the commonly used URL format, such as http://www.somewhere.com. It consists of three parts: protocol, target, and params.
protocol dictates what type of connection will be created by the open() method. There are several possible values for protocol, as listed in Table 9.1.
Table 9.1 Protocol Values
Value |
Connection Usage |
file |
File I/O |
comm |
Serial port communication |
socket |
TCP/IP socket communication |
datagram |
Datagram communication |
http |
Accessing Web servers |
target can be a hostname, a network port number, a file name, or a communication port number.
params is optional. It specifies the additional information needed to complete the connect string.
The following examples demonstrate how to use the open() method to create different types of communication based on different protocols:
HTTP communication:
Connection hc = Connector.open("http://www.webyu.com")
Socket communication:
Connection sc = Connector.open("socket://localhost:9000")
Datagram communication:
Connection dc = Connector.open("datagram://http://www.webyu.com:9000")
Serial port communication:
Connection cc = Connector.open("comm:0;baudrate=9000")
File I/O:
Connection fc = Connector.open("file:/foo.dat")
NOTE
Actual support for these protocols varies from vendor to vendor. Of all the J2ME MIDP implementations we have evaluated (Sun's J2ME Wireless Toolkit, MotoSDK from Motorola, and RIMSDK from Research in Motion), MotoSDK supports all three networking protocols that we are concerned with in this chapter: socket (TCP/IP), datagram (UDP), and http (HTTP). For this reason, all the sample codes in this chapter are compiled and run under MotoSDK (release 0.7).
A ConnectionNotFoundException will be thrown if your MIDlet program tries to create a connection based on a protocol that is not supported by your device manufacturer's MIDP implementation.
Even though we said that Sun's J2ME Wireless Toolkit only supports the http communication, there is actually an undocumented feature that will let you run socket or datagram programs under the Toolkit if you set the environment variable ENABLE_CLDC_PROTOCOLS=INTUITIVE_TOOLKIT. Because it is an undocumented feature that is not officially supported by Sun, we chose not to use Sun's J2ME Wireless Toolkit to run our samples in this chapter.
The Methods in the Connector Class
This section takes a close look at the Connector class. The Connector class is the only concrete class in Generic Connection framework in CLDC. It contains seven static methods:
static Connection open(String connectString)
This method creates and opens a new Connection based on the connectString.
static Connection open(String connectString, int mode)
This method creates and opens a new Connection based on the connectString. The additional mode parameter specifies the access mode for the connection. There are three access modes: Connector.READ, Connector.READ_WRITE, and Connector.WRITE. If mode is not specified, the default value is Connector.READ_WRITE. The validity of the actual setting is protocol dependent. If the access mode is not allowed for a protocol, an IllegalArgumentException will be thrown.
static Connection open(String connectString, int mode, boolean timeouts)
This method creates and opens a new Connection based on the connectString. The additional timeouts parameter is a Boolean flag that dictates whether the method will throw a timeout exception InterruptedIOException. The default timeouts value is false, which indicates that no exception will be thrown.
static DataInputStream openDataInputStream(String connectString)
This method creates and opens a new DataInputStream based on the connectString.
static DataOutputStream openDataOutputStream(String connectString)
This method creates and opens a DataOutputStream from the connectString.
static InputStream openInputStream(String connectString)
This method creates and opens a new InputStream from the connectString.
static OutputStream openOutputStream(String connectString)This method creates and opens a new OutputStream from the connectString.
The last four I/O stream-creation methods combine creating the connection and opening the input/output stream into one step. For example, the following statement
DataInputStream dis = Connector.openDataInputStream(http://www.webyu.com);
is the equivalent of the following two statements:
InputConnection ic = (InputConnection) Connector.open("http://www.webyu.com", Connector.READ, false); DataInputStream dis = ic.openDataInputStream();
An IllegalArgumentException will be thrown if a malformed connectString is received. A ConnectionNotFoundException will be thrown if the protocol specified in connectString is not supported. An IOException will be thrown for other types of I/O errors.
Listing 9.1 contains an example of how an http connection is created and how a DataInputStream is opened on top of the connection.
Listing 9.1 Listing1.txt
/** * This sample code block demonstrates how to open an * http connection, how to establish an InputStream from * this http connection, and how to free them up after use. **/ // include the networking class libraries import javax.microedition.io.*; // include the I/O class libraries import java.io.*; // more code here ... // define the connect string with protocol: http // and hostname: 64.28.105.110 String connectString = "http://64.28.105.110"; InputConnection hc = null; DataInputStream dis = null; // IOException must be caught when Connector.open() is called try { // an http connection is established with read access. // The returned object is cast into an InputConnection object. hc = (InputConnection) Connector.open(connectString, Connector.READ, false); // an InputStream is created on top of the InputConnection // object for read operations. dis = hc.openDataInputStream(); // perform read operations here ... } catch (IOException e) { System.err.println("IOException:" + e); } finally { // free up the I/O stream after use try { if (dis != null ) dis.close(); } catch (IOException ignored) {} // free up the connection after use try { if ( hc != null ) hc.close(); } catch (IOException ignored) {} } // more code here ...
Connection Interfaces
This section takes a look at all the connection interfaces defined in the javax.microedition.io package including the seven connections from the Generic Connection framework in CLDC and the HttpConnection in MIDP:
Connection ContentConnection DatagramConnection InputConnection OutputConnection StreamConnection StreamConnectionNotifier HttpConnection
Connection
The Connection interface has one method:
void close()
This method closes the connection.
InputConnection
The InputConnection interface has two methods:
DataInputStream openDataInputStream()
This method opens a data input stream from the connection.
InputStream openInputStream()
This method opens an input stream from the connection.
OutputConnection
The OutputConnection interface has two methods:
DataOutputStream openDataOutputStream()
This method opens a data output stream from the connection.
OutputStream openOutputStream()
This method opens an output stream from the connection.
DatagramConnection
The DatagramConnection interface is used to create a datagram for a UDP communication. More details regarding this interface are discussed in the section "Wireless Network Programming Using Datagrams." This interface has eight methods:
int getMaximumLength()
This method returns the maximum length that is allowed for a datagram packet.
int getNominalLength()
This method returns the nominal length for datagram packets.
Datagram newDatagram(byte[] buf, int size)
This method creates a new Datagram object. buf is the placeholder for the data packet, and size is the length of the buffer to be allocated for the Datagram object.
Datagram newDatagram(byte[] buf, int size, String addr)
This method creates a new Datagram object. The additional parameter addr specifies the destination of this datagram message. It is in the format {protocol}://[{host}]:{port}.
Datagram newDatagram(int size)
This method creates a new Datagram object with an automatically allocated buffer with length size.
Datagram newDatagram(int size, String addr)
This method creates a new Datagram object. addr specifies the destination of this datagram message.
void receive(Datagram dgram)
This method receives a Datagram object dgram from the remote host.
void send(Datagram dgram)
This method sends a Datagram object dgram to the remote host.
StreamConnection
The StreamConnection interface offers both send and receive capabilities for socket-based communication. All four of its methods are inherited from InputConnection and OutputConnection:
DataInputStream openDataInputStream() InputStream openInputStream() DataOutputStream openDataOutputStream() OutputStream openOutputStream()
StreamConnectionNotifier
The StreamConnectionNotifier interface has one method:
StreamConnection acceptAndOpen()
This method returns a StreamConnection that represents a server-side socket connection to communicate with a client.
ContentConnection
The ContentConnection interface extends from StreamConnection and adds three methods to determine an HTTP stream's character encoding, MIME type, and size:
String getEncoding()
This method returns the value of the content-encoding in the HTTP header of an HTTP stream.
long getLength()
This method returns the value of the content-length in the HTTP header of an HTTP stream.
String getType()
This method returns the value of the content-type in the HTTP header of an HTTP stream.
The methods inherited from StreamConnection are as follows:
DataInputStream openDataInputStream() InputStream openInputStream() DataOutputStream openDataOutputStream() OutputStream openOutputStream()
HttpConnection
The HttpConnection extends from ContentConnection. It adds the following methods to support the HTTP 1.1 protocol:
long getDate() long getExpiration() String getFile() String getHeaderField(int index) String getHeaderField(String name) long getHeaderFieldDate(String name, long def) int getHeaderFieldInt(String name, int def) String getHeaderFieldKey(int n) String getHost() long getLastModified() int getPort() String getProtocol() String getQuery() String getRef() String getRequestMethod() String getRequestProperty(String key) int getResponseCode() String getResponseMessage() String getURL() void setRequestMethod(String method) void setRequestProperty(String key, String value)
The HttpConnection interface is mandatory for all MIDP vendor implementations. However, the underlying support mechanisms could be different from vendor to vendor. Some vendors may support the HTTP stack on top of non-IPbased protocols such as WSP transport or TL/PDC-P, and other vendors may use HTTP over TCP/IP. To support the HTTP protocol on MIDP devices, non-IP networks may have to install gateways in order to convert HTTP requests from the wireless network format to a TCP/IP format to be able to access the Internet.
Figure 9.2 illustrates the possible implementations of HttpConnection, based on different wireless network infrastructures.
The section "Wireless Network Programming Using HttpConnection" discusses HttpConnection in detail.
Figure 9.2 Implementations of HttpConnection on different underlying transports.