Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

ActionSubstitutor.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.actions;
  23. import com.dmdirc.FrameContainer;
  24. import com.dmdirc.Precondition;
  25. import com.dmdirc.Server;
  26. import com.dmdirc.ServerState;
  27. import com.dmdirc.actions.interfaces.ActionComponent;
  28. import com.dmdirc.actions.interfaces.ActionType;
  29. import com.dmdirc.commandparser.CommandArguments;
  30. import com.dmdirc.config.ConfigManager;
  31. import com.dmdirc.config.IdentityManager;
  32. import com.dmdirc.ui.interfaces.Window;
  33. import java.util.Arrays;
  34. import java.util.HashMap;
  35. import java.util.Map;
  36. import java.util.Set;
  37. import java.util.regex.Matcher;
  38. import java.util.regex.Pattern;
  39. /**
  40. * Handles the substitution of variables into action targets and responses.
  41. *
  42. * @author Chris
  43. */
  44. public class ActionSubstitutor {
  45. /** Substitution to use when a component requires a connected server. */
  46. private static final String ERR_NOT_CONNECTED = "not_connected";
  47. /** Substitution to use to replace an unknown substitution. */
  48. private static final String ERR_NOT_DEFINED = "not_defined";
  49. /** Substitution to use to replace a chain that evaluates to null. */
  50. private static final String ERR_NULL_CHAIN = "null_component";
  51. /** Substitution to use to replace subs with illegal components. */
  52. private static final String ERR_ILLEGAL_COMPONENT = "illegal_component";
  53. /** Pattern used to match braced substitutions. */
  54. private static final Pattern BRACES_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)"
  55. + "(\\$\\{([^{}]*?)\\})");
  56. /** Pattern used to match all other substitutions. */
  57. private static final Pattern OTHER_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)(\\$("
  58. + "[0-9]+(-([0-9]+)?)?|" // Word subs - $1, $1-, $1-2
  59. + "[0-9]+(\\.([A-Z_]+))+|" // Component subs - 2.FOO_BAR
  60. + "[a-z0-9A-Z_\\.]+" // Config/server subs
  61. + "))");
  62. /** Pattern to determine if a substitution is a word number type. */
  63. private static final Pattern NUMBER_PATTERN = Pattern.compile("([0-9]+)(-([0-9]+)?)?");
  64. /** Pattern to determine if a substitution is an argument+component type. */
  65. private static final Pattern COMP_PATTERN = Pattern.compile("([0-9]+)\\.([A-Z_]+(\\.[A-Z_]+)*)");
  66. /** Pattern to determine if a substitution is a server component type. */
  67. private static final Pattern SERVER_PATTERN = Pattern.compile("[A-Z_]+(\\.[A-Z_]+)*");
  68. /** The action type this substitutor is for. */
  69. private final ActionType type;
  70. /**
  71. * Creates a new substitutor for the specified action type.
  72. *
  73. * @param type The action type this substitutor is for
  74. */
  75. public ActionSubstitutor(final ActionType type) {
  76. this.type = type;
  77. }
  78. /**
  79. * Retrieves a list of global config variables that will be substituted.
  80. * Note: does not include initial $.
  81. *
  82. * @return A list of global variable names that will be substituted
  83. */
  84. public Set<String> getConfigSubstitutions() {
  85. return IdentityManager.getGlobalConfig().getOptions("actions").keySet();
  86. }
  87. /**
  88. * Retrieves a list of substitutions derived from argument and component
  89. * combinations, along with a corresponding friendly name for them.
  90. * Note: does not include initial $.
  91. *
  92. * @return A map of component substitution names and their descriptions
  93. */
  94. public Map<String, String> getComponentSubstitutions() {
  95. final Map<String, String> res = new HashMap<String, String>();
  96. int i = 0;
  97. for (Class<?> myClass : type.getType().getArgTypes()) {
  98. for (ActionComponent comp : ActionManager.getActionManager()
  99. .findCompatibleComponents(myClass)) {
  100. final String key = "{" + i + "." + comp.toString() + "}";
  101. final String desc = type.getType().getArgNames()[i] + "'s " + comp.getName();
  102. res.put(key, desc);
  103. }
  104. i++;
  105. }
  106. return res;
  107. }
  108. /**
  109. * Retrieves a list of server substitutions, if this action type supports
  110. * them.
  111. * Note: does not include initial $.
  112. *
  113. * @return A map of server substitution names and their descriptions.
  114. */
  115. public Map<String, String> getServerSubstitutions() {
  116. final Map<String, String> res = new HashMap<String, String>();
  117. if (hasFrameContainer()) {
  118. for (ActionComponent comp : ActionManager.getActionManager()
  119. .findCompatibleComponents(Server.class)) {
  120. final String key = "{" + comp.toString() + "}";
  121. final String desc = "The connection's " + comp.getName();
  122. res.put(key, desc);
  123. }
  124. }
  125. return res;
  126. }
  127. /**
  128. * Returns true if this action type's first argument is a frame container,
  129. * or descendent of one.
  130. *
  131. * @return True if this action type's first arg extends or is a FrameContainer
  132. */
  133. private boolean hasFrameContainer() {
  134. Class<?> target = null;
  135. if (type.getType().getArgTypes().length > 0) {
  136. target = type.getType().getArgTypes()[0];
  137. while (target != null && target != FrameContainer.class) {
  138. target = target.getSuperclass();
  139. }
  140. }
  141. return target == FrameContainer.class;
  142. }
  143. /**
  144. * Determines whether or not word substitutions will work for this action
  145. * type. Word substitutions take the form $1, $1-5, $6-, etc.
  146. *
  147. * @return True if word substitutions are supported, false otherwise.
  148. */
  149. public boolean usesWordSubstitutions() {
  150. return type.getType().getArgTypes().length > 2
  151. && (type.getType().getArgTypes()[2] == String[].class
  152. || type.getType().getArgTypes()[2] == String.class);
  153. }
  154. /**
  155. * Performs all applicable substitutions on the specified string, with the
  156. * specified arguments.
  157. *
  158. * @param target The string to be altered
  159. * @param args The arguments for the action type
  160. * @return The substituted string
  161. */
  162. @Precondition("Number of arguments given equals the number of arguments "
  163. + "required by this substitutor's type")
  164. public String doSubstitution(final String target, final Object ... args) {
  165. if (type.getType().getArity() != args.length) {
  166. throw new IllegalArgumentException("Invalid number of arguments "
  167. + "for doSubstitution: expected " + type.getType().getArity() + ", got "
  168. + args.length + ". Type: " + type.getName());
  169. }
  170. final StringBuilder res = new StringBuilder(target);
  171. Matcher bracesMatcher = BRACES_PATTERN.matcher(res);
  172. Matcher otherMatcher = OTHER_PATTERN.matcher(res);
  173. boolean first;
  174. while ((first = bracesMatcher.find()) || otherMatcher.find()) {
  175. final Matcher matcher = first ? bracesMatcher : otherMatcher;
  176. final String group = matcher.group(3);
  177. final int start = matcher.start() + matcher.group(1).length(), end = matcher.end();
  178. res.delete(start, end);
  179. res.insert(start, getSubstitution(doSubstitution(group, args), args));
  180. bracesMatcher = BRACES_PATTERN.matcher(res);
  181. otherMatcher = OTHER_PATTERN.matcher(res);
  182. }
  183. return res.toString().replaceAll("\\\\(.)", "$1");
  184. }
  185. /**
  186. * Retrieves the value which should be used for the specified substitution.
  187. *
  188. * @param substitution The substitution, without leading $
  189. * @param args The arguments for the action
  190. * @return The substitution to be used
  191. */
  192. private String getSubstitution(final String substitution, final Object ... args) {
  193. final Matcher numberMatcher = NUMBER_PATTERN.matcher(substitution);
  194. final Matcher compMatcher = COMP_PATTERN.matcher(substitution);
  195. final Matcher serverMatcher = SERVER_PATTERN.matcher(substitution);
  196. if (usesWordSubstitutions() && numberMatcher.matches()) {
  197. final CommandArguments words = args[2] instanceof String
  198. ? new CommandArguments((String) args[2])
  199. : new CommandArguments(Arrays.asList((String[]) args[2]));
  200. int start, end;
  201. start = end = Integer.parseInt(numberMatcher.group(1)) - 1;
  202. if (numberMatcher.group(3) != null) {
  203. end = Integer.parseInt(numberMatcher.group(3)) - 1;
  204. } else if (numberMatcher.group(2) != null) {
  205. end = words.getWords().length - 1;
  206. }
  207. return words.getWordsAsString(start, end);
  208. }
  209. if (compMatcher.matches()) {
  210. final int argument = Integer.parseInt(compMatcher.group(1));
  211. try {
  212. final ActionComponentChain chain = new ActionComponentChain(
  213. type.getType().getArgTypes()[argument], compMatcher.group(2));
  214. return escape(checkConnection(chain, args, args[argument]));
  215. } catch (IllegalArgumentException ex) {
  216. return ERR_ILLEGAL_COMPONENT;
  217. }
  218. }
  219. final ConfigManager manager = getConfigManager(args);
  220. if (manager.hasOptionString("actions", substitution)) {
  221. return manager.getOption("actions", substitution);
  222. }
  223. if (hasFrameContainer() && serverMatcher.matches()) {
  224. final Server server = ((FrameContainer) args[0]).getServer();
  225. if (server != null) {
  226. try {
  227. final ActionComponentChain chain = new ActionComponentChain(
  228. Server.class, substitution);
  229. return escape(checkConnection(chain, args, server));
  230. } catch (IllegalArgumentException ex) {
  231. return ERR_ILLEGAL_COMPONENT;
  232. }
  233. }
  234. }
  235. return ERR_NOT_DEFINED;
  236. }
  237. /**
  238. * Checks the connection status of any server associated with the specified
  239. * arguments. If the specified component chain requires a server with an
  240. * established connection and no such server is present, this method
  241. * returns the string <code>not_connected</code> without attempting to
  242. * evaluate any components in the chain.
  243. *
  244. * @since 0.6.4
  245. * @param chain The chain to be checked
  246. * @param args The arguments for this invocation
  247. * @param argument The argument used as a base for the chain
  248. * @return The value of the evaluated chain, or <code>not_connected</code>
  249. */
  250. protected String checkConnection(final ActionComponentChain chain,
  251. final Object[] args, final Object argument) {
  252. if ((chain.requiresConnection() && args[0] instanceof FrameContainer
  253. && ((FrameContainer) args[0]).getServer().getState()
  254. == ServerState.CONNECTED) || !chain.requiresConnection()) {
  255. final Object res = chain.get(argument);
  256. return res == null ? ERR_NULL_CHAIN : res.toString();
  257. }
  258. return ERR_NOT_CONNECTED;
  259. }
  260. /**
  261. * Tries to retrieve an appropriate configuration manager from the
  262. * specified set of arguments. If any of the arguments is an instance of
  263. * {@link FrameContainer} or {@link Window}, the config manager is
  264. * requested from them. Otherwise, the global config is returned.
  265. *
  266. * @param args The arguments to be tested
  267. * @return The best config manager to use for those arguments
  268. * @since 0.6.3m2
  269. */
  270. protected ConfigManager getConfigManager(final Object ... args) {
  271. for (Object arg : args) {
  272. if (arg instanceof FrameContainer) {
  273. return ((FrameContainer) arg).getConfigManager();
  274. } else if (arg instanceof Window) {
  275. return ((Window) arg).getContainer().getConfigManager();
  276. }
  277. }
  278. return IdentityManager.getGlobalConfig();
  279. }
  280. /**
  281. * Escapes all special characters in the specified input. This will result
  282. * in the input being treated as a plain string when passed through the
  283. * substitutor (i.e., no substitutions will occur).
  284. *
  285. * @param input The string to be escaped
  286. * @return An escaped version of the specified string
  287. * @since 0.6.4
  288. */
  289. protected static String escape(final String input) {
  290. return input.replace("\\", "\\\\").replace("$", "\\$");
  291. }
  292. }