Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ConfigFileBackedConfigProvider.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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.provider.ConfigChangeListener;
  19. import com.dmdirc.config.provider.ConfigProvider;
  20. import com.dmdirc.util.io.ConfigFile;
  21. import com.dmdirc.util.io.InvalidConfigFileException;
  22. import com.dmdirc.util.validators.Validator;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.lang.ref.WeakReference;
  26. import java.nio.file.Path;
  27. import java.util.Collection;
  28. import java.util.HashMap;
  29. import java.util.HashSet;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Objects;
  34. import java.util.Set;
  35. import java.util.concurrent.CopyOnWriteArrayList;
  36. import javax.annotation.Nullable;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. /**
  40. * Provides configuration settings from a {@link ConfigFile}.
  41. */
  42. public class ConfigFileBackedConfigProvider implements ConfigProvider {
  43. private static final Logger LOG = LoggerFactory.getLogger(ConfigFileBackedConfigProvider.class);
  44. /** The domain used for identity settings. */
  45. private static final String DOMAIN = "identity";
  46. /** The domain used for profile settings. */
  47. private static final String PROFILE_DOMAIN = "profile";
  48. /** The target for this identity. */
  49. protected final ConfigTarget myTarget;
  50. /** The identity manager to use for writable configs. */
  51. @Nullable
  52. private final IdentityManager identityManager;
  53. /** The configuration details for this identity. */
  54. protected final ConfigFile file;
  55. /** The global config manager. */
  56. protected ConfigManager globalConfig;
  57. /** The config change listeners for this source. */
  58. protected final List<WeakReference<ConfigChangeListener>> listeners =
  59. new CopyOnWriteArrayList<>();
  60. /** Whether this identity needs to be saved. */
  61. private boolean needSave;
  62. /**
  63. * Creates a new instance of Identity.
  64. *
  65. * @param identityManager The manager to use for hackily reading global state.
  66. * @param file The file to load this identity from
  67. * @param forceDefault Whether to force this identity to be loaded as default identity or not
  68. *
  69. * @throws InvalidIdentityFileException Missing required properties
  70. * @throws IOException Input/output exception
  71. */
  72. public ConfigFileBackedConfigProvider(
  73. @Nullable final IdentityManager identityManager, final Path file,
  74. final boolean forceDefault) throws IOException, InvalidIdentityFileException {
  75. this.identityManager = identityManager;
  76. this.file = new ConfigFile(file);
  77. this.file.setAutomake(true);
  78. initFile(forceDefault);
  79. myTarget = getTarget(forceDefault);
  80. }
  81. /**
  82. * Creates a new read-only identity.
  83. *
  84. * @param stream The input stream to read the identity from
  85. * @param forceDefault Whether to force this identity to be loaded as default identity or not
  86. *
  87. * @throws InvalidIdentityFileException Missing required properties
  88. * @throws IOException Input/output exception
  89. */
  90. public ConfigFileBackedConfigProvider(final InputStream stream,
  91. final boolean forceDefault) throws IOException, InvalidIdentityFileException {
  92. this.identityManager = null;
  93. this.file = new ConfigFile(stream);
  94. file.setAutomake(true);
  95. initFile(forceDefault);
  96. myTarget = getTarget(forceDefault);
  97. }
  98. /**
  99. * Creates a new identity from the specified config file.
  100. *
  101. * @param identityManager The manager to use for hackily reading global state.
  102. * @param configFile The config file to use
  103. * @param target The target of this identity
  104. */
  105. public ConfigFileBackedConfigProvider(@Nullable final IdentityManager identityManager,
  106. final ConfigFile configFile, final ConfigTarget target) {
  107. this.identityManager = identityManager;
  108. this.file = configFile;
  109. file.setAutomake(true);
  110. this.myTarget = target;
  111. }
  112. /**
  113. * Determines and returns the target for this identity from its contents.
  114. *
  115. * @param forceDefault Whether to force this to be a default identity
  116. *
  117. * @return A ConfigTarget for this identity
  118. *
  119. * @throws InvalidIdentityFileException If the identity isn't valid
  120. */
  121. private ConfigTarget getTarget(final boolean forceDefault)
  122. throws InvalidIdentityFileException {
  123. final ConfigTarget target = new ConfigTarget();
  124. if (hasOptionString(DOMAIN, "ircd")) {
  125. target.setIrcd(getOption(DOMAIN, "ircd"));
  126. } else if (hasOptionString(DOMAIN, "protocol")) {
  127. target.setProtocol(getOption(DOMAIN, "protocol"));
  128. } else if (hasOptionString(DOMAIN, "network")) {
  129. target.setNetwork(getOption(DOMAIN, "network"));
  130. } else if (hasOptionString(DOMAIN, "server")) {
  131. target.setServer(getOption(DOMAIN, "server"));
  132. } else if (hasOptionString(DOMAIN, "channel")) {
  133. target.setChannel(getOption(DOMAIN, "channel"));
  134. } else if (hasOptionString(DOMAIN, "globaldefault")) {
  135. target.setGlobalDefault();
  136. } else if (hasOptionString(DOMAIN, "global") || forceDefault && !isProfile()) {
  137. target.setGlobal();
  138. } else if (isProfile()) {
  139. target.setCustom(PROFILE_DOMAIN);
  140. } else if (hasOptionString(DOMAIN, "type")) {
  141. target.setCustom(getOption(DOMAIN, "type"));
  142. } else {
  143. throw new InvalidIdentityFileException("No target and no profile");
  144. }
  145. if (hasOptionString(DOMAIN, "order")) {
  146. target.setOrder(getOptionInt(DOMAIN, "order"));
  147. }
  148. return target;
  149. }
  150. /**
  151. * Initialises this identity from a file.
  152. *
  153. * @since 0.6.3
  154. * @param forceDefault Whether to force this to be a default identity
  155. *
  156. * @throws InvalidIdentityFileException if the identity file is invalid
  157. * @throws IOException On I/O exception when reading the identity
  158. */
  159. private void initFile(final boolean forceDefault)
  160. throws InvalidIdentityFileException, IOException {
  161. try {
  162. file.read();
  163. } catch (InvalidConfigFileException ex) {
  164. throw new InvalidIdentityFileException(ex);
  165. }
  166. if (!hasOptionString(DOMAIN, "name") && !forceDefault) {
  167. throw new InvalidIdentityFileException("No name specified");
  168. }
  169. }
  170. @Override
  171. public void reload() throws IOException, InvalidConfigFileException {
  172. if (needSave) {
  173. return;
  174. }
  175. final Collection<String[]> changes = new LinkedList<>();
  176. synchronized (this) {
  177. final Map<String, Map<String, String>> oldProps = new HashMap<>(file.getKeyDomains());
  178. file.read();
  179. for (Map.Entry<String, Map<String, String>> entry : file.getKeyDomains().entrySet()) {
  180. final String domain = entry.getKey();
  181. for (Map.Entry<String, String> subentry : entry.getValue().entrySet()) {
  182. final String key = subentry.getKey();
  183. final String value = subentry.getValue();
  184. if (!oldProps.containsKey(domain) || !oldProps.get(domain).containsKey(key)) {
  185. // Newly added (didn't exist in the old file)
  186. changes.add(new String[]{domain, key});
  187. } else if (!oldProps.get(domain).get(key).equals(value)) {
  188. // Modified in some way
  189. changes.add(new String[]{domain, key});
  190. oldProps.get(domain).remove(key);
  191. } else {
  192. // Not modified
  193. oldProps.get(domain).remove(key);
  194. }
  195. }
  196. // Anything left in the domain must have been moved
  197. if (oldProps.containsKey(domain)) {
  198. for (String key : oldProps.get(domain).keySet()) {
  199. changes.add(new String[]{domain, key});
  200. }
  201. }
  202. oldProps.remove(domain);
  203. }
  204. // Any domains left must have been removed
  205. for (Map.Entry<String, Map<String, String>> entry : oldProps.entrySet()) {
  206. for (String key : entry.getValue().keySet()) {
  207. changes.add(new String[]{entry.getKey(), key});
  208. }
  209. }
  210. }
  211. for (String[] change : changes) {
  212. fireSettingChange(change[0], change[1]);
  213. }
  214. }
  215. /**
  216. * Fires the config changed listener for the specified option after this identity is reloaded.
  217. *
  218. * @param domain The domain of the option that's changed
  219. * @param key The key of the option that's changed
  220. *
  221. * @since 0.6.3m1
  222. */
  223. private void fireSettingChange(final String domain, final String key) {
  224. listeners.stream()
  225. .map(WeakReference::get)
  226. .filter(Objects::nonNull)
  227. .forEach(l -> l.configChanged(domain, key));
  228. }
  229. @Override
  230. public String getName() {
  231. if (hasOptionString(DOMAIN, "name")) {
  232. return getOption(DOMAIN, "name");
  233. } else {
  234. return "Unnamed";
  235. }
  236. }
  237. public boolean isProfile() {
  238. return (hasOptionString(PROFILE_DOMAIN, "nicknames")
  239. || hasOptionString(PROFILE_DOMAIN, "nickname"))
  240. && hasOptionString(PROFILE_DOMAIN, "realname");
  241. }
  242. @Override
  243. public boolean hasOption(final String domain, final String option,
  244. final Validator<String> validator) {
  245. return file.isKeyDomain(domain)
  246. && file.getKeyDomain(domain).containsKey(option)
  247. && !validator.validate(file.getKeyDomain(domain).get(option)).isFailure();
  248. }
  249. @Override
  250. public synchronized String getOption(final String domain,
  251. final String option, final Validator<String> validator) {
  252. final String value = file.getKeyDomain(domain).get(option);
  253. if (validator.validate(value).isFailure()) {
  254. return null;
  255. }
  256. return value;
  257. }
  258. @Override
  259. public void setOption(final String domain, final String option,
  260. final String value) {
  261. final String oldValue;
  262. boolean unset = false;
  263. synchronized (this) {
  264. oldValue = getOption(domain, option);
  265. LOG.trace("{}: setting {}.{} to {} (was: {})", getName(), domain, option, value,
  266. oldValue);
  267. if (myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
  268. // If we're the global config, don't set useless settings that are
  269. // covered by global defaults.
  270. if (globalConfig == null) {
  271. // TODO: This is horrible. Filtering of saves should be abstracted.
  272. globalConfig = (ConfigManager) identityManager
  273. .createAggregateConfig("", "", "", "");
  274. }
  275. globalConfig.removeIdentity(this);
  276. if (globalConfig.hasOptionString(domain, option)
  277. && globalConfig.getOption(domain, option).equals(value)) {
  278. // The new value is covered by a default setting
  279. if (oldValue == null) {
  280. // There was no old value, so we don't need to do anything
  281. return;
  282. } else {
  283. // There was an old value, so we need to unset it so
  284. // that the default shows through.
  285. file.getKeyDomain(domain).remove(option);
  286. needSave = true;
  287. unset = true;
  288. }
  289. }
  290. }
  291. if (!unset && (oldValue == null && value != null
  292. || oldValue != null && !oldValue.equals(value))) {
  293. file.getKeyDomain(domain).put(option, value);
  294. needSave = true;
  295. }
  296. }
  297. // Fire any setting change listeners now we're no longer holding
  298. // a lock on this identity.
  299. if (unset || !Objects.equals(oldValue, value)) {
  300. fireSettingChange(domain, option);
  301. }
  302. }
  303. @Override
  304. public void setOption(final String domain, final String option,
  305. final int value) {
  306. setOption(domain, option, String.valueOf(value));
  307. }
  308. @Override
  309. public void setOption(final String domain, final String option,
  310. final boolean value) {
  311. setOption(domain, option, String.valueOf(value));
  312. }
  313. @Override
  314. public void setOption(final String domain, final String option,
  315. final List<String> value) {
  316. final StringBuilder temp = new StringBuilder();
  317. for (String part : value) {
  318. temp.append('\n');
  319. temp.append(part);
  320. }
  321. setOption(domain, option, temp.length() > 0 ? temp.substring(1) : temp.toString());
  322. }
  323. @Override
  324. public void unsetOption(final String domain, final String option) {
  325. if (!file.isKeyDomain(domain) || !file.getKeyDomain(domain).containsKey(option)) {
  326. return;
  327. }
  328. synchronized (this) {
  329. file.getKeyDomain(domain).remove(option);
  330. needSave = true;
  331. }
  332. fireSettingChange(domain, option);
  333. }
  334. @Override
  335. public Set<String> getDomains() {
  336. return new HashSet<>(file.getKeyDomains().keySet());
  337. }
  338. @Override
  339. public synchronized Map<String, String> getOptions(final String domain) {
  340. return new HashMap<>(file.getKeyDomain(domain));
  341. }
  342. @Override
  343. public synchronized void save() {
  344. LOG.info("{}: saving. Needsave = {}", new Object[]{getName(), needSave});
  345. if (needSave && file.isWritable()) {
  346. if (myTarget != null && myTarget.getType() == ConfigTarget.TYPE.GLOBAL) {
  347. LOG.debug("{}: I'm a global config", getName());
  348. // This branch is executed if this identity is global. In this
  349. // case, we build a global config (removing ourself and the
  350. // versions identity) and compare our values to the values
  351. // contained in that. Any values that are the same can be unset
  352. // from this identity (as they will default to their current
  353. // value).
  354. //
  355. // Note that the updater channel is included in the version
  356. // identity, and this is excluded from the global config. This
  357. // means that once you manually set the channel it will stay
  358. // like that until you manually change it again, as opposed
  359. // to being removed as soon as you use a build from that
  360. // channel.
  361. // TODO: This behaviour should be managed by something else.
  362. if (globalConfig == null) {
  363. globalConfig = (ConfigManager) identityManager
  364. .createAggregateConfig("", "", "", "");
  365. }
  366. globalConfig.removeIdentity(this);
  367. globalConfig.removeIdentity(identityManager.getVersionSettings());
  368. if (LOG.isTraceEnabled()) {
  369. for (ConfigProvider source : globalConfig.getSources()) {
  370. LOG.trace("{}: source: {}",
  371. new Object[]{getName(), source.getName()});
  372. }
  373. }
  374. for (Map.Entry<String, Map<String, String>> entry
  375. : file.getKeyDomains().entrySet()) {
  376. final String domain = entry.getKey();
  377. for (Map.Entry<String, String> subentry : new HashSet<>(entry.getValue().
  378. entrySet())) {
  379. final String key = subentry.getKey();
  380. final String value = subentry.getValue();
  381. if (globalConfig.hasOptionString(domain, key)
  382. && globalConfig.getOption(domain, key).equals(value)) {
  383. LOG.debug("{}: found superfluous setting: {}.{} (= {})", getName(),
  384. domain, key, value);
  385. file.getKeyDomain(domain).remove(key);
  386. }
  387. }
  388. }
  389. }
  390. if (file.isKeyDomain("temp")) {
  391. file.getKeyDomain("temp").clear();
  392. }
  393. try {
  394. file.write();
  395. needSave = false;
  396. } catch (IOException ex) {
  397. LOG.warn("Unable to save identity file", ex);
  398. }
  399. }
  400. }
  401. @Override
  402. public synchronized void delete() throws IOException {
  403. file.delete();
  404. identityManager.removeConfigProvider(this);
  405. }
  406. public ConfigTarget getTarget() {
  407. return myTarget;
  408. }
  409. @Override
  410. public void addListener(final ConfigChangeListener listener) {
  411. listeners.add(new WeakReference<>(listener));
  412. }
  413. @Override
  414. public void removeListener(final ConfigChangeListener listener) {
  415. listeners.stream().filter(w -> {
  416. final ConfigChangeListener target = w.get();
  417. return target == null || target.equals(listener);
  418. }).forEach(listeners::remove);
  419. }
  420. /**
  421. * Returns a string representation of this object (its name).
  422. *
  423. * @return A string representation of this object
  424. */
  425. @Override
  426. public String toString() {
  427. return getName();
  428. }
  429. @Override
  430. public int hashCode() {
  431. return getName().hashCode() + getTarget().hashCode();
  432. }
  433. @Override
  434. public boolean equals(final Object obj) {
  435. return obj instanceof ConfigFileBackedConfigProvider
  436. && getName().equals(((ConfigProvider) obj).getName())
  437. && getTarget() == ((ConfigFileBackedConfigProvider) obj).getTarget();
  438. }
  439. }