Java Code Examples for org.apache.curator.framework.recipes.cache.ChildData#getData()

The following examples show how to use org.apache.curator.framework.recipes.cache.ChildData#getData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ViewChildListener.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * update the meta if the view updated
 */
private void createOrUpdateViewMeta(ChildData childData, boolean isReplace) throws Exception {
    String path = childData.getPath();
    String[] paths = path.split("/");
    String jsonValue = new String(childData.getData(), StandardCharsets.UTF_8);
    JSONObject obj = (JSONObject) JSONObject.parse(jsonValue);

    //if the view is create or replace by this server it self
    String serverId = obj.getString(SERVER_ID);
    if (serverId.equals(ZkConfig.getInstance().getValue(ClusterParamCfg.CLUSTER_CFG_MYID))) {
        return;
    }
    String createSql = obj.getString(CREATE_SQL);
    String schema = paths[paths.length - 1].split(SCHEMA_VIEW_SPLIT)[0];

    ViewMeta vm = new ViewMeta(schema, createSql, ProxyMeta.getInstance().getTmManager());
    vm.init(isReplace);
    vm.addMeta(false);

}
 
Example 2
Source File: DDLChildListener.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private void lockTableByNewNode(ChildData childData) throws Exception {
    String data = new String(childData.getData(), StandardCharsets.UTF_8);
    LOGGER.info("DDL node " + childData.getPath() + " created , and data is " + data);
    DDLInfo ddlInfo = new DDLInfo(data);
    final String fromNode = ddlInfo.getFrom();
    if (fromNode.equals(ZkConfig.getInstance().getValue(ClusterParamCfg.CLUSTER_CFG_MYID))) {
        return; //self node
    }
    if (DDLStatus.INIT != ddlInfo.getStatus()) {
        return;
    }
    String nodeName = childData.getPath().substring(childData.getPath().lastIndexOf("/") + 1);
    String[] tableInfo = nodeName.split("\\.");
    final String schema = StringUtil.removeBackQuote(tableInfo[0]);
    final String table = StringUtil.removeBackQuote(tableInfo[1]);
    ClusterDelayProvider.delayBeforeUpdateMeta();
    try {
        ProxyMeta.getInstance().getTmManager().addMetaLock(schema, table, ddlInfo.getSql());
    } catch (Exception t) {
        ProxyMeta.getInstance().getTmManager().removeMetaLock(schema, table);
        throw t;
    }
}
 
Example 3
Source File: ZKDelegationTokenSecretManager.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void processTokenAddOrUpdate(ChildData data) throws IOException {
  ByteArrayInputStream bin = new ByteArrayInputStream(data.getData());
  DataInputStream din = new DataInputStream(bin);
  TokenIdent ident = createIdentifier();
  ident.readFields(din);
  long renewDate = din.readLong();
  int pwdLen = din.readInt();
  byte[] password = new byte[pwdLen];
  int numRead = din.read(password, 0, pwdLen);
  if (numRead > -1) {
    DelegationTokenInformation tokenInfo =
        new DelegationTokenInformation(renewDate, password);
    synchronized (this) {
      currentTokens.put(ident, tokenInfo);
      // The cancel task might be waiting
      notifyAll();
    }
  }
}
 
Example 4
Source File: MonitorService.java    From shardingsphere-elasticjob-lite with Apache License 2.0 6 votes vote down vote up
private void dumpDirectly(final String path, final List<String> result) {
    for (String each : regCenter.getChildrenKeys(path)) {
        String zkPath = path + "/" + each;
        String zkValue = regCenter.get(zkPath);
        if (null == zkValue) {
            zkValue = "";
        }
        TreeCache treeCache = (TreeCache) regCenter.getRawCache("/" + jobName);
        ChildData treeCacheData = treeCache.getCurrentData(zkPath);
        String treeCachePath = null == treeCacheData ? "" : treeCacheData.getPath();
        String treeCacheValue = null == treeCacheData ? "" : new String(treeCacheData.getData());
        if (zkValue.equals(treeCacheValue) && zkPath.equals(treeCachePath)) {
            result.add(Joiner.on(" | ").join(zkPath, zkValue));
        } else {
            result.add(Joiner.on(" | ").join(zkPath, zkValue, treeCachePath, treeCacheValue));
        }
        dumpDirectly(zkPath, result);
    }
}
 
