背景
zookeeper有几个ui工具,但都不支持目录的复制,反正我没有找到。做项目时配置中心使用zk来维护的,当重新搭建环境想私有化一份配置时,那个费劲,既然找不到自己写一个小助手,作为其他ui工具的补充吧~
需求
先写个能凑合用,写一个GUI的,得空再把它写成web的~ 且做的时候比较急,并没有什么设计可言,可能代码稍乱,得空整理一下,马上放假了~ 先放上~build
简单需求:
- 目录复制
- 不同机器复制
- 目录删除
- 级联创建节点
- 查询节点
- 实现简单参数校验
成品截图
输入相应参数时,有校验提示,只做了简单的校验,并未全覆盖
创建更新时,如果节点存在会提示是否覆盖~
动手
创建maven工程~略
配置pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ling.zookeeper</groupId>
<artifactId>zookeeperUtil</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>zookeeperUtil</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<logback.version>1.2.3</logback.version>
<log4j.version>1.7.25</log4j.version>
<slf4j.version>1.7.10</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.1</version>
</dependency>
<!-- 本来想做成自动生成文档,先算了~先解决问题再说完善的事~呵呵-->
<!-- <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency> -->
</dependencies>
</project>
首先实现Watcher
@Override
public void process(WatchedEvent event){}
实现基本的连接、关闭、增、删、改、查等操作
package com.ling.zookeeper.zookeeperUtil;
import (略)
/**
*
* @author yueling
*
*/
public class BaseZookeeper implements Watcher
{
private final static Logger logger = LoggerFactory.getLogger(BaseZookeeper.class);
public ZooKeeper zooKeeper;
private static final int SESSION_TIME_OUT = 2000;
private CountDownLatch countDownLatch = new CountDownLatch(1);
/**
* 连接zookeeper
*
* @param host
* @throws IOException
* @throws InterruptedException
*/
public void connectZookeeper(String host) throws IOException,
InterruptedException
{
zooKeeper = new ZooKeeper(host, SESSION_TIME_OUT, this);
countDownLatch.await();
logger.info("--------connect zookeeper success-----------");
}
/**
* 实现watcher的接口方法,当连接zookeeper成功后,zookeeper会通过此方法通知watcher<br>
* 此处为如果接受到连接成功的event,则countDown,让当前线程继续其他事情。
*/
@Override
public void process(WatchedEvent event)
{
if (event.getState() == KeeperState.SyncConnected)
{
logger.info("--------watcher received event-----------");
countDownLatch.countDown();
}
}
/**
* 根据路径创建节点,并且设置节点数据
* @param path
* @param data
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public String createNode(String path, byte[] data) throws KeeperException,
InterruptedException
{
return this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
/**
* 根据路径创建节点,并且设置节点数据
* @param path
* @param data
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public String create(String path, byte[] data) throws KeeperException,InterruptedException
{
try {
/*List<String> nodes = zooKeeper.getChildren(groupName, false);
for (String node : nodes) {
delete(groupName + "/" + node);
}
zooKeeper.create(groupName, -1);
logger.info("delete {}",groupName);*/
} catch (Exception e) {
e.printStackTrace();
}
return this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
/**
* 根据路径获取所有孩子节点
*
* @param path
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public List<String> getChildren(String path) throws KeeperException,
InterruptedException
{
return this.zooKeeper.getChildren(path, false);
}
public Stat setData(String path, byte [] data, int version) throws KeeperException, InterruptedException
{
return this.zooKeeper.setData(path, data, version);
}
/**
* 根据路径获取节点数据
*
* @param path
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public byte[] getData(String path) throws KeeperException,
InterruptedException
{
return this.zooKeeper.getData(path, false, null);
}
/**
* 删除节点
*
* @param path
* @param version
* @throws InterruptedException
* @throws KeeperException
*/
public void deletNode(String path, int version)
throws InterruptedException, KeeperException
{
this.zooKeeper.delete(path, version);
}
/**
* 删除节点(递归)
*
* @param path
* @param version
* @throws InterruptedException
* @throws KeeperException
*/
public void delete(String groupName) throws Exception {
//String path = "/" + groupName;
try {
List<String> nodes = zooKeeper.getChildren(groupName, false);
for (String node : nodes) {
delete(groupName + "/" + node);
}
zooKeeper.delete(groupName, -1);
logger.info("delete {}",groupName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭zookeeper连接
*
* @throws InterruptedException
*/
public void closeConnect() throws InterruptedException
{
if (null != zooKeeper)
{
zooKeeper.close();
}
}
}
写一些逻辑处理
package com.ling.zookeeper.zookeeperUtil;
import (略)
/**
*
* @author yueling
* zookeeper操作集合
*/
public class ZkUtils {
private final static Logger logger = LoggerFactory.getLogger(ZkUtils.class);
/**
* zk设置节点值
*
* @param node:zookeeper
* node path
* @param data:new
* value for update
* @param baseZookeeper:zookeeper
*/
public static void zkSetNodeData(String node, String data, BaseZookeeper baseZookeeper) {
try {
baseZookeeper.setData(node, data.getBytes(), -1);
} catch (KeeperException |InterruptedException e) {
logger.error("context", e);
}
}
/**
* zk获取节点数据
*
* @param node
* @param baseZookeeper
* @return
*/
public static String zkGetNodeData(String node, BaseZookeeper baseZookeeper) {
byte[] nodeData = null;
try {
nodeData = baseZookeeper.getData(node);
} catch (KeeperException |InterruptedException e) {
logger.error("context", e);
}
return new String(nodeData);
}
/**
* zk删除节点(递归)
*
* @param node
* @param baseZookeeper
*/
public static void zkRmNode(String node, BaseZookeeper baseZookeeper) {
try {
baseZookeeper.delete(node);
logger.info("delete [{}] sucess", node);
} catch (Exception e) {
logger.error("context", e);
}
}
/**
* 删除节点初始化,参数验证并返回提示信息
* @param node
* @param baseZookeeper
* @return
*/
public static String zkRmNodeInit(String node, BaseZookeeper baseZookeeper) {
boolean checkParam = true;
String result="";
//先格式化一下
if (node.trim().endsWith("/")) {
node=node.trim().substring(0, node.trim().length()-1);
}
if (!node.startsWith("/")) {
checkParam=false;
result=result+"待删除节点路径不正确\n";
}
if(!isExist(node, baseZookeeper)){
checkParam=false;
result=result+"源节点不存在\n";
logger.info("源节点不存在");
}
if (checkParam) {
result=result+"开始删除节点:"+node;
zkRmNode(node,baseZookeeper);
result=result+"删除结束";
}else {
logger.info("检查配置 :\n\n{}",result);
}
return result;
}
/**
* 创建和更新参数化检查并返回结果.如果节点存在提示是否更新;如果节点不存在创建
* @param node
* @param data
* @param baseZookeeper
* @return
*/
public static String zkCreateNodeInit(String node, String data,BaseZookeeper baseZookeeper) {
boolean checkParam = true;
String result="";
//先格式化一下
if (node.trim().endsWith("/")) {
node=node.trim().substring(0, node.trim().length()-1);
}
if (!node.startsWith("/")) {
checkParam=false;
result=result+"节点路径不正确\n";
}
if (checkParam) {
if(!isExist(node, baseZookeeper)){
//创建~
String [] pathArr=node.split("/");
String path="/";
for (int i = 1; i < pathArr.length; i++) {
path=path+pathArr[i];
if(!isExist(path, baseZookeeper)){
if (i==pathArr.length-1) {
zkCreateNode(path, data, baseZookeeper);
} else {
zkCreateNode(path, "", baseZookeeper);
}
}
path=path+"/";
}
logger.info("节点不存在,创建");
}else {
//覆盖
int res=JOptionPane.showConfirmDialog(null, "是否覆盖");
if (res==JOptionPane.YES_OPTION) {
zkSetNodeData(node, data, baseZookeeper);
}
}
}else {
logger.info("检查配置 :\n\n{}",result);
}
return result;
}
/**
* 查询参数验证并返回结果
* @param node
* @param baseZookeeper
* @return
*/
public static String zkQueryNodeInit(String node, BaseZookeeper baseZookeeper) {
boolean checkParam = true;
String result="";
//先格式化一下
if (node.trim().endsWith("/")) {
node=node.trim().substring(0, node.trim().length()-1);
}
if (!node.startsWith("/")) {
checkParam=false;
result=result+"节点路径不正确\n";
}
if(!isExist(node, baseZookeeper)){
checkParam=false;
result=result+"源节点不存在\n";
logger.info("源节点不存在");
}
if (checkParam) {
result=result+node+"="+zkGetNodeData(node,baseZookeeper);
result=result+"查询结束";
}else {
logger.info("检查配置 :\n\n{}",result);
}
return result;
}
/**
* zk创建单个的节点
*
* @param node
* @param baseZookeeper
*/
public static String zkCreateNode(String node, String data, BaseZookeeper baseZookeeper) {
String returnPath = null;
try {
returnPath = baseZookeeper.createNode(node, data.getBytes());
} catch (KeeperException |InterruptedException e) {
logger.error("context", e);
}
return returnPath;
}
/**
* zk复制节点(包括子节点)
*
* 限制:同一个zk实例上的复制
*
* @param node
* @param destNode
* @param baseZookeeper
*/
public static void zkCopyNodes(String node, String destNode, BaseZookeeper baseZookeeper) {
zkCopyNodes(node, destNode, baseZookeeper, baseZookeeper);
}
/**
* zk复制节点(包括子节点)
*
* 在同一个zk实例、不同实例之间、不同机器之间复制
*
* @param node
* @param destNode
* @param baseZookeeper
* @param destZookeeper
*/
public static void zkCopyNodes(String node, String destNode, BaseZookeeper baseZookeeper,
BaseZookeeper destZookeeper) {
zkCreateNode(destNode, zkGetNodeData(node, baseZookeeper), destZookeeper);
if (zkHasChildNode(node, baseZookeeper)) {
List<String> list = zkGetChildNode(node, baseZookeeper);
for (int i = 0; i < list.size(); i++) {
zkCopyNodes(node + "/" + list.get(i), destNode + "/" + list.get(i), baseZookeeper, destZookeeper);
}
}
}
/**
* zk复制节点包括子节点
*
* 在同一个zk实例、不同实例之间、不同机器之间
*
* @param node
* @param destNode
* @param baseZookeeper
* @param destZookeeper
*/
public static String zkCopyNodesInit(String node,String destNode,BaseZookeeper baseZookeeper,BaseZookeeper destZookeeper) {
/*
* 检查node在baseZookeeper上是否存在
* 检查destNode在destZookeeper上是否存在
*
* 如果目录存在
* 覆盖:先删除
* 取消:终止操作(保险)
* 合并:逐级合并(有风险,挖个坑先不实现……不服你来)
*
*/
//没有合适的api如何……自己写,从根遍历
//是否是合法路径 是否以/开始 startwith
//是否包含非法字符 删除末尾空格和/
//
//传入路径和值 返回是否存在的结果
boolean checkParam = true;
String result="";
//先格式化一下
if (node.trim().endsWith("/")) {
node=node.trim().substring(0, node.trim().length()-2);
}
if (destNode.trim().endsWith("/")) {
destNode=destNode.trim().substring(0, destNode.trim().length()-2);
}
if (!node.startsWith("/")) {
checkParam=false;
result=result+"源节点路径不正确\n";
}
if (!destNode.startsWith("/")) {
checkParam=false;
result=result+"目标节点路径不正确\n";
}
if(!isExist(node, baseZookeeper)){
checkParam=false;
result=result+"源节点不存在\n";
logger.info("源节点不存在");
}
if(isExist(destNode, destZookeeper,1)){
if(isExist(destNode, destZookeeper)){
checkParam=false;
result=result+"目标节点已经存在\n";
logger.info("目标节点已经存在");
}
}else {
checkParam=false;
result=result+"目标节点的父节点不存在\n";
logger.info("目标节点的父节点不存在");
}
if (checkParam) {
result=result+"开始复制***\n<br>";
zkCopyNodes(node, destNode, baseZookeeper, destZookeeper);
result=result+"结束复制***\n请检查目标目录:【"+destNode+"】";
}else {
logger.info("检查配置 :\n\n{}",result);
}
return result;
}
/**
* 目录下是否包含指定的节点
*
* 如:/usr/ 下是否包含local
*
* @param nodePath
* @param node
* @param baseZookeeper
* @return
*/
public static boolean isContains(String nodePath, String node, BaseZookeeper baseZookeeper) {
System.out.println(nodePath+"\t"+node+"\t"+zkGetChildNode(nodePath, baseZookeeper).contains(node));
return zkGetChildNode(nodePath, baseZookeeper).contains(node);
}
/**
* 指定路径的节点是否存在
*
* 如:/usr/local 是否存在
*
* @param node
* @param baseZookeeper
* @return
*/
public static boolean isExist(String node, BaseZookeeper baseZookeeper) {
return isExist(node,baseZookeeper,0);
}
/**
* 指定路径的节点是否存在
*
* 如:/usr/local 是否存在
*
* @param node
* @param baseZookeeper
* @param offset
* @return
*/
public static boolean isExist(String node, BaseZookeeper baseZookeeper,int offset) {
String[] splitNode = node.split("/");
String root = "/";
boolean result = true;
for (int i = 1; i < splitNode.length-offset; i++) {
if (!isContains(root, splitNode[i], baseZookeeper)) {
result = false;
break;
}
root = (root + "/" + splitNode[i]).replace("//", "/");
}
return result;
}
/**
* zk获取某个zk节点的下属的子节点
*
* @param node
* @param baseZookeeper
* @return
*/
public static List<String> zkGetChildNode(String node, BaseZookeeper baseZookeeper) {
List<String> child = null;
try {
child = baseZookeeper.getChildren(node);
} catch (KeeperException |InterruptedException e) {
logger.error("context", e);
}
return child;
}
/**
* zk路径下是否有子节点
*
* @param node
* @param baseZookeeper
* @return
*/
public static boolean zkHasChildNode(String node, BaseZookeeper baseZookeeper) {
List<String> child = null;
try {
child = baseZookeeper.getChildren(node);
if (child.isEmpty()) {
return false;
}
} catch (KeeperException |InterruptedException e) {
logger.error("context", e);
}
return true;
}
/**
* 从zk中获取某个节点的json并转存为jsonObject
*
* @param node
* @param baseZookeeper
* @return
*/
public static JsonObject getZkNodedaToJsonObject(String node, BaseZookeeper baseZookeeper) {
String json = zkGetNodeData(node, baseZookeeper);
logger.info("getZkNodeDataToJsonArray:path {} \n json String :{}", node, json);
JsonParser parser = new JsonParser(); // 创建JSON解析器
JsonObject jsonObject = (JsonObject) parser.parse(json);
return jsonObject;
}
/**
* 从zk中获取某节点的json,并转存为JsonArray
*
* @param node
* @param baseZookeeper
* @return
*/
public static JsonArray getZkNodeDataToJsonArray(String node, BaseZookeeper baseZookeeper) {
String json = zkGetNodeData(node, baseZookeeper);
logger.info("getZkNodeDataToJsonArray:path {} \n json String :{}", node, json);
JsonParser parser = new JsonParser(); // 创建JSON解析器
JsonArray jsonArray = (JsonArray) parser.parse(json);
return jsonArray;
}
}
设计界面
package com.ling.zookeeper.zookeeperUtil;
import (略)
/**
*
* @author yueling
* 界面布局
*/
public class Uidesin extends JFrame{
/**
* 创建前缀提示label
*/
public JLabel srcZklabel=new JLabel();
public JLabel srcNodeLabel=new JLabel();
public JLabel destZklabel=new JLabel();
public JLabel destNodeLabel=new JLabel();
public JLabel zklabel=new JLabel();
public JLabel zkNodeLabel=new JLabel();
public JLabel zkNodeDataLabel=new JLabel();
/**
* 创建结果展示label
*/
public JLabel srcZkResultlabel=new JLabel();
public JLabel srcNodeResultLabel=new JLabel();
public JLabel destZkResultlabel=new JLabel();
public JLabel destNodeResultLabel=new JLabel();
public JLabel deleteZkResultlabel=new JLabel();
public JLabel deleteNodeResultLabel=new JLabel();
/**
* 创建信息显示label
*/
public JLabel infoLabel=new JLabel();
/**
* 创建按钮
*/
public JButton buttonOk=new JButton("");
public JButton buttondelete=new JButton("");
public JButton buttonQuery=new JButton("");
public JButton buttonCreate=new JButton("");
/**
* 创建文本框
*/
public JTextField srcZkText=new JTextField();
public JTextField srcNodeText=new JTextField();
public JTextField destZkText=new JTextField();
public JTextField destNodeText=new JTextField();
public JTextField infoText=new JTextField();
public JTextField zkText=new JTextField();
public JTextField zkNodeText=new JTextField();
public JTextField nodeData=new JTextField();
/**
* 构造函数
*/
public Uidesin() {
super();
setSize(700, 600);
getContentPane().setLayout(null);// 设置布局控制器
/**
* 添加复制配置信息……
*/
this.add(this.getLabel(this.srcZklabel, "源zk地址+端口", 40, 50, 110, 30), null);// 添加标签
this.add(this.getLabel(this.srcNodeLabel, "源节点路径", 40, 90, 110, 30), null);// 添加标签
this.add(this.getLabel(this.destZklabel, "目标zk地址+端口", 40, 135, 110, 30), null);// 添加标签
this.add(this.getLabel(this.destNodeLabel, "目标节点路径", 40, 175, 110, 30), null);// 添加标签
this.add(this.getTextField(this.srcZkText, "src_ip:port //只检查连通性,不检查zk服务是否存在,自己保证~~", 155, 50, 500, 30), null);// 添加文本框
this.add(this.getTextField(this.srcNodeText, "/path/path", 155, 90, 500, 30), null);// 添加文本框
this.add(this.getTextField(this.destZkText, "dest_ip:port //只检查连通性,不检查zk服务是否存在,自己保证~~", 155, 135, 500, 30), null);// 添加文本框
this.add(this.getTextField(this.destNodeText, "/pathx/pathy", 155, 175, 500, 30), null);// 添加文本框
this.add(this.getButton(buttonOk,"开始复制",155, 215, 500, 30), null);// 添加按钮
/**
* 添加信息展示区域
*/
this.add(this.getLabel(this.infoLabel, "提示信息……", 155, 255, 500, 100), null);// 添加标签
this.infoLabel.setVerticalAlignment(JLabel.TOP);
this.infoLabel.setBorder(BorderFactory.createLineBorder(Color.red));
//this.add(this.getTextField(this.infoText, "提示信息……", 155, 255, 500, 110), null);// 添加文本框
/**
* 添加创建、删除、查询的配置信息
*/
this.add(this.getLabel(this.zklabel, "zk地址+端口", 40, 365, 110, 30), null);// 添加标签
this.add(this.getLabel(this.zkNodeLabel, "节点路径", 40, 405, 110, 30), null);// 添加标签
this.add(this.getLabel(this.zkNodeDataLabel, "节点数据", 40, 445, 110, 30), null);// 添加标签
this.add(this.getTextField(this.zkText, "src_ip:port //只检查连通性,不检查zk服务是否存在,自己保证~~", 155, 365, 500, 30), null);// 添加文本框
this.add(this.getTextField(this.zkNodeText, "/pathx/pathy 删除/更新时慎用!慎用!删错/覆盖 自己撞墙~~", 155, 405, 500, 30), null);// 添加文本框
this.add(this.getTextField(this.nodeData, "创建/更新时使用,删除和查询可以不设置~", 155, 445, 500, 30), null);// 添加文本框
/**
* 添加创建、删除、查询按钮
*/
this.add(this.getButton(buttondelete,"删除",155, 485, 150, 30), null);// 添加按钮
this.add(this.getButton(buttonCreate,"创建/更新",330, 485, 150, 30), null);// 添加按钮
this.add(this.getButton(buttonQuery,"查询",505, 485, 150, 30), null);// 添加按钮
/**
* 添加结果展示label
*/
this.add(this.getLabel(this.srcZkResultlabel, "", 665, 50, 30, 30), null);// 添加标签
this.add(this.getLabel(this.srcNodeResultLabel, "", 665, 90, 30, 30), null);// 添加标签
this.add(this.getLabel(this.destZkResultlabel, "", 665, 135, 30, 30), null);// 添加标签
this.add(this.getLabel(this.destNodeResultLabel, "", 665, 175, 30, 30), null);// 添加标签
this.add(this.getLabel(this.deleteZkResultlabel, "", 665, 365, 30, 30), null);// 添加标签
this.add(this.getLabel(this.deleteNodeResultLabel, "", 665, 405, 30, 30), null);// 添加标签
/**
* 添加文本的焦点事件
*/
addFocusEvent(srcZkText);
addFocusEvent(srcNodeText);
addFocusEvent(destZkText);
addFocusEvent(destNodeText);
addFocusEvent(infoText);
addFocusEvent(zkText);
addFocusEvent(zkNodeText);
setTitle("zookeeper copy&delete @yueling");// 设置窗口标题
}
/**
* 设置标签
*
* @return 设置好的标签
*/
private JLabel getLabel(JLabel jLabel, String defaultText, int x, int y, int width, int height) {
if (jLabel == null) {
jLabel = new JLabel();
jLabel.setBounds(x, y, width, height);
jLabel.setText(defaultText);
jLabel.setToolTipText(defaultText);
}else {
jLabel.setBounds(x, y, width, height);
jLabel.setText(defaultText);
jLabel.setToolTipText(defaultText);
}
return jLabel;
}
/**
* 设置按钮
*
* @return 设置按钮
*/
private JButton getButton(JButton jButton,String defaultText, int x, int y, int width, int height) {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(x, y, width, height);
jButton.setText(defaultText);
jButton.setToolTipText(defaultText);
}else {
jButton.setBounds(x, y, width, height);
jButton.setText(defaultText);
jButton.setToolTipText(defaultText);
}
return jButton;
}
/**
* 设定文本域
*
* @return
*/
private JTextField getTextField(JTextField jTextField, String defaultText, int x, int y, int width, int height) {
if (jTextField == null) {
jTextField = new JTextField();
jTextField.setBounds(x, y, width, height);
jTextField.setText(defaultText);
jTextField.setToolTipText(defaultText);
}else{
jTextField.setBounds(x, y, width, height);
jTextField.setText(defaultText);
jTextField.setToolTipText(defaultText);
}
return jTextField;
}
/**
* 添加文本区域的获取焦点事件
* @param jTextField
*/
private void addFocusEvent(JTextField jTextField){
jTextField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
}
@Override
public void focusGained(FocusEvent e) {
jTextField.selectAll();
}
});
}
}
创建主函数
package com.ling.zookeeper.zookeeperMain;
import (略)
/**
*
* @author yueling
*
*/
public class ZKTest {
private final static Logger logger = LoggerFactory.getLogger(ZKTest.class);
public static void main(final String[] args) throws Exception {
Uidesin uidesin = new Uidesin();
uidesin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 一定要设置关闭
uidesin.setLocationRelativeTo(null);
uidesin.infoLabel.setText("请按照提示和样例输入对应的源和目标信息……");
// 响应复制事件
uidesin.buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
BaseZookeeper baseZookeeper = new BaseZookeeper();
BaseZookeeper destZookeeper = new BaseZookeeper();
if (PingUtils.pingServer(uidesin.srcZkText.getText().trim())) {
if (PingUtils.pingServer(uidesin.destZkText.getText().trim())) {
try {
baseZookeeper.connectZookeeper(uidesin.srcZkText.getText().trim());
destZookeeper.connectZookeeper(uidesin.destZkText.getText().trim());
logger.info("--------connect zookeeper success-----------");
uidesin.infoLabel.setText("--------connect zookeeper success-----------");
uidesin.infoLabel.setText(ZkUtils.zkCopyNodesInit(uidesin.srcNodeText.getText().trim(),
uidesin.destNodeText.getText().trim(), baseZookeeper, destZookeeper));
} catch (Exception e) {
uidesin.infoLabel.setText("connect zookeeper failed !check ip:port");
e.printStackTrace();
}
try {
baseZookeeper.closeConnect();
destZookeeper.closeConnect();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
uidesin.infoLabel.setText("ping 【" + uidesin.destZkText.getText().trim().split(":")[0] + "】 failed!check ip:port");
}
} else {
uidesin.infoLabel.setText("ping 【" + uidesin.srcZkText.getText().trim().split(":")[0] + "】 failed!check ip:port");
}
}
});
// 响应删除按钮事件
uidesin.buttondelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
BaseZookeeper baseZookeeper = new BaseZookeeper();
if (PingUtils.pingServer(uidesin.zkText.getText().trim())) {
try {
baseZookeeper.connectZookeeper(uidesin.zkText.getText().trim());
logger.info("--------connect zookeeper success-----------");
uidesin.infoLabel.setText("--------connect zookeeper success-----------");
uidesin.infoLabel
.setText(ZkUtils.zkRmNodeInit(uidesin.zkNodeText.getText(), baseZookeeper));
baseZookeeper.closeConnect();
} catch (Exception e) {
uidesin.infoLabel.setText("connect zookeeper failed !check ip:port");
e.printStackTrace();
}
} else {
uidesin.infoLabel.setText("ping 【" + uidesin.zkNodeText.getText().trim().split(":")[0] + "】 failed!check ip:port");
}
}
});
//响应创建按钮事件
uidesin.buttonCreate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
BaseZookeeper baseZookeeper = new BaseZookeeper();
if (PingUtils.pingServer(uidesin.zkText.getText().trim())) {
try {
baseZookeeper.connectZookeeper(uidesin.zkText.getText().trim());
logger.info("--------connect zookeeper success-----------");
uidesin.infoLabel.setText("--------connect zookeeper success-----------");
uidesin.infoLabel
.setText(ZkUtils.zkCreateNodeInit(uidesin.zkNodeText.getText(),uidesin.nodeData.getText(),baseZookeeper));
baseZookeeper.closeConnect();
} catch (Exception e) {
uidesin.infoLabel.setText("connect zookeeper failed !check ip:port");
e.printStackTrace();
}
} else {
uidesin.infoLabel.setText("ping 【" + uidesin.zkNodeText.getText().trim().split(":")[0] + "】 failed!check ip:port");
}
}
});
//响应查询按钮事件
uidesin.buttonQuery.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
BaseZookeeper baseZookeeper = new BaseZookeeper();
if (PingUtils.pingServer(uidesin.zkText.getText().trim())) {
try {
baseZookeeper.connectZookeeper(uidesin.zkText.getText().trim());
logger.info("--------connect zookeeper success-----------");
uidesin.infoLabel.setText("--------connect zookeeper success-----------");
uidesin.infoLabel
.setText(ZkUtils.zkQueryNodeInit(uidesin.zkNodeText.getText(), baseZookeeper));
baseZookeeper.closeConnect();
} catch (Exception e) {
uidesin.infoLabel.setText("connect zookeeper failed !check ip:port");
e.printStackTrace();
}
} else {
uidesin.infoLabel.setText("ping 【" + uidesin.zkNodeText.getText().trim().split(":")[0] + "】 failed!check ip:port");
}
}
});
addDocumentEvent(uidesin.srcZkText,uidesin.srcZkResultlabel,"ip");
addDocumentEvent(uidesin.destZkText,uidesin.destZkResultlabel,"ip");
addDocumentEvent(uidesin.zkText,uidesin.deleteZkResultlabel,"ip");
addDocumentEvent(uidesin.srcNodeText,uidesin.srcNodeResultLabel,"path");
addDocumentEvent(uidesin.destNodeText,uidesin.destNodeResultLabel,"path");
addDocumentEvent(uidesin.zkNodeText,uidesin.deleteNodeResultLabel,"path");
uidesin.setResizable(false);
uidesin.setVisible(true);
}
private static void addDocumentEvent(JTextField jTextField,JLabel jLabel,String flag){
jTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
if (flag.toUpperCase().equals("IP")) {
if(PingUtils.ipCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}else if (flag.toUpperCase().equals("PATH")) {
if(PingUtils.pathCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}
}
@Override
public void insertUpdate(DocumentEvent e) {
if (flag.toUpperCase().equals("IP")) {
if(PingUtils.ipCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}else if (flag.toUpperCase().equals("PATH")) {
if(PingUtils.pathCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (flag.toUpperCase().equals("IP")) {
if(PingUtils.ipCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}else if (flag.toUpperCase().equals("PATH")) {
if(PingUtils.pathCheck(jTextField.getText().trim())){
jLabel.setText("√");
jLabel.setForeground(Color.green);
}else {
jLabel.setText("×");
jLabel.setForeground(Color.red);
}
}
}
});
}
}
ping和相关正则
package com.ling.zookeeper.zookeeperUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PingUtils {
public static boolean pingServer(String ip) {
BufferedReader br = null;
int pingCount = 0;
boolean pingFlag = false;
try {
Process p = Runtime.getRuntime().exec("ping -n 1 " + ip.split(":")[0]);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
if (line.toUpperCase().contains("TTL")) {
pingCount++;
}
}
if (pingCount > 0) {
pingFlag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return pingFlag;
}
public static boolean ipCheck(String text) {
if (text != null && !text.isEmpty()) {
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d):[1-9]\\d+$";
if (text.matches(regex)) {
return true;
} else {
return false;
}
}
return false;
}
public static boolean pathCheck(String text) {
if (text != null && !text.isEmpty()) {
String regex = "^/([0-9a-zA-Z-_!@#$%^&*()+=]+/){0,}([0-9a-zA-Z-_!@#$%^&*()+=]+)?";
if (text.matches(regex)) {
return true;
} else {
return false;
}
}
return false;
}
}
导出
导出可执行文件