You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConfigManager.java 16KB

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