Example 5
Source File: ZkServiceDiscover.java    From redant with Apache License 2.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    ChildData data = event.getData();
    if(data==null || data.getData()==null){
        return;
    }
    Node node = Node.parse(JSON.parseObject(data.getData(),JSONObject.class));
    if(node ==null){
        LOGGER.error("get a null slave with eventType={},path={},data={}",event.getType(),data.getPath(),data.getData());
    }else {
        switch (event.getType()) {
            case CHILD_ADDED:
                nodeMap.put(node.getId(), node);
                LOGGER.info("CHILD_ADDED with path={},data={},current slave size={}", data.getPath(), new String(data.getData(),CharsetUtil.UTF_8), nodeMap.size());
                break;
            case CHILD_REMOVED:
                nodeMap.remove(node.getId());
                LOGGER.info("CHILD_REMOVED with path={},data={},current slave size={}", data.getPath(), new String(data.getData(),CharsetUtil.UTF_8), nodeMap.size());
                break;
            case CHILD_UPDATED:
                nodeMap.replace(node.getId(), node);
                LOGGER.info("CHILD_UPDATED with path={},data={},current slave size={}", data.getPath(), new String(data.getData(),CharsetUtil.UTF_8), nodeMap.size());
                break;
            default:
                break;
        }
    }
}
 
Example 6
Source File: ZKDelegationTokenSecretManager.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void processTokenRemoved(ChildData data) throws IOException {
  ByteArrayInputStream bin = new ByteArrayInputStream(data.getData());
  DataInputStream din = new DataInputStream(bin);
  TokenIdent ident = createIdentifier();
  ident.readFields(din);
  synchronized (this) {
    currentTokens.remove(ident);
    // The cancel task might be waiting
    notifyAll();
  }
}
 
Example 7
Source File: PollingZooKeeperConfigurationProvider.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private void refreshConfiguration() throws IOException {
    LOGGER.info("Refreshing configuration from ZooKeeper");
    byte[] data = null;
    ChildData childData = agentNodeCache.getCurrentData();
    if (childData != null) {
        data = childData.getData();
    }
    flumeConfiguration = configFromBytes(data);
    eventBus.post(getConfiguration());
}
 
Example 8
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private String getCurrentTSOInfoFoundInZK(String currentTsoPath) {
    ChildData currentTSOData = currentTSOZNode.getCurrentData();
    if (currentTSOData == null) {
        throw new IllegalStateException("No data found in ZKNode " + currentTsoPath);
    }
    byte[] currentTSOAndEpochAsBytes = currentTSOData.getData();
    if (currentTSOAndEpochAsBytes == null) {
        throw new IllegalStateException("No data found for current TSO in ZKNode " + currentTsoPath);
    }
    return new String(currentTSOAndEpochAsBytes, Charsets.UTF_8);
}
 
Example 9
Source File: ZookeeperRegistryCenter.java    From shardingsphere-elasticjob-lite with Apache License 2.0 5 votes vote down vote up
@Override
public String get(final String key) {
    TreeCache cache = findTreeCache(key);
    if (null == cache) {
        return getDirectly(key);
    }
    ChildData resultInCache = cache.getCurrentData(key);
    if (null != resultInCache) {
        return null == resultInCache.getData() ? null : new String(resultInCache.getData(), Charsets.UTF_8);
    }
    return getDirectly(key);
}
 
Example 10
Source File: DataHostStatusListener.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void updateStatus(ChildData childData) {
    try {
        if (DbleServer.getInstance().isUseOuterHa()) {
            String nodeName = childData.getPath().substring(childData.getPath().lastIndexOf("/") + 1);
            String data = new String(childData.getData(), StandardCharsets.UTF_8);
            int id = HaConfigManager.getInstance().haStart(HaInfo.HaStage.RESPONSE_NOTIFY, HaInfo.HaStartType.CLUSTER_NOTIFY, "");
            PhysicalDataHost physicalDBPool = DbleServer.getInstance().getConfig().getDataHosts().get(nodeName);
            PhysicalDataHost dataHost = (PhysicalDataHost) physicalDBPool;
            dataHost.changeIntoLatestStatus(data);
            HaConfigManager.getInstance().haFinish(id, null, data);
        }
    } catch (Exception e) {
        LOGGER.warn("get Error when update Ha status", e);
    }
}
 
