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

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

import org.infinispan.client.hotrod.DefaultTemplate;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent;
import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;

public class TestFunctional {
    @ClientListener
    private static class MyListener {
        @ClientCacheEntryCreated
        public void entryAdded(ClientCacheEntryCreatedEvent<String> e) {
            System.out.printf("Add : %s\n", e.getKey());
        }
        @ClientCacheEntryRemoved
        public void entryRemoved(ClientCacheEntryRemovedEvent<String> e) {
            System.out.printf("Remove : %s\n", e.getKey());
        }
    }
    private static void test(RemoteCache<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.addClientListener(new MyListener());
        cache.put("x", 123);
        cache.remove("x");
        Thread.sleep(10); // ensure sufficient time to call listener 
    }
    public static void main(String[] args) throws Exception {
          ConfigurationBuilder b = new ConfigurationBuilder();
          b.addServer().host("localhost").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
          RemoteCacheManager rcm = new RemoteCacheManager(b.build());
          RemoteCache<String,Integer> cache = rcm.administration().getOrCreateCache("functional_cache", DefaultTemplate.DIST_SYNC);
          test(cache);
          rcm.stop();
          rcm.close();
    }
}
