Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

MessageBoard

MessageBoard represents the in-memory repository of messages. It allows messages to be added and retrieved using a Hashtable. Because this entity need not be exposed, it doesn't implement any of the ActionForm interfaces.

Listing 5 MessageBoard.java

import java.util.Hashtable;

public class MessageBoard {
    protected static MessageBoard singleton;
    protected Hashtable messages = new Hashtable();
    protected int count = 1;

    protected MessageBoard() {
        OOMessage firstMessage = new OOMessage();
        String id = count + "";
        firstMessage.setId(id);
        messages.put(id, firstMessage);
        count ++;
    }

    public synchronized OOMessage addMessage(Message msgElements,
           String parentId) {
        if (parentId == null || messages.get(parentId) == null) {
            parentId = "1";
        }
        OOMessage parent = getMessage(parentId);
        String id = count + "";
        msgElements.setId(id);

        OOMessage reply = new OOMessage(msgElements);
        reply.setCurrentTimestamp();
        reply.setParent(parent);
        messages.put(id, reply);

        count++;
        return reply;
    }

    public OOMessage getRootMessage() {
        return (OOMessage) messages.get("1");
    }

    public OOMessage getMessage(String msgId) {
        return (OOMessage) messages.get(msgId);
    }

    public static MessageBoard getSingleton() {
        if (singleton == null) {
            singleton = new MessageBoard();
        }
        return singleton;
    }
}

To provide scalability for the application, you would need to provide persistence for the messages—as in storing them in a database.

In the next article, you will develop the application’s view components.

  • + Share This
  • 🔖 Save To Your Account