Example 11
Source File: CuratorClientService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void nodeChanged() throws Exception {
    String path = null;
    byte[] data = null;

    ChildData cd = nodeCache.getCurrentData();
    if (cd != null) {
        path = cd.getPath();
        data = cd.getData();
    }

    if (path != null) {
        delegate.entryChanged(client, path, data);
    }
}
 
Example 12
Source File: ZookeeperDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public String readSource() throws Exception {
    if (this.zkClient == null) {
        throw new IllegalStateException("Zookeeper has not been initialized or error occurred");
    }
    String configInfo = null;
    ChildData childData = nodeCache.getCurrentData();
    if (null != childData && childData.getData() != null) {

        configInfo = new String(childData.getData());
    }
    return configInfo;
}
 
Example 13
Source File: ZooKeeperScanPolicyObserver.java    From hbase with Apache License 2.0 5 votes vote down vote up
private OptionalLong getExpireBefore() {
  ChildData data = cache.getCurrentData();
  if (data == null) {
    return OptionalLong.empty();
  }
  byte[] bytes = data.getData();
  if (bytes == null || bytes.length != Long.BYTES) {
    return OptionalLong.empty();
  }
  return OptionalLong.of(Bytes.toLong(bytes));
}
 
Example 14
Source File: ZkPathManager.java    From xian with Apache License 2.0 5 votes vote down vote up
public static boolean isServiceNode(ChildData zNode) {
    String path = zNode.getPath();
    LOG.debug("正在检查节点路径:   " + path);
    LOG.debug("服务注册路径:   " + getNodeBasePath());
    if (!path.startsWith(getNodeBasePath()) || path.equals(getNodeBasePath())) {
        return false;
    }
    String name = path.substring((getNodeBasePath() + "/").length());
    String[] names = name.split("/");
    if (names.length != 2) {
        return false;
    }
    /*if (!SystemEnum.isServiceNodeName(names[0])) {
        todo 由于去掉了systemEnum类,我们在watch到zk外部服务注册事件之前,根本不知道到底有哪些application
        return false;
    }*/
    String zNodeDataStr = new String(zNode.getData());
    JSONObject zNodeData;
    try {
        zNodeData = JSON.parseObject(zNodeDataStr);
    } catch (JSONException notJsonString) {
        LOG.debug(String.format("节点%s的data是%s,它不是我们要找的那个服务节点,排除掉!  这是我期待结果之一,不打印堆栈", path, zNodeDataStr));
        return false;
    }
    try {
        if (zNodeData.getJSONObject("payload") == null) {
            LOG.debug(String.format("节点=%s,内容=%s,其内缺少payload属性,它不是我们预期的服务节点!", path, zNodeDataStr));
            return false;
        }
    } catch (JSONException payloadIsNotJsonString) {
        LOG.info(String.format("节点%s的data=%s,其内的payload属性是不是json格式,肯定是有非预期的节点混入,这里排除之", path, zNodeDataStr));
        return false;
    }
    return true;
}
 
Example 15
Source File: ZKDelegationTokenSecretManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void processTokenRemoved(ChildData data) throws IOException {
  ByteArrayInputStream bin = new ByteArrayInputStream(data.getData());
  DataInputStream din = new DataInputStream(bin);
  TokenIdent ident = createIdentifier();
  ident.readFields(din);
  synchronized (this) {
    currentTokens.remove(ident);
    // The cancel task might be waiting
    notifyAll();
  }
}
 
Example 16
Source File: AbstractGenericData.java    From niubi-job with Apache License 2.0 4 votes vote down vote up
public AbstractGenericData(ChildData childData) {
    this(childData.getPath(), childData.getData());
}
 
