Search code examples
javanetwork-programmingirc

Call function which waits till hashmap changes


When using the api Pircbot (Irc Bot API) i need to call a method which waits till a hasmap gets changed from a different method. Example: User excecutes command !isRegistered. Now Pircbot checks if the user is registererd by NickServ.

@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
    if (command("isRegistered", message) && checkRegistered(sender)) {
        sendMessage(sender,"You are registered);
    }
};

I thought, that a HashMap<String, Boolean> would be the correct way on doing this.

private void checkRegistered(String sender) {
checkRegister.put(Sender,null);
sendMessage("NickServ", "info sender");
//Wait till onNotices changes the HashMap so that i can get an result (hasmap content: null -> true, or false) and returning this result)

//A simple Thread.sleep(); does not work, because everything runs on the main Thread. -> When     sleeping the bot times out, because it can't reply to the /ping command from the server. 
}

Whenever pircbot receives a NOTICE i can get the string with

@Override protected void onNotice(String sourceNick, String sourceLogin, String sourceHostname, String target, String notice) {

So i did this:

@Override
protected void onNotice(String sourceNick, String sourceLogin, String sourceHostname, String target, String notice) {
    if (sourceLogin.equals("NickServ")) {
        for (String s : checkRegister.keySet()) {
            if (notice.contains("Nickname:") && notice.contains(s)) {
                checkRegister.put(s, notice.contains("<< ONLINE >>"));
            }
        }
    }
}

How do i now check if the hasmap changed e.g. from null -> true or from null -> false inside the checkRegistered(); Method?


Solution

  • You could do a mix of Observer-Observable and a HashMap.

    In the beginning, clients register themselves as Observers or the HashMap, and when something changes in the Map then a message would be sent to all Observers.

    Observer sample code:

    http://javarevisited.blogspot.ca/2011/12/observer-design-pattern-java-example.html http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial

    Specifically, to your question "How do i now check if the hasmap changed e.g. from null -> true or from null -> false inside the checkRegistered(); Method?"

    The client would be notified that the value of the attribute was changed from one value to another value, which means, the message would contain the attribute name, the current value, and the new value.