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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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.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. protected 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. ActionManager.processEvent(CoreActionType.ACTION_CREATED, null, this);
  127. save();
  128. ActionManager.registerAction(this);
  129. }
  130. /**
  131. * Loads this action from the config instance.
  132. */
  133. protected void loadActionFromConfig() {
  134. if (config.isFlatDomain(DOMAIN_TRIGGERS)) {
  135. if (!loadTriggers(config.getFlatDomain(DOMAIN_TRIGGERS))) {
  136. return;
  137. }
  138. } else {
  139. error("No trigger specified");
  140. return;
  141. }
  142. if (config.isFlatDomain(DOMAIN_RESPONSE)) {
  143. response = new String[config.getFlatDomain(DOMAIN_RESPONSE).size()];
  144. int i = 0;
  145. for (String line: config.getFlatDomain(DOMAIN_RESPONSE)) {
  146. response[i++] = line;
  147. }
  148. } else {
  149. error("No response specified");
  150. return;
  151. }
  152. if (config.isFlatDomain(DOMAIN_FORMAT)) {
  153. newFormat = config.getFlatDomain(DOMAIN_FORMAT).size() == 0 ? "" :
  154. config.getFlatDomain(DOMAIN_FORMAT).get(0);
  155. }
  156. for (int cond = 0; config.isKeyDomain("condition " + cond); cond++) {
  157. if (!readCondition(config.getKeyDomain("condition " + cond))) {
  158. return;
  159. }
  160. }
  161. if (config.isFlatDomain(DOMAIN_CONDITIONTREE)
  162. && config.getFlatDomain(DOMAIN_CONDITIONTREE).size() > 0) {
  163. conditionTree = ConditionTree.parseString(
  164. config.getFlatDomain(DOMAIN_CONDITIONTREE).get(0));
  165. if (conditionTree == null) {
  166. error("Unable to parse condition tree");
  167. return;
  168. }
  169. if (conditionTree.getMaximumArgument() >= conditions.size()) {
  170. error("Condition tree references condition "
  171. + conditionTree.getMaximumArgument() + " but there are"
  172. + " only " + conditions.size() + " conditions");
  173. return;
  174. }
  175. }
  176. ActionManager.registerAction(this);
  177. checkMetaData();
  178. }
  179. /**
  180. * Checks to see if this action contains group meta-data, and adds it to
  181. * the group as appropriate.
  182. */
  183. private void checkMetaData() {
  184. if (config.isKeyDomain(DOMAIN_METADATA)) {
  185. final ActionGroup myGroup = ActionManager.getGroup(group);
  186. final Map<String, String> data = config.getKeyDomain(DOMAIN_METADATA);
  187. if (data.containsKey("description")) {
  188. myGroup.setDescription(data.get("description"));
  189. }
  190. if (data.containsKey("author")) {
  191. myGroup.setAuthor(data.get("author"));
  192. }
  193. if (data.containsKey("version")) {
  194. try {
  195. myGroup.setVersion(Integer.parseInt(data.get("version")));
  196. } catch (NumberFormatException ex) {
  197. // Do nothing
  198. }
  199. }
  200. if (data.containsKey("component")) {
  201. try {
  202. myGroup.setComponent(Integer.parseInt(data.get("component")));
  203. } catch (NumberFormatException ex) {
  204. // Do nothing
  205. }
  206. }
  207. }
  208. for (int i = 0; config.isKeyDomain("setting " + i); i++) {
  209. final ActionGroup myGroup = ActionManager.getGroup(group);
  210. final Map<String, String> data = config.getKeyDomain("setting " + i);
  211. if (data.containsKey("type") && data.containsKey("setting")
  212. && data.containsKey("title") && data.containsKey("default")
  213. && data.containsKey("tooltip")) {
  214. ActionManager.registerDefault(data.get("setting"), data.get("default"));
  215. myGroup.getSettings().put(data.get("setting"), new PreferencesSetting(
  216. PreferencesType.valueOf(data.get("type")), "actions",
  217. data.get("setting"), data.get("title"), data.get("tooltip")));
  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. ActionManager.processEvent(CoreActionType.ACTION_UPDATED, null, this);
  304. }
  305. /**
  306. * Reads a condition from the specified configuration section.
  307. *
  308. * @param data The relevant section of the action configuration
  309. * @return True if the condition is valid, false otherwise
  310. */
  311. private boolean readCondition(final Map<String,String> data) {
  312. int arg = 0;
  313. ActionComponent component = null;
  314. ActionComparison comparison = null;
  315. String target = "";
  316. String starget = null;
  317. // ------ Read the argument
  318. try {
  319. arg = Integer.parseInt(data.get("argument"));
  320. } catch (NumberFormatException ex) {
  321. error("Invalid argument number specified: " + data.get("argument"));
  322. return false;
  323. }
  324. if (arg < -1 || arg >= triggers[0].getType().getArity()) {
  325. error("Invalid argument number specified: " + arg);
  326. return false;
  327. }
  328. // ------ Read the component or the source
  329. if (arg == -1) {
  330. starget = data.get("starget");
  331. if (starget == null) {
  332. error("No starget specified");
  333. return false;
  334. }
  335. } else {
  336. component = readComponent(data, arg);
  337. if (component == null) {
  338. return false;
  339. }
  340. }
  341. // ------ Read the comparison
  342. comparison = ActionManager.getActionComparison(data.get("comparison"));
  343. if (comparison == null) {
  344. error("Invalid comparison specified: " + data.get("comparison"));
  345. return false;
  346. }
  347. if ((arg != -1 && !comparison.appliesTo().equals(component.getType()))
  348. || (arg == -1 && !comparison.appliesTo().equals(String.class))) {
  349. error("Comparison cannot be applied to specified component: " + data.get("comparison"));
  350. return false;
  351. }
  352. // ------ Read the target
  353. target = data.get("target");
  354. if (target == null) {
  355. error("No target specified for condition");
  356. return false;
  357. }
  358. if (arg == -1) {
  359. conditions.add(new ActionCondition(starget, comparison, target));
  360. } else {
  361. conditions.add(new ActionCondition(arg, component, comparison, target));
  362. }
  363. return true;
  364. }
  365. /**
  366. * Reads a component from the specified data section for the specified argument.
  367. *
  368. * @param data The relevant section of the action configuration
  369. * @param arg The argument number that the component should apply to
  370. * @return The corresponding ActionComponent, or null if the specified
  371. * component is invalid.
  372. */
  373. private ActionComponent readComponent(final Map<String, String> data, final int arg) {
  374. final String componentName = data.get("component");
  375. ActionComponent component;
  376. if (componentName.indexOf('.') == -1) {
  377. component = ActionManager.getActionComponent(componentName);
  378. } else {
  379. try {
  380. component = new ActionComponentChain(triggers[0].getType().getArgTypes()[arg],
  381. componentName);
  382. } catch (IllegalArgumentException iae) {
  383. error(iae.getMessage());
  384. return null;
  385. }
  386. }
  387. if (component == null) {
  388. error("Unknown component: " + componentName);
  389. return null;
  390. }
  391. if (!component.appliesTo().equals(triggers[0].getType().getArgTypes()[arg])) {
  392. error("Component cannot be applied to specified arg in condition: " + componentName);
  393. return null;
  394. }
  395. return component;
  396. }
  397. /**
  398. * Raises a trivial error, informing the user of the problem.
  399. *
  400. * @param message The message to be raised
  401. */
  402. private void error(final String message) {
  403. Logger.userError(ErrorLevel.LOW, "Error when parsing action: "
  404. + group + "/" + name + ": " + message);
  405. }
  406. /** {@inheritDoc} */
  407. @Override
  408. public void setName(final String newName) {
  409. super.setName(newName);
  410. new File(location).delete();
  411. location = ActionManager.getDirectory() + group + File.separator + newName;
  412. save();
  413. }
  414. /** {@inheritDoc} */
  415. @Override
  416. public void setGroup(final String newGroup) {
  417. super.setGroup(newGroup);
  418. new File(location).delete();
  419. final String dir = ActionManager.getDirectory() + group + File.separator;
  420. location = dir + name;
  421. new File(dir).mkdirs();
  422. save();
  423. }
  424. /**
  425. * Deletes this action.
  426. */
  427. public void delete() {
  428. ActionManager.processEvent(CoreActionType.ACTION_DELETED, null, getGroup(), getName());
  429. new File(location).delete();
  430. }
  431. /** {@inheritDoc} */
  432. @Override
  433. public String toString() {
  434. final String parent = super.toString();
  435. return parent.substring(0, parent.length() - 1)
  436. + ",location=" + location + "]";
  437. }
  438. }