Debian Codegraph @

curator-examples/src/main/java/cache/PathCacheExample.java

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package cache;
21
22 import com.google.common.collect.Lists;
23 import discovery.ExampleServer;
24 import java.io.BufferedReader;
25 import java.io.InputStreamReader;
26 import java.util.Arrays;
27 import java.util.List;
28 import org.apache.curator.framework.CuratorFramework;
29 import org.apache.curator.framework.CuratorFrameworkFactory;
30 import org.apache.curator.framework.recipes.cache.ChildData;
31 import org.apache.curator.framework.recipes.cache.PathChildrenCache;
32 import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
33 import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
34 import org.apache.curator.retry.ExponentialBackoffRetry;
35 import org.apache.curator.test.TestingServer;
36 import org.apache.curator.utils.CloseableUtils;
37 import org.apache.curator.utils.ZKPaths;
38 import org.apache.zookeeper.KeeperException;
39
40 /**
41 * An example of the PathChildrenCache. The example "harness" is a command processor
42 * that allows adding/updating/removed nodes in a path. A PathChildrenCache keeps a
43 * cache of these changes and outputs when updates occurs.
44 */
45 public class PathCacheExample {
46 private static final String PATH = "/example/cache";
47
48 public static void main(String[] args) throws Exception {
49 TestingServer server = new TestingServer();
50 CuratorFramework client = null;
51 PathChildrenCache cache = null;
52 try {
53 client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
54 client.start();
55
56 // in this example we will cache data. Notice that this is optional.
57 cache = new PathChildrenCache(client, PATH, true);
58 cache.start();
59
60 processCommands(client, cache);
61 } finally {
62 CloseableUtils.closeQuietly(cache);
63 CloseableUtils.closeQuietly(client);
64 CloseableUtils.closeQuietly(server);
65 }
66 }
67
68 private static void addListener(PathChildrenCache cache) {
69 // a PathChildrenCacheListener is optional. Here, it's used just to log changes
70 PathChildrenCacheListener listener = new PathChildrenCacheListener() {
71 @Override
72 public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
73 switch (event.getType()) {
74 case CHILD_ADDED: {
75 System.out.println("Node added: "
76 + ZKPaths.getNodeFromPath(event.getData().getPath()));
77 break;
78 }
79
80 case CHILD_UPDATED: {
81 System.out.println("Node changed: "
82 + ZKPaths.getNodeFromPath(event.getData().getPath()));
83 break;
84 }
85
86 case CHILD_REMOVED: {
87 System.out.println("Node removed: "
88 + ZKPaths.getNodeFromPath(event.getData().getPath()));
89 break;
90 }
91 }
92 }
93 };
94 cache.getListenable().addListener(listener);
95 }
96
97 private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception {
98 // More scaffolding that does a simple command line processor
99
100 printHelp();
101
102 List<ExampleServer> servers = Lists.newArrayList();
103 try {
104 addListener(cache);
105
106 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
107 boolean done = false;
108 while (!done) {
109 System.out.print("> ");
110
111 String line = in.readLine();
112 if (line == null) {
113 break;
114 }
115
116 String command = line.trim();
117 String[] parts = command.split("\\s");
118 if (parts.length == 0) {
119 continue;
120 }
121 String operation = parts[0];
122 String args[] = Arrays.copyOfRange(parts, 1, parts.length);
123
124 if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
125 printHelp();
126 } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
127 done = true;
128 } else if (operation.equals("set")) {
129 setValue(client, command, args);
130 } else if (operation.equals("remove")) {
131 remove(client, command, args);
132 } else if (operation.equals("list")) {
133 list(cache);
134 }
135
136 Thread.sleep(1000); // just to allow the console output to catch up
137 }
138 } finally {
139 for (ExampleServer server : servers) {
140 CloseableUtils.closeQuietly(server);
141 }
142 }
143 }
144
145 private static void list(PathChildrenCache cache) {
146 if (cache.getCurrentData().size() == 0) {
147 System.out.println("* empty *");
148 } else {
149 for (ChildData data : cache.getCurrentData()) {
150 System.out.println(data.getPath() + " = " + new String(data.getData()));
151 }
152 }
153 }
154
155 private static void remove(CuratorFramework client, String command, String[] args) throws Exception {
156 if (args.length != 1) {
157 System.err.println("syntax error (expected remove <path>): " + command);
158 return;
159 }
160
161 String name = args[0];
162 if (name.contains("/")) {
163 System.err.println("Invalid node name" + name);
164 return;
165 }
166 String path = ZKPaths.makePath(PATH, name);
167
168 try {
169 client.delete().forPath(path);
170 } catch (KeeperException.NoNodeException e) {
171 // ignore
172 }
173 }
174
175 private static void setValue(CuratorFramework client, String command, String[] args) throws Exception {
176 if (args.length != 2) {
177 System.err.println("syntax error (expected set <path> <value>): " + command);
178 return;
179 }
180
181 String name = args[0];
182 if (name.contains("/")) {
183 System.err.println("Invalid node name" + name);
184 return;
185 }
186 String path = ZKPaths.makePath(PATH, name);
187
188 byte[] bytes = args[1].getBytes();
189 try {
190 client.setData().forPath(path, bytes);
191 } catch (KeeperException.NoNodeException e) {
192 client.create().creatingParentContainersIfNeeded().forPath(path, bytes);
193 }
194 }
195
196 private static void printHelp() {
197 System.out.println(
198 "An example of using PathChildrenCache. This example is driven by entering commands at the prompt:\n");
199 System.out.println("set <name> <value>: Adds or updates a node with the given name");
200 System.out.println("remove <name>: Deletes the node with the given name");
201 System.out.println("list: List the nodes/values in the cache");
202 System.out.println("quit: Quit the example");
203 System.out.println();
204 }
205 }