package roart.zkutil;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;

import roart.util.Constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZKMessageUtil {

    static Logger log = LoggerFactory.getLogger(ZKMessageUtil.class);

    public static List<String> getChildren(String dir, Watcher watcher) throws KeeperException, InterruptedException {
	    try {
	        return ZKInitialize.zk.getChildren(dir, watcher);
	    } catch (KeeperException.NoNodeException e){
	        throw e;
	    }
	}

	public static void dorefresh(String nodename) {
	if (ZKInitialize.zk == null) {
	    return;
	}
	log.info("sendMsgRefresh");
	try {
	    List<String> nodes = ZKInitialize.zk.getChildren("/" + Constants.AETHER + "/" + Constants.NODES, false);
	    for (String node : nodes) {
		if (!nodename.equals(node)) {
			ZKInitialize.createTempIfNotExists(ZKInitialize.zk, "/" + Constants.AETHER + "/" + Constants.NODES + "/" + node + "/" + Constants.REFRESH);
		    log.info("send refresh to " + node);
		}
	    }
	} catch (Exception e) {
	    log.error(Constants.EXCEPTION, e);
	}
	}

    public static void doreconfig(String nodename) {
    if (ZKInitialize.zk == null) {
        return;
    }
    log.info("sendMsgReconfig");
    try {
        List<String> nodes = ZKInitialize.zk.getChildren("/" + Constants.AETHER + "/" + Constants.NODES, false);
        for (String node : nodes) {
        if (!nodename.equals(node)) {
            ZKInitialize.createTempIfNotExists(ZKInitialize.zk,"/" + Constants.AETHER + "/" + Constants.NODES + "/" + node + "/" + Constants.RECONFIG);
            log.info("send reconfig to " + node);
        }
        }
    } catch (Exception e) {
        log.error(Constants.EXCEPTION, e);
    }
    }

public static class MessageWatcher implements Watcher {

CountDownLatch latch;

public MessageWatcher() {
    try {
	latch = new CountDownLatch(1);
    } catch (Exception e) {
	log.error(Constants.EXCEPTION, e);
    }
}

public void process(WatchedEvent event) {
    log.info("Process " + event.getPath() + " state " + event.getState() + " type " + event.getType());
    if (event.getPath() == null) {
	return;
    }
    latch.countDown();
}

    public void await() throws InterruptedException {
        latch.await();
    }

}

}

@@ -288,16 +288,55 @@
 efs.Ids;
+%0Aimport org.apache.zookeeper.data.Stat;
 %0A%0Aimport
@@ -644,24 +644,79 @@
 %0A%09    try %7B%0A
+%09        Stat i = ZKInitialize.zk.exists(null, false);%0A
 %09        ret

Check exist.