Saturday, April 23, 2011

J2ME RMS Sorting Example

This example simply shows how to use of RMS package. In this example we are going to sort the specified string by the implementing of RecordComparator interface as given:


class Comparator implements RecordComparator{
public int compare(byte[] rec1, byte[] rec2){
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0){
return RecordComparator.EQUIVALENT;
} else if (result < 0){ return RecordComparator.PRECEDES; } else { return RecordComparator.FOLLOWS; } } }


In the javax.microedition.rms package only one method is as follows:

compare(byte[] rec1, byte[] rec2):- This is the integer type method and it returns
RecordComparator.PRECEDES, RecordComparator.FOLLOWS, RecordComparator.EQUIVALENT. The PRECEDES apply if rec1 precedes rec2 in sort order, the FOLLOWS apply if rec1 follows rec2 in sort order and the EQUIVALENT apply if rec1 and rec2 are equivalent in terms of sort order.

The Application is as follows:




RMSMIDlet.java



import java.io.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;

public class RMSMIDlet extends MIDlet{
private RecordStore record;
static final String REC_STORE = "SORT";

public void startApp(){
openRecord();
writeRecord("RAKESH");
writeRecord("SANDEEP");
writeRecord("NEELAM");
writeRecord("ANUSMITA");
writeRecord("VIJAY");
readRecord();
closeRecord();
deleteRecord();
}

public void pauseApp(){}

public void destroyApp(boolean unconditional){
notifyDestroyed();
}

public void openRecord(){
try{
record = RecordStore.openRecordStore(REC_STORE, true );
}catch (Exception e){
db(e.toString());
}
}

public void closeRecord(){
try{
record.closeRecordStore();
}catch (Exception e){
db(e.toString());
}
}

public void deleteRecord(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(REC_STORE);
}catch (Exception e){
db(e.toString());
}
}
}

public void writeRecord(String str){
byte[] rec = str.getBytes();
try{
record.addRecord(rec, 0, rec.length);
}catch (Exception e){
db(e.toString());
}
}

public void readRecord(){
try{
if (record.getNumRecords() > 0){
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);

while (re.hasNextElement()){
String str = new String(re.nextRecord());
System.out.println("------------------------------");
System.out.println(str);
System.out.println("------------------------------");
}
}
} catch (Exception e){
db(e.toString());
}
}

private void db(String error){
System.err.println("Exception: " + error);
}
}

class Comparator implements RecordComparator{
public int compare(byte[] rec1, byte[] rec2){
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0){
return RecordComparator.EQUIVALENT;
} else if (result < 0){ return RecordComparator.PRECEDES; } else { return RecordComparator.FOLLOWS; } } }

How to Obtain an IP Address of a Mobile ?

IntroductionIn style of a wired host computer, a mobile phone does expose limited information to Internet servers. These include User-Agent tag and an IP address. This basically means a mobile device does actually not be treated any differently than it would be a home computer accessing the remote server.

For wired host computers IP address can be very useful for web services, in attempt to geolocate the computer and thus providing targeted local area information based on where the accessing computer has been detected. This has been quite successful, even the commonness of NAT (Network Address Translation) boxes and IP addresses created dynamically.

Locating mobile phones based on their IP address, on the other hand, is not as functional. First of the reasons for the difficulties on an accurate geolocation for mobiles are their IP being changing in somewhat fast manner during network requests (mainly HTTP).This can result in web service recognizing different address for the same mobile device even a fast pace in executing queries. Secondly the same or similar IP address may be shown towards the server from mobile devices located even very far from each others, so they may still share same IP-address space.

This simply means that the mobile device IP address will not provide any very pinpoint information of their whereabouts. Opposing to the mobile devices. wired computers IP addresses stay stationary with very high accuracy from the web service host point of view. Geolocation services may however implement reported cell tower IDs in together with the strength of radio signals that the mobile device receives from different cell towers to increase accuracy.

Obtaining the IP address by the method on how presented next in this Wiki article, does not try to compete with the GPS positioning (Global Positioning System), but exposes some possible good use cases. Most definitely the mobile device IP address bases on the NAT (Network Address Translation) performed by the gateway of the service provider. This will result a "masquerading" IP address, for which reason the mobile device is not visible to the outside world with that IP. Such IP address is called "private".

This will result e.g. so that the mobile device web browser in a "masqueraded network" can browse a website outside, but this does not work the other way. It depends on the network administrator if the translation table entries will be configured for permanent use, often referred to "static NAT" or port forwarding, thus allowing traffic from outside network to access into that "hidden" network.

Request IP address in J2METhe example MIDlet works the way, that when started it will first ask the user permission:

"Allow application to use network and send or receive data?"


If the user either selects "Once" or "Allow for this session" we will further continue trying to open a connector using ServerSocketConnection:

ssc = (ServerSocketConnection) Connector.open("socket://:1234");


Note: On a PC mobile emulator or device where GPRS has been idling, you may be returned with the localhost IP address of 127.0.0.1. This is called "loopback". Depending on the settings on your mobile, if the GPRS has been set to "use when available", the network provider IP address should be returned with high probability. If available, WIFI network connection would work similar way.

With the ServerSocketConnection the mobile device will basically become a client and would be waiting for the server to respond.

In the code is commented out another query that could be also performed, namely the System.getProperty("microedition.hostname"). If you want to see results for that, and maybe find useful, uncomment these lines:

...

