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.

ActionSubstitutor.java 13KB

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