{"id":4900,"date":"2014-03-30T16:38:08","date_gmt":"2014-03-30T16:38:08","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/zookeeper-for-java-spring-config-collection-of-common-programming-errors\/"},"modified":"2014-03-30T16:38:08","modified_gmt":"2014-03-30T16:38:08","slug":"zookeeper-for-java-spring-config-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/zookeeper-for-java-spring-config-collection-of-common-programming-errors\/","title":{"rendered":"ZooKeeper for Java\/Spring Config?-Collection of common programming errors"},"content":{"rendered":"<p>Are there any well documented use cases of Apache ZooKeeper being used to distribute configuration of Java applications, and in particular Spring services?<\/p>\n<p>Like many users of cloud services I have a requirement to change the configuration of a variable amount of Java services, preferably at run-time without needing to restart the services.<\/p>\n<p><strong>UPDATE<\/strong><\/p>\n<p>Eventually I ended up writing something that would load a ZooKeeper node as a properties file, and create a <code>ResourcePropertySource<\/code> and insert it into a Spring context. Note that this will not reflect changes in the ZooKeeper node after the context has started.<\/p>\n<pre><code>public class ZooKeeperPropertiesApplicationContextInitializer implements ApplicationContextInitializer {\n    private static final Logger logger = LoggerFactory.getLogger(ZooKeeperPropertiesApplicationContextInitializer.class);\n\n    private final CuratorFramework curator;\n    private String projectName;\n    private String projectVersion;\n\n    public ZooKeeperPropertiesApplicationContextInitializer() throws IOException {\n        logger.trace(\"Attempting to construct CuratorFramework instance\");\n\n        RetryPolicy retryPolicy = new ExponentialBackoffRetry(10, 100);\n        curator = CuratorFrameworkFactory.newClient(\"zookeeper\", retryPolicy);\n        curator.start();\n    }\n\n    \/**\n     * Add a primary property source to the application context, populated from\n     * a pre-existing ZooKeeper node.\n     *\/\n    @Override\n    public void initialize(ConfigurableApplicationContext applicationContext) {\n        logger.trace(\"Attempting to add ZooKeeper-derived properties to ApplicationContext PropertySources\");\n\n        try {\n            populateProjectProperties();\n            Properties properties = populatePropertiesFromZooKeeper();\n            PropertiesPropertySource propertySource = new PropertiesPropertySource(\"zookeeper\", properties);\n            applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);\n\n            logger.debug(\"Added ZooKeeper-derived properties to ApplicationContext PropertySources\");\n            curator.close();\n        } catch (IOException e) {\n            logger.error(\"IO error attempting to load properties from ZooKeeper\", e);\n            throw new IllegalStateException(\"Could not load ZooKeeper configuration\");\n        } catch (Exception e) {\n            logger.error(\"IO error attempting to load properties from ZooKeeper\", e);\n            throw new IllegalStateException(\"Could not load ZooKeeper configuration\");\n        } finally {\n            if (curator != null &amp;&amp; curator.isStarted()) {\n                curator.close();\n            }\n        }\n    }\n\n    \/**\n     * Populate the Maven artifact name and version from a property file that\n     * should be on the classpath, with values entered via Maven filtering.\n     * \n     * There is a way of doing these with manifests, but it's a right faff when\n     * creating shaded uber-jars.\n     * \n     * @throws IOException\n     *\/\n    private void populateProjectProperties() throws IOException {\n        logger.trace(\"Attempting to get project name and version from properties file\");\n\n        try {\n            ResourcePropertySource projectProps = new ResourcePropertySource(\"project.properties\");\n            this.projectName = (String) projectProps.getProperty(\"project.name\");\n            this.projectVersion = (String) projectProps.getProperty(\"project.version\");\n        } catch (IOException e) {\n            logger.error(\"IO error trying to find project name and version, in order to get properties from ZooKeeper\");\n        }\n    }\n\n    \/**\n     * Do the actual loading of properties.\n     * \n     * @return\n     * @throws Exception\n     * @throws IOException\n     *\/\n    private Properties populatePropertiesFromZooKeeper() throws Exception, IOException {\n        logger.debug(\"Attempting to get properties from ZooKeeper\");\n\n        try {\n            byte[] bytes = curator.getData().forPath(\"\/distributed-config\/\" + projectName + \"\/\" + projectVersion);\n            InputStream in = new ByteArrayInputStream(bytes);\n            Properties properties = new Properties();\n            properties.load(in);\n            return properties;\n        } catch (NoNodeException e) {\n            logger.error(\"Could not load application configuration from ZooKeeper as no node existed for project [{}]:[{}]\", projectName, projectVersion);\n            throw e;\n        }\n\n    }\n\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Are there any well documented use cases of Apache ZooKeeper being used to distribute configuration of Java applications, and in particular Spring services? Like many users of cloud services I have a requirement to change the configuration of a variable amount of Java services, preferably at run-time without needing to restart the services. UPDATE Eventually [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4900","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4900","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=4900"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4900\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=4900"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=4900"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=4900"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}