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.

Action.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * Copyright (c) 2006-2008 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.actions.interfaces.ActionComparison;
  26. import com.dmdirc.config.prefs.PreferencesSetting;
  27. import com.dmdirc.config.prefs.PreferencesType;
  28. import com.dmdirc.logger.ErrorLevel;
  29. import com.dmdirc.logger.Logger;
  30. import com.dmdirc.util.ConfigFile;
  31. import com.dmdirc.util.InvalidConfigFileException;
  32. import java.io.File;
  33. import java.io.IOException;
  34. import java.io.Serializable;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. /**
  41. * Describes a single action.
  42. *
  43. * @author chris
  44. */
  45. public class Action extends ActionModel implements Serializable {
  46. /**
  47. * A version number for this class. It should be changed whenever the class
  48. * structure is changed (or anything else that would prevent serialized
  49. * objects being unserialized with the new class).
  50. */
  51. private static final long serialVersionUID = 1;
  52. /** The domain name for condition trees. */
  53. private static final String DOMAIN_CONDITIONTREE = "conditiontree".intern();
  54. /** The domain name for format changes. */
  55. private static final String DOMAIN_FORMAT = "format".intern();
  56. /** The domain name for meta-data. */
  57. private static final String DOMAIN_METADATA = "metadata".intern();
  58. /** The domain name for response information. */
  59. private static final String DOMAIN_RESPONSE = "response".intern();
  60. /** The domain name for triggers. */
  61. private static final String DOMAIN_TRIGGERS = "triggers".intern();
  62. /** The location of the file we're reading/saving. */
  63. private String location;
  64. /** The config file we're using. */
  65. private ConfigFile config;
  66. /**
  67. * Creates a new instance of Action. The group and name specified must
  68. * be the group and name of a valid action already saved to disk.
  69. *
  70. * @param group The group the action belongs to
  71. * @param name The name of the action
  72. */
  73. public Action(final String group, final String name) {
  74. super(group, name);
  75. location = ActionManager.getDirectory() + group + File.separator + name;
  76. try {
  77. config = new ConfigFile(location);
  78. config.read();
  79. loadActionFromConfig();
  80. } catch (InvalidConfigFileException ex) {
  81. // This isn't a valid config file. Maybe it's a properties file?
  82. Logger.userError(ErrorLevel.MEDIUM, "Unable to parse action file: "
  83. + group + "/" + name + ": " + ex.getMessage());
  84. } catch (IOException ex) {
  85. Logger.userError(ErrorLevel.HIGH, "I/O error when loading action: "
  86. + group + "/" + name + ": " + ex.getMessage());
  87. }
  88. }
  89. /**
  90. * Creates a new instance of Action with the specified properties and saves
  91. * it to disk.
  92. *
  93. * @param group The group the action belongs to
  94. * @param name The name of the action
  95. * @param triggers The triggers to use
  96. * @param response The response to use
  97. * @param conditions The conditions to use
  98. * @param newFormat The new formatter to use
  99. */
  100. public Action(final String group, final String name,
  101. final ActionType[] triggers, final String[] response,
  102. final List<ActionCondition> conditions, final String newFormat) {
  103. this(group, name, triggers, response, conditions,
  104. ConditionTree.createConjunction(conditions.size()), newFormat);
  105. }
  106. /**
  107. * Creates a new instance of Action with the specified properties and saves
  108. * it to disk.
  109. *
  110. * @param group The group the action belongs to
  111. * @param name The name of the action
  112. * @param triggers The triggers to use
  113. * @param response The response to use
  114. * @param conditions The conditions to use
  115. * @param conditionTree The condition tree to use
  116. * @param newFormat The new formatter to use
  117. */
  118. public Action(final String group, final String name,
  119. final ActionType[] triggers, final String[] response,
  120. final List<ActionCondition> conditions,
  121. final ConditionTree conditionTree, final String newFormat) {
  122. super(group, name, triggers, response, conditions, conditionTree, newFormat);
  123. final String dir = ActionManager.getDirectory() + group + File.separator;
  124. location = dir + name;
  125. new File(dir).mkdirs();
  126. save();
  127. ActionManager.registerAction(this);
  128. }
  129. /**
  130. * Loads this action from the config instance.
  131. */
  132. private void loadActionFromConfig() {
  133. if (config.isFlatDomain(DOMAIN_TRIGGERS)) {
  134. if (!loadTriggers(config.getFlatDomain(DOMAIN_TRIGGERS))) {
  135. return;
  136. }
  137. } else {
  138. error("No trigger specified");
  139. return;
  140. }
  141. if (config.isFlatDomain(DOMAIN_RESPONSE)) {
  142. response = new String[config.getFlatDomain(DOMAIN_RESPONSE).size()];
  143. int i = 0;
  144. for (String line: config.getFlatDomain(DOMAIN_RESPONSE)) {
  145. response[i++] = line;
  146. }
  147. } else {
  148. error("No response specified");
  149. return;
  150. }
  151. if (config.isFlatDomain(DOMAIN_FORMAT)) {
  152. newFormat = config.getFlatDomain(DOMAIN_FORMAT).size() == 0 ? "" :
  153. config.getFlatDomain(DOMAIN_FORMAT).get(0);
  154. }
  155. for (int cond = 0; config.isKeyDomain("condition " + cond); cond++) {
  156. if (!readCondition(config.getKeyDomain("condition " + cond))) {
  157. return;
  158. }
  159. }
  160. if (config.isFlatDomain(DOMAIN_CONDITIONTREE)
  161. && config.getFlatDomain(DOMAIN_CONDITIONTREE).size() > 0) {
  162. conditionTree = ConditionTree.parseString(
  163. config.getFlatDomain(DOMAIN_CONDITIONTREE).get(0));
  164. if (conditionTree == null) {
  165. error("Unable to parse condition tree");
  166. return;
  167. }
  168. if (conditionTree.getMaximumArgument() >= conditions.size()) {
  169. error("Condition tree references condition "
  170. + conditionTree.getMaximumArgument() + " but there are"
  171. + " only " + conditions.size() + " conditions");
  172. return;
  173. }
  174. }
  175. ActionManager.registerAction(this);
  176. checkMetaData();
  177. }
  178. /**
  179. * Checks to see if this action contains group meta-data, and adds it to
  180. * the group as appropriate.
  181. */
  182. private void checkMetaData() {
  183. if (config.isKeyDomain(DOMAIN_METADATA)) {
  184. final ActionGroup myGroup = ActionManager.getGroup(group);
  185. final Map<String, String> data = config.getKeyDomain(DOMAIN_METADATA);
  186. if (data.containsKey("description")) {
  187. myGroup.setDescription(data.get("description"));
  188. }
  189. if (data.containsKey("author")) {
  190. myGroup.setAuthor(data.get("author"));
  191. }
  192. if (data.containsKey("version")) {
  193. try {
  194. myGroup.setVersion(Integer.parseInt(data.get("version")));
  195. } catch (NumberFormatException ex) {
  196. // Do nothing
  197. }
  198. }
  199. if (data.containsKey("component")) {
  200. try {
  201. myGroup.setComponent(Integer.parseInt(data.get("component")));
  202. } catch (NumberFormatException ex) {
  203. // Do nothing
  204. }
  205. }
  206. }
  207. for (int i = 0; config.isKeyDomain("setting " + i); i++) {
  208. final ActionGroup myGroup = ActionManager.getGroup(group);
  209. final Map<String, String> data = config.getKeyDomain("setting " + i);
  210. if (data.containsKey("type") && data.containsKey("setting")
  211. && data.containsKey("title") && data.containsKey("default")
  212. && data.containsKey("tooltip")) {
  213. myGroup.getSettings().add(new PreferencesSetting(
  214. PreferencesType.valueOf(data.get("type")), "actions",
  215. data.get("setting"), data.get("title"),
  216. data.get("tooltip"), data.get("default")));
  217. ActionManager.registerDefault(data.get("setting"), data.get("default"));
  218. }
  219. }
  220. }
  221. /**
  222. * Loads a list of triggers with the specified names.
  223. *
  224. * @param newTriggers A list of trigger names
  225. * @return True if all triggers are valid and compatible, false otherwise.
  226. */
  227. private boolean loadTriggers(final List<String> newTriggers) {
  228. triggers = new ActionType[newTriggers.size()];
  229. for (int i = 0; i < triggers.length; i++) {
  230. triggers[i] = ActionManager.getActionType(newTriggers.get(i));
  231. if (triggers[i] == null) {
  232. error("Invalid trigger specified: " + newTriggers.get(i));
  233. return false;
  234. } else if (i != 0 && !triggers[i].getType().equals(triggers[0].getType())) {
  235. error("Triggers are not compatible");
  236. return false;
  237. }
  238. }
  239. return true;
  240. }
  241. /**
  242. * Called to save the action.
  243. */
  244. public void save() {
  245. if (!isModified()) {
  246. return;
  247. }
  248. final ConfigFile newConfig = new ConfigFile(location);
  249. final List<String> triggerNames = new ArrayList<String>();
  250. final List<String> responseLines = new ArrayList<String>();
  251. for (ActionType trigger : triggers) {
  252. if (trigger == null) {
  253. Logger.appError(ErrorLevel.LOW, "ActionType was null",
  254. new IllegalArgumentException("Triggers: "
  255. + Arrays.toString(triggers)));
  256. continue;
  257. }
  258. triggerNames.add(trigger.toString());
  259. }
  260. for (String line : response) {
  261. responseLines.add(line);
  262. }
  263. newConfig.addDomain(DOMAIN_TRIGGERS, triggerNames);
  264. newConfig.addDomain(DOMAIN_RESPONSE, responseLines);
  265. if (conditionTree != null) {
  266. newConfig.addDomain(DOMAIN_CONDITIONTREE, new ArrayList<String>());
  267. newConfig.getFlatDomain(DOMAIN_CONDITIONTREE).add(conditionTree.toString());
  268. }
  269. if (newFormat != null) {
  270. newConfig.addDomain(DOMAIN_FORMAT, new ArrayList<String>());
  271. newConfig.getFlatDomain(DOMAIN_FORMAT).add(newFormat);
  272. }
  273. int i = 0;
  274. for (ActionCondition condition : conditions) {
  275. final Map<String, String> data = new HashMap<String, String>();
  276. data.put("argument", String.valueOf(condition.getArg()));
  277. if (condition.getArg() == -1) {
  278. data.put("starget", condition.getStarget());
  279. } else {
  280. data.put("component", condition.getComponent().toString());
  281. }
  282. data.put("comparison", condition.getComparison().toString());
  283. data.put("target", condition.getTarget());
  284. newConfig.addDomain("condition " + i, data);
  285. i++;
  286. }
  287. if (config != null) {
  288. // Preserve any meta-data
  289. if (config.isKeyDomain(DOMAIN_METADATA)) {
  290. newConfig.addDomain(DOMAIN_METADATA, config.getKeyDomain(DOMAIN_METADATA));
  291. }
  292. for (i = 0; config.isKeyDomain("setting " + i); i++) {
  293. newConfig.addDomain("setting " + i, config.getKeyDomain("setting " + i));
  294. }
  295. }
  296. try {
  297. newConfig.write();
  298. resetModified();
  299. } catch (IOException ex) {
  300. Logger.userError(ErrorLevel.HIGH, "I/O error when saving action: "
  301. + group + "/" + name + ": " + ex.getMessage());
  302. }
  303. }
  304. /**
  305. * Reads a condition from the specified configuration section.
  306. *
  307. * @param data The relevant section of the action configuration
  308. * @return True if the condition is valid, false otherwise
  309. */
  310. private boolean readCondition(final Map<String,String> data) {
  311. int arg = 0;
  312. ActionComponent component = null;
  313. ActionComparison comparison = null;
  314. String target = "";
  315. String starget = null;
  316. // ------ Read the argument
  317. try {
  318. arg = Integer.parseInt(data.get("argument"));
  319. } catch (NumberFormatException ex) {
  320. error("Invalid argument number specified: " + data.get("argument"));
  321. return false;
  322. }
  323. if (arg < -1 || arg >= triggers[0].getType().getArity()) {
  324. error("Invalid argument number specified: " + arg);
  325. return false;
  326. }
  327. // ------ Read the component or the source
  328. if (arg == -1) {
  329. starget = data.get("starget");
  330. if (starget == null) {
  331. error("No starget specified");
  332. return false;
  333. }
  334. } else {
  335. component = readComponent(data, arg);
  336. if (component == null) {
  337. return false;
  338. }
  339. }
  340. // ------ Read the comparison
  341. comparison = ActionManager.getActionComparison(data.get("comparison"));
  342. if (comparison == null) {
  343. error("Invalid comparison specified: " + data.get("comparison"));
  344. return false;
  345. }
  346. if ((arg != -1 && !comparison.appliesTo().equals(component.getType()))
  347. || (arg == -1 && !comparison.appliesTo().equals(String.class))) {
  348. error("Comparison cannot be applied to specified component: " + data.get("comparison"));
  349. return false;
  350. }
  351. // ------ Read the target
  352. target = data.get("target");
  353. if (target == null) {
  354. error("No target specified for condition");
  355. return false;
  356. }
  357. if (arg == -1) {
  358. conditions.add(new ActionCondition(starget, comparison, target));
  359. } else {
  360. conditions.add(new ActionCondition(arg, component, comparison, target));
  361. }
  362. return true;
  363. }
  364. /**
  365. * Reads a component from the specified data section for the specified argument.
  366. *
  367. * @param data The relevant section of the action configuration
  368. * @param arg The argument number that the component should apply to
  369. * @return The corresponding ActionComponent, or null if the specified
  370. * component is invalid.
  371. */
  372. private ActionComponent readComponent(final Map<String, String> data, final int arg) {
  373. final String componentName = data.get("component");
  374. ActionComponent component;
  375. if (componentName.indexOf('.') == -1) {
  376. component = ActionManager.getActionComponent(componentName);
  377. } else {
  378. try {
  379. component = new ActionComponentChain(triggers[0].getType().getArgTypes()[arg],
  380. componentName);
  381. } catch (IllegalArgumentException iae) {
  382. error(iae.getMessage());
  383. return null;
  384. }
  385. }
  386. if (component == null) {
  387. error("Unknown component: " + componentName);
  388. return null;
  389. }
  390. if (!component.appliesTo().equals(triggers[0].getType().getArgTypes()[arg])) {
  391. error("Component cannot be applied to specified arg in condition: " + componentName);
  392. return null;
  393. }
  394. return component;
  395. }
  396. /**
  397. * Raises a trivial error, informing the user of the problem.
  398. *
  399. * @param message The message to be raised
  400. */
  401. private void error(final String message) {
  402. Logger.userError(ErrorLevel.LOW, "Error when parsing action: "
  403. + group + "/" + name + ": " + message);
  404. }
  405. /** {@inheritDoc} */
  406. @Override
  407. public void setName(final String newName) {
  408. super.setName(newName);
  409. new File(location).delete();
  410. location = ActionManager.getDirectory() + group + File.separator + newName;
  411. save();
  412. }
  413. /** {@inheritDoc} */
  414. @Override
  415. public void setGroup(final String newGroup) {
  416. super.setGroup(newGroup);
  417. new File(location).delete();
  418. location = ActionManager.getDirectory() + group + File.separator + name;
  419. save();
  420. }
  421. /**
  422. * Deletes this action.
  423. */
  424. public void delete() {
  425. new File(location).delete();
  426. }
  427. /** {@inheritDoc} */
  428. @Override
  429. public String toString() {
  430. final String parent = super.toString();
  431. return parent.substring(0, parent.length() - 1)
  432. + ",location=" + location + "]";
  433. }
  434. }