docx

guitarchanceSoftware and s/w Development

Aug 15, 2012 (4 years and 11 months ago)

212 views



Page
1

of
10



Lab

3
:
Location API, Threads
,
Communication
,

and Databases


Objective


The objective
to

this lab is to

get experience with
:

1.

The location API

2.

Threads

3.

Network communication
API
s

4.

Using a database over the network

5.

Develop a

custom client

application using these
APIs



Experiment

1

Develop a
n
application
that will integrate/use all the APIs included in
the objective.


In this experiment
,

you are asked to develop a MIDlet that will use the Location
API
to
obtain the cell phone’s position
,

create a thread to send the GPS fix over the network, and
store it in a database created for such purpose.


First, the application will obta
in the GPS fix

only when asked to do so. Upon the
reception of the fix, it will create a thread to establish a soc
ket (TCP) connection with a
server, send the fix
,

and store it in the database. This implies the creation of the MIDlet
for the client, the server application to receive the GPS fix, and the database to store it.


A file with GPS fixes will be provided to
simulate the GPS system.







Page
2

of
10

Listing 1
:



Code example of client


//Most of the methods are self
-
generated by Netbeans. We will show the most important
modification of a standard J
ava
ME project.


import javax.microedition.midlet.*;

import
javax.microedition.lcdui.*;


//Packages for Location API

import javax.microedition.location.LocationException;

import javax.microedition.location.Coordinates;

import javax.microedition.location.Criteria;

import javax.microedition.location.LocationProvider;


//Packages for Communication

import java.io.IOException;

import java.io.OutputStream;

import javax.microedition.io.Connector;

import javax.microedition.io.SocketConnection;


public class GPSTest extends MID
let implements CommandListener
{


private boolean

midletPaused = false;

private boolean midletStopped = false;

private LocationProvider lp;

private Thread myThread;


protected SocketConnection sockConn;

protected OutputStream outstream;

String serv_address = "131.247.3.164";

String serv_port = "7894";


p
ublic GPSTest() {


}


private void initialize() {


// Include these lines inside the initialize method


Criteria cr = new Criteria();


cr.setHorizontalAccuracy(30);


try {



lp = LocationProvider.getInstance(cr);


}


catch (Exception e2)


{



java.lang.System.out.println("Error getting Location
Provider: " + e2);


}



}


public void commandAction(Command command, Displayable displayable)


if (displayable == form)


if (
command == exitCommand)


myThread = new Thread(){public void run(){



Page
3

of
10


stopConnection();


}};


myThread.start();



} else if (command == okCommand) {


// write pre
-
action user code here




// write post
-
action user code here




myThread = new Thread(){public void run(){


updateLocatio
n();


}};


myThread.start();


}


}



// From this point

up to the end
, copy all in your code


/**


* Returns a display instance.


* @return the display instance.


*/


public Display getDisplay () {


return Display.getDisplay(this);


}



/**


* Exits MIDlet.


*/


public void exitMIDlet() {


switchDisplayable (null, null);


destroyApp(true);


notifyDestroyed();


}



public void stopConnection(){


/*Send the termination message to the server to notify the end
of the connection*/



String end_str = "end";


byte[] data = end_str.getBytes();



System.out.println(data);



try


{


outstream.write(data);



}catch(IOException ex){


System.out.println("Could not write to socket stream: " +
ex);


}



try


{


outstream.close();



Page
4

of
10


sockConn.close();


}catch(IOException ex){


Syst
em.out.println("Could not write to socket stream: "
+ ex);


}



}



/**


* Called when MIDlet is started.


* Checks whether the MIDlet have been already started and
initialize/starts or resumes the MIDlet.


*/


public void startApp() {


if (midletPaused) {


resumeMIDlet ();


} else {


initialize ();


startMIDlet ();


}


midletPaused = false;


}



/**


* Called when MIDlet is paused.


*/



public void pauseApp() {


midletPaused = true;


}



