source: trunk/src/org/expeditee/actions/Actions.java@ 181

Last change on this file since 181 was 181, checked in by ra33, 16 years ago

Work on Bridging the Gap between SimpleStatements and Actions/Agents

File size: 20.6 KB
Line 
1package org.expeditee.actions;
2
3import java.awt.GraphicsEnvironment;
4import java.io.File;
5import java.lang.reflect.Constructor;
6import java.lang.reflect.Method;
7import java.lang.reflect.Modifier;
8import java.net.URL;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Enumeration;
12import java.util.HashMap;
13import java.util.LinkedList;
14import java.util.List;
15import java.util.jar.JarFile;
16import java.util.zip.ZipEntry;
17
18import org.expeditee.agents.Agent;
19import org.expeditee.gui.DisplayIO;
20import org.expeditee.gui.Frame;
21import org.expeditee.gui.FrameGraphics;
22import org.expeditee.gui.FrameIO;
23import org.expeditee.gui.FrameUtils;
24import org.expeditee.gui.FreeItems;
25import org.expeditee.gui.MessageBay;
26import org.expeditee.io.Conversion;
27import org.expeditee.io.Logger;
28import org.expeditee.items.Item;
29import org.expeditee.items.ItemUtils;
30
31/**
32 * The Action class is used to launch Actions and Agents.
33 *
34 * This class checks all class files in the same directory, and reads in and
35 * adds all the methods from them. The methods are stored in a Hashtable so that
36 * the lowercase method names can be mapped to the correctly capatilized method
37 * names (to provide case-insensitivity)
38 *
39 * When adding an action to a class in the actions folder the following must be
40 * considered:
41 * <li> If the first parameter is of type Frame, the current frame will be
42 * passed as a parameter.
43 * <li> If the next param is of type Item the item on the end of the cursor will
44 * be passed or the item that was clicked to execute the action if nothing is on
45 * the end of the cursor. current frame or item.</li>
46 * <li> If there are multiple overloads for the same method they should be
47 * declared in order of the methods with the most parameteres to least
48 * parameters.</li>
49 */
50public class Actions {
51
52 private static final String INVALID_PARAMETERS_ERROR = "Invalid parameters for agent: "; //$NON-NLS-1$
53
54 // the currently running agent (if there is one)
55 private static Agent _Agent = null;
56
57 // maps lower case method names to the method
58 private static HashMap<String, Method> _Actions = new HashMap<String, Method>();
59
60 // map lower case fonts to capitalized fonts
61 private static HashMap<String, String> _Fonts = new HashMap<String, String>();
62
63 // maps lower case JAG class names to capitalized JAG names
64 private static HashMap<String, String> _JAGs = new HashMap<String, String>();
65
66 public static final String ROOT_PACKAGE = "org.expeditee.";
67
68 // Package and class file locations
69 private static final String ACTIONS_PACKAGE = ROOT_PACKAGE + "actions.";
70
71 private static final String AGENTS_PACKAGE = ROOT_PACKAGE + "agents.";
72
73 private static final String NAVIGATIONS_CLASS = ROOT_PACKAGE
74 + "actions.NavigationActions";
75
76 public static Class[] getClasses(String pckgname)
77 throws ClassNotFoundException {
78 ArrayList<Class> classes = new ArrayList<Class>();
79 // Get a File object for the package
80 File directory = null;
81 // Must be a forward slash for loading resources
82 String path = pckgname.replace('.', '/');
83 // System.out.println("Get classes: " + path);
84 try {
85 ClassLoader cld = Thread.currentThread().getContextClassLoader();
86 if (cld == null) {
87 throw new ClassNotFoundException("Can't get class loader.");
88 }
89 URL resource = null;
90 try {
91 Enumeration<URL> resources = cld.getResources(path);
92 while (resources.hasMoreElements()) {
93 URL url = resources.nextElement();
94 // Ingore the classes in the test folder when we are running
95 // the program from Eclipse
96 // This doesnt apply when running directly from the jar
97 // because the test classes are not compiled into the jar.
98 if (!url.toString().toLowerCase().contains("test")) {
99 resource = url;
100 break;
101 }
102 }
103 } catch (Exception e) {
104
105 }
106 if (resource == null) {
107 throw new ClassNotFoundException("No resource for " + path);
108 }
109 directory = new File(resource.getFile());
110 } catch (NullPointerException x) {
111 throw new ClassNotFoundException(pckgname + " (" + directory
112 + ") does not appear to be a valid package");
113 }
114 // System.out.println("Path:" + directory.getPath());
115 int splitPoint = directory.getPath().indexOf('!');
116 if (splitPoint > 0) {
117 try {
118 String jarName = directory.getPath().substring(
119 "file:".length(), splitPoint);
120 // Windows HACK
121 if (jarName.indexOf(":") >= 0)
122 jarName = jarName.substring(1);
123
124 if (jarName.indexOf("%20") > 0) {
125 jarName = jarName.replace("%20", " ");
126 }
127 // System.out.println("JarName:" + jarName);
128 JarFile jarFile = new JarFile(jarName);
129
130 Enumeration entries = jarFile.entries();
131 int classCount = 0;
132 while (entries.hasMoreElements()) {
133 ZipEntry entry = (ZipEntry) entries.nextElement();
134 String className = entry.getName();
135 if (className.startsWith(path)) {
136 if (className.endsWith(".class")
137 && !className.contains("$")) {
138 classCount++;
139 // The forward slash below is a forwards slash for
140 // both windows and linux
141 classes.add(Class.forName(className.substring(0,
142 className.length() - 6).replace('/', '.')));
143 }
144 }
145 }
146 jarFile.close();
147 // System.out.println("Loaded " + classCount + " classes from "
148 // + pckgname);
149
150 } catch (Exception e) {
151 e.printStackTrace();
152 }
153
154 } else {
155
156 if (directory.exists()) {
157 // Get the list of the files contained in the package
158 String[] files = directory.list();
159 for (int i = 0; i < files.length; i++) {
160 // we are only interested in .class files
161 if (files[i].endsWith(".class") && !files[i].contains("$")
162 && !files[i].equals("Actions.class")) {
163 // removes the .class extension
164 classes
165 .add(Class.forName(pckgname
166 + files[i].substring(0, files[i]
167 .length() - 6)));
168 }
169 }
170 } else {
171 throw new ClassNotFoundException(pckgname + " (" + directory
172 + ") does not appear to be a valid package");
173 }
174 }
175 Class[] classesA = new Class[classes.size()];
176 classes.toArray(classesA);
177 return classesA;
178 }
179
180 /**
181 * Clears out the Action and JAG Hashtables and refills them. Normally this
182 * is only called once when the system starts.
183 *
184 * @return a warning message if there were any problems loading agents or
185 * actions.
186 */
187 public static Collection<String> Init() {
188
189 Collection<String> warnings = new LinkedList<String>();
190 Class[] classes;
191
192 try {
193 classes = getClasses(AGENTS_PACKAGE);
194
195 for (int i = 0; i < classes.length; i++) {
196 String name = classes[i].getSimpleName();
197 // maps lower case name to correct capitalised name
198 _JAGs.put(name.toLowerCase(), name);
199 }
200 } catch (Exception e) {
201 warnings.add("You must have Java 1.5 or higher to run Expeditee");
202 warnings.add(e.getMessage());
203 }
204 try {
205 classes = getClasses(ACTIONS_PACKAGE);
206
207 for (int i = 0; i < classes.length; i++) {
208 String name = classes[i].getSimpleName();
209 // Ignore the test classes
210 if (name.toLowerCase().contains("test"))
211 continue;
212 // read in all the methods from the class
213 try {
214 // System.out.println(name)
215 LoadMethods(Class.forName(ACTIONS_PACKAGE + name));
216 } catch (ClassNotFoundException e) {
217 Logger.Log(e);
218 e.printStackTrace();
219 }
220 }
221 } catch (Exception e) {
222 warnings.add(e.getMessage());
223 }
224 return warnings;
225 }
226
227 /**
228 * Loads all the Methods that meet the requirements checked by MethodCheck
229 * into the hashtable.
230 *
231 * @param c
232 * The Class to load the Methods from.
233 */
234 private static void LoadMethods(Class c) {
235 // list of methods to test
236 Method[] toLoad = c.getMethods();
237
238 for (Method m : toLoad) {
239 // only allow methods with the right modifiers
240 if (MethodCheck(m)) {
241 String lowercaseName = m.getName().toLowerCase();
242 if (!(_Actions.containsKey(lowercaseName)))
243 _Actions.put(lowercaseName, m);
244 else {
245 int i = 0;
246 while (_Actions.containsKey(lowercaseName + i))
247 i++;
248
249 _Actions.put(lowercaseName + i, m);
250 }
251
252 }
253 }
254 }
255
256 /**
257 * Checks if the given Method corresponds to the restrictions of Action
258 * commands, namely: Declared (not inherited), Public, and Static, with a
259 * void return type.
260 *
261 * @param m
262 * The Method to check
263 * @return True if the Method meets the above conditions, false otherwise.
264 */
265 private static boolean MethodCheck(Method m) {
266 int mods = m.getModifiers();
267
268 // check the method is declared (not inherited)
269 if ((mods & Method.DECLARED) != Method.DECLARED)
270 return false;
271
272 // check the method is public
273 if ((mods & Modifier.PUBLIC) != Modifier.PUBLIC)
274 return false;
275
276 // check the method is static
277 if ((mods & Modifier.STATIC) != Modifier.STATIC)
278 return false;
279
280 // if we have not returned yet, then the tests have all passed
281 return true;
282 }
283
284 /**
285 * Performs the given action command. The source Frame and Item are given
286 * because they are required by some actions. Note that the source frame
287 * does not have to be the Item's parent Frame.
288 *
289 * @param source
290 * The Frame that the action should apply to
291 * @param launcher
292 * The Item that has the action assigned to it
293 * @param command
294 * The action to perform
295 */
296 public static Object PerformAction(Frame source, Item launcher,
297 String command) throws Exception {
298 // if (!command.equalsIgnoreCase("Restore"))
299 // FrameIO.SaveFrame(source, false);
300 // TODO make restore UNDO the changes made by the last action
301
302 // separate method name and parameter names
303 String mname = getName(command);
304 if (command.length() > mname.length())
305 command = command.substring(mname.length() + 1);
306 else
307 command = "";
308
309 // Strip off the @ from annotation items
310 if (mname.startsWith("@"))
311 mname = mname.substring(1);
312
313 mname = mname.trim();
314 String lowercaseName = mname.toLowerCase();
315 // check for protection on frame
316 if (ItemUtils.ContainsTag(source.getItems(), "@No" + mname)) {
317 throw new RuntimeException("Frame is protected by @No" + mname
318 + " tag.");
319 }
320
321 // retrieve methods that match the name
322 Method toRun = _Actions.get(lowercaseName);
323
324 // if this is not the name of a method, it may be the name of an agent
325 if (toRun == null) {
326 LaunchAgent(mname, command, source, launcher);
327 return null;
328 }
329
330 // Need to save the frame if we are navigating away from it so we dont
331 // loose changes
332 if (toRun.getDeclaringClass().getName().equals(NAVIGATIONS_CLASS)) {
333 FrameIO.SaveFrame(DisplayIO.getCurrentFrame());
334 }
335
336 // if there are duplicate methods with the same name
337 List<Method> possibles = new LinkedList<Method>();
338 possibles.add(toRun);
339 int i = 0;
340 while (_Actions.containsKey(lowercaseName + i)) {
341 possibles.add(_Actions.get(lowercaseName + i));
342 i++;
343 }
344
345 for (Method possible : possibles) {
346 // try first with the launching item as a parameter
347
348 // run method
349 try {
350 // convert parameters to objects and get the method to invoke
351 Object[] parameters = CreateObjects(possible, source, launcher,
352 command);
353 // Check that there are the same amount of params
354 if (parameters == null) {
355 continue;
356 }
357
358 return possible.invoke(null, parameters);
359 } catch (Exception e) {
360 Logger.Log(e);
361 e.printStackTrace();
362 }
363 }
364 //If the actions was not found... then it is run as an agent
365 assert (possibles.size() > 0);
366 throw new RuntimeException("Incorrect parameters for " + mname);
367 }
368
369 /**
370 * Launches an agent with the given name, and passes in the given parameters
371 *
372 * @param name
373 * The name of the JAG to load
374 * @param parameters
375 * The parameters to pass to the JAG
376 * @param source
377 * The starting Frame that the JAG is being launched on
378 */
379 private static void LaunchAgent(String name, String parameters,
380 Frame source, Item clicked) throws Exception {
381 // Use the correct case version for printing error messages
382 String nameWithCorrectCase = name;
383 name = name.toLowerCase();
384
385 try {
386 // check for stored capitalisation
387 if (_JAGs.containsKey(name)) {
388 name = _JAGs.get(name);
389 } else if (name.endsWith("tree")) {
390 parameters = name.substring(0, name.length() - "tree".length())
391 + " " + parameters;
392 name = "writetree";
393 } else if (name.endsWith("frame")) {
394 parameters = name
395 .substring(0, name.length() - "frame".length())
396 + " " + parameters;
397 name = "writeframe";
398 }
399
400 // load the JAG class
401 Class agentClass = Class.forName(AGENTS_PACKAGE + name);
402
403 // get the constructor for the JAG class
404 Constructor con = null;
405 Constructor[] constructors = agentClass.getConstructors();
406 Object[] params = null;
407
408 // determine correct parameters for constructor
409 for (Constructor c : constructors) {
410 if (parameters.length() > 0
411 && c.getParameterTypes().length == 1) {
412 con = c;
413 params = new String[1];
414 params[0] = parameters;
415 break;
416 } else if (c.getParameterTypes().length == 0 && con == null) {
417 con = c;
418 }
419 }
420
421 // if there is no constructor, return
422 if (con == null) {
423 throw new RuntimeException(INVALID_PARAMETERS_ERROR
424 + nameWithCorrectCase);
425 }
426
427 // create the JAG
428 _Agent = (Agent) con.newInstance(params);
429
430 Thread t = new Thread(_Agent);
431 t.setPriority(Thread.MIN_PRIORITY);
432
433 Item itemParam = clicked;
434 if (FreeItems.textAttachedToCursor()) {
435 itemParam = FreeItems.getItemAttachedToCursor();
436 }
437
438 // check for errors during initialisation
439 if (!_Agent.initialise(source, itemParam)) {
440 _Agent = null;
441 throw new RuntimeException("Error initialising agent: "
442 + nameWithCorrectCase);
443 }
444
445 // save the current frame (if necesssary)
446 // TODO make this nicer... ie. make Format an action rather than an
447 // agent and save frames only before running agents
448 if (!name.equals("format") && !name.equals("sort")) {
449 FrameUtils.LeavingFrame(source);
450 }
451
452 if (_Agent.hasResultString()) {
453 // Just run the agent on this thread... dont run it in the
454 // background
455 t.run();
456 String result = _Agent.toString();
457 // Attach the result to the cursor
458 if (FreeItems.textAttachedToCursor()) {
459 Item resultItem = FreeItems.getItemAttachedToCursor();
460 resultItem.setText(result);
461 }
462 // if there is a completion frame, then display it to the user
463 } else {
464 t.start();
465 if (_Agent.hasResultFrame()) {
466 // TODO We want to be able to navigate through the frames as
467 // the results are loading
468 Frame next = _Agent.getResultFrame();
469 FrameUtils.DisplayFrame(next, true);
470 }
471 }
472
473 } catch (ClassNotFoundException cnf) {
474 _Agent = null;
475 throw new RuntimeException(nameWithCorrectCase
476 + "' is not an action or agent.");
477 } catch (Exception e) {
478 _Agent = null;
479 e.printStackTrace();
480 throw new RuntimeException("Error creating Agent: '"
481 + nameWithCorrectCase + "'");
482 }
483 FrameGraphics.refresh(false);
484
485 return;
486 }
487
488 /**
489 * Used to determine if the previously launched agent is still executing.
490 *
491 * @return True if the last Agent is still executing, False otherwise.
492 */
493 public static boolean isAgentRunning() {
494 if (_Agent != null)
495 return _Agent.isRunning();
496
497 return false;
498 }
499
500 /**
501 * Stops the currently running Agent (If there is one) by calling
502 * Agent.stop(). Note: This may not stop the Agent immediately, but the
503 * Agent should terminate as soon as it is safe to do so.
504 */
505 public static void stopAgent() {
506 if (_Agent != null && _Agent.isRunning()) {
507 MessageBay.errorMessage("Stopping Agent...");
508 _Agent.stop();
509 }
510 }
511
512 public static void interruptAgent() {
513 if (_Agent != null) {
514 _Agent.interrupt();
515 }
516 }
517
518 /**
519 * Converts the given String of values into an array of Objects
520 *
521 * @param launcher
522 * The Item used to launch the action, it may be required as a
523 * parameter
524 * @param values
525 * A list of space separated String values to convert to objects
526 * @return The created array of Objects
527 */
528 public static Object[] CreateObjects(Method method, Frame source,
529 Item launcher, String values) {
530 // The parameter types that should be created from the given String
531 Class[] paramTypes = method.getParameterTypes();
532
533 int paramCount = paramTypes.length;
534 // if the method has no parameters
535 if (paramCount == 0)
536 return new Object[0];
537
538 Object[] objects = new Object[paramCount];
539 int ind = 0;
540
541 // if the first class in the list is a frame or item, it is the source
542 //or launcher
543 // length must be at least one if we are still running
544 if (paramTypes[ind] == Frame.class) {
545 objects[ind] = source;
546 ind++;
547 }
548
549 //Check if the second item is an item
550 if (paramCount > ind && Item.class.isAssignableFrom(paramTypes[ind])) {
551 objects[ind] = launcher;
552 ind++;
553 }//If there is stuff on the cursor use it for the rest of the params
554 else if (launcher != null && launcher.isFloating()){
555 values = launcher.getText();
556 }
557
558 String param = values;
559 // convert the rest of the objects
560 for (; ind < objects.length; ind++) {
561 // check if its the last param and combine
562 if (values.length() > 0 && ind == objects.length - 1) {
563 param = values.trim();
564 // check if its a string
565 if (param.length() > 0 && param.charAt(0) == '"') {
566 int endOfString = param.indexOf('"', 1);
567 if (endOfString > 0) {
568 param = param.substring(1, endOfString);
569 }
570 }
571 } else {// strip off the next value
572 param = ParseValue(values);
573 values = RemainingParams(values);
574 }
575 // convert the value to an object
576 try {
577 Object o = Conversion.Convert(paramTypes[ind], param);
578 if (o == null)
579 return null;
580 objects[ind] = o;
581 } catch (Exception e) {
582 return null;
583 }
584 }
585
586 return objects;
587 }
588
589 /**
590 * Returns a string containing the remaining params after ignoring the first
591 * one.
592 *
593 * @param params
594 * a space sparated list of N parameters
595 * @return the remaining N - 1 parameters
596 */
597 public static String RemainingParams(String params) {
598 if (params.length() == 0)
599 return null;
600
601 // remove leading and trailing spaces
602 params = params.trim();
603
604 // if there are no more parameters, we are done
605 if (params.indexOf(" ") < 0) {
606 return "";
607 }
608
609 // Check if we have a string parameter
610 if (params.charAt(0) == '"') {
611 int endOfString = params.indexOf('"', 1);
612 if (endOfString > 0) {
613 if (endOfString > params.length())
614 return "";
615 return params.substring(endOfString + 1).trim();
616 }
617 }
618
619 return params.substring(params.indexOf(" ")).trim();
620 }
621
622 /**
623 * Returns the first value in the space separated String of parameters
624 * passed in. Strings are enclosed in double quotes.
625 *
626 * @param params
627 * The String of space separated values
628 * @return The first value in the String
629 */
630 public static String ParseValue(String params) {
631 if (params.length() == 0)
632 return null;
633
634 // remove leading and trailing spaces
635 String param = params.trim();
636
637 // Check if we have a string parameter
638 if (param.charAt(0) == '"') {
639 int endOfString = param.indexOf('"', 1);
640 if (endOfString > 0)
641 return param.substring(1, endOfString);
642 }
643
644 // if there are no more parameters, we are done
645 if (param.indexOf(" ") < 0) {
646 return param;
647 }
648
649 return param.substring(0, param.indexOf(" "));
650 }
651
652 /**
653 * Separates the name of the given command from any parameters and returns
654 * them
655 *
656 * @param command
657 * The String to separate out the Action or Agent name from
658 * @return The name of the Action of Agent with parameters stripped off
659 */
660 private static String getName(String command) {
661 if (command.indexOf(" ") < 0)
662 return command;
663
664 return command.substring(0, command.indexOf(" "));
665 }
666
667 /**
668 * Gets an uncapitalized font name and returns the capitalized font name.
669 * The capitalized form can be used with the Font.decoded method to get a
670 * corresponding Font object.
671 *
672 * @param fontName
673 * a font name in mixed case
674 * @return the correct capitalized form of the font name
675 */
676 public static String getCapitalizedFontName(String fontName) {
677 // Initialize the fonts if they have not already been loaded
678 initFonts();
679 return _Fonts.get(fontName.toLowerCase());
680 }
681
682 /**
683 * Initialise the fontsList if it has not been done already
684 */
685 private static void initFonts() {
686 if (_Fonts.size() == 0) {
687 String[] availableFonts = GraphicsEnvironment
688 .getLocalGraphicsEnvironment()
689 .getAvailableFontFamilyNames();
690 for (String s : availableFonts) {
691 _Fonts.put(s.toLowerCase(), s);
692 }
693 }
694 }
695
696 public static HashMap<String, String> getFonts() {
697 initFonts();
698 return _Fonts;
699 }
700
701 public static Object PerformActionCatchErrors(Frame current, Item launcher, String command) {
702 try{
703 return PerformAction(current, launcher, command);
704 }catch(Exception e) {
705 MessageBay.errorMessage(e.getMessage());
706 }
707 return null;
708 }
709}
Note: See TracBrowser for help on using the repository browser.