// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package cache.hazelcast;

import java.util.Iterator;
import java.util.Map.Entry;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.map.listener.EntryAddedListener;
import com.hazelcast.map.listener.EntryRemovedListener;

public class TestFunctional {
    private static void test(IMap<String,Integer> cache) throws InterruptedException {
        // basic put, get and remove
        cache.put("v", 123);
        System.out.println(cache.get("v"));
        cache.remove("v");
        System.out.println(cache.get("v"));
        cache.put("v", 123);
        System.out.println(cache.get("v"));
        // persistence
        Integer counter = cache.get("counter");
        if(counter == null) {
            counter = 0;
        }
        counter++;
        System.out.println(counter);
        cache.put("counter", counter);
        // list all (old style)
        Iterator<Entry<String,Integer>> it = cache.entrySet().iterator();
        while(it.hasNext()) {
            Entry<String,Integer> e = it.next();
            System.out.printf("%s = %d\n", e.getKey(), e.getValue());
        }
        // list all (new style)
        cache.forEach((k,v) -> System.out.printf("%s = %d\n", k, v));
        // listener
        cache.addEntryListener(new EntryAddedListener<String,Integer>() {
            @Override
            public void entryAdded(EntryEvent<String, Integer> ee) {
                System.out.printf("Add : %s = %d\n", ee.getKey(), ee.getValue());
            }
        }, true);
        cache.addEntryListener(new EntryRemovedListener<String,Integer>() {
            @Override
            public void entryRemoved(EntryEvent<String, Integer> ee) {
                System.out.printf("Remove : %s\n", ee.getKey());
            }
        }, true);
        cache.put("x", 123);
        cache.remove("x");
        Thread.sleep(10); // ensure sufficient time to call listener 
    }
    public static void main(String[] args) throws Exception {
        ClientConfig cfg = new ClientConfig();
        HazelcastInstance cli = HazelcastClient.newHazelcastClient(cfg);
        IMap<String,Integer> cache = cli.getMap("functional_cache");
        test(cache);
        cli.shutdown();
    }
}
