jira-importer commented on issue #554:
URL: https://github.com/apache/curator/issues/554#issuecomment-2604695677

   <i><a 
href="https://issues.apache.org/jira/secure/ViewProfile.jspa?name=githubbot";>githubbot</a>:</i>
   <p>Github user Randgalt commented on a diff in the pull request:</p>
   
   <p>    <a 
href="https://github.com/apache/curator/pull/17#discussion_r15641822"; 
class="external-link" target="_blank" rel="nofollow 
noopener">https://github.com/apache/curator/pull/17#discussion_r15641822</a></p>
   
   <p>    &#8212; Diff: 
curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java
 &#8212;<br/>
       @@ -0,0 +1,605 @@<br/>
       +/**<br/>
       + * Licensed to the Apache Software Foundation (ASF) under one<br/>
       + * or more contributor license agreements.  See the NOTICE file<br/>
       + * distributed with this work for additional information<br/>
       + * regarding copyright ownership.  The ASF licenses this file<br/>
       + * to you under the Apache License, Version 2.0 (the<br/>
       + * "License"); you may not use this file except in compliance<br/>
       + * with the License.  You may obtain a copy of the License at<br/>
       + *<br/>
       + *   <a href="http://www.apache.org/licenses/LICENSE-2.0"; 
class="external-link" target="_blank" rel="nofollow 
noopener">http://www.apache.org/licenses/LICENSE-2.0</a><br/>
       + *<br/>
       + * Unless required by applicable law or agreed to in writing,<br/>
       + * software distributed under the License is distributed on an<br/>
       + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY<br/>
       + * KIND, either express or implied.  See the License for the<br/>
       + * specific language governing permissions and limitations<br/>
       + * under the License.<br/>
       + */<br/>
       +<br/>
       +package org.apache.curator.framework.recipes.cache;<br/>
       +<br/>
       +import com.google.common.base.Function;<br/>
       +import com.google.common.collect.ImmutableSortedSet;<br/>
       +import com.google.common.collect.Maps;<br/>
       +import org.apache.curator.framework.CuratorFramework;<br/>
       +import org.apache.curator.framework.api.BackgroundCallback;<br/>
       +import org.apache.curator.framework.api.CuratorEvent;<br/>
       +import org.apache.curator.framework.listen.ListenerContainer;<br/>
       +import org.apache.curator.framework.state.ConnectionState;<br/>
       +import org.apache.curator.framework.state.ConnectionStateListener;<br/>
       +import org.apache.curator.utils.CloseableExecutorService;<br/>
       +import org.apache.curator.utils.ThreadUtils;<br/>
       +import org.apache.curator.utils.ZKPaths;<br/>
       +import org.apache.zookeeper.KeeperException;<br/>
       +import org.apache.zookeeper.WatchedEvent;<br/>
       +import org.apache.zookeeper.Watcher;<br/>
       +import org.apache.zookeeper.data.Stat;<br/>
       +import org.slf4j.Logger;<br/>
       +import org.slf4j.LoggerFactory;<br/>
       +import java.io.Closeable;<br/>
       +import java.io.IOException;<br/>
       +import java.util.ArrayList;<br/>
       +import java.util.Collections;<br/>
       +import java.util.List;<br/>
       +import java.util.SortedSet;<br/>
       +import java.util.concurrent.ConcurrentMap;<br/>
       +import java.util.concurrent.ExecutorService;<br/>
       +import java.util.concurrent.Executors;<br/>
       +import java.util.concurrent.ThreadFactory;<br/>
       +import java.util.concurrent.atomic.AtomicLong;<br/>
       +import java.util.concurrent.atomic.AtomicReference;<br/>
       +<br/>
       +/**<br/>
       + * <p>A utility that attempts to keep all data from all children of a 
ZK path locally cached. This class<br/>
       + * will watch the ZK path, respond to update/create/delete events, pull 
down the data, etc. You can<br/>
       + * register a listener that will get notified when changes 
occur.</p><br/>
       + * <p></p><br/>
       + * <p><b>IMPORTANT</b> - it's not possible to stay transactionally in 
sync. Users of this class must<br/>
       + * be prepared for false-positives and false-negatives. Additionally, 
always use the version number<br/>
       + * when updating data to avoid overwriting another process' 
change.</p><br/>
       + */<br/>
       +public class TreeCache implements Closeable<br/>
       +{<br/>
       +    private static final Logger LOG = 
LoggerFactory.getLogger(TreeCache.class);<br/>
       +<br/>
       +    private enum NodeState<br/>
       +    </p>
   {
       +PENDING, LIVE, DEAD
       +    }
   <p>    +<br/>
       +    final class TreeNode implements Watcher, BackgroundCallback<br/>
       +    {<br/>
       +private final AtomicReference<NodeState> nodeState = new 
AtomicReference<NodeState>(NodeState.PENDING);<br/>
       +private final String path;<br/>
       +private final TreeNode parent;<br/>
       +private final AtomicReference<Stat> stat = new 
AtomicReference<Stat>();<br/>
       +private final AtomicReference<byte[]> data = new 
AtomicReference<byte[]>();<br/>
       +private final AtomicReference<ConcurrentMap<String, TreeNode>> children 
= new AtomicReference<ConcurrentMap<String, TreeNode>>();<br/>
       +<br/>
       +TreeNode(String path, TreeNode parent)<br/>
       +</p>
   {
       +    this.path = path;
       +    this.parent = parent;
       +}
   <p>    +<br/>
       +private void refreshChildren() throws Exception<br/>
       +</p>
   {
       +    outstandingOps.incrementAndGet();
       +    
client.getChildren().usingWatcher(this).inBackground(this).forPath(path);
       +}
   <p>    +<br/>
       +private void refreshData() throws Exception<br/>
       +{<br/>
       +    outstandingOps.incrementAndGet();<br/>
       +    if ( dataIsCompressed )<br/>
       +    </p>
   {
       
+client.getData().decompressed().usingWatcher(this).inBackground(this).forPath(path);
       +    }
   <p>    +    else<br/>
       +    </p>
   {
       +client.getData().usingWatcher(this).inBackground(this).forPath(path);
       +    }
   <p>    +}<br/>
       +<br/>
       +private void wasReconnected() throws Exception<br/>
       +{<br/>
       +    refreshData();<br/>
       +    refreshChildren();<br/>
       +    ConcurrentMap<String, TreeNode> childMap = children.get();<br/>
       +    if ( childMap != null )<br/>
       +    {<br/>
       +for ( TreeNode child : childMap.values() )<br/>
       +</p>
   {
       +    child.wasReconnected();
       +}
   <p>    +    }<br/>
       +}<br/>
       +<br/>
       +private void wasCreated() throws Exception<br/>
       +</p>
   {
       +    refreshData();
       +    refreshChildren();
       +}
   <p>    +<br/>
       +private void wasDeleted() throws Exception<br/>
       +{<br/>
       +    stat.set(null);<br/>
       +    data.set(null);<br/>
       +    client.clearWatcherReferences(this);<br/>
       +    ConcurrentMap<String, TreeNode> childMap = 
children.getAndSet(null);<br/>
       +    if ( childMap != null )<br/>
       +    {<br/>
       +ArrayList<TreeNode> childCopy = new 
ArrayList<TreeNode>(childMap.values());<br/>
       +childMap.clear();<br/>
       +for ( TreeNode child : childCopy )<br/>
       +</p>
   {
       +    child.wasDeleted();
       +}
   <p>    +    }<br/>
       +<br/>
       +    if ( treeState.get() == TreeState.CLOSED )<br/>
       +    </p>
   {
       +return;
       +    }
   <p>    +<br/>
       +    if ( nodeState.compareAndSet(NodeState.LIVE, NodeState.DEAD) )<br/>
       +    </p>
   {
       +publishEvent(TreeCacheEvent.Type.NODE_REMOVED, path);
       +    }
   <p>    +<br/>
       +    if ( parent == null )<br/>
       +    </p>
   {
       +// Root node; use an exist query to watch for existence.
       +client.checkExists().usingWatcher(this).inBackground().forPath(path);
       +    }
   <p>    +    else<br/>
       +    {<br/>
       +// Remove from parent if we're currently a child<br/>
       +ConcurrentMap<String, TreeNode> parentChildMap = 
parent.children.get();<br/>
       +if ( parentChildMap != null )<br/>
       +</p>
   {
       +    parentChildMap.remove(ZKPaths.getNodeFromPath(path), this);
       +}
   <p>    +    }<br/>
       +}<br/>
       +<br/>
       +@Override<br/>
       +public void process(WatchedEvent event)<br/>
       +{<br/>
       +    try<br/>
       +    {<br/>
       +switch ( event.getType() )<br/>
       +</p>
   {
       +case NodeCreated:
       +    assert parent == null;
       +    wasCreated();
       +    break;
       +case NodeChildrenChanged:
       +    refreshChildren();
       +    break;
       +case NodeDataChanged:
       +    refreshData();
       +    break;
       +case NodeDeleted:
       +    wasDeleted();
       +    break;
       +}
   <p>    +    }<br/>
       +    catch ( Exception e )<br/>
       +    </p>
   {
       +handleException(e);
       +    }<br/>
       +}<br/>
       +<br/>
       +@Override<br/>
       +public void processResult(CuratorFramework client, CuratorEvent event) 
throws Exception<br/>
       +{<br/>
       +    switch ( event.getType() )<br/>
       +    {<br/>
       +    case EXISTS:<br/>
       +// TODO: should only happen for root node<br/>
       +if ( event.getResultCode() == KeeperException.Code.OK.intValue() )<br/>
       +{
       +    nodeState.compareAndSet(NodeState.DEAD, NodeState.PENDING);
       +    wasCreated();
       +}<br/>
       +else if ( event.getResultCode() == 
KeeperException.Code.NONODE.intValue() )<br/>
       +{
       +    wasDeleted();
       +}<br/>
       +break;<br/>
       +    case CHILDREN:<br/>
       +if ( event.getResultCode() == KeeperException.Code.OK.intValue() )<br/>
       +{<br/>
       +    stat.set(event.getStat());<br/>
       +<br/>
       +    if ( event.getChildren().isEmpty() )<br/>
       +    {
       +break;
       +    }<br/>
       +<br/>
       +    ConcurrentMap<String, TreeNode> childMap = children.get();<br/>
       +    if ( childMap == null )<br/>
       +    {<br/>
       +childMap = Maps.newConcurrentMap();<br/>
       +if ( !children.compareAndSet(null, childMap) )<br/>
       +{
       +    childMap = children.get();
       +}<br/>
       +    }<br/>
       +<br/>
       +    // Present new children in sorted order for test determinism.<br/>
       +    List<String> newChildren = new ArrayList<String>();<br/>
       +    for ( String child : event.getChildren() )<br/>
       +    {<br/>
       +if ( !childMap.containsKey(child) )<br/>
       +{
       +    newChildren.add(child);
       +}<br/>
       +    }<br/>
       +<br/>
       +    Collections.sort(newChildren);<br/>
       +    for ( String child : newChildren )<br/>
       +    {<br/>
       +String fullPath = ZKPaths.makePath(path, child);<br/>
       +TreeNode node = new TreeNode(fullPath, this);<br/>
       +if ( childMap.putIfAbsent(child, node) == null )<br/>
       +{
       +    node.wasCreated();
       +}<br/>
       +    }<br/>
       +}<br/>
       +else if ( event.getResultCode() == 
KeeperException.Code.NONODE.intValue() )<br/>
       +{    +    wasDeleted();    +}<br/>
       +break;<br/>
       +    case GET_DATA:<br/>
       +if ( event.getResultCode() == KeeperException.Code.OK.intValue() )<br/>
       +{<br/>
       +    Stat oldStat = stat.getAndSet(event.getStat());<br/>
       +    if ( cacheData )<br/>
       +    {
       +data.set(event.getData());
       +    }<br/>
       +<br/>
       +    if ( nodeState.compareAndSet(NodeState.PENDING, NodeState.LIVE) 
)<br/>
       +    {
       +publishEvent(TreeCacheEvent.Type.NODE_ADDED, new 
ChildData(event.getPath(), event.getStat(), event.getData()));
       +    }<br/>
       +    else if ( oldStat.getMzxid() != event.getStat().getMzxid() )<br/>
       +    {
       +publishEvent(TreeCacheEvent.Type.NODE_UPDATED, new 
ChildData(event.getPath(), event.getStat(), event.getData()));
       +    }<br/>
       +}<br/>
       +else if ( event.getResultCode() == 
KeeperException.Code.NONODE.intValue() )<br/>
       +{
       +    wasDeleted();
       +}<br/>
       +break;<br/>
       +    default:<br/>
       +handleException(new Exception(String.format("Unknown event %s", 
event)));<br/>
       +    }<br/>
       +<br/>
       +    if ( outstandingOps.decrementAndGet() == 0 )<br/>
       +    {<br/>
       +if ( treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED) )<br/>
       +{
       +    publishEvent(TreeCacheEvent.Type.INITIALIZED);
       +}<br/>
       +    }<br/>
       +}<br/>
       +    }<br/>
       +<br/>
       +    private enum TreeState<br/>
       +    {
       +LATENT,
       +STARTED,
       +CLOSED
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Detemines when to publish the initialized event.<br/>
       +     */<br/>
       +    private final AtomicLong outstandingOps = new AtomicLong(0);<br/>
       +<br/>
       +    private final TreeNode root;<br/>
       +    private final CuratorFramework client;<br/>
       +    private final CloseableExecutorService executorService;<br/>
       +    private final boolean cacheData;<br/>
       +    private final boolean dataIsCompressed;<br/>
       +    private final ListenerContainer<TreeCacheListener> listeners = new 
ListenerContainer<TreeCacheListener>();<br/>
       +    private final AtomicReference<TreeState> treeState = new 
AtomicReference<TreeState>(TreeState.LATENT);<br/>
       +<br/>
       +    private final ConnectionStateListener connectionStateListener = new 
ConnectionStateListener()<br/>
       +    {<br/>
       +@Override<br/>
       +public void stateChanged(CuratorFramework client, ConnectionState 
newState)<br/>
       +{
       +    handleStateChange(newState);
       +}<br/>
       +    };<br/>
       +<br/>
       +    private static final ThreadFactory defaultThreadFactory = 
ThreadUtils.newThreadFactory("TreeCache");<br/>
       +<br/>
       +    /**<br/>
       +     * @param client    the client<br/>
       +     * @param path      path to watch<br/>
       +     * @param cacheData if true, node contents are cached in addition 
to the stat<br/>
       +     */<br/>
       +    public TreeCache(CuratorFramework client, String path, boolean 
cacheData)<br/>
       +    {
       +this(client, path, cacheData, false, new 
CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory),
 true));
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * @param clientthe client<br/>
       +     * @param path  path to watch<br/>
       +     * @param cacheData     if true, node contents are cached in 
