Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ConfigBinder.java 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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.logger.ErrorLevel;
  26. import com.dmdirc.logger.Logger;
  27. import com.dmdirc.ui.Colour;
  28. import com.dmdirc.util.collections.MapList;
  29. import java.lang.reflect.AccessibleObject;
  30. import java.lang.reflect.Field;
  31. import java.lang.reflect.InvocationTargetException;
  32. import java.lang.reflect.Method;
  33. import java.util.ArrayList;
  34. import java.util.Arrays;
  35. import java.util.Collection;
  36. import java.util.List;
  37. /**
  38. * Facilitates automatically binding fields or methods annotated with a
  39. * {@link ConfigBinding} element to a configuration value.
  40. */
  41. public class ConfigBinder {
  42. /** A map of instances to created listeners. */
  43. private final MapList<Object, ConfigChangeListener> listeners = new MapList<>();
  44. /** The configuration manager to use to retrieve settings. */
  45. private final AggregateConfigProvider manager;
  46. public ConfigBinder(final AggregateConfigProvider manager) {
  47. this.manager = manager;
  48. }
  49. /**
  50. * Binds all annotated methods and fields of the given instance to this
  51. * binder's configuration manager.
  52. *
  53. * @param instance The instance to be bound
  54. * @param clazz The class to read bindings from
  55. */
  56. @SuppressWarnings("unchecked")
  57. public void bind(final Object instance, final Class<?> clazz) {
  58. final List<ConfigChangeListener> newListeners = new ArrayList<>();
  59. final List<AccessibleObject> elements = new ArrayList<>();
  60. elements.addAll(Arrays.asList(clazz.getDeclaredMethods()));
  61. elements.addAll(Arrays.asList(clazz.getDeclaredFields()));
  62. for (AccessibleObject element : elements) {
  63. final ConfigBinding binding = element.getAnnotation(ConfigBinding.class);
  64. if (binding != null) {
  65. final ConfigChangeListener listener = getListener(instance, element, binding);
  66. newListeners.add(listener);
  67. manager.addChangeListener(binding.domain(), binding.key(), listener);
  68. for (int i = 0; i < binding.fallbacks().length - 1; i += 2) {
  69. manager.addChangeListener(binding.fallbacks()[i], binding.fallbacks()[i + 1], listener);
  70. }
  71. if (binding.applyInitially()) {
  72. updateBoundMember(instance, element, binding);
  73. }
  74. }
  75. }
  76. addListeners(instance, newListeners);
  77. }
  78. /**
  79. * Creates a new listener which will call
  80. * {@link #updateBoundMember(Object, AccessibleObject, ConfigBinding)}
  81. * with the given arguments.
  82. *
  83. * @param instance The instance to create a listener for
  84. * @param element The element to create a listener for
  85. * @param binding The binding annotation on the above element
  86. * @return An appropriate config change listener
  87. */
  88. private ConfigChangeListener getListener(final Object instance,
  89. final AccessibleObject element, final ConfigBinding binding) {
  90. return new ConfigChangeListener() {
  91. /** {@inheritDoc} */
  92. @Override
  93. public void configChanged(final String domain, final String key) {
  94. updateBoundMember(instance, element, binding);
  95. }
  96. };
  97. }
  98. /**
  99. * Updates the specified element of the given instance with the current
  100. * value of the configuration key(s) specified by its binding.
  101. *
  102. * @param instance The instance to be updated
  103. * @param element The element to be updated
  104. * @param binding The binding which defines the configuration properties
  105. */
  106. private void updateBoundMember(final Object instance,
  107. final AccessibleObject element, final ConfigBinding binding) {
  108. if (!element.isAccessible()) {
  109. element.setAccessible(true);
  110. }
  111. final Object value = getValue(binding, getTargetClass(element));
  112. if (element instanceof Field) {
  113. try {
  114. ((Field) element).set(instance, value);
  115. } catch (IllegalAccessException | IllegalArgumentException ex) {
  116. // Ignore
  117. }
  118. }
  119. if (element instanceof Method) {
  120. try {
  121. ((Method) element).invoke(instance, value);
  122. } catch (IllegalAccessException | IllegalArgumentException ex) {
  123. // Ignore
  124. } catch (InvocationTargetException ex) {
  125. Logger.appError(ErrorLevel.HIGH,
  126. "Exception when updating bound setting", ex);
  127. }
  128. }
  129. }
  130. /**
  131. * Gets a value from the configuration manager for use with the given
  132. * binding, and attempts to coerce it into the given class.
  133. *
  134. * @param binding The binding defining configuration parameters
  135. * @param targetClass The desired class
  136. * @return An object representing the current value of the configuration
  137. * key(s) associated with the binding, of the desired target class, or null
  138. * if the type conversion couldn't be performed.
  139. */
  140. private Object getValue(final ConfigBinding binding,
  141. final Class<?> targetClass) {
  142. if (targetClass.equals(String.class)) {
  143. return manager.getOptionString(binding.domain(), binding.key(), binding.fallbacks());
  144. }
  145. if (targetClass.equals(Colour.class)) {
  146. return manager.getOptionColour(binding.domain(), binding.key(), binding.fallbacks());
  147. }
  148. if (targetClass.equals(Boolean.class) || targetClass.equals(Boolean.TYPE)) {
  149. return manager.getOptionBool(binding.domain(), binding.key());
  150. }
  151. if (targetClass.equals(Character.class) || targetClass.equals(Character.TYPE)) {
  152. return manager.getOptionChar(binding.domain(), binding.key());
  153. }
  154. if (targetClass.equals(Integer.class) || targetClass.equals(Integer.TYPE)) {
  155. return manager.getOptionInt(binding.domain(), binding.key(), binding.fallbacks());
  156. }
  157. return null;
  158. }
  159. /**
  160. * Gets the type required for setting the given element.
  161. *
  162. * @param element The element to determine a type for
  163. * @return If the given element is a field, then the type of that field;
  164. * if the element is a method then the type of the first parameter;
  165. * otherwise, <code>String.class</code>.
  166. */
  167. private Class<?> getTargetClass(final AccessibleObject element) {
  168. if (element instanceof Field) {
  169. return ((Field) element).getType();
  170. }
  171. if (element instanceof Method) {
  172. return ((Method) element).getParameterTypes()[0];
  173. }
  174. return String.class;
  175. }
  176. /**
  177. * Adds the given listeners to the given instance's collection.
  178. *
  179. * @param instance The instance to add listeners for
  180. * @param newListeners The listeners to be added
  181. */
  182. private void addListeners(final Object instance,
  183. final Collection<ConfigChangeListener> newListeners) {
  184. synchronized (listeners) {
  185. listeners.add(instance, newListeners);
  186. }
  187. }
  188. /**
  189. * Unbinds all elements of the given instance that have been bound using
  190. * this ConfigBinder.
  191. *
  192. * @param instance The instance to be unbound
  193. */
  194. public void unbind(final Object instance) {
  195. synchronized (listeners) {
  196. for (ConfigChangeListener listener : listeners.safeGet(instance)) {
  197. manager.removeListener(listener);
  198. }
  199. listeners.remove(instance);
  200. }
  201. }
  202. }