Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ConfigManager.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.config;
  18. import com.dmdirc.config.binding.ConfigBinder;
  19. import com.dmdirc.config.provider.AggregateConfigProvider;
  20. import com.dmdirc.config.provider.ConfigChangeListener;
  21. import com.dmdirc.config.provider.ConfigProvider;
  22. import com.dmdirc.config.provider.ConfigProviderMigrator;
  23. import com.dmdirc.util.ClientInfo;
  24. import com.dmdirc.util.validators.Validator;
  25. import com.google.common.collect.ArrayListMultimap;
  26. import com.google.common.collect.Multimap;
  27. import java.util.ArrayList;
  28. import java.util.Collection;
  29. import java.util.HashMap;
  30. import java.util.HashSet;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import java.util.TreeMap;
  35. import org.slf4j.Logger;
  36. import org.slf4j.LoggerFactory;
  37. /**
  38. * The config manager manages the various config sources for each entity.
  39. */
  40. class ConfigManager implements ConfigChangeListener, ConfigProviderListener,
  41. AggregateConfigProvider {
  42. private static final Logger LOG = LoggerFactory.getLogger(ConfigManager.class);
  43. /** Temporary map for lookup stats. */
  44. private static final Map<String, Integer> STATS = new TreeMap<>();
  45. /** Magical domain to redirect to the version identity. */
  46. private static final String VERSION_DOMAIN = "version";
  47. /** A list of sources for this config manager. */
  48. private final List<ConfigFileBackedConfigProvider> sources = new ArrayList<>();
  49. /** The listeners registered for this manager. */
  50. private final Multimap<String, ConfigChangeListener> listeners = ArrayListMultimap.create();
  51. /** The config binder to use for this manager. */
  52. private final ConfigBinder binder;
  53. /** The manager to use to fetch global state. */
  54. private final IdentityManager manager;
  55. /** Client info object. */
  56. private final ClientInfo clientInfo;
  57. /** The protocol this manager is for. */
  58. private String protocol;
  59. /** The ircd this manager is for. */
  60. private String ircd;
  61. /** The network this manager is for. */
  62. private String network;
  63. /** The server this manager is for. */
  64. private String server;
  65. /** The channel this manager is for. */
  66. private String channel;
  67. /**
  68. * Creates a new instance of ConfigManager.
  69. *
  70. * @param manager The manager to use to retrieve global state horribly.
  71. * @param protocol The protocol for this manager
  72. * @param ircd The name of the ircd for this manager
  73. * @param network The name of the network for this manager
  74. * @param server The name of the server for this manager
  75. *
  76. * @since 0.6.3
  77. */
  78. ConfigManager(
  79. final ClientInfo clientInfo,
  80. final IdentityManager manager,
  81. final String protocol, final String ircd,
  82. final String network, final String server) {
  83. this(clientInfo, manager, protocol, ircd, network, server, "<Unknown>");
  84. }
  85. /**
  86. * Creates a new instance of ConfigManager.
  87. *
  88. * @param manager The manager to use to retrieve global state horribly.
  89. * @param protocol The protocol for this manager
  90. * @param ircd The name of the ircd for this manager
  91. * @param network The name of the network for this manager
  92. * @param server The name of the server for this manager
  93. * @param channel The name of the channel for this manager
  94. *
  95. * @since 0.6.3
  96. */
  97. ConfigManager(
  98. final ClientInfo clientInfo,
  99. final IdentityManager manager,
  100. final String protocol, final String ircd,
  101. final String network, final String server, final String channel) {
  102. final String chanName = channel + '@' + network;
  103. this.clientInfo = clientInfo;
  104. this.manager = manager;
  105. this.protocol = protocol;
  106. this.ircd = ircd;
  107. this.network = network;
  108. this.server = server;
  109. this.channel = chanName;
  110. binder = new ConfigBinderImpl(this);
  111. }
  112. @Override
  113. public ConfigBinder getBinder() {
  114. return binder;
  115. }
  116. @Override
  117. public String getOption(final String domain, final String option,
  118. final Validator<String> validator) {
  119. doStats(domain, option);
  120. if (VERSION_DOMAIN.equals(domain)) {
  121. final String response = clientInfo.getVersionConfigSetting(VERSION_DOMAIN, option);
  122. if (response == null || validator.validate(response).isFailure()) {
  123. return null;
  124. }
  125. return response;
  126. }
  127. synchronized (sources) {
  128. for (ConfigProvider source : sources) {
  129. if (source.hasOption(domain, option, validator)) {
  130. return source.getOption(domain, option, validator);
  131. }
  132. }
  133. }
  134. return null;
  135. }
  136. @Override
  137. public boolean hasOption(final String domain, final String option,
  138. final Validator<String> validator) {
  139. doStats(domain, option);
  140. if (VERSION_DOMAIN.equals(domain)) {
  141. final String response = clientInfo.getVersionConfigSetting(VERSION_DOMAIN, option);
  142. return response != null && !validator.validate(response).isFailure();
  143. }
  144. synchronized (sources) {
  145. for (ConfigProvider source : sources) {
  146. if (source.hasOption(domain, option, validator)) {
  147. return true;
  148. }
  149. }
  150. }
  151. return false;
  152. }
  153. @Override
  154. public Map<String, String> getOptions(final String domain) {
  155. if (VERSION_DOMAIN.equals(domain)) {
  156. return manager.getVersionSettings().getOptions(domain);
  157. }
  158. final Map<String, String> res = new HashMap<>();
  159. synchronized (sources) {
  160. for (int i = sources.size() - 1; i >= 0; i--) {
  161. res.putAll(sources.get(i).getOptions(domain));
  162. }
  163. }
  164. return res;
  165. }
  166. /**
  167. * Removes the specified identity from this manager.
  168. *
  169. * @param identity The identity to be removed
  170. */
  171. public void removeIdentity(final ConfigProvider identity) {
  172. if (!sources.contains(identity)) {
  173. return;
  174. }
  175. final Collection<String[]> changed = new ArrayList<>();
  176. // Determine which settings will have changed
  177. for (String domain : identity.getDomains()) {
  178. identity.getOptions(domain).keySet().stream()
  179. .filter(option -> identity.equals(getScope(domain, option)))
  180. .forEach(option -> changed.add(new String[]{domain, option}));
  181. }
  182. synchronized (sources) {
  183. identity.removeListener(this);
  184. sources.remove(identity);
  185. }
  186. // Fire change listeners
  187. for (String[] setting : changed) {
  188. configChanged(setting[0], setting[1]);
  189. }
  190. }
  191. /**
  192. * Retrieves the identity that currently defines the specified domain and option.
  193. *
  194. * @param domain The domain to search for
  195. * @param option The option to search for
  196. *
  197. * @return The identity that defines that setting, or null on failure
  198. */
  199. protected ConfigProvider getScope(final String domain, final String option) {
  200. if (VERSION_DOMAIN.equals(domain)) {
  201. return manager.getVersionSettings();
  202. }
  203. synchronized (sources) {
  204. for (ConfigProvider source : sources) {
  205. if (source.hasOptionString(domain, option)) {
  206. return source;
  207. }
  208. }
  209. }
  210. return null;
  211. }
  212. /**
  213. * Checks whether the specified identity applies to this config manager.
  214. *
  215. * @param identity The identity to test
  216. *
  217. * @return True if the identity applies, false otherwise
  218. */
  219. public boolean identityApplies(final ConfigFileBackedConfigProvider identity) {
  220. final String comp;
  221. switch (identity.getTarget().getType()) {
  222. case PROTOCOL:
  223. comp = protocol;
  224. break;
  225. case IRCD:
  226. comp = ircd;
  227. break;
  228. case NETWORK:
  229. comp = network;
  230. break;
  231. case SERVER:
  232. comp = server;
  233. break;
  234. case CHANNEL:
  235. comp = channel;
  236. break;
  237. case CUSTOM:
  238. // We don't want custom identities
  239. comp = null;
  240. break;
  241. default:
  242. comp = "";
  243. break;
  244. }
  245. final boolean result = comp != null
  246. && identityTargetMatches(identity.getTarget().getData(), comp);
  247. LOG.trace("Checking if identity {} applies. Comparison: {}, target: {}, result: {}",
  248. identity, comp, identity.getTarget().getData(), result);
  249. return result;
  250. }
  251. /**
  252. * Determines whether the specified identity target matches the desired target. If the desired
  253. * target is prefixed with "re:", it is treated as a regular expression; otherwise the strings
  254. * are compared lexicographically to determine a match.
  255. *
  256. * @param desired The target string required by this config manager
  257. * @param actual The target string supplied by the identity
  258. *
  259. * @return True if the identity should be applied, false otherwise
  260. *
  261. * @since 0.6.3m2
  262. */
  263. protected boolean identityTargetMatches(final String actual, final String desired) {
  264. return actual.startsWith("re:") ? desired.matches(actual.substring(3))
  265. : actual.equalsIgnoreCase(desired);
  266. }
  267. /**
  268. * Called whenever there is a new identity available. Checks if the identity is relevant for
  269. * this manager, and adds it if it is.
  270. *
  271. * @param identity The identity to be checked
  272. */
  273. public void checkIdentity(final ConfigFileBackedConfigProvider identity) {
  274. if (!sources.contains(identity) && identityApplies(identity)) {
  275. synchronized (sources) {
  276. sources.add(identity);
  277. identity.addListener(this);
  278. sources.sort(new ConfigProviderTargetComparator());
  279. }
  280. // Determine which settings will have changed
  281. for (String domain : identity.getDomains()) {
  282. identity.getOptions(domain).keySet().stream()
  283. .filter(option -> identity.equals(getScope(domain, option)))
  284. .forEach(option -> configChanged(domain, option));
  285. }
  286. }
  287. }
  288. @Override
  289. public Set<String> getDomains() {
  290. final Set<String> res = new HashSet<>();
  291. synchronized (sources) {
  292. for (ConfigProvider source : sources) {
  293. res.addAll(source.getDomains());
  294. }
  295. }
  296. return res;
  297. }
  298. @Override
  299. public List<ConfigProvider> getSources() {
  300. return new ArrayList<>(sources);
  301. }
  302. /**
  303. * Migrates this manager from its current configuration to the appropriate one for the specified
  304. * new parameters, firing listeners where settings have changed.
  305. *
  306. * <p>
  307. * This is package private - only callers with access to a {@link ConfigProviderMigrator}
  308. * should be able to migrate managers.
  309. *
  310. * @param protocol The protocol for this manager
  311. * @param ircd The new name of the ircd for this manager
  312. * @param network The new name of the network for this manager
  313. * @param server The new name of the server for this manager
  314. * @param channel The new name of the channel for this manager
  315. */
  316. void migrate(final String protocol, final String ircd,
  317. final String network, final String server, final String channel) {
  318. LOG.debug("Migrating from {{}, {}, {}, {}, {}} to {{}, {}, {}, {}, {}}", this.protocol,
  319. this.ircd, this.network, this.server, this.channel, protocol, ircd, network, server,
  320. channel);
  321. this.protocol = protocol;
  322. this.ircd = ircd;
  323. this.network = network;
  324. this.server = server;
  325. this.channel = channel + '@' + network;
  326. new ArrayList<>(sources).stream().filter(identity -> !identityApplies(identity))
  327. .forEach(identity -> {
  328. LOG.debug("Removing identity that no longer applies: {}", identity);
  329. removeIdentity(identity);
  330. });
  331. final List<ConfigFileBackedConfigProvider> newSources = manager.getIdentitiesForManager(this);
  332. for (ConfigFileBackedConfigProvider identity : newSources) {
  333. LOG.trace("Testing new identity: {}", identity);
  334. checkIdentity(identity);
  335. }
  336. LOG.debug("New identities: {}", sources);
  337. }
  338. /**
  339. * Records the lookup request for the specified domain and option.
  340. *
  341. * @param domain The domain that is being looked up
  342. * @param option The option that is being looked up
  343. */
  344. @SuppressWarnings("PMD.AvoidCatchingNPE")
  345. protected static void doStats(final String domain, final String option) {
  346. final String key = domain + '.' + option;
  347. try {
  348. STATS.put(key, 1 + (STATS.containsKey(key) ? STATS.get(key) : 0));
  349. } catch (NullPointerException ex) {
  350. // JVM bugs ftl.
  351. }
  352. }
  353. /**
  354. * Retrieves the statistic map.
  355. *
  356. * @return A map of config options to lookup counts
  357. */
  358. public static Map<String, Integer> getStats() {
  359. return STATS;
  360. }
  361. @Override
  362. public void addChangeListener(final String domain,
  363. final ConfigChangeListener listener) {
  364. addListener(domain, listener);
  365. }
  366. @Override
  367. public void addChangeListener(final String domain, final String key,
  368. final ConfigChangeListener listener) {
  369. addListener(domain + '.' + key, listener);
  370. }
  371. @Override
  372. public void removeListener(final ConfigChangeListener listener) {
  373. synchronized (listeners) {
  374. final Iterable<String> keys = new HashSet<>(listeners.keySet());
  375. keys.forEach(k -> listeners.remove(k, listener));
  376. }
  377. }
  378. /**
  379. * Adds the specified listener to the internal map/list.
  380. *
  381. * @param key The key to use (domain or domain.key)
  382. * @param listener The listener to register
  383. */
  384. private void addListener(final String key,
  385. final ConfigChangeListener listener) {
  386. synchronized (listeners) {
  387. listeners.put(key, listener);
  388. }
  389. }
  390. @Override
  391. public void configChanged(final String domain, final String key) {
  392. final Collection<ConfigChangeListener> targets = new ArrayList<>();
  393. if (listeners.containsKey(domain)) {
  394. targets.addAll(listeners.get(domain));
  395. }
  396. if (listeners.containsKey(domain + '.' + key)) {
  397. targets.addAll(listeners.get(domain + '.' + key));
  398. }
  399. for (ConfigChangeListener listener : targets) {
  400. listener.configChanged(domain, key);
  401. }
  402. }
  403. @Override
  404. public void configProviderAdded(final ConfigFileBackedConfigProvider configProvider) {
  405. checkIdentity(configProvider);
  406. }
  407. @Override
  408. public void configProviderRemoved(final ConfigFileBackedConfigProvider configProvider) {
  409. removeIdentity(configProvider);
  410. }
  411. }