Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for display Fibonacci series in Midlet
Previous Home Next

Introduction

In program, a Http request is made form Midlet to Java Servlet which run on Web Server ( Apache Tomcat ) through HTTP POST method to access doPost method ofservlet in Midlet.

In which a string is passing to servlet through Midlet class and get requested series form servlet, which further display in Midlet client class.

Midlet Program


/*
 * Save as a FibonacciMidlet.java
 */
package r4r.Mobile.Application;

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

/**
 * @author R4R
 */
public class FibonacciMidlet extends MIDlet implements CommandListener {

    final Command OK = new Command("OK", Command.OK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private Form form;
    private TextField T_num;

    public FibonacciMidlet() {
        // declaration field with initialization
        form = new Form("Generate Fibonacci Series");
        T_num = new TextField("Series Generate Upto # ", "", 2, TextField.NUMERIC);
        form.append(T_num);
        form.addCommand(OK);
        form.addCommand(EXIT);
        form.setCommandListener(this);
    }

    public void startApp() {
        Display.getDisplay(this).setCurrent(form);
    }

    public void pauseApp() {
    }

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

    public void commandAction(Command c, Displayable d) {
        if (c == EXIT) {
            destroyApp(true);   //terminate application
        } else if (c == OK) {
            // Store value form TextField to String 
            String num = T_num.getString().trim();
            // User can't allow to leave any TextField blank
            if (!num.equals("")) {
                // initialize new Class
                FibonacciClient client = new FibonacciClient(this, num);
                client.start();
            } else {
                Alert a = new Alert("Blank Field Error", 
					"Please Don't leave any Block empty!", null, AlertType.ALARM);
                a.setTimeout(1000);
                Display.getDisplay(this).setCurrent(a, d);
            }
        }
    }
}

/*
 * --------------------------------------------------
 * Class FibonacciClient handle Client side request 
 * or Receive server response.
 * --------------------------------------------------
 */
class FibonacciClient implements Runnable, CommandListener {

    //client can invoke servlet through SERVLET_URL 
    final String SERVLET_URL = "http://localhost:8084/MobileServlet/FibonacciServlet";
    final Command BACK = new Command("Back", Command.BACK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private FibonacciMidlet parent;
    private Display display;
    private TextBox tb;
    private String num;
    private HttpConnection hc;
    private InputStream is;
    private OutputStream os;
    StringBuffer sb = new StringBuffer();

    FibonacciClient(FibonacciMidlet aThis, String num) {
        this.parent = aThis;  //set field
        this.num = num;

        // declaration field with initialization
        display = Display.getDisplay(aThis);
        tb = new TextBox("Client Site Response..", null, 1024, 0);
        tb.addCommand(BACK);
        tb.addCommand(EXIT);
        tb.setCommandListener(this);
        display.setCurrent(tb);
    }

    void start() {
        // invoke new thread and begin in execution
        new Thread(this).start();
    }

    public void run() {
        try {
            //Open HTTP connection 
            hc = (HttpConnection) Connector.open(SERVLET_URL);
            // client access servlet POST method 
            hc.setRequestMethod(HttpConnection.POST);
            //Sets the general request property 
            hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            hc.setRequestProperty("CONTENT-TYPE", "application/x-www-form-encoded");

            //Open DataOutputStream and write data into Stream(in byte form)
            os = hc.openDataOutputStream();
            os.write((num).getBytes());
            os.flush();

            //Open DataInputStream for a connection.
            is = hc.openDataInputStream();
            int ch;
            //Read the data form DataInputStream
            while ((ch = is.read()) != -1) {
                sb.append((char) ch);           // Convert Byte to character
                System.out.println((char) ch);  // Display data on console
            }
            tb.setString(sb.toString());        // append String to the TextBox
        } catch (IOException ex) {
            Alert a = new Alert("SERVLET Server Error!",
				"Cannot connect to server. Ping to
			server and make sure it's in running state....",
                      null, AlertType.ERROR);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);
        } finally {
            // close all the Stream and connection
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == BACK) {
            parent.startApp();        // Invoke Startapp() method
        } else if (c == EXIT || c == Alert.DISMISS_COMMAND) {
            parent.destroyApp(true);  // terminate application
        }
    }
}

servlet program


/*
 * Save as a FibonacciServlet.java
 */
package r4r.MobileServlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author R4R
 */
public class FibonacciServlet extends HttpServlet {

    //private Field
    private int MAX_INDEX = 0;
    private String value = null;

    @Override
    protected void doGet(HttpServletRequest request,
		HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request,
		HttpServletResponse response)
            throws ServletException, IOException {

        // Set the response message's MIME type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Reads line of text from a character-input stream
        BufferedReader br = request.getReader();
        // Get a Specific String value from line of text.
        String s = br.readLine();
        // Convert number into Integer
        MAX_INDEX = Integer.parseInt(s);

        out.println(getServletInfo());
        // Generate Series
        int hi = 1;
        int lo = 1;

        out.println("1 : " + lo);
        for (int i = 2; i < MAX_INDEX; i++) {
            if ((i % 2) == 0) {
                value = "+";
            } else {
                value = "";
            }
            out.println(i + " : " + hi + value);
            hi = lo + hi;
            lo = hi - lo;
        }
        out.close();
    }

    @Override
    public String getServletInfo() {
        return "Fibonacci Series -";
    }
}


output
Previous Home Next