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.

ConfigBinder.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /*
  2. * Copyright (c) 2006-2011 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.ConfigChangeListener;
  24. import com.dmdirc.logger.ErrorLevel;
  25. import com.dmdirc.logger.Logger;
  26. import com.dmdirc.ui.Colour;
  27. import com.dmdirc.util.collections.MapList;
  28. import java.lang.reflect.AccessibleObject;
  29. import java.lang.reflect.Field;
  30. import java.lang.reflect.InvocationTargetException;
  31. import java.lang.reflect.Method;
  32. import java.util.ArrayList;
  33. import java.util.Arrays;
  34. import java.util.Collection;
  35. import java.util.List;
  36. import lombok.AllArgsConstructor;
  37. import lombok.Synchronized;
  38. /**
  39. * Facilitates automatically binding fields or methods annotated with a
  40. * {@link ConfigBinding} element to a configuration value.
  41. */
  42. @AllArgsConstructor
  43. public class ConfigBinder {
  44. /** A map of instances to created listeners. */
  45. private final MapList<Object, ConfigChangeListener> listeners
  46. = new MapList<Object, ConfigChangeListener>();
  47. /** The configuration manager to use to retrieve settings. */
  48. private final ConfigManager manager;
  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<ConfigChangeListener>();
  59. final List<AccessibleObject> elements = new ArrayList<AccessibleObject>();
  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 ex) {
  116. // Ignore
  117. } catch (IllegalArgumentException ex) {
  118. // Ignore
  119. }
  120. }
  121. if (element instanceof Method) {
  122. try {
  123. ((Method) element).invoke(instance, value);
  124. } catch (IllegalAccessException ex) {
  125. // Ignore
  126. } catch (IllegalArgumentException ex) {
  127. // Ignore
  128. } catch (InvocationTargetException ex) {
  129. Logger.appError(ErrorLevel.HIGH,
  130. "Exception when updating bound setting", ex);
  131. }
  132. }
  133. }
  134. /**
  135. * Gets a value from the configuration manager for use with the given
  136. * binding, and attempts to coerce it into the given class.
  137. *
  138. * @param binding The binding defining configuration parameters
  139. * @param targetClass The desired class
  140. * @return An object representing the current value of the configuration
  141. * key(s) associated with the binding, of the desired target class, or null
  142. * if the type conversion couldn't be performed.
  143. */
  144. private Object getValue(final ConfigBinding binding,
  145. final Class<?> targetClass) {
  146. if (targetClass.equals(String.class)) {
  147. return manager.getOptionString(binding.domain(), binding.key(), binding.fallbacks());
  148. }
  149. if (targetClass.equals(Colour.class)) {
  150. return manager.getOptionColour(binding.domain(), binding.key(), binding.fallbacks());
  151. }
  152. if (targetClass.equals(Boolean.class) || targetClass.equals(Boolean.TYPE)) {
  153. return manager.getOptionBool(binding.domain(), binding.key());
  154. }
  155. if (targetClass.equals(Character.class) || targetClass.equals(Character.TYPE)) {
  156. return manager.getOptionChar(binding.domain(), binding.key());
  157. }
  158. return null;
  159. }
  160. /**
  161. * Gets the type required for setting the given element.
  162. *
  163. * @param element The element to determine a type for
  164. * @return If the given element is a field, then the type of that field;
  165. * if the element is a method then the type of the first parameter;
  166. * otherwise, <code>String.class</code>.
  167. */
  168. private Class<?> getTargetClass(final AccessibleObject element) {
  169. if (element instanceof Field) {
  170. return ((Field) element).getType();
  171. }
  172. if (element instanceof Method) {
  173. return ((Method) element).getParameterTypes()[0];
  174. }
  175. return String.class;
  176. }
  177. /**
  178. * Adds the given listeners to the given instance's collection.
  179. *
  180. * @param instance The instance to add listeners for
  181. * @param newListeners The listeners to be added
  182. */
  183. @Synchronized
  184. private void addListeners(final Object instance,
  185. final Collection<ConfigChangeListener> newListeners) {
  186. listeners.add(instance, newListeners);
  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. @Synchronized
  195. public void unbind(final Object instance) {
  196. for (ConfigChangeListener listener : listeners.safeGet(instance)) {
  197. manager.removeListener(listener);
  198. }
  199. listeners.remove(instance);
  200. }
  201. }