/**


* Called to signal the MIDlet to terminate.


* @param unconditional if true, then the MIDlet has to be
unconditionally terminated and all resources has to be released.


*/


public void destroyApp(boolean unconditional) {


midletStopped=true;


}



public void updateLocation()


{


try {


javax.microedition.location.Location l =
lp.getLocation(30);


Coordinates c = l.getQualifiedCoordinates();


if(c != null)


{



sendFix(""+c.getLatitude()+"@"+c.getLongitude()+"@"+S
ystem.currentTimeMillis()+"@");



}


}


catch (LocationException ex)


{


ex.printStackTrace();



Page
5

of
10


} catch (InterruptedException ex)


{


ex.printStackTrace();


}



}



public void sendFix(String location){



if(sockConn == null){


try


{


sockConn = (SocketConnection)
Connector.open("socket://" + serv_address + ":" + serv_port);


}catch(IOException ex){


System.out.println("Could not create

connection: " + ex);


}


try


{


sockConn.setSocketOption(SocketConnection.KEEPALIVE, 1);



}catch(IOException ex)


{


System.out.println("Could not set socket option: " + ex
);


}


try{


outstream = sockConn.openOutputStream();


}catch(IOException ex){


System.out.println("Could not open socket stream: " + ex);


}


}



// get the payload



byte[] data = location.getBytes();




System.out.println(location);



try


{


outstream.write(data);


}catch(IOException ex){


System.out.println("Could not write to socket stream: " + ex);


}



}




}




Page
6

of
10

Listing 2
:


Code example of server application


// This class starts both TCP and UDP server connections. Just
the TCP will be shown.

import java.io.IOException;

import java.util.logging.Level;

import java.util.logging.Logger;


public
class ListenerManager {






private static TCPTestServer unsecuredServer;


private static UDPTestReceiver theUDPReceiver;




public static void initialize(){




try{


System.out.println("Server started...");


unsecuredServer = new TCPTestServer(7894, false);


unsecuredServer.start();


try


{


//theUDPReceiver = new UDPTestReceiver(2009,
"lbsbook");


//theUDPReceiver.start();



} catch (Exception ex) {


Logger.getLogger(ListenerManager.class.getName()).log(Level.SEVERE,
null, ex);


}




}catch(IOException ioex){


System.err.println("Error initializing a TCPTestServer!");



ioex.printStackTrace();


}



}




public static void shutdown(){




if (unsecuredServer != null && unsecuredServer.isAlive()){


unsecuredServer.shutdown();


unsecuredServer = null;


}



if (theUDPReceiver != null && theUDPReceiver.isAlive()){


theUDPReceiver.setActive(false);


}


}


}







Page
7

of
10

//Package for database manipulation

import java.sql.*;


//Packages for communication

import java.io.IOException;

import
java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;


import java.util.LinkedList;