//private String msg2;
//msg2 = System.getProperty("microedition.hostname");
//form.append("Hostname by 'getproperty' is:\n");
...

On devices that support this it should return the host name of the device, most likely it will give string "localhost" as return value.

Code Example:

Code example

package MyIpAddress;
 
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.midlet.*;;
import javax.microedition.lcdui.*;
 
public class MyIPaddress extends MIDlet implements CommandListener{
 
private Display display;    
private Form form;       
private Command exit;     
private String msg;
private String msg2;
private Alert modalAlert;
 
public void startApp() {
display = Display.getDisplay(this);                        
exit = new Command("Exit", Command.EXIT, 1);
form = new Form("MyIPaddress");
form.addCommand(exit);
form.setCommandListener(this);        
display.setCurrent(form);
form.append("Requesting your IP now...\n");
 
try {
ServerSocketConnection ssc = null;
try {                                           
ssc = (ServerSocketConnection) Connector.open("socket://:1234");
} catch (IOException ex) {
modalAlert = new Alert("Error", "Problem with connecting!",null, AlertType.ERROR);
modalAlert.setTimeout(4000);
display.setCurrent(modalAlert);
form.append("\nNo IP address received!\n");
 
ex.printStackTrace();
}
msg = ssc.getLocalAddress();
form.append("Success! Your IP is:\n");
form.append(msg);
msg2 = System.getProperty("microedition.hostname");
form.append("\nHostname is:\n");
form.append(msg2);
 
} catch (IOException ex) {
modalAlert = new Alert("Error", "Exiting application!",null, AlertType.ERROR);
modalAlert.setTimeout(4000);
display.setCurrent(modalAlert);
ex.printStackTrace();
}
}
 
public void pauseApp() {
}
 
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
 
public void commandAction(Command c, Displayable s){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(false);
}
}
 
}

Screenshot :

Datagram Sender


import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

public class DatagramSender {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: DatagramSender port length");
System.exit(1);
}

try {
DatagramConnection sender =
(DatagramConnection)Connector.open("datagram://localhost:" + args[0]);
int length = Integer.parseInt(args[1]);
byte[] buffer = new byte[length];
for (int i = 0; i < length; i++) { buffer[i] = (byte)('0' + (i % 10)); } Datagram dgram = sender.newDatagram(buffer, buffer.length); sender.send(dgram); // Wait for the packet to be returned for (int i = 0; i < length; i++) { buffer[i] = (byte)0; } sender.receive(dgram); length = dgram.getLength(); System.out.println("Received return packet, length is " + length); // Show the content of the datagram. for (int i = 0; i < length; i++) { System.out.print(buffer[i] + " "); } System.out.println(); } catch (IOException ex) { System.out.println("IOException: " + ex); } } }

Datagram Receiver


import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

public class DatagramReceiver {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: DatagramReceiver port");
System.exit(1);
}

try {
DatagramConnection receiver =
(DatagramConnection)Connector.open("datagram://:" + args[0]);
byte[] buffer = new byte[256];
Datagram dgram = receiver.newDatagram(buffer, buffer.length);
for (;;) {
dgram.setLength(buffer.length);
receiver.receive(dgram);
int length = dgram.getLength();
System.out.println("Datagram received. Length is " + length);

// Show the content of the datagram.
for (int i = 0; i < length; i++) { System.out.print(buffer[i] + " "); } System.out.println(); // Send it back... receiver.send(dgram); } } catch (IOException ex) { System.out.println("IOException: " + ex); } } }

Client Server in J2ME (Socket Programming sample)

Sockets are different than datagrams because they use a connection-based paradigm to transmit data. This means that both a sender and a receiver must be running and establish a communication channel for data to be exchanged. To use a real-world analogy, a socket connection is like calling a friend on the telephone. If the friend does not answer, a conversation cannot take place. Datagrams on the other hand are more like sending a letter to a friend, where a note is placed into an envelope, addressed, and mailed.

The following code demonstrates how to set up a listener to monitor a port for an inbound socket connection.


try{
  SocketConnection sc = (SocketConnection) 
    Connector.open("socket://localhost:9002");
  OutputStream os = null;
  try{
    os = sc.openOutputStream();
    byte[] data = "Hello from a socket!".getBytes();
    os.write(data);
  } finally{
      sc.close();
      os.close();
  }
} catch (IOException x){
 x.printStackTrace();
}
In this example a ServerSocketConnection is opened on port 9002. This type of connection is used for sole purpose of listening for an inbound socket connection. The code goes into a wait state when the acceptAndOpen() method is called. When a socket connection is established, the acceptAndOpen() method returns with an instance of a SocketConnection. Opening an input stream on this connection allows data to be read from the transmission.
The next example demonstrates the code required by the client to initiate the socket connection


try{
  SocketConnection sc = (SocketConnection) 
    Connector.open("socket://localhost:9002");
  OutputStream os = null;
  try{
    os = sc.openOutputStream();
    byte[] data = "Hello from a socket!".getBytes();
    os.write(data);
  } finally{
      sc.close();
      os.close();
  }
} catch (IOException x){
 x.printStackTrace();
}
In this example a SocketConnection is established on port 9002 of the local machine. When using sockets, this is the point on the server side that the acceptAndOpen() method returns. If the connection is successfully opened, the OutputStream is obtained and a message is written to the stream. Note that because sockets are connection based, if there is no server listening for an incoming socket connection an exception will be thrown.

Search This Blog

Total Pageviews