Debian Codegraph @

owner-extras/src/main/java/org/aeonbits/owner/loaders/ZooKeeperLoader.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2012-2015, Luigi R. Viggiano
3 * All rights reserved.
4 *
5 * This software is distributable under the BSD license.
6 * See the terms of the BSD license in the documentation provided with this software.
7 */
8
9 package org.aeonbits.owner.loaders;
10
11 import org.apache.curator.RetryPolicy;
12 import org.apache.curator.RetrySleeper;
13 import org.apache.curator.framework.CuratorFramework;
14 import org.apache.curator.framework.CuratorFrameworkFactory;
15 import org.apache.curator.utils.ZKPaths;
16
17 import java.io.IOException;
18 import java.io.InterruptedIOException;
19 import java.net.URI;
20 import java.util.Properties;
21
22 import static java.lang.Integer.parseInt;
23 import static java.lang.System.getProperty;
24 import static java.util.concurrent.TimeUnit.SECONDS;
25
26 /**
27 * @author Koray Sariteke
28 * @author Luigi R. Viggiano
29 *
30 */
31 public class ZooKeeperLoader implements Loader {
32
33 private static final String SCHEME = "zookeeper";
34 private static final String ZOOKEEPER_CONNECTION_TIMEOUT_SECONDS = "owner.zookeeper.connection.timeout.seconds";
35
36
37 public boolean accept(URI uri) {
38 return uri.getScheme().equals(SCHEME);
39 }
40
41 public void load(Properties result, URI uri) throws IOException {
42 CuratorFramework client = getClient(uri);
43 try {
44 connect(client);
45
46 String basePath = uri.getPath();
47
48 for (String key : client.getChildren().forPath(basePath))
49 result.put(key, getValue(client, basePath, key));
50
51 } catch (InterruptedException e) {
52 Thread.currentThread().interrupt();
53 throw (IOException) new InterruptedIOException().initCause(e);
54 } catch (Exception e) {
55 throw new IOException(e);
56 } finally {
57 client.close();
58 }
59 }
60
61 private String getValue(CuratorFramework client, String basePath, String key) throws Exception {
62 return new String(client.getData().forPath(ZKPaths.makePath(basePath, key)));
63 }
64
65 private void connect(CuratorFramework client) throws InterruptedException {
66 client.start();
67 int timeout = parseInt(getProperty(ZOOKEEPER_CONNECTION_TIMEOUT_SECONDS, "30"));
68 client.blockUntilConnected(timeout, SECONDS);
69 }
70
71 private CuratorFramework getClient(URI uri) {
72 String host = uri.getHost();
73 int port = uri.getPort();
74
75 String connectString = (port == -1) ? host : host + ":" + port;
76 return CuratorFrameworkFactory.newClient(connectString, new RetryPolicy() {
77 public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
78 return false;
79 }
80 });
81 }
82
83 public String defaultSpecFor(String urlPrefix) {
84 return null;
85 }
86 }