javaExample.html 28 KB

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