Skip to content
Marcin Kłopotek edited this page Oct 15, 2019 · 2 revisions

Take a look airomem-chatsample. This is simple chat system (web based) build on airomem. Besides this is JEE7 project.

Domain

Domain consists of three classes:

How do we controll the domain?

See ChatControllerImpl.

@ApplicationScoped
public class ChatControllerImpl implements ChatController {

    private PersistenceController<DataRoot<ChatView, Chat>, ChatView> controller;

    @PostConstruct
    void initController() {
        final PersistenceFactory factory = new PersistenceFactory();
        controller = factory.initOptional("chat", () -> new DataRoot<>(new Chat()));
    }

    @Override
    public List<MessageView> getRecentMessages() {
        return controller.query((view) -> view.getRecentMessages());
    }

    public void addMessage(String nick, String message) {
        controller.execute((chat, ctx) -> {
            chat.getDataObject().addMessage(nick, message, LocalDateTime.ofInstant(ctx.time, ZoneId.systemDefault()));
        });
    }
}
  • In initController persistence is initialized (controller object is like PersistenceContext in JEE),
  • In getRecentMessages last messages are queried to display them in a Page.
  • In addMessage a new message (from web) is stored,
(chat, ctx) -> {
    chat.getDataObject().addMessage(nick, message, LocalDateTime.ofInstant(ctx.time, ZoneId.systemDefault()));
}

This is the lambda that changes domain states and this lambda is preserved (in so-called Journal).

In case the system goes down unexpectedly Journal Lambdas are restored and reapplied to model. That's is why... the last argument of addMessages which should be current date looks so (instead of LocalDateTime.now()). This one of few things to remember.

So how does Chat class look like?

... it is just java object.

public class Chat implements ChatView, Serializable {

    private CopyOnWriteArrayList<Message> messages;

    public Chat() {
        this.messages = new CopyOnWriteArrayList<>();
    }

    public void addMessage(String nick, String content, LocalDateTime time) {
        assert WriteChecker.hasPrevalanceContext();
        final Author author = new Author(nick);
        final Message msg = new Message(author, content, time);
        this.messages.add(msg);

    }

    @Override
    public List<MessageView> getRecentMessages() {
        int count = this.messages.size();
        final List<MessageView> res = this.messages.stream().skip(Math.max(count - 10, 0))
                .limit(10)
                .collect(Collectors.toList());
        return res;
    }
}

And that is all...