Ch07 code
From SCMAD Book
Contents |
HTTP Connection (Listing 7.1)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; /** * This MIDlet is to test the functionality of the HttpConnection interface and * its methods. * * * @author Ko Ko Naing */ public class HTTPMIDlet extends MIDlet { /** * Creates a new instance of HTTPMIDlet */ public HTTPMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares an HTTP connection, an input stream and a connection string */ HttpConnection httpConnection = null; InputStream inputStream = null; String connStr = "http://www.google.com/wml"; try { /* Opens a HTTP connection using the Connector class */ httpConnection = (HttpConnection) Connector.open(connStr); /* Sets the request method for the HTTP connection */ httpConnection.setRequestMethod(HttpConnection.POST); /* Sets the request properties for the HTTP connection */ httpConnection.setRequestProperty("Last-Modified", "15 Nov 2004 12:45:24 GMT"); httpConnection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); httpConnection.setRequestProperty("Accept-Charset", "iso-8859-5"); /** * Opens the input stream associated with the connection */ inputStream = httpConnection.openInputStream(); /* Gets the content type of the connection */ String contentType = httpConnection.getType(); doSomethingWithType(contentType); /* Gets the content length of the connection */ int contentLength = (int) httpConnection.getLength(); /* Reads the data from the input stream */ if (contentLength > 0) { int bytesread = 0; int totalBytesRead = 0; byte[] dataArr = new byte[contentLength]; while ((totalBytesRead != contentLength) && (bytesread != -1)) { bytesread = inputStream.read(dataArr, totalBytesRead, contentLength - totalBytesRead); totalBytesRead += bytesread; } doSomethingWithData(dataArr); } } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a HTTP connection"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (httpConnection != null) { try { httpConnection.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } private void doSomethingWithData(byte[] data) { // Do something with the retrieved data // ... } private void doSomethingWithType(String contentType) { // Do something with the retrieved content type // ... } }
HTTPS Connection (Listing 7.2)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.pki.*; /** * This MIDlet is to test the functionality of the HttpsConnection interface and * its methods. * * * @author Ko Ko Naing */ public class HTTPSMIDlet extends MIDlet { /** * Creates a new instance of HTTPSMIDlet */ public HTTPSMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares an HTTPS connection, an input stream, a connection string * and a security information */ HttpsConnection httpsConnection = null; InputStream inputStream = null; String connStr = "https://www.YourSecureServer.com"; SecurityInfo securityInfo = null; try { /* Opens a HTTPS connection using the Connector class */ httpsConnection = (HttpsConnection) Connector.open(connStr); /** * Sets the request method for the HTTPS connection The following * call can be omitted, because the default request method is GET */ httpsConnection.setRequestMethod(HttpsConnection.GET); /* Sets the request method for the HTTPS connection */ httpsConnection.setRequestProperty("Last-Modified", "15 Nov 2004 12:45:24 GMT"); httpsConnection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); httpsConnection.setRequestProperty("Accept-Charset", "iso-8859-5"); /** * Opens the input stream associated with the connection */ inputStream = httpsConnection.openInputStream(); /* Gets the content type of the connection */ String contentType = httpsConnection.getType(); doSomethingWithType(contentType); /* Gets the content length of the connection */ int contentLength = (int) httpsConnection.getLength(); /* Reads the data from the input stream */ if (contentLength > 0) { int bytesread = 0; int totalBytesRead = 0; byte[] dataArr = new byte[contentLength]; while ((totalBytesRead != contentLength) && (bytesread != -1)) { bytesread = inputStream.read(dataArr, totalBytesRead, contentLength - totalBytesRead); totalBytesRead += bytesread; } doSomethingWithData(dataArr); } /** * Retrieves the security info associated with the connection */ securityInfo = httpsConnection.getSecurityInfo(); /** * Retrieves the certificate associated with the connection */ Certificate certificate = securityInfo.getServerCertificate(); doSomethingWithCertificate(certificate); } catch (CertificateException ce) { System.out.println("The secure link cannot be established"); } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a HTTPS connection"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (httpsConnection != null) { try { httpsConnection.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } private void doSomethingWithData(byte[] data) { // Do something with the retrieved data // ... } private void doSomethingWithType(String contentType) { // Do something with the retrieved content type // ... } private void doSomethingWithCertificate(Certificate certificate) { // Do something with the retrieved certificate // ... } }
Socket Connection (Listing 7.3)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; /** * This MIDlet is to test the functionality of the SocketConnection interface * and its methods. * * * @author Ko Ko Naing */ public class SocketMIDlet extends MIDlet { /** * Creates a new instance of SocketMIDlet */ public SocketMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares a socket connection, a data output stream, and a connection * string */ SocketConnection socketConn = null; DataOutputStream dOutputStream = null; String connStr = "socket://124.120.220.169:5000"; try { /** * Opens a socket connection using the Connector class */ socketConn = (SocketConnection) Connector.open(connStr); /* Sets a socket option for the socket connection */ socketConn.setSocketOption(SocketConnection.KEEPALIVE, 3); /** * Opens the output stream associated with the connection */ dOutputStream = socketConn.openDataOutputStream(); /* Gets address information */ String localAddress = socketConn.getLocalAddress(); int localPort = socketConn.getLocalPort(); /* Writes the data to the output stream */ dOutputStream.writeUTF("Hi, I'm from " + localAddress + ":" + localPort); } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a socket connection"); } finally { if (dOutputStream != null) { try { dOutputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (socketConn != null) { try { socketConn.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } }
Server Socket Connection (Listing 7.4)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; /** * This MIDlet is to test the functionality of the ServerSocketConnection * interface and its methods. * * * @author Ko Ko Naing */ public class ServerSocketMIDlet extends MIDlet { /** * Creates a new instance of ServerSocketMIDlet */ public ServerSocketMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares a server socket connection, a socket connection and a data * input stream */ ServerSocketConnection ssConnection = null; SocketConnection socketConn = null; DataInputStream dInputStream = null; try { ssConnection = (ServerSocketConnection) Connector .open("socket://:5000"); socketConn = (SocketConnection) ssConnection.acceptAndOpen(); /* Sets socket options for the socket connection */ socketConn.setSocketOption(SocketConnection.KEEPALIVE, 5); socketConn.setSocketOption(SocketConnection.DELAY, 0); socketConn.setSocketOption(SocketConnection.LINGER, 5); /* Opens the input stream associated with the connection */ dInputStream = socketConn.openDataInputStream(); /* Gets address information */ String localAddress = ssConnection.getLocalAddress(); int localPort = ssConnection.getLocalPort(); String remoteAddress = socketConn.getAddress(); int remotePort = socketConn.getPort(); /* Reads the data from the input stream */ String message = dInputStream.readUTF(); if (message != null && !message.equals("")) { String tempMessage = localAddress + ":" + localPort + " received \"" + message + "\" from " + remoteAddress + ":" + remotePort; System.out.println(tempMessage); } } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a socket connection"); } finally { if (dInputStream != null) { try { dInputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (socketConn != null) { try { socketConn.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } }
Secure Connection (Listing 7.5)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.pki.*; /** * This MIDlet is to test the functionality of the SecureConnection interface * and its methods. * * * @author Ko Ko Naing */ public class SecureMIDlet extends MIDlet { /** * Creates a new instance of SecureMIDlet */ public SecureMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares a secure ssl connection, an input stream, an output stream * and a security information */ SecureConnection secureConn = null; DataInputStream dInputStream = null; DataOutputStream dOutputStream = null; SecurityInfo securityInfo = null; try { /** * Opens a secure connection using the Connector class */ secureConn = (SecureConnection) Connector .open("ssl://icicibank.com"); /* Sets socket options for the secure connection */ secureConn.setSocketOption(SecureConnection.KEEPALIVE, 3); secureConn.setSocketOption(SecureConnection.LINGER, 3); /** * Opens the input stream associated with the connection */ dInputStream = secureConn.openDataInputStream(); /** * Opens the output stream associated with the connection */ dOutputStream = secureConn.openDataOutputStream(); /* Retrieves address information */ String localAddress = secureConn.getLocalAddress(); int localPort = secureConn.getLocalPort(); String remoteAddress = secureConn.getAddress(); int remotePort = secureConn.getPort(); /** * Retrieves the security information associated with the connection */ securityInfo = secureConn.getSecurityInfo(); /** * Retrieves the security protocol information associated with the * connection */ String protocolName = securityInfo.getProtocolName(); String protocolVersion = securityInfo.getProtocolVersion(); /* Reads the data from the input stream */ String message = dInputStream.readUTF(); if (message != null && !message.equals("")) { String tempMessage = localAddress + ":" + localPort + " received \"" + message + "\" from " + remoteAddress + ":" + remotePort + " using " + protocolName + " version-" + protocolVersion; dOutputStream.writeUTF(tempMessage); } } catch (CertificateException ce) { System.out.println("The secure link cannot be established"); } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a secure socket stream connection"); } finally { if (dInputStream != null) { try { dInputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (dOutputStream != null) { try { dOutputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (secureConn != null) { try { secureConn.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } }
UDP Datagram Connection (Listing 7.6)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; /** * This MIDlet is to test the functionality of the UDPDatagramConnection * interface and its methods. * * * @author Ko Ko Naing */ public class UDPMIDlet extends MIDlet { /** * Creates a new instance of UDPMIDlet */ public UDPMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declares a UDP connection and a datagram */ UDPDatagramConnection udpDatagramConnection = null; Datagram datagram = null; try { /* Opens a UDP connection using the Connector class */ udpDatagramConnection = (UDPDatagramConnection) Connector.open("datagram://:5500"); /* Instantiates the datagram with the size of 200 bytes */ datagram = udpDatagramConnection.newDatagram(200); /* Retrieves address information */ String localAddress = udpDatagramConnection.getLocalAddress(); int localPort = udpDatagramConnection.getLocalPort(); /* Receives the datagram from the connection */ udpDatagramConnection.receive(datagram); doSomethingWithDatagram(datagram); } catch (InterruptedIOException ioe) { System.out.println("I/O operation interrupted"); } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out.println("Invalid connection string for a socket connection"); } finally { if (udpDatagramConnection != null) { try { udpDatagramConnection.close(); } catch(IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } private void doSomethingWithDatagram(Datagram datagram) { // Do something with the retrieved datagram // ... } }
Communications Connection (Listing 7.7)
package com.scmadkit.ch07; import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; /** * This MIDlet is to test the functionality of the CommConnection interface and * its methods. * * * @author Ko Ko Naing */ public class CommMIDlet extends MIDlet { /** * Creates a new instance of CommMIDlet */ public CommMIDlet() { } /* Signals that the MIDlet has entered the Active state */ protected void startApp() { /** * Declare a serial communication connection and an input stream * variables */ CommConnection commConn = null; InputStream inputStream = null; try { /** * Open the serial communication connection using the Connector * class */ commConn = (CommConnection) Connector .open("comm:com0;baudrate=9600"); /** * Open the input stream associated with the connection */ inputStream = commConn.openInputStream(); /* Retrieve baud rate information */ int baudRate = commConn.getBaudRate(); doSomethingWithBaudRate(baudRate); /* Read the data from the input stream */ int charRead = 0; while (true) { StringBuffer buffer = new StringBuffer(); charRead = 0; while (charRead != '\r') { charRead = inputStream.read(); buffer.append((char) charRead); } System.out.println(buffer.toString()); } } catch (ConnectionNotFoundException cnfe) { System.out.println("The connection target cannot be found"); } catch (IOException ioe) { System.out.println("I/O access error"); } catch (ClassCastException cce) { System.out .println("Invalid connection string for a serial communication connection"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } if (commConn != null) { try { commConn.close(); } catch (IOException ioe) { System.out.println("I/O access error"); } } } } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } private void doSomethingWithBaudRate(int baudRate) { // Do something with the retrieved baudrate // ... } }
