FileDocCategorySizeDatePackage
ProtocolBase.javaAPI DocphoneME MR2 API (J2ME)17053Wed May 02 18:00:32 BST 2007com.sun.midp.io.j2me

ProtocolBase

public abstract class ProtocolBase extends Object implements javax.wireless.messaging.MessageConnection, com.sun.cldc.io.ConnectionBaseInterface, javax.microedition.io.StreamConnection
Base class for SMS/CBS/MMS message connection implementation. Protocol itself is not instantiated. Instead, the application calls Connector.open with an URL string and obtains a {@link javax.wireless.messaging.MessageConnection MessageConnection} object. It is an instance of MessageConnection that is instantiated. The Generic Connection Framework mechanism in CLDC will return a Protocol object, which is the implementation of MessageConnection. The Protocol object represents a connection to a low-level transport mechanism.

Optional packages, such as Protocol, cannot reside in small devices. The Generic Connection Framework allows an application to reach the optional packages and classes indirectly. For example, an application can be written with a string that is used to open a connection. Inside the implementation of Connector, the string is mapped to a particular implementation: Protocol, in this case. This allows the implementation to be optional even though the interface, MessageConnection, is required.

Closing the connection frees an instance of MessageConnection.

The Protocol class contains methods to open and close the connection to the low-level transport mechanism. The messages passed on the transport mechanism are defined by the {@link MessageObject MessageObject} class. Connections can be made in either client mode or server mode.

  • Client mode connections are for sending messages only. They are created by passing a string identifying a destination address to the Connector.open() method.
  • Server mode connections are for receiving and sending messages. They are created by passing a string that identifies a port, or equivalent, on the local host to the Connector.open() method.
The class also contains methods to send, receive, and construct Message objects.

This class declares that it implements StreamConnection so it can intercept calls to Connector.open*Stream() to throw an IllegalArgumentException.

Fields Summary
protected String
ADDRESS_PREFIX
Prefic for addressed message connections.
protected com.sun.midp.midlet.MIDletSuite
midletSuite
Handle to the MIDlet suite containing this MIDlet.
protected boolean
open
Indicates whether the connection is open or closed. If it is closed, subsequent operations should throw an exception.
protected int
connHandle
Local handle to connection
protected String
appID
Connection parameter from the URL.
protected int
m_mode
Connector mode.
protected String
host
Machine name - the parsed target address from the URL.
private static com.sun.midp.security.SecurityToken
classSecurityToken
This class has a different security domain than the MIDlet suite
volatile javax.wireless.messaging.MessageListener
m_listener
Message listener for async notifications.
Thread
m_listenerThread
Listener thread.
protected Object
closeLock
Used to protect read-modify operation on open field during close()
protected boolean
openPermission
Indicates whether a trusted application is allowed to open the message connection. Set to true if the permission check passes. Note: return true to override Security Permissions
protected boolean
readPermission
Indicates whether a trusted application is allowed to read from the message connection. Set to true if the permission check passes. Note: return true to override Security Permissions
protected boolean
writePermission
Indicates whether a trusted application is allowed to write to the message connection. Set to true if the permission check passes. Note: return true to override Security Permissions
Constructors Summary
public ProtocolBase()
Creates a message connection protocol handler.


           
      
	midletSuite = Scheduler.getScheduler().getMIDletSuite();
    
Methods Summary
protected abstract voidcheckReceivePermission()
Checks internal setting of receive permission. Called from receive and setMessageListener methods.

exception
InterruptedIOException if permission dialog was preempted

protected abstract intclose00(int connHandle, int deRegister)
Close connection.

param
connHandle handle returned by open0
param
deRegister Deregistration appID when parameter is 1.
return
0 on success, -1 on failure

public voidensureOpen()
Ensures that the connection is open.

exception
IOException if the connection is closed

	if (!open) {
	    throw new IOException("Connection closed");
	}
    
protected abstract java.lang.StringgetAppID()
Gets the connection parameter in string mode.

return
string that contains a parameter

protected voidio2InterruptedIOExc(java.io.IOException ex, java.lang.String name)
Generates InterruptedIOException when connection is closed.

param
ex input IOException
param
name name of operation: sending or receiving
exception
IOException if the connection is not closed

        try {
            ensureOpen();
        } catch (IOException ioe) {
            throw new InterruptedIOException("Connection closed " +
                                         "during " + name);
        }
        throw ex;
    
public abstract javax.wireless.messaging.MessagenewMessage(java.lang.String type)
Construct a new message object from the given type.

param
type MULTIPART_MESSAGE is the only type permitted.
return
A new MMS Message object.

public abstract javax.wireless.messaging.MessagenewMessage(java.lang.String type, java.lang.String addr)
Constructs a new message object from the given type and address.

param
type TEXT_MESSAGE or BINARY_MESSAGE.
param
addr the destination address of the message.
return
a new Message object.

