MorkaLork Development

Interesting stuff I've picked up over the years...

Network connection part 2: Read from the server

2009-07-20 13:22:54 | 345 views | java network server netbeans tomcat

What are we going to do?


We are going to create a Web application and a MIDlet that will read files from that web application.
We will create two projects, WebApplication1 (a web application) and HttpProject (a MIDlet).
The web application will host a file called java.txt which is the one we will read from the MIDlet.

This article will also show how to create a web application using a Tomcat server.


Creating a web application


Take these steps to create a web application:

Press New Project

Choose project:
Java Web -> Web Application

Next

Name and Location:
Project name: WebApplication1
The rest as default

Next

Server and Settings:
Add to Enterprise Application: <none>
Server: Tomcat 6.0 (or whatever version)
The rest as default

Next

Frameworks:
As default

Finish


Now, if you run this web application (enter 'http://localhost:8080/' in a browser), the index.jsp file will be launched in your browser of choice. This file can be altered in any way you want, but it's not something we'll bother with right now.
Create a text file in the Web Pages map, call it java.txt and fill it with a couple of lines of text, here is an exquisite example:


Hello World!
What a boring world...
GOOD BYE WORLD!


Marvelous! Now we have a web application with a file to read! It should look like this:
The project explorer after creating java.txt


The MIDlet


Our mobile application will be connecting to our web application and read it over a network connection.
Create a new project, J2ME, with a MIDlet. Call the project HttpProject and the MIDlet ReadTextFile.java (the naming of files is however not that vital, it's just to avoid missunderstandings).

The ReadTextFile MIDlet will read and display the java.txt file located on the web application. The code looks like this:


package org.morkalork.http;


import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* An applet to read files from a network
* @author maffelu
*/
public class ReadTextFile extends MIDlet implements CommandListener{
//======================FIELDS===================
private String url = "http://localhost:8080/WebApplication1/java.txt";
private Command cmdExit;
private Command cmdRead;
private TextBox textBox;

//=====================PROPERTIES================
/**
* Returns an exit command
* @return A Command object
*/
public Command getCmdExit(){
if(cmdExit == null){
cmdExit = new Command("Exit", Command.EXIT, 0);
}
return cmdExit;
}

/**
* Returns a read command
* @return A Command object
*/
public Command getCmdRead(){
if(cmdRead == null){
cmdRead = new Command("Read", Command.OK, 1);
}
return cmdRead;
}

/**
* Returns a textbox
* @return A TextBox object
*/
public TextBox getTextBox(){
if(textBox == null){
textBox = new TextBox("TextFileTest", "Click to fetch textfile...", 255, TextField.ANY);
textBox.addCommand(getCmdExit());
textBox.addCommand(getCmdRead());
textBox.setCommandListener(this);
}
return textBox;
}

//====================METHODS==========================
public Display getDisplay(){
return Display.getDisplay(this);
}

/**
* Switches the current display
* @param alert An alert object, can be NULL
* @param displayable The displayable object to switch to
*/
public void switchDisplay(Alert alert, Displayable displayable){
Display display = getDisplay();
if(alert == null){
display.setCurrent(displayable);
} else {
display.setCurrent(alert, displayable);
}
}

public void startMIDlet(){
switchDisplay(null, getTextBox());
}

public void exitMIDlet(){
switchDisplay(null, null);
destroyApp(true);
notifyDestroyed();
}

/**
* Reads the textfile and outputs it in the TextBox
* @param urlString The address to the file to read
*/
private void readTextFile(String urlString){
StreamConnection conn = null;
InputStream in = null;
StringBuffer data = new StringBuffer();
try{
conn = (StreamConnection)Connector.open(urlString);
in = conn.openInputStream();
int ch;
while((ch = in.read()) != -1){
data.append((char)ch);
}
} catch (IOException ioe){
System.err.println(ioe.getMessage());
} finally {
try{
if(in != null){
in.close();
}
if(conn != null){
conn.close();
}
} catch (IOException ioe){
System.err.println(ioe.getMessage());
}
}
textBox.setString(data.toString());
switchDisplay(null, textBox);
}

public void commandAction(Command command, Displayable displayable){
if(displayable == textBox){
if(command == cmdExit){
exitMIDlet();
} else if(command == cmdRead){
Form waitForm = new Form("Wait");
switchDisplay(null, waitForm);
Thread t = new Thread(){
public void run(){
readTextFile(url);
}
};
t.start();
}
}
}

public void startApp() {
startMIDlet();
}


public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}


The interesting part here is of course the readTextFile method. This method takes a urlString as parameter and the connects to this url by using the StreamConnection interface and the Connector class.
It really isn't very complicated, these four lines are the core of the method:


conn = (StreamConnection)Connector.open(urlString);
in = conn.openInputStream();
int ch;
while((ch = in.read()) != -1){
data.append((char)ch);
}


They open a connection and then opens an input stream from which it reads the file char by char (appending it to a StringBuffer object).


Screenshots



The opening screen telling you what to do:

The opening screen


A warning that you are planning on using airtime:

A warning, oh nose!


Aha, we managed to read the file! Success!!!
The text, read from the web application



Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.