Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ConfigFileBackedConfigProvider.java 19KB

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