public abstract javax.wireless.messaging.Messagereceive()
Receives the bytes that have been sent over the connection, constructs a Message object, and returns it.

If there are no Messages waiting on the connection, this method will block until a message is received, or the MessageConnection is closed.

return
a Message object.
exception
java.io.IOException if an error occurs while receiving a message.
exception
java.io.InterruptedIOException if during this method call this MessageConnection object is closed.
exception
java.lang.SecurityException if the application doesn't have permission to receive messages on the given port.

public abstract voidsend(javax.wireless.messaging.Message dmsg)
Sends a message over the connection. This method extracts the data payload from the Message object so that it can be sent as a datagram.

param
dmsg a Message object
exception
java.io.IOException if the message could not be sent or because of network failure
exception
java.lang.IllegalArgumentException if the message contains invalid information or is incomplete, or the message's payload exceeds the maximal length for the given protocol.
exception
java.io.InterruptedIOException either if this Connection object is closed during the execution of this send method or if a timeout occurs while trying to send the message.
exception
java.lang.NullPointerException if the parameter is null.
exception
java.lang.SecurityException if the application doesn't have permission for sending the message.

protected abstract voidsetAppID(java.lang.String newValue)
Sets the connection parameter in string mode.

param
newValue new value of connection parameter

public voidsetMessageListener(javax.wireless.messaging.MessageListener listener)
Registers a MessageListener object.

The platform will notify this listener object when a message has been received to this MessageConnection.

If the queue of this MessageConnection contains some incoming messages that the application haven't read before the call of this method, the newly registered listener will be notified immediately exactly once for each such message in the queue.

There can be at most one listener object registered for a MessageConnection object at any given point in time. Setting a new listener will implicitly de-register the possibly previously set listener.

Passing null as the parameter de-registers the currently registered listener, if any.

param
listener MessageListener object to be registered. If null, the possibly currently registered listener will be de-registered and will not receive notifications.
exception
java.lang.SecurityException if the application does not have a permission to receive messages using the given port number
exception
java.io.IOException if it is requested to register a listener on a client connection or if the connection has been closed


        boolean needStopReceiver = false;

        if (listener != null) {
            /*
             * Make sure the connection is still open.
             */
            ensureOpen();

            /*
             * Check if we have permission to recieve.
             */
            checkReceivePermission();

            /*
             * Don't let the application waste time listening on a client
             * connection, which can not be used for receive operations.
	         */
            if (host != null && host.length() > 0) {
                throw new IOException("Cannot listen on client connection");
            }
        }

        synchronized (this) {
	    if ((m_listener != null) && (listener == null)) {
                needStopReceiver = true;
            }
            m_listener = listener;
            /* Start a new receive thread when need */
	    if ((listener != null) && (m_listenerThread == null)) {
                startReceiverThread();
            }
        }

        /* Kill listener when need */
        if (needStopReceiver) {
            String save_appID = getAppID();
            /* Close thread without deregistering */
            close00(connHandle, 0);
            setAppID(null);
            try {
                m_listenerThread.join();
            } catch (InterruptedException ie) {
            }  /* Ignore interrupted exception */
            m_listenerThread = null;

            setAppID(save_appID);
            /* Unblock the low level */
            unblock00(MIDletSuite.UNUSED_SUITE_ID);
        }
    
private voidstartReceiverThread()
Start receiver thread

	final MessageConnection messageConnection = this;

	if (m_listenerThread == null) {

	    m_listenerThread = new Thread() {

		/**
		 * Run the steps that wait for a new message.
		 */
		public void run() {

		    int messageLength = 0;
		    do {

			/* No message, initially. */
			messageLength = -1;
			try {
		            messageLength =
                                waitUntilMessageAvailable00(connHandle);
                            if (getAppID() == null) {
                                break;
                            }
				/*
				 * If a message is available and there are
				 * listeners, notify all listeners of the
				 * incoming message.
				 */
				if (messageLength >= 0) {
                                    synchronized (this) {
                                        if (m_listener != null) {

					    // Invoke registered listener.
					    m_listener.notifyIncomingMessage(
                                                messageConnection);
                                        }
                                    }
                                }
			} catch (InterruptedIOException iioe) {
                            /*
                             * Terminate, the reader thread has been
                             * interrupted
                             */
                            break;
                        } catch (IOException exception) {
                            break;
                        } catch (IllegalArgumentException iae) {
                            /*
                             * This happens if port has been set to 0;
                             * which indicates that the connection has been
                             * closed. So Terminate.
                             */
                            break;
			}

                    /*
                     * m_iport = 0 on close
                     */
		    } while (getAppID() != null);
		}
            };

            m_listenerThread.start();
	}
    
protected abstract intunblock00(int msid)
Unblock the receive thread.

param
msid The MIDlet suite ID.
return
returns handle to the connection.

protected abstract intwaitUntilMessageAvailable00(int handle)
Waits until message available

param
handle handle to connection
return
0 on success, -1 on failure
exception
IOException if an I/O error occurs