javaExample.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta content="Apache Forrest" name="Generator">
  6. <meta name="Forrest-version" content="0.8">
  7. <meta name="Forrest-skin-name" content="pelt">
  8. <title>ZooKeeper Java Example</title>
  9. <link type="text/css" href="skin/basic.css" rel="stylesheet">
  10. <link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
  11. <link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
  12. <link type="text/css" href="skin/profile.css" rel="stylesheet">
  13. <script src="skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="skin/fontsize.js" language="javascript" type="text/javascript"></script>
  14. <link rel="shortcut icon" href="images/favicon.ico">
  15. </head>
  16. <body onload="init()">
  17. <script type="text/javascript">ndeSetTextSize();</script>
  18. <div id="top">
  19. <!--+
  20. |breadtrail
  21. +-->
  22. <div class="breadtrail">
  23. <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://hadoop.apache.org/">Hadoop</a> &gt; <a href="http://hadoop.apache.org/zookeeper/">ZooKeeper</a><script src="skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
  24. </div>
  25. <!--+
  26. |header
  27. +-->
  28. <div class="header">
  29. <!--+
  30. |start group logo
  31. +-->
  32. <div class="grouplogo">
  33. <a href="http://hadoop.apache.org/"><img class="logoImage" alt="Hadoop" src="images/hadoop-logo.jpg" title="Apache Hadoop"></a>
  34. </div>
  35. <!--+
  36. |end group logo
  37. +-->
  38. <!--+
  39. |start Project Logo
  40. +-->
  41. <div class="projectlogo">
  42. <a href="http://hadoop.apache.org/zookeeper/"><img class="logoImage" alt="ZooKeeper" src="images/zookeeper_small.gif" title="ZooKeeper: distributed coordination"></a>
  43. </div>
  44. <!--+
  45. |end Project Logo
  46. +-->
  47. <!--+
  48. |start Search
  49. +-->
  50. <div class="searchbox">
  51. <form action="http://www.google.com/search" method="get" class="roundtopsmall">
  52. <input value="hadoop.apache.org" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">&nbsp;
  53. <input name="Search" value="Search" type="submit">
  54. </form>
  55. </div>
  56. <!--+
  57. |end search
  58. +-->
  59. <!--+
  60. |start Tabs
  61. +-->
  62. <ul id="tabs">
  63. <li>
  64. <a class="unselected" href="http://hadoop.apache.org/zookeeper/">Project</a>
  65. </li>
  66. <li>
  67. <a class="unselected" href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  68. </li>
  69. <li class="current">
  70. <a class="selected" href="index.html">ZooKeeper 3.3 Documentation</a>
  71. </li>
  72. </ul>
  73. <!--+
  74. |end Tabs
  75. +-->
  76. </div>
  77. </div>
  78. <div id="main">
  79. <div id="publishedStrip">
  80. <!--+
  81. |start Subtabs
  82. +-->
  83. <div id="level2tabs"></div>
  84. <!--+
  85. |end Endtabs
  86. +-->
  87. <script type="text/javascript"><!--
  88. document.write("Last Published: " + document.lastModified);
  89. // --></script>
  90. </div>
  91. <!--+
  92. |breadtrail
  93. +-->
  94. <div class="breadtrail">
  95. &nbsp;
  96. </div>
  97. <!--+
  98. |start Menu, mainarea
  99. +-->
  100. <!--+
  101. |start Menu
  102. +-->
  103. <div id="menu">
  104. <div onclick="SwitchMenu('menu_1.1', 'skin/')" id="menu_1.1Title" class="menutitle">Overview</div>
  105. <div id="menu_1.1" class="menuitemgroup">
  106. <div class="menuitem">
  107. <a href="index.html">Welcome</a>
  108. </div>
  109. <div class="menuitem">
  110. <a href="zookeeperOver.html">Overview</a>
  111. </div>
  112. <div class="menuitem">
  113. <a href="zookeeperStarted.html">Getting Started</a>
  114. </div>
  115. <div class="menuitem">
  116. <a href="releasenotes.html">Release Notes</a>
  117. </div>
  118. </div>
  119. <div onclick="SwitchMenu('menu_selected_1.2', 'skin/')" id="menu_selected_1.2Title" class="menutitle" style="background-image: url('skin/images/chapter_open.gif');">Developer</div>
  120. <div id="menu_selected_1.2" class="selectedmenuitemgroup" style="display: block;">
  121. <div class="menuitem">
  122. <a href="api/index.html">API Docs</a>
  123. </div>
  124. <div class="menuitem">
  125. <a href="zookeeperProgrammers.html">Programmer's Guide</a>
  126. </div>
  127. <div class="menupage">
  128. <div class="menupagetitle">Java Example</div>
  129. </div>
  130. <div class="menuitem">
  131. <a href="zookeeperTutorial.html">Barrier and Queue Tutorial</a>
  132. </div>
  133. <div class="menuitem">
  134. <a href="recipes.html">Recipes</a>
  135. </div>
  136. </div>
  137. <div onclick="SwitchMenu('menu_1.3', 'skin/')" id="menu_1.3Title" class="menutitle">BookKeeper</div>
  138. <div id="menu_1.3" class="menuitemgroup">
  139. <div class="menuitem">
  140. <a href="bookkeeperStarted.html">Getting started</a>
  141. </div>
  142. <div class="menuitem">
  143. <a href="bookkeeperOverview.html">Overview</a>
  144. </div>
  145. <div class="menuitem">
  146. <a href="bookkeeperConfig.html">Setup guide</a>
  147. </div>
  148. <div class="menuitem">
  149. <a href="bookkeeperProgrammer.html">Programmer's guide</a>
  150. </div>
  151. </div>
  152. <div onclick="SwitchMenu('menu_1.4', 'skin/')" id="menu_1.4Title" class="menutitle">Admin &amp; Ops</div>
  153. <div id="menu_1.4" class="menuitemgroup">
  154. <div class="menuitem">
  155. <a href="zookeeperAdmin.html">Administrator's Guide</a>
  156. </div>
  157. <div class="menuitem">
  158. <a href="zookeeperQuotas.html">Quota Guide</a>
  159. </div>
  160. <div class="menuitem">
  161. <a href="zookeeperJMX.html">JMX</a>
  162. </div>
  163. </div>
  164. <div onclick="SwitchMenu('menu_1.5', 'skin/')" id="menu_1.5Title" class="menutitle">Contributor</div>
  165. <div id="menu_1.5" class="menuitemgroup">
  166. <div class="menuitem">
  167. <a href="zookeeperInternals.html">ZooKeeper Internals</a>
  168. </div>
  169. </div>
  170. <div onclick="SwitchMenu('menu_1.6', 'skin/')" id="menu_1.6Title" class="menutitle">Miscellaneous</div>
  171. <div id="menu_1.6" class="menuitemgroup">
  172. <div class="menuitem">
  173. <a href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  174. </div>
  175. <div class="menuitem">
  176. <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ">FAQ</a>
  177. </div>
  178. <div class="menuitem">
  179. <a href="http://hadoop.apache.org/zookeeper/mailing_lists.html">Mailing Lists</a>
  180. </div>
  181. </div>
  182. <div id="credit"></div>
  183. <div id="roundbottom">
  184. <img style="display: none" class="corner" height="15" width="15" alt="" src="skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
  185. <!--+
  186. |alternative credits
  187. +-->
  188. <div id="credit2"></div>
  189. </div>
  190. <!--+
  191. |end Menu
  192. +-->
  193. <!--+
  194. |start content
  195. +-->
  196. <div id="content">
  197. <div title="Portable Document Format" class="pdflink">
  198. <a class="dida" href="javaExample.pdf"><img alt="PDF -icon" src="skin/images/pdfdoc.gif" class="skin"><br>
  199. PDF</a>
  200. </div>
  201. <h1>ZooKeeper Java Example</h1>
  202. <div id="minitoc-area">
  203. <ul class="minitoc">
  204. <li>
  205. <a href="#ch_Introduction">A Simple Watch Client</a>
  206. <ul class="minitoc">
  207. <li>
  208. <a href="#sc_requirements">Requirements</a>
  209. </li>
  210. <li>
  211. <a href="#sc_design">Program Design</a>
  212. </li>
  213. </ul>
  214. </li>
  215. <li>
  216. <a href="#sc_executor">The Executor Class</a>
  217. </li>
  218. <li>
  219. <a href="#sc_DataMonitor">The DataMonitor Class</a>
  220. </li>
  221. <li>
  222. <a href="#sc_completeSourceCode">Complete Source Listings</a>
  223. </li>
  224. </ul>
  225. </div>
  226. <a name="N10009"></a><a name="ch_Introduction"></a>
  227. <h2 class="h3">A Simple Watch Client</h2>
  228. <div class="section">
  229. <p>To introduce you to the ZooKeeper Java API, we develop here a very simple
  230. watch client. This ZooKeeper client watches a ZooKeeper node for changes
  231. and responds to by starting or stopping a program.</p>
  232. <a name="N10012"></a><a name="sc_requirements"></a>
  233. <h3 class="h4">Requirements</h3>
  234. <p>The client has four requirements:</p>
  235. <ul>
  236. <li>
  237. <p>It takes as parameters:</p>
  238. <ul>
  239. <li>
  240. <p>the address of the ZooKeeper service</p>
  241. </li>
  242. <li>
  243. <p>then name of a znode - the one to be watched</p>
  244. </li>
  245. <li>
  246. <p>an executable with arguments.</p>
  247. </li>
  248. </ul>
  249. </li>
  250. <li>
  251. <p>It fetches the data associated with the znode and starts the executable.</p>
  252. </li>
  253. <li>
  254. <p>If the znode changes, the client refetches the contents and restarts the executable.</p>
  255. </li>
  256. <li>
  257. <p>If the znode disappears, the client kills the executable.</p>
  258. </li>
  259. </ul>
  260. <a name="N1003B"></a><a name="sc_design"></a>
  261. <h3 class="h4">Program Design</h3>
  262. <p>Conventionally, ZooKeeper applications are broken into two units, one which maintains the connection,
  263. and the other which monitors data. In this application, the class called the <strong>Executor</strong>
  264. maintains the ZooKeeper connection, and the class called the <strong>DataMonitor</strong> monitors the data
  265. in the ZooKeeper tree. Also, Executor contains the main thread and contains the execution logic.
  266. It is responsible for what little user interaction there is, as well as interaction with the exectuable program you
  267. pass in as an argument and which the sample (per the requirements) shuts down and restarts, according to the
  268. state of the znode.</p>
  269. </div>
  270. <a name="N1004C"></a><a name="sc_executor"></a>
  271. <h2 class="h3">The Executor Class</h2>
  272. <div class="section">
  273. <p>The Executor object is the primary container of the sample application. It contains
  274. both the <strong>ZooKeeper</strong> object, <strong>DataMonitor</strong>, as described above in
  275. <a href="#sc_design">Program Design</a>. </p>
  276. <pre class="code">
  277. // from the Executor class...
  278. public static void main(String[] args) {
  279. if (args.length &lt; 4) {
  280. System.err
  281. .println("USAGE: Executor hostPort znode filename program [args ...]");
  282. System.exit(2);
  283. }
  284. String hostPort = args[0];
  285. String znode = args[1];
  286. String filename = args[2];
  287. String exec[] = new String[args.length - 3];
  288. System.arraycopy(args, 3, exec, 0, exec.length);
  289. try {
  290. new Executor(hostPort, znode, filename, exec).run();
  291. } catch (Exception e) {
  292. e.printStackTrace();
  293. }
  294. }
  295. public Executor(String hostPort, String znode, String filename,
  296. String exec[]) throws KeeperException, IOException {
  297. this.filename = filename;
  298. this.exec = exec;
  299. zk = new ZooKeeper(hostPort, 3000, this);
  300. dm = new DataMonitor(zk, znode, null, this);
  301. }
  302. public void run() {
  303. try {
  304. synchronized (this) {
  305. while (!dm.dead) {
  306. wait();
  307. }
  308. }
  309. } catch (InterruptedException e) {
  310. }
  311. }
  312. </pre>
  313. <p>
  314. Recall that the Executor's job is to starts and stop the executable whose name you pass in on the command line.
  315. It does this in response to events fired by the ZooKeeper object. As you can see in the code above, the Executor passes
  316. a reference to itself as the Watcher argument in the ZooKeeper constructor. It also passes a reference to itself
  317. as DataMonitorListener argument to the DataMonitor constructor. Per the Executor's definition, it implements both these
  318. interfaces:
  319. </p>
  320. <pre class="code">
  321. public class Executor implements Watcher, Runnable, DataMonitor.DataMonitorListener {
  322. ...</pre>
  323. <p>The <strong>Watcher</strong> interface is defined by the ZooKeeper Java API.
  324. ZooKeeper uses it to communicate back to its container. It supports only one method, <span class="codefrag command">process()</span>, and ZooKeeper uses
  325. it to communciates generic events that the main thread would be intersted in, such as the state of the ZooKeeper connection or the ZooKeeper session.The Executor
  326. in this example simply forwards those events down to the DataMonitor to decide what to do with them. It does this simply to illustrate
  327. the point that, by convention, the Executor or some Executor-like object "owns" the ZooKeeper connection, but it is free to delegate the events to other
  328. events to other objects. It also uses this as the default channel on which to fire watch events. (More on this later.)</p>
  329. <pre class="code">
  330. public void process(WatchedEvent event) {
  331. dm.process(event);
  332. }
  333. </pre>
  334. <p>The <strong>DataMonitorListener</strong>
  335. interface, on the other hand, is not part of the the ZooKeeper API. It is a completely custom interface,
  336. designed for this sample application. The DataMonitor object uses it to communicate back to its container, which
  337. is also the the Executor object.The DataMonitorListener interface looks like this:</p>
  338. <pre class="code">
  339. public interface DataMonitorListener {
  340. /**
  341. * The existence status of the node has changed.
  342. */
  343. void exists(byte data[]);
  344. /**
  345. * The ZooKeeper session is no longer valid.
  346. *
  347. * @param rc
  348. * the ZooKeeper reason code
  349. */
  350. void closing(int rc);
  351. }
  352. </pre>
  353. <p>This interface is defined in the DataMonitor class and implemented in the Executor class.
  354. When <span class="codefrag command">Executor.exists()</span> is invoked,
  355. the Executor decides whether to start up or shut down per the requirements. Recall that the requires say to kill the executable when the
  356. znode ceases to <em>exist</em>. </p>
  357. <p>When <span class="codefrag command">Executor.closing()</span>
  358. is invoked, the Executor decides whether or not to shut itself down in response to the ZooKeeper connection permanently disappearing.</p>
  359. <p>As you might have guessed, DataMonitor is the object that invokes
  360. these methods, in response to changes in ZooKeeper's state.</p>
  361. <p>Here are Executor's implementation of
  362. <span class="codefrag command">DataMonitorListener.exists()</span> and <span class="codefrag command">DataMonitorListener.closing</span>:
  363. </p>
  364. <pre class="code">
  365. public void exists( byte[] data ) {
  366. if (data == null) {
  367. if (child != null) {
  368. System.out.println("Killing process");
  369. child.destroy();
  370. try {
  371. child.waitFor();
  372. } catch (InterruptedException e) {
  373. }
  374. }
  375. child = null;
  376. } else {
  377. if (child != null) {
  378. System.out.println("Stopping child");
  379. child.destroy();
  380. try {
  381. child.waitFor();
  382. } catch (InterruptedException e) {
  383. e.printStackTrace();
  384. }
  385. }
  386. try {
  387. FileOutputStream fos = new FileOutputStream(filename);
  388. fos.write(data);
  389. fos.close();
  390. } catch (IOException e) {
  391. e.printStackTrace();
  392. }
  393. try {
  394. System.out.println("Starting child");
  395. child = Runtime.getRuntime().exec(exec);
  396. new StreamWriter(child.getInputStream(), System.out);
  397. new StreamWriter(child.getErrorStream(), System.err);
  398. } catch (IOException e) {
  399. e.printStackTrace();
  400. }
  401. }
  402. }
  403. public void closing(int rc) {
  404. synchronized (this) {
  405. notifyAll();
  406. }
  407. }
  408. </pre>
  409. </div>
  410. <a name="N100A0"></a><a name="sc_DataMonitor"></a>
  411. <h2 class="h3">The DataMonitor Class</h2>
  412. <div class="section">
  413. <p>
  414. The DataMonitor class has the meat of the ZooKeeper logic. It is mostly
  415. asynchronous and event driven. DataMonitor kicks things off in the constructor with:</p>
  416. <pre class="code">
  417. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  418. DataMonitorListener listener) {
  419. this.zk = zk;
  420. this.znode = znode;
  421. this.chainedWatcher = chainedWatcher;
  422. this.listener = listener;
  423. // Get things started by checking if the node exists. We are going
  424. // to be completely event driven
  425. <strong>zk.exists(znode, true, this, null);</strong>
  426. }
  427. </pre>
  428. <p>The call to <span class="codefrag command">ZooKeeper.exists()</span> checks for the existence of the znode,
  429. sets a watch, and passes a reference to itself (<span class="codefrag command">this</span>)
  430. as the completion callback object. In this sense, it kicks things off, since the
  431. real processing happens when the watch is triggered.</p>
  432. <div class="note">
  433. <div class="label">Note</div>
  434. <div class="content">
  435. <p>Don't confuse the completion callback with the watch callback. The <span class="codefrag command">ZooKeeper.exists()</span>
  436. completion callback, which happens to be the method <span class="codefrag command">StatCallback.processResult()</span> implemented
  437. in the DataMonitor object, is invoked when the asynchronous <em>setting of the watch</em> operation
  438. (by <span class="codefrag command">ZooKeeper.exists()</span>) completes on the server. </p>
  439. <p>
  440. The triggering of the watch, on the other hand, sends an event to the <em>Executor</em> object, since
  441. the Executor registered as the Watcher of the ZooKeeper object.</p>
  442. <p>As an aside, you might note that the DataMonitor could also register itself as the Watcher
  443. for this particular watch event. This is new to ZooKeeper 3.0.0 (the support of multiple Watchers). In this
  444. example, however, DataMonitor does not register as the Watcher.</p>
  445. </div>
  446. </div>
  447. <p>When the <span class="codefrag command">ZooKeeper.exists()</span> operation completes on the server, the ZooKeeper API invokes this completion callback on
  448. the client:</p>
  449. <pre class="code">
  450. public void processResult(int rc, String path, Object ctx, Stat stat) {
  451. boolean exists;
  452. switch (rc) {
  453. case Code.Ok:
  454. exists = true;
  455. break;
  456. case Code.NoNode:
  457. exists = false;
  458. break;
  459. case Code.SessionExpired:
  460. case Code.NoAuth:
  461. dead = true;
  462. listener.closing(rc);
  463. return;
  464. default:
  465. // Retry errors
  466. zk.exists(znode, true, this, null);
  467. return;
  468. }
  469. byte b[] = null;
  470. if (exists) {
  471. try {
  472. <strong>b = zk.getData(znode, false, null);</strong>
  473. } catch (KeeperException e) {
  474. // We don't need to worry about recovering now. The watch
  475. // callbacks will kick off any exception handling
  476. e.printStackTrace();
  477. } catch (InterruptedException e) {
  478. return;
  479. }
  480. }
  481. if ((b == null &amp;&amp; b != prevData)
  482. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  483. <strong>listener.exists(b);</strong>
  484. prevData = b;
  485. }
  486. }
  487. </pre>
  488. <p>
  489. The code first checks the error codes for znode existence, fatal errors, and
  490. recoverable errors. If the file (or znode) exists, it gets the data from the znode, and
  491. then invoke the exists() callback of Executor if the state has changed. Note,
  492. it doesn't have to do any Exception processing for the getData call because it
  493. has watches pending for anything that could cause an error: if the node is deleted
  494. before it calls <span class="codefrag command">ZooKeeper.getData()</span>, the watch event set by
  495. the <span class="codefrag command">ZooKeeper.exists()</span> triggers a callback;
  496. if there is a communication error, a connection watch event fires when
  497. the connection comes back up.
  498. </p>
  499. <p>Finally, notice how DataMonitor processes watch events: </p>
  500. <pre class="code">
  501. public void process(WatchedEvent event) {
  502. String path = event.getPath();
  503. if (event.getType() == Event.EventType.None) {
  504. // We are are being told that the state of the
  505. // connection has changed
  506. switch (event.getState()) {
  507. case SyncConnected:
  508. // In this particular example we don't need to do anything
  509. // here - watches are automatically re-registered with
  510. // server and any watches triggered while the client was
  511. // disconnected will be delivered (in order of course)
  512. break;
  513. case Expired:
  514. // It's all over
  515. dead = true;
  516. listener.closing(KeeperException.Code.SessionExpired);
  517. break;
  518. }
  519. } else {
  520. if (path != null &amp;&amp; path.equals(znode)) {
  521. // Something has changed on the node, let's find out
  522. zk.exists(znode, true, this, null);
  523. }
  524. }
  525. if (chainedWatcher != null) {
  526. chainedWatcher.process(event);
  527. }
  528. }
  529. </pre>
  530. <p>
  531. If the client-side ZooKeeper libraries can re-establish the
  532. communication channel (SyncConnected event) to ZooKeeper before
  533. session expiration (Expired event) all of the session's watches will
  534. automatically be re-established with the server (auto-reset of watches
  535. is new in ZooKeeper 3.0.0). See <a href="zookeeperProgrammers.html#ch_zkWatches">ZooKeeper Watches</a>
  536. in the programmer guide for more on this. A bit lower down in this
  537. function, when DataMonitor gets an event for a znode, it calls
  538. <span class="codefrag command">ZooKeeper.exists()</span> to find out what has changed.
  539. </p>
  540. </div>
  541. <a name="N10104"></a><a name="sc_completeSourceCode"></a>
  542. <h2 class="h3">Complete Source Listings</h2>
  543. <div class="section">
  544. <div class="note example">
  545. <div class="label">Executor.java</div>
  546. <div class="content">
  547. <title>Executor.java</title>
  548. <pre class="code">
  549. /**
  550. * A simple example program to use DataMonitor to start and
  551. * stop executables based on a znode. The program watches the
  552. * specified znode and saves the data that corresponds to the
  553. * znode in the filesystem. It also starts the specified program
  554. * with the specified arguments when the znode exists and kills
  555. * the program if the znode goes away.
  556. */
  557. import java.io.FileOutputStream;
  558. import java.io.IOException;
  559. import java.io.InputStream;
  560. import java.io.OutputStream;
  561. import org.apache.zookeeper.KeeperException;
  562. import org.apache.zookeeper.WatchedEvent;
  563. import org.apache.zookeeper.Watcher;
  564. import org.apache.zookeeper.ZooKeeper;
  565. public class Executor
  566. implements Watcher, Runnable, DataMonitor.DataMonitorListener
  567. {
  568. String znode;
  569. DataMonitor dm;
  570. ZooKeeper zk;
  571. String filename;
  572. String exec[];
  573. Process child;
  574. public Executor(String hostPort, String znode, String filename,
  575. String exec[]) throws KeeperException, IOException {
  576. this.filename = filename;
  577. this.exec = exec;
  578. zk = new ZooKeeper(hostPort, 3000, this);
  579. dm = new DataMonitor(zk, znode, null, this);
  580. }
  581. /**
  582. * @param args
  583. */
  584. public static void main(String[] args) {
  585. if (args.length &lt; 4) {
  586. System.err
  587. .println("USAGE: Executor hostPort znode filename program [args ...]");
  588. System.exit(2);
  589. }
  590. String hostPort = args[0];
  591. String znode = args[1];
  592. String filename = args[2];
  593. String exec[] = new String[args.length - 3];
  594. System.arraycopy(args, 3, exec, 0, exec.length);
  595. try {
  596. new Executor(hostPort, znode, filename, exec).run();
  597. } catch (Exception e) {
  598. e.printStackTrace();
  599. }
  600. }
  601. /***************************************************************************
  602. * We do process any events ourselves, we just need to forward them on.
  603. *
  604. * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
  605. */
  606. public void process(WatchedEvent event) {
  607. dm.process(event);
  608. }
  609. public void run() {
  610. try {
  611. synchronized (this) {
  612. while (!dm.dead) {
  613. wait();
  614. }
  615. }
  616. } catch (InterruptedException e) {
  617. }
  618. }
  619. public void closing(int rc) {
  620. synchronized (this) {
  621. notifyAll();
  622. }
  623. }
  624. static class StreamWriter extends Thread {
  625. OutputStream os;
  626. InputStream is;
  627. StreamWriter(InputStream is, OutputStream os) {
  628. this.is = is;
  629. this.os = os;
  630. start();
  631. }
  632. public void run() {
  633. byte b[] = new byte[80];
  634. int rc;
  635. try {
  636. while ((rc = is.read(b)) &gt; 0) {
  637. os.write(b, 0, rc);
  638. }
  639. } catch (IOException e) {
  640. }
  641. }
  642. }
  643. public void exists(byte[] data) {
  644. if (data == null) {
  645. if (child != null) {
  646. System.out.println("Killing process");
  647. child.destroy();
  648. try {
  649. child.waitFor();
  650. } catch (InterruptedException e) {
  651. }
  652. }
  653. child = null;
  654. } else {
  655. if (child != null) {
  656. System.out.println("Stopping child");
  657. child.destroy();
  658. try {
  659. child.waitFor();
  660. } catch (InterruptedException e) {
  661. e.printStackTrace();
  662. }
  663. }
  664. try {
  665. FileOutputStream fos = new FileOutputStream(filename);
  666. fos.write(data);
  667. fos.close();
  668. } catch (IOException e) {
  669. e.printStackTrace();
  670. }
  671. try {
  672. System.out.println("Starting child");
  673. child = Runtime.getRuntime().exec(exec);
  674. new StreamWriter(child.getInputStream(), System.out);
  675. new StreamWriter(child.getErrorStream(), System.err);
  676. } catch (IOException e) {
  677. e.printStackTrace();
  678. }
  679. }
  680. }
  681. }
  682. </pre>
  683. </div>
  684. </div>
  685. <div class="note example">
  686. <div class="label">DataMonitor.java</div>
  687. <div class="content">
  688. <title>DataMonitor.java</title>
  689. <pre class="code">
  690. /**
  691. * A simple class that monitors the data and existence of a ZooKeeper
  692. * node. It uses asynchronous ZooKeeper APIs.
  693. */
  694. import java.util.Arrays;
  695. import org.apache.zookeeper.KeeperException;
  696. import org.apache.zookeeper.WatchedEvent;
  697. import org.apache.zookeeper.Watcher;
  698. import org.apache.zookeeper.ZooKeeper;
  699. import org.apache.zookeeper.AsyncCallback.StatCallback;
  700. import org.apache.zookeeper.KeeperException.Code;
  701. import org.apache.zookeeper.data.Stat;
  702. public class DataMonitor implements Watcher, StatCallback {
  703. ZooKeeper zk;
  704. String znode;
  705. Watcher chainedWatcher;
  706. boolean dead;
  707. DataMonitorListener listener;
  708. byte prevData[];
  709. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  710. DataMonitorListener listener) {
  711. this.zk = zk;
  712. this.znode = znode;
  713. this.chainedWatcher = chainedWatcher;
  714. this.listener = listener;
  715. // Get things started by checking if the node exists. We are going
  716. // to be completely event driven
  717. zk.exists(znode, true, this, null);
  718. }
  719. /**
  720. * Other classes use the DataMonitor by implementing this method
  721. */
  722. public interface DataMonitorListener {
  723. /**
  724. * The existence status of the node has changed.
  725. */
  726. void exists(byte data[]);
  727. /**
  728. * The ZooKeeper session is no longer valid.
  729. *
  730. * @param rc
  731. * the ZooKeeper reason code
  732. */
  733. void closing(int rc);
  734. }
  735. public void process(WatchedEvent event) {
  736. String path = event.getPath();
  737. if (event.getType() == Event.EventType.None) {
  738. // We are are being told that the state of the
  739. // connection has changed
  740. switch (event.getState()) {
  741. case SyncConnected:
  742. // In this particular example we don't need to do anything
  743. // here - watches are automatically re-registered with
  744. // server and any watches triggered while the client was
  745. // disconnected will be delivered (in order of course)
  746. break;
  747. case Expired:
  748. // It's all over
  749. dead = true;
  750. listener.closing(KeeperException.Code.SessionExpired);
  751. break;
  752. }
  753. } else {
  754. if (path != null &amp;&amp; path.equals(znode)) {
  755. // Something has changed on the node, let's find out
  756. zk.exists(znode, true, this, null);
  757. }
  758. }
  759. if (chainedWatcher != null) {
  760. chainedWatcher.process(event);
  761. }
  762. }
  763. public void processResult(int rc, String path, Object ctx, Stat stat) {
  764. boolean exists;
  765. switch (rc) {
  766. case Code.Ok:
  767. exists = true;
  768. break;
  769. case Code.NoNode:
  770. exists = false;
  771. break;
  772. case Code.SessionExpired:
  773. case Code.NoAuth:
  774. dead = true;
  775. listener.closing(rc);
  776. return;
  777. default:
  778. // Retry errors
  779. zk.exists(znode, true, this, null);
  780. return;
  781. }
  782. byte b[] = null;
  783. if (exists) {
  784. try {
  785. b = zk.getData(znode, false, null);
  786. } catch (KeeperException e) {
  787. // We don't need to worry about recovering now. The watch
  788. // callbacks will kick off any exception handling
  789. e.printStackTrace();
  790. } catch (InterruptedException e) {
  791. return;
  792. }
  793. }
  794. if ((b == null &amp;&amp; b != prevData)
  795. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  796. listener.exists(b);
  797. prevData = b;
  798. }
  799. }
  800. }
  801. </pre>
  802. </div>
  803. </div>
  804. </div>
  805. <p align="right">
  806. <font size="-2"></font>
  807. </p>
  808. </div>
  809. <!--+
  810. |end content
  811. +-->
  812. <div class="clearboth">&nbsp;</div>
  813. </div>
  814. <div id="footer">
  815. <!--+
  816. |start bottomstrip
  817. +-->
  818. <div class="lastmodified">
  819. <script type="text/javascript"><!--
  820. document.write("Last Published: " + document.lastModified);
  821. // --></script>
  822. </div>
  823. <div class="copyright">
  824. Copyright &copy;
  825. 2008 <a href="http://www.apache.org/licenses/">The Apache Software Foundation.</a>
  826. </div>
  827. <!--+
  828. |end bottomstrip
  829. +-->
  830. </div>
  831. </body>
  832. </html>