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

Last change on this file since 185 was 185, checked in by ra33, 16 years ago
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 } catch (ClassNotFoundException cnf) {
473 _Agent = null;
474 throw new RuntimeException(nameWithCorrectCase
475 + "' is not an action or agent.");
476 } catch (Exception e) {
477 _Agent = null;
478 e.printStackTrace();
479 throw new RuntimeException("Error creating Agent: '"
480 + nameWithCorrectCase + "'");
481 }
482 FrameGraphics.refresh(false);
483
484 return;
485 }
486
487 /**
488 * Used to determine if the previously launched agent is still executing.
489 *
490 * @return True if the last Agent is still executing, False otherwise.
491 */
492 public static boolean isAgentRunning() {
493 if (_Agent != null)
494 return _Agent.isRunning();
495
496 return false;
497 }
498
499 /**
500 * Stops the currently running Agent (If there is one) by calling
501 * Agent.stop(). Note: This may not stop the Agent immediately, but the
502 * Agent should terminate as soon as it is safe to do so.
503 */
504 public static void stopAgent() {
505 if (_Agent != null && _Agent.isRunning()) {
506 MessageBay.errorMessage("Stopping Agent...");
507 _Agent.stop();
508 }
509 }
510
511 public static void interruptAgent() {
512 if (_Agent != null) {
513 _Agent.interrupt();
514 }
515 }
516
517 /**
518 * Converts the given String of values into an array of Objects
519 *
520 * @param launcher
521 * The Item used to launch the action, it may be required as a
522 * parameter
523 * @param values
524 * A list of space separated String values to convert to objects
525 * @return The created array of Objects
526 */
527 public static Object[] CreateObjects(Method method, Frame source,
528 Item launcher, String values) {
529 // The parameter types that should be created from the given String
530 Class[] paramTypes = method.getParameterTypes();
531
532 int paramCount = paramTypes.length;
533 // if the method has no parameters
534 if (paramCount == 0)
535 return new Object[0];
536
537 Object[] objects = new Object[paramCount];
538 int ind = 0;
539
540 // if the first class in the list is a frame or item, it is the source
541 //or launcher
542 // length must be at least one if we are still running
543 if (paramTypes[ind] == Frame.class) {
544 objects[ind] = source;
545 ind++;
546 }
547
548 //Check if the second item is an item
549 if (paramCount > ind && Item.class.isAssignableFrom(paramTypes[ind])) {
550 objects[ind] = launcher;
551 ind++;
552 }//If there is stuff on the cursor use it for the rest of the params
553 else if (launcher != null && launcher.isFloating()){
554 values = launcher.getText();
555 }
556
557 String param = values;
558 // convert the rest of the objects
559 for (; ind < objects.length; ind++) {
560 // check if its the last param and combine
561 if (values.length() > 0 && ind == objects.length - 1) {
562 param = values.trim();
563 // check if its a string
564 if (param.length() > 0 && param.charAt(0) == '"') {
565 int endOfString = param.indexOf('"', 1);
566 if (endOfString > 0) {
567 param = param.substring(1, endOfString);
568 }
569 }
570 } else {// strip off the next value
571 param = ParseValue(values);
572 values = RemainingParams(values);
573 }
574 // convert the value to an object
575 try {
576 Object o = Conversion.Convert(paramTypes[ind], param);
577 if (o == null)
578 return null;
579 objects[ind] = o;
580 } catch (Exception e) {
581 return null;
582 }
583 }
584
585 return objects;
586 }
587
588 /**
589 * Returns a string containing the remaining params after ignoring the first
590 * one.
591 *
592 * @param params
593 * a space sparated list of N parameters
594 * @return the remaining N - 1 parameters
595 */
596 public static String RemainingParams(String params) {
597 if (params.length() == 0)
598 return null;
599
600 // remove leading and trailing spaces
601 params = params.trim();
602
603 // if there are no more parameters, we are done
604 if (params.indexOf(" ") < 0) {
605 return "";
606 }
607
608 // Check if we have a string parameter
609 if (params.charAt(0) == '"') {
610 int endOfString = params.indexOf('"', 1);
611 if (endOfString > 0) {
612 if (endOfString > params.length())
613 return "";
614 return params.substring(endOfString + 1).trim();
615 }
616 }
617
618 return params.substring(params.indexOf(" ")).trim();
619 }
620
621 /**
622 * Returns the first value in the space separated String of parameters
623 * passed in. Strings are enclosed in double quotes.
624 *
625 * @param params
626 * The String of space separated values
627 * @return The first value in the String
628 */
629 public static String ParseValue(String params) {
630 if (params.length() == 0)
631 return null;
632
633 // remove leading and trailing spaces
634 String param = params.trim();
635
636 // Check if we have a string parameter
637 if (param.charAt(0) == '"') {
638 int endOfString = param.indexOf('"', 1);
639 if (endOfString > 0)
640 return param.substring(1, endOfString);
641 }
642
643 // if there are no more parameters, we are done
644 if (param.indexOf(" ") < 0) {
645 return param;
646 }
647
648 return param.substring(0, param.indexOf(" "));
649 }
650
651 /**
652 * Separates the name of the given command from any parameters and returns
653 * them
654 *
655 * @param command
656 * The String to separate out the Action or Agent name from
657 * @return The name of the Action of Agent with parameters stripped off
658 */
659 private static String getName(String command) {
660 if (command.indexOf(" ") < 0)
661 return command;
662
663 return command.substring(0, command.indexOf(" "));
664 }
665
666 /**
667 * Gets an uncapitalized font name and returns the capitalized font name.
668 * The capitalized form can be used with the Font.decoded method to get a
669 * corresponding Font object.
670 *
671 * @param fontName
672 * a font name in mixed case
673 * @return the correct capitalized form of the font name
674 */
675 public static String getCapitalizedFontName(String fontName) {
676 // Initialize the fonts if they have not already been loaded
677 initFonts();
678 return _Fonts.get(fontName.toLowerCase());
679 }
680
681 /**
682 * Initialise the fontsList if it has not been done already
683 */
684 private static void initFonts() {
685 if (_Fonts.size() == 0) {
686 String[] availableFonts = GraphicsEnvironment
687 .getLocalGraphicsEnvironment()
688 .getAvailableFontFamilyNames();
689 for (String s : availableFonts) {
690 _Fonts.put(s.toLowerCase(), s);
691 }
692 }
693 }
694
695 public static HashMap<String, String> getFonts() {
696 initFonts();
697 return _Fonts;
698 }
699
700 public static Object PerformActionCatchErrors(Frame current, Item launcher, String command) {
701 try{
702 return PerformAction(current, launcher, command);
703 }catch(Exception e) {
704 MessageBay.errorMessage(e.getMessage());
705 }
706 return null;
707 }
708}
Note: See TracBrowser for help on using the repository browser.