com.oneapm.base.tools.ZookeeperClient.java Source code

Java tutorial

Introduction

Here is the source code for com.oneapm.base.tools.ZookeeperClient.java

Source

package com.oneapm.base.tools;

import com.alibaba.fastjson.JSON;
import com.oneapm.base.alertbean.Alert;
import com.oneapm.base.alertbean.RuleRecover;
import com.oneapm.base.alertbean.Rules;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * zookeeper???
 * Created by tianjin on 3/17/16.
 */
public class ZookeeperClient implements Watcher {

    public static final Logger LOG = LoggerFactory.getLogger(ZookeeperClient.class);

    private static final Properties PROP = Config.getConfig("alert.cnf");

    private static final int SESSION_TIMEOUT = 200000;

    private ZooKeeper zk;

    private List<RuleRecover> rules = new ArrayList<>();

    //    private Map<ClientKey, BaseData> client = new HashMap<>();
    //    private Map<HostKey, BaseData> hostName = new HashMap<>();
    //    private Map<ServiceKey, BaseData> service = new HashMap<>();
    //    private Map<SubnetKey, BaseData> subnet = new HashMap<>();
    //    private Map<VlanKey, BaseData> vlan = new HashMap<>();

    private int detect_interval;

    private String license;

    public String getLicense() {
        return license;
    }

    public void setLicense(String path) {
        String data = readData(path);
        if (isExists(path) && data != null) {
            this.license = data;
        } else {
            this.license = "";
        }
    }

    private ZookeeperClient() {
        super();
    }

    public static final ZookeeperClient getInstance() {
        return LazyHolder.INSTANCE;
    }

    private static class LazyHolder {
        private static final ZookeeperClient INSTANCE = new ZookeeperClient();
    }

    public static void main(String[] args) {
        ZookeeperClient zookeeperClient = ZookeeperClient.getInstance();
        zookeeperClient.connectZookeeper("10.128.9.207:2181");
        zookeeperClient.setLicense("/ni/license");
        String license = zookeeperClient.getLicense();
        String ok = license.split("\n")[3].split("=")[1];
        System.out.println(ok);
    }

    public int getDetect_interval() {
        return detect_interval;
    }

    public void setDetect_interval(int detect_interval) {
        this.detect_interval = detect_interval;
    }

    public List<RuleRecover> getRules() {

        return rules;
    }

    /**
     * ??List<Rule>,???
     *
     * @param path
     */
    public void setRules(String path) {
        String data = readData(path);
        if (isExists(path) && data != null) {
            Rules fullRule = JSON.parseObject(data, Rules.class);
            rules.clear();
            setDetect_interval(Integer.parseInt(fullRule.getDetect_interval()));
            List<Alert> alerts = fullRule.getRules();
            for (Alert al : alerts) {
                RuleRecover recover = new RuleRecover(al.getTrigger_param(), al.getSend_param().getRecovery());
                rules.add(recover);
            }
        }
    }

    /**
     * zookeeper,SESSION_TIMEOUT10000
     *
     * @param address
     */
    public void connectZookeeper(String address) {
        connectZookeeper(address, SESSION_TIMEOUT);
    }

    /**
     * zookeeper,timeout
     *
     * @param address
     * @param sessionTimeout
     */
    public void connectZookeeper(String address, int sessionTimeout) {
        try {
            zk = new ZooKeeper(address, sessionTimeout, this);
            LOG.info("?, address: " + address + ", timeout: " + sessionTimeout);
        } catch (IOException e) {
            LOG.error("? IOException , e " + e.getMessage(), e);
        }
    }

    /**
     * 
     *
     * @param path
     * @param data
     * @return
     */
    public boolean createNode(String path, String data, boolean flag) {

        if (isExists(path)) {
            return true;
        }

        try {
            String zkPath;
            if (flag) {
                zkPath = zk.create(path, data.getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            } else {
                zkPath = zk.create(path, data.getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            }
            LOG.info("?, Path: " + zkPath + ", content: " + data);
            return true;
        } catch (UnsupportedEncodingException e) {
            LOG.error(", ?UnsupportedEncodingException! path: " + path + ", data:" + data
                    + ", errMsg:" + e.getMessage(), e);
        } catch (KeeperException e) {
            LOG.error(", ?KeeperException! path: " + path + ", data:" + data + ", errMsg:"
                    + e.getMessage(), e);
        } catch (InterruptedException e) {
            LOG.error(", ? InterruptedException! path: " + path + ", data:" + data
                    + ", errMsg:" + e.getMessage(), e);
        }
        return false;
    }

    /**
     * 
     *
     * @param path
     * @return
     */
    public boolean deleteNode(String path) {
        try {
            this.zk.delete(path, -1);
            LOG.info("?, Path: " + path);
            return true;
        } catch (KeeperException e) {
            LOG.error(", ?KeeperException! path: " + path + ", errMsg:" + e.getMessage(), e);
        } catch (InterruptedException e) {
            LOG.error(
                    ", ? InterruptedException! path: " + path + ", errMsg:" + e.getMessage(),
                    e);
        }
        return false;
    }

    /**
     * ?
     *
     * @param path
     * @return
     */
    public boolean isExists(String path) {
        try {
            Stat stat = this.zk.exists(path, false);
            return null != stat;
        } catch (KeeperException e) {
            LOG.error("??,?KeeperException! path: " + path + ", errMsg:" + e.getMessage(), e);
        } catch (InterruptedException e) {
            LOG.error("??,?InterruptedException! path: " + path + ", errMsg:" + e.getMessage(),
                    e);
        }
        return false;
    }

    /**
     * ??
     *
     * @param path
     * @param data
     * @return
     */
    public boolean writeData(String path, String data) {
        try {
            Stat stat = zk.setData(path, data.getBytes(), -1);
            //            LOG.info("??, path" + path + ", stat: " + stat);
            return true;
        } catch (KeeperException e) {
            LOG.error("?, ?KeeperException! path: " + path + ", data:" + data + ", errMsg:"
                    + e.getMessage(), e);
        } catch (InterruptedException e) {
            LOG.error("?, ?InterruptedException! path: " + path + ", data:" + data
                    + ", errMsg:" + e.getMessage(), e);
        }

        return false;
    }

    /**
     * ??
     *
     * @param path
     * @return
     */
    public String readData(String path) {
        String data = null;
        try {
            byte[] bt = zk.getData(path, this, null);
            if (bt != null) {
                data = new String(bt);
            }
            LOG.info("???, path:" + path + ", content:" + data);
        } catch (KeeperException e) {
            LOG.error("??,?KeeperException! path: " + path + ", errMsg:" + e.getMessage(), e);
        } catch (InterruptedException e) {
            LOG.error("??,?InterruptedException! path: " + path + ", errMsg:" + e.getMessage(),
                    e);
        }
        return data;
    }

    /**
     * ??,?
     *
     * @param event
     */
    @Override
    public void process(WatchedEvent event) {
        LOG.info("" + event.getState());
        if (event.getType() == Event.EventType.NodeDataChanged && event.getPath().equals("/ni/caution")) {
            setRules(event.getPath());
        }
        if (event.getType() == Event.EventType.NodeDataChanged && event.getPath().equals("/ni/license")) {
            setLicense(event.getPath());
        }
    }

}