addition to the stat<br/>
       +     * @param threadFactory factory to use when creating internal 
threads<br/>
       +     */<br/>
       +    public TreeCache(CuratorFramework client, String path, boolean 
cacheData, ThreadFactory threadFactory)<br/>
       +    {
       +this(client, path, cacheData, false, new 
CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), 
true));
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * @param client   the client<br/>
       +     * @param path     path to watch<br/>
       +     * @param cacheDataif true, node contents are cached in addition to 
the stat<br/>
       +     * @param dataIsCompressed if true, data in the path is 
compressed<br/>
       +     * @param threadFactory    factory to use when creating internal 
threads<br/>
       +     */<br/>
       +    public TreeCache(CuratorFramework client, String path, boolean 
cacheData, boolean dataIsCompressed, ThreadFactory threadFactory)<br/>
       +    {
       +this(client, path, cacheData, dataIsCompressed, new 
CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), 
true));
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * @param client   the client<br/>
       +     * @param path     path to watch<br/>
       +     * @param cacheDataif true, node contents are cached in addition to 
the stat<br/>
       +     * @param dataIsCompressed if true, data in the path is 
compressed<br/>
       +     * @param executorService  ExecutorService to use for the 
TreeCache's background thread<br/>
       +     */<br/>
       +    public TreeCache(CuratorFramework client, String path, boolean 
cacheData, boolean dataIsCompressed, final ExecutorService executorService)<br/>
       +    {
       +this(client, path, cacheData, dataIsCompressed, new 
CloseableExecutorService(executorService));
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * @param client   the client<br/>
       +     * @param path     path to watch<br/>
       +     * @param cacheDataif true, node contents are cached in addition to 
the stat<br/>
       +     * @param dataIsCompressed if true, data in the path is 
compressed<br/>
       +     * @param executorService  Closeable ExecutorService to use for the 
TreeCache's background thread<br/>
       +     */<br/>
       +    public TreeCache(CuratorFramework client, String path, boolean 
cacheData, boolean dataIsCompressed, final CloseableExecutorService 
executorService)<br/>
       +    {
       +this.root = new TreeNode(path, null);
       +this.client = client;
       +this.cacheData = cacheData;
       +this.dataIsCompressed = dataIsCompressed;
       +this.executorService = executorService;
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Start the cache. The cache is not started automatically. You 
must call this method.<br/>
       +     *<br/>
       +     * @throws Exception errors<br/>
       +     */<br/>
       +    public void start() throws Exception<br/>
       +    {
       
+client.getConnectionStateListenable().addListener(connectionStateListener);
       +root.wasCreated();
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Close/end the cache<br/>
       +     *<br/>
       +     * @throws java.io.IOException errors<br/>
       +     */<br/>
       +    @Override<br/>
       +    public void close() throws IOException<br/>
       +    {<br/>
       +if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) )<br/>
       +{<br/>
       +    
client.getConnectionStateListenable().removeListener(connectionStateListener);<br/>
       +    listeners.clear();<br/>
       +    executorService.close();<br/>
       +    try<br/>
       +    {
       +root.wasDeleted();
       +    }<br/>
       +    catch ( Exception e )<br/>
       +    {    +handleException(e);    +    }
   <p>    +}<br/>
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Return the cache listenable<br/>
       +     *<br/>
       +     * @return listenable<br/>
       +     */<br/>
       +    public ListenerContainer<TreeCacheListener> getListenable()<br/>
       +    </p>
   {
       +return listeners;
       +    }
   <p>    +<br/>
       +    private TreeNode find(String fullPath)<br/>
       +    {<br/>
       +if ( !fullPath.startsWith(root.path) )<br/>
       +</p>
   {
       +    return null;
       +}<br/>
       +<br/>
       +TreeNode current = root;<br/>
       +if ( fullPath.length() > root.path.length() )<br/>
       +{<br/>
       +    List<String> split = 
ZKPaths.split(fullPath.substring(root.path.length()));<br/>
       +    for ( String part : split )<br/>
       +    {<br/>
       +ConcurrentMap<String, TreeNode> map = current.children.get();<br/>
       +if ( map == null )<br/>
       +{
       +    return null;
       +}<br/>
       +current = map.get(part);<br/>
       +if ( current == null )<br/>
       +{    +    return null;    +}<br/>
       +    }<br/>
       +}<br/>
       +return current;<br/>
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Return the current set of children. There are no guarantees of 
accuracy. This is<br/>
       +     * merely the most recent view of the data. The data is returned in 
sorted order. If there is<br/>
       +     * no child with that path, <code>null</code> is returned.<br/>
       +     *<br/>
       +     * @param fullPath full path to the node to check<br/>
       +     * @return a possibly-empty list of children if the node is alive, 
or null<br/>
       +     */<br/>
       +    public SortedSet<String> getCurrentChildren(String fullPath)<br/>
       +    {<br/>
       +TreeNode node = find(fullPath);<br/>
       +if ( node == null || node.nodeState.get() != NodeState.LIVE )<br/>
       +{    +    return null;    +}
   <p>    +ConcurrentMap<String, TreeNode> map = node.children.get();<br/>
       +SortedSet<String> result;<br/>
       +if ( map == null )<br/>
       +</p>
   {
       +    result = ImmutableSortedSet.of();
       +}
   <p>    +else<br/>
       +</p>
   {
       +    result = ImmutableSortedSet.copyOf(map.keySet());
       +}
   <p>    +<br/>
       +// Double-check liveness after retreiving children.<br/>
       +return node.nodeState.get() == NodeState.LIVE ? result : null;<br/>
       +    }<br/>
       +<br/>
       +    /**<br/>
       +     * Return the current data for the given path. There are no 
guarantees of accuracy. This is<br/>
       +     * merely the most recent view of the data. If there is no child 
with that path,<br/>
       +     * <code>null</code> is returned.<br/>
       +     *<br/>
       +     * @param fullPath full path to the node to check<br/>
       +     * @return data if the node is alive, or null<br/>
       +     */<br/>
       +    public ChildData getCurrentData(String fullPath)<br/>
       +    {<br/>
       +TreeNode node = find(fullPath);<br/>
       +if ( node == null || node.nodeState.get() != NodeState.LIVE )<br/>
       +</p>
   {
       +    return null;
       +}
   <p>    +ChildData result = new ChildData(node.path, node.stat.get(), 
node.data.get());<br/>
       +// Double-check liveness after retreiving stat / data.<br/>
       +return node.nodeState.get() == NodeState.LIVE ? result : null;<br/>
       +    }<br/>
       +<br/>
       +    void callListeners(final TreeCacheEvent event)<br/>
       &#8212; End diff &#8211;</p>
   
   <p>    can be private</p>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@curator.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to