1 32 33 package websphinx.workbench; 34 35 import websphinx.*; 36 import java.io.IOException ; 37 import rcm.awt.PopupDialog; 38 39 public class Script implements Action,LinkPredicate,PagePredicate { 40 String script; 41 boolean asLinkPredicate; 42 43 transient Crawler crawler; 44 transient ScriptInterpreter interp; 45 transient Object function; 46 47 public Script (String script, boolean asLinkPredicate) { 48 this.script = script; 49 this.asLinkPredicate = asLinkPredicate; 50 } 51 52 public String getScript () { 53 return script; 54 } 55 56 public boolean equals (Object object) { 57 if (! (object instanceof Script)) 58 return false; 59 Script s = (Script)object; 60 return s.script.equals (script) 61 && s.asLinkPredicate == asLinkPredicate; 62 } 63 64 static String [] argsLink = {"crawler", "link"}; 65 static String [] argsPage = {"crawler", "page"}; 66 67 public void connected (Crawler crawler) { 68 this.crawler = crawler; 69 interp = Context.getScriptInterpreter (); 70 if (interp != null) { 71 try { 72 function = interp.lambda (asLinkPredicate 73 ? argsLink : argsPage, 74 script); 75 } catch (ScriptException e) { 76 PopupDialog.warn (null, "Script Error", e.toString()); 77 function = null; 78 } 79 } 80 } 81 82 public void disconnected (Crawler crawler) { 83 crawler = null; 84 interp = null; 85 function = null; 86 } 87 88 public boolean shouldVisit (Link link) { 89 try { 90 if (interp == null || function == null) 91 throw new ScriptException ("Scripting language is not available"); 93 94 Object [] args = new Object [2]; 95 args[0] = crawler; 96 args[1] = link; 97 return toBool (interp.apply (function, args)); 98 } catch (ScriptException e) { 99 System.err.println (e); return false; 101 } 102 } 103 104 public boolean shouldActOn (Page page) { 105 try { 106 if (interp == null || function == null) 107 throw new ScriptException ("Scripting language is not available"); 108 109 Object [] args = new Object [2]; 110 args[0] = crawler; 111 args[1] = page; 112 return toBool (interp.apply (function, args)); 113 } catch (ScriptException e) { 114 System.err.println (e); return false; 116 } 117 } 118 119 public void visit (Page page) { 120 try { 121 if (interp == null || function == null) 122 throw new ScriptException ("Scripting language is not available"); 124 125 Object [] args = new Object [2]; 126 args[0] = crawler; 127 args[1] = page; 128 interp.apply (function, args); 129 } catch (ScriptException e) { 130 throw new RuntimeException (e.toString()); 131 } 132 } 133 134 boolean toBool (Object obj) { 135 if (! (obj instanceof Boolean )) 136 return false; 137 return ((Boolean )obj).booleanValue(); 138 } 139 140 } 141 | Popular Tags |