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.

ConfigFileBackedConfigProvider.java 20KB

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