Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for send email through localhost
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 of servlet in Midlet. In which a respectively string is passing to servlet through Midlet class and get requested parameter form servlet, which display in Midlet client class.

Midlet Program


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

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

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

    final Command SEND = new Command("Send", Command.SCREEN, 1);
    final Command DISCARD = new Command("Discard", Command.EXIT, 2);
    private Form form;
    private TextField T_from, T_sendTo, T_subject, T_body;

    public emaiServletMidlet() {
        // declaration field with initialization
        form = new Form("Compose Email");
        T_from = new TextField("Form", "", 30, TextField.EMAILADDR);
        T_sendTo = new TextField("Send To", "", 30, TextField.EMAILADDR);
        T_subject = new TextField("Email Subject", "", 40, TextField.ANY);
        T_body = new TextField("Massage", "", 50, TextField.ANY);
        form.append(T_from);
        form.append(T_sendTo);
        form.append(T_subject);
        form.append(T_body);
        form.addCommand(SEND);
        form.addCommand(DISCARD);
        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 == DISCARD) {
            destroyApp(true);  //terminate application
        } else if (c == SEND) {
            // Store value form TextField to String 
            String frm = T_from.getString().trim();
            String to = T_sendTo.getString().trim();
            String subject = T_subject.getString().trim();
            String body = T_body.getString().trim();
            // initialize new Cla
	EmailServletClient client = new EmailServletClient
		(this, frm, to, subject, body);
            client.start();
        }
    }
}

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

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

    EmailServletClient(emaiServletMidlet aThis, String frm, 
		String to, String subject, String body) {
        this.parent = aThis;  // set field
        this.frm = frm;
        this.to = to;
        this.subject = subject;
        this.body = body;

        // declaration field with initialization
        display = Display.getDisplay(aThis);
        tb = new TextBox("Client Site Response....", null, 2024, TextField.ANY);
        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);
            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)
            String data = frm + "?" + to + "?" + subject + "?" + body + "?";
            os = hc.openDataOutputStream();
            os.write((data).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 into character
                System.out.println((char) ch); // Display data on console
            }
            tb.setString(sb.toString());       // data append to textBox 
        } catch (IOException ex) {
            Alert a = new Alert("SERVLET Server Error!", 
				"Cannot connect to server. Ping the 
			server to 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 (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (IOException e) {
            }
        }
    }

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


Servlet Program


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

import java.io.*;
import java.util.Properties;
import java.util.logging.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;

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

    @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();
        String s = br.readLine();

        // Get a Specific String value from line of text.
        String frm = s.substring(0, s.indexOf("?"));

        int start = s.indexOf("?") + 1;
        int end = s.indexOf('?', start + 1);
        String to = s.substring(start, end);

        start = s.indexOf('?', start + 1);
        end = s.indexOf('?', start + 1);
        String subject = s.substring(start + 1, end);

        start = s.indexOf('?', start + 1);
        end = s.indexOf('?', start + 1);
        String body = s.substring(start + 1, end);

        sendMail(frm, to, subject, body);         // invoke sendMail method
        // send response to the client
        out.println("Mail Send through Servlet-- \n");
        out.println(" From =" + frm + "\n TO =" + to +
			"\n Subject =" + subject + "\n Body =" + body);
        out.close();    // close text-output stream 
    }

    /*
     * -----------------------------------------------------
     * Method sendMail handle sending mail through localhost
     * -----------------------------------------------------
     */
    private void sendMail(String frm, String to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "localhost";

        props.setProperty("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        try {
            // set mail property
            message.setFrom(new InternetAddress(frm));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(body);

            // send mail
            Transport.send(message);
            System.out.println("Mail send to -" + to);

        } catch (MessagingException ex) {
            Logger.getLogger(emailServlet.class.getName())
				.log(Level.SEVERE, "An Exception occurred due processing request", ex);
        }
    }
}


output
Previous Home Next