1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.common.keymaster.client.zookeeper;
20
21 import com.fasterxml.jackson.databind.json.JsonMapper;
22 import java.util.Map;
23 import java.util.Optional;
24 import java.util.TreeMap;
25 import org.apache.curator.framework.CuratorFramework;
26 import org.apache.syncope.common.keymaster.client.api.ConfParamOps;
27 import org.apache.syncope.common.keymaster.client.api.KeymasterException;
28 import org.apache.zookeeper.KeeperException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32
33
34
35 public class ZookeeperConfParamOps implements ConfParamOps {
36
37 protected static final Logger LOG = LoggerFactory.getLogger(ConfParamOps.class);
38
39 protected static final JsonMapper MAPPER = JsonMapper.builder().findAndAddModules().build();
40
41 protected static final String CONF_PATH = "/conf";
42
43 protected final CuratorFramework client;
44
45 protected static String buildConfPath(final String... parts) {
46 return CONF_PATH + '/' + String.join("/", parts);
47 }
48
49 public ZookeeperConfParamOps(final CuratorFramework client) {
50 this.client = client;
51 }
52
53 @Override
54 public Map<String, Object> list(final String domain) {
55 try {
56 if (client.checkExists().forPath(buildConfPath(domain)) == null) {
57 client.create().creatingParentContainersIfNeeded().forPath(buildConfPath(domain));
58 }
59
60 Map<String, Object> list = new TreeMap<>();
61 for (String child : client.getChildren().forPath(buildConfPath(domain))) {
62 list.put(child, MAPPER.readValue(client.getData().forPath(buildConfPath(domain, child)), Object.class));
63 }
64
65 return list;
66 } catch (Exception e) {
67 throw new KeymasterException(e);
68 }
69 }
70
71 @Override
72 public <T> T get(final String domain, final String key, final T defaultValue, final Class<T> reference) {
73 T value = null;
74 try {
75 value = MAPPER.readValue(client.getData().forPath(buildConfPath(domain, key)), reference);
76 } catch (KeeperException.NoNodeException e) {
77 LOG.debug("Node {} was not found", buildConfPath(domain, key));
78 } catch (Exception e) {
79 throw new KeymasterException(e);
80 }
81
82 return Optional.ofNullable(value).orElse(defaultValue);
83 }
84
85 @Override
86 public <T> void set(final String domain, final String key, final T value) {
87 if (value == null) {
88 remove(domain, key);
89 } else {
90 try {
91 if (client.checkExists().forPath(buildConfPath(domain, key)) == null) {
92 client.create().creatingParentContainersIfNeeded().forPath(buildConfPath(domain, key));
93 }
94
95 client.setData().forPath(buildConfPath(domain, key), MAPPER.writeValueAsBytes(value));
96 } catch (Exception e) {
97 throw new KeymasterException(e);
98 }
99 }
100 }
101
102 @Override
103 public void remove(final String domain, final String key) {
104 try {
105 client.delete().forPath(buildConfPath(domain, key));
106 } catch (Exception e) {
107 throw new KeymasterException(e);
108 }
109 }
110 }