HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"A Beginner's Guide to Writing Applications for the MID Profile"
Vol. 6, Issue 9, p. 114

	


Listing 1 PhoneEJB.java

import java.io.*;
import java.g.*;
import javax.ejb.*;


public class PhoneEJB implements SessionBean {


  String user;
  Map phoneBook;


  public void ejbCreate(String user) throws CreateException {


    DataInputStream dis = null;


    try {
      if (user == null) {
        throw new CreateException("Null user not allowed.");
      }
      else {
        this.user = user;
      }


      phoneBook = new HashMap();


      File f = new File(user + ".dat");
      if (f.exists() && f.canRead()) {
        dis = new DataInputStream(new FileInputStream(f));


        while (dis.available() > 0) {
          String name = dis.readUTF();
          String phone = dis.readUTF();


          phoneBook.put(name,phone);
        }
      }
    }
    catch (IOException e) {
      throw new CreateException("unable to read data file : " + e.getMessage());
    }
    finally {
      if (dis != null) {
        try { dis.close(); } catch (Exception e) { }
        dis = null;
      }
    } 


  }


  public void ejbRemove() {
    DataOutputStream dos = null;
    try {
      dos = new DataOutputStream(new FileOutputStream(user + ".dat"));


      Iterator iter = phoneBook.keySet().iterator();
      String name, phone;
      while (iter.hasNext()) {
        name = (String)iter.next();
        phone = (String)phoneBook.get(name);


        dos.writeUTF(name);
        dos.writeUTF(phone);
      }


    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      if (dos != null) {
        try { dos.close(); } catch (Exception e) { }
        dos = null;
      }
    }


  }



  public void add(String name, String phone) {
    phoneBook.put(name, phone);
  }


  public void remove(String name) {
    if (phoneBook.containsKey(name)) {
      phoneBook.remove(name);
    }
  }


  public Map getPhoneBook() {
    return phoneBook;
  }


  public PhoneEJB() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void setSessionContext(SessionContext sc) {}


}




Listing 2 : TestPhoneServlet.java (part of doGet method)

1.    Context initial = new InitialContext();
2.    Object objref   = initial.lookup("MyPhoneEJB");
3.
4.    PhoneHome home  = (PhoneHome)PortableRemoteObject.narrow(objref, PhoneHome.class);
5.
6.    phoneejb  = home.create("test");
7.
8.    action    = request.getParameter("action");
9.    if (action == null || action.equals("")) {
10.
11.     Map phoneBook   = phoneejb.getPhoneBook();
12.
13.     Iterator iter = phoneBook.keySet().iterator();
14.     while (iter.hasNext()) {
15.       String name = (String)iter.next();
16.       String phone = (String)phoneBook.get(name);
17.
18.       out.println(name + phone);
19.     }
20.
21.   }
22.   else if (action.equals("add")) {
23.     String name = request.getParameter("name");
24.     String phone = request.getParameter("phone");
25.     if (name == null || phone == null) {
26.       throw new Exception("missing name and/or phone");
27.     }
28.
29.     phoneejb.add(name,phone);
30.
31.     out.println("");
32.   }
33.   else if (action.equals("remove")) {
34.     String name = request.getParameter("name");
35.     if (name == null) {
36.       throw new Exception("missing name");
37.     }
38.
39.     phoneejb.remove(name);
40.
41.     out.println("");
42.   }
43.   else {
44.     out.println("%ERROR : unrecognized command");
45.   }



Listing 3 : PhoneBook.java (initRecordStore method)

private final void initRecordStore() throws Exception {
    store = RecordStore.openRecordStore("PhoneBook",true);


    String s = sendToServer("http://localhost:8080/servlet/TestPhoneServlet");


    if (s != null && !s.equals("") && !s.startsWith("%ERROR")) {
      recordEnum = store.enumerateRecords(null, pbcomp, false);
      while (recordEnum.hasNextElement()) {
        int id = recordEnum.nextRecordId();


        store.deleteRecord(id);
      }


      String line = "";
      for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '\n') {
          if (line.length() > 0) {
save(line.substring(0,MAX_NAME_LENGTH),line.substring(MAX_NAME_LENGTH), false);
          }


          line = "";
        }
        else {
          line += s.charAt(i);
        }
      }
      if (line.length() > 0) {
save(line.substring(0,MAX_NAME_LENGTH),line.substring(MAX_NAME_LENGTH), false);
      }
    }


    recordEnum = store.enumerateRecords(null, pbcomp, false);
  }




Listing 4 : PhoneBook.java (save and erase methods)

/**
  * save a name and phone number to the record store
  */
  private final void save(String name, String phone, boolean sendToServer) throws Exception {
    if (isEmpty(name)) {
      throw new Exception("No name entered");
    }
    else if (isEmpty(phone)) {
      throw new Exception("No phone entered");
    }
    else if (name.length() > MAX_NAME_LENGTH) {
      throw new Exception("Name too long, max=" + MAX_NAME_LENGTH);
    }
    else {
      byte n[] = rpad(name,10,' ').getBytes();
      byte p[] = rpad(phone,0,' ').getBytes();
      byte rec[] = new byte[n.length + p.length];
      System.arraycopy(n,0,rec,0,n.length);
      System.arraycopy(p,0,rec,n.length,p.length);


      if (sendToServer) {
        String send = "http://localhost:8080/servlet/TestPhoneServlet?action=add&name=" + rpad(replace(name,' ','+'),10,'+') + "&phone=" + phone;
        String rtn = sendToServer(send);


        if (rtn != null && !rtn.trim().equals("")) {
          throw new Exception("Server error : "+ rtn);
        }
      }


      store.addRecord(rec,0,rec.length);



      n = null;
      p = null;
      rec = null;
    }
  }


 /**
  * erase the current record
  */
  private final void erase(boolean sendToServer) throws Exception {
    if (currentRecordID < 0) {
      return;
    }


    try {
      if (sendToServer) {
        String send = "http://localhost:8080/servlet/TestPhoneServlet?action=remove&name=" + rpad(replace(list.getName(),' ','+'),10,'+');
        String rtn = sendToServer(send);


        if (rtn != null && !rtn.trim().equals("")) {
          throw new Exception("Server error : "+ rtn);
        }
      }



      store.deleteRecord(currentRecordID);
      if (store.getNumRecords() < 1) {
        currentRecordID = -1;
        set(null);
      }
    }
    catch (InvalidRecordIDException irie) {
      throw new Exception("Invalid record");
    }
    catch (Exception e) {
      throw new Exception("Unhandled.");
    }


  }

  
 
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.