Example 17
Source File: ZooKeeperLeaderElectionService.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
public void nodeChanged() throws Exception {
	try {
		// leaderSessionID is null if the leader contender has not yet confirmed the session ID
		if (leaderLatch.hasLeadership()) {
			synchronized (lock) {
				if (running) {
					if (LOG.isDebugEnabled()) {
						LOG.debug(
							"Leader node changed while {} is the leader with session ID {}.",
							leaderContender.getAddress(),
							confirmedLeaderSessionID);
					}

					if (confirmedLeaderSessionID != null) {
						ChildData childData = cache.getCurrentData();

						if (childData == null) {
							if (LOG.isDebugEnabled()) {
								LOG.debug(
									"Writing leader information into empty node by {}.",
									leaderContender.getAddress());
							}
							writeLeaderInformation(confirmedLeaderSessionID);
						} else {
							byte[] data = childData.getData();

							if (data == null || data.length == 0) {
								// the data field seems to be empty, rewrite information
								if (LOG.isDebugEnabled()) {
									LOG.debug(
										"Writing leader information into node with empty data field by {}.",
										leaderContender.getAddress());
								}
								writeLeaderInformation(confirmedLeaderSessionID);
							} else {
								ByteArrayInputStream bais = new ByteArrayInputStream(data);
								ObjectInputStream ois = new ObjectInputStream(bais);

								String leaderAddress = ois.readUTF();
								UUID leaderSessionID = (UUID) ois.readObject();

								if (!leaderAddress.equals(this.leaderContender.getAddress()) ||
									(leaderSessionID == null || !leaderSessionID.equals(confirmedLeaderSessionID))) {
									// the data field does not correspond to the expected leader information
									if (LOG.isDebugEnabled()) {
										LOG.debug(
											"Correcting leader information by {}.",
											leaderContender.getAddress());
									}
									writeLeaderInformation(confirmedLeaderSessionID);
								}
							}
						}
					}
				} else {
					LOG.debug("Ignoring node change notification since the service has already been stopped.");
				}
			}
		}
	} catch (Exception e) {
		leaderContender.handleError(new Exception("Could not handle node changed event.", e));
		throw e;
	}
}
 
Example 18
Source File: DDLChildListener.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
private void deleteNode(ChildData childData) {
    String data = new String(childData.getData(), StandardCharsets.UTF_8);
    DDLInfo ddlInfo = new DDLInfo(data);
    LOGGER.info("DDL node " + childData.getPath() + " removed , and DDL info is " + ddlInfo.toString());
}
 
Example 19
Source File: ZooKeeperLeaderElectionService.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override
public void nodeChanged() throws Exception {
	try {
		// leaderSessionID is null if the leader contender has not yet confirmed the session ID
		if (leaderLatch.hasLeadership()) {
			synchronized (lock) {
				if (running) {
					if (LOG.isDebugEnabled()) {
						LOG.debug(
							"Leader node changed while {} is the leader with session ID {}.",
							leaderContender.getAddress(),
							confirmedLeaderSessionID);
					}

					if (confirmedLeaderSessionID != null) {
						ChildData childData = cache.getCurrentData();

						if (childData == null) {
							if (LOG.isDebugEnabled()) {
								LOG.debug(
									"Writing leader information into empty node by {}.",
									leaderContender.getAddress());
							}
							writeLeaderInformation(confirmedLeaderSessionID);
						} else {
							byte[] data = childData.getData();

							if (data == null || data.length == 0) {
								// the data field seems to be empty, rewrite information
								if (LOG.isDebugEnabled()) {
									LOG.debug(
										"Writing leader information into node with empty data field by {}.",
										leaderContender.getAddress());
								}
								writeLeaderInformation(confirmedLeaderSessionID);
							} else {
								ByteArrayInputStream bais = new ByteArrayInputStream(data);
								ObjectInputStream ois = new ObjectInputStream(bais);

								String leaderAddress = ois.readUTF();
								UUID leaderSessionID = (UUID) ois.readObject();

								if (!leaderAddress.equals(this.leaderContender.getAddress()) ||
									(leaderSessionID == null || !leaderSessionID.equals(confirmedLeaderSessionID))) {
									// the data field does not correspond to the expected leader information
									if (LOG.isDebugEnabled()) {
										LOG.debug(
											"Correcting leader information by {}.",
											leaderContender.getAddress());
									}
									writeLeaderInformation(confirmedLeaderSessionID);
								}
							}
						}
					}
				} else {
					LOG.debug("Ignoring node change notification since the service has already been stopped.");
				}
			}
		}
	} catch (Exception e) {
		leaderContender.handleError(new Exception("Could not handle node changed event.", e));
		throw e;
	}
}
 
Example 20
Source File: ZKRegistry.java    From joyrpc with Apache License 2.0 3 votes vote down vote up
/**
 * 添加事件
 *
 * @param events    事件集合
 * @param type      事件类型
 * @param childData 节点数据
 */
protected void addEvent(final List<ShardEvent> events, final ShardEventType type, final ChildData childData) {
    byte[] data = childData.getData();
    if (data != null) {
        events.add(new ShardEvent(new DefaultShard(URL.valueOf(new String(data, UTF_8))), type));
    }
}