public class TCPTestServer extends Thread {




private final int port;


// private final boolean secure;




private ServerSocket serv_socket;




private LinkedList<ConnectionDump> dump_list;




/**


* Takes in a port number and binds a ServerSocket to that port and
listens for it.


* @param port port number to listen to


* @pa
ram secure if the connection is to be secure


* @throws java.io.IOException if the socket could not be created.


*/


public TCPTestServer(int port,boolean secure) throws IOException {


this.port = port;


this.serv_socket = ne
w ServerSocket(port);


// set blocking timeout for accept() call


this.serv_socket.setSoTimeout(10*1000);


this.dump_list = new LinkedList<ConnectionDump>();


}




@Override


public void run(){


Socket tmp_socket = new Soc
ket();



//System.out.println("TCPTestServer
-

now accepting incoming
connections...");




while (this.serv_socket != null){


try{
// this blocks for 10 seconds.


tmp_socket =
this.serv_socket.accept();


if(tmp_socket.isConnected())


{this.dump_list.add(new ConnectionDump(tmp_socket));}


}catch(IOException _){}


finally{ tmp_socket = null;}


}


}





public void shutdown(){


try{


this.serv_socket.close();



Page
8

of
10


for (ConnectionDump dump : this.dump_list){


dump.shutdown();


}


}catch(IOException _){}


this.serv_socket = null;


}




protected class Connec
tionDump extends Thread{




Socket sock;


InputStream instream;


boolean active;




public ConnectionDump(Socket sock){


this.sock = sock;


if (sock.isConnected()){


try{


this.instream = sock.getInputStream();


}catch(IOException ioex){


System.err.println("Error getting inputstream for
incoming connection.");


ioex.printStackTrace();


}


}


this.active = true;


this.start();


}



@override


public void run(){


while(active){


try{


byte[] b = new byte[124];


this.instream.read(b); // just throwing away bytes
read from the stream


String data = new String(b);

//Define the finalization condition for the
connection


if(!data.startsWith("end")){


System.out.println("TCPTestServer
-

incoming
string:" + data);


saveData(data);


}else{


active = false;


this.shutdown();


}


}catch(IOException ioex){


System.err.println("Error reading from
inputstream");


ioex.printStackTrace();


this.shutdown();


}


}


}





public void shutdown() {


this.active = false;



Page
9

of
10


try {


this.instream.close();


this.sock.close();


} catch (IOException _) {


// just fail silently


this.instream

= null;


this.sock = null;


}


System.out.println("Connection Closed!");


}


}


public void saveData(String data){



try{





/*Establishing the connection with the database. The name
of the database is the JDBC Resource registered in the server where
this application will be deployed.*/



javax.naming.InitialContext ic =


new javax.naming.InitialConte
xt();



javax.sql.DataSource dataSource =


(javax.sql.DataSource)ic.lookup("jdbc/__lbsbook");



Connection lbs_book = dataSource.getConnection();





// Just for debugging


System.out.println("Saving data:

"+data);




// All operations on the databases are defined here!



double XLong=0, YLat=0;


long timefix=0;


String[] data_fields;



data_fields = data.split("@");



//Obtain individual fields from the data


if(data_fields.length == 4){


try{


XLong = Double.parseDouble(data_fields[0]);


YLat = Double.parseDouble(data_fields[1]);


tim
efix = Long.parseLong(data_fields[2]);


}catch(Exception ex){ex.printStackTrace();}


}


// Creating SQL statement

to instert data in the database


PreparedStatement insertStatement =
lbs_book.prepareStatement("INSERT

INTO tracking (tracking_id,
date_collection, shift_id, tracking_point, date_insertion) VALUES
(nextval('tracking_point_sequence'),?,?,ST_GeomFromText(?,32661),?)");




//Update fields in the prepared statement


insertStatement.setTimestamp(1,ne
w
java.sql.Timestamp(timefix));



Page
10

of
10



insertStatement.setLong(2, 9999);



String coordinate = "POINT("+XLong+" "+YLat+")";



insertStatement.setString(3,coordinate);



insertStatement.setTimestamp(4,new java.sql.Time
stamp(new
java.util.Date().getTime()));




//Execute SQL statement


insertStatement.executeUpdate();




//Just for debugging


System.out.println("Saving complete!");




//Close DB connection


lbs_book.close();



}catch(Exception ex){ex.printStackTrace();}




}


}



Exercise 1

Run the application described above
.


Exercise 2
Modify the application described above so that now the client uses the
Location API to request GPS fixes every four seconds and
use UDP to send and store the
fixes in the database.


Exercise 3

Test your
application in

a real cellular phone (OPTIONAL)


This part is optional but highly recommended. The more experience you get deploying
your applications in real phones and networks,
the better.



Report


Turn in your software and a written report including:

1.

N
ame

of group members

2.

D
ate of the project’s submission

3.

Names of all project folders submitted

4.

A brief set of instructions for using your application

5.

Design of the datab
a
se

6.

Screen
shots of your application, as appropriate

7.

A brief summary of the activities and description of any problems you
encountered