1
15
16 package gate;
17
18 import java.io.*;
19 import java.net.*;
20 import java.util.*;
21 import org.jdom.Element;
22 import org.jdom.JDOMException;
23 import org.jdom.input.SAXBuilder;
24
25 import gate.config.ConfigDataProcessor;
26 import gate.creole.CreoleRegisterImpl;
27 import gate.creole.ResourceData;
28 import gate.event.CreoleListener;
29 import gate.util.*;
30
31
35 public class Gate implements GateConstants
36 {
37
38 private static final boolean DEBUG = false;
39
40
45 public static final int STRINGBUFFER_SIZE = 1024;
46
47
53 public static final int HASH_STH_SIZE = 4;
54
55
56
62 public static final String DB_OWNER = "gateadmin";
63
64
65
66 private static String builtinCreoleDirectoryUrls[] = {
67
69 };
73
74
75
76 public static final String URI = "http://www.gate.ac.uk";
77
78
79 protected static final String MIN_JDK_VERSION = "1.4";
80
81
82 public static String getMinJdkVersion() { return MIN_JDK_VERSION; }
83
84
89 public static void init() throws GateException {
90
91 System.setProperty(
93 "java.protocol.handler.pkgs",
94 System.getProperty("java.protocol.handler.pkgs")
95 + "|" + "gate.util.protocols"
96 );
97
98
101 lastSym = 0;
103
104 if(classLoader == null)
106 classLoader = new GateClassLoader(Gate.class.getClassLoader());
107 if(creoleRegister == null)
108 creoleRegister = new CreoleRegisterImpl();
109 if(knownPlugins == null) knownPlugins = new ArrayList();
110 if(autoloadPlugins == null) autoloadPlugins = new ArrayList();
111 if(pluginData == null) pluginData = new HashMap();
112 initCreoleRegister();
114 initDataStoreRegister();
116 initConfigData();
119
120 initCreoleRepositories();
121 dataStoreRegister.addCreoleListener(creoleRegister);
123
124 Factory.addCreoleListener(creoleRegister);
126
127 if(System.getProperty("java.version").compareTo(MIN_JDK_VERSION) < 0) {
129 throw new GateException(
130 "GATE requires JDK " + MIN_JDK_VERSION + " or newer"
131 );
132 }
133
134 try{
136 registerIREngine("gate.creole.ir.lucene.LuceneIREngine");
137 }catch(ClassNotFoundException cnfe){
138 throw new GateRuntimeException(cnfe);
139 }
140 }
142
147 protected static void initCreoleRepositories(){
148
155 String knownPluginsPath = (String)getUserConfig().get(KNOWN_PLUGIN_PATH_KEY);
157 if(knownPluginsPath != null && knownPluginsPath.length() > 0){
158 StringTokenizer strTok = new StringTokenizer(knownPluginsPath, ";", false);
159 while(strTok.hasMoreTokens()){
160 String aKnownPluginPath = strTok.nextToken();
161 try{
162 URL aPluginURL = new URL(aKnownPluginPath);
163 addKnownPlugin(aPluginURL);
164 }catch(MalformedURLException mue){
165 Err.prln("Plugin error: " + aKnownPluginPath + " is an invalid URL!");
166 }
167 }
168 }
169 File pluginsHome = new File(System.getProperty(GATE_HOME_SYSPROP_KEY),
171 "plugins");
172 File[] dirs = pluginsHome.listFiles();
173 for(int i = 0; i < dirs.length; i++){
174 File creoleFile = new File(dirs[i], "creole.xml");
175 if(creoleFile.exists()){
176 try{
177 URL pluginURL = dirs[i].toURL();
178 if(!knownPlugins.contains(pluginURL))
179 knownPlugins.add(pluginURL);
180 }catch(MalformedURLException mue){
181 throw new GateRuntimeException(mue);
183 }
184 }
185 }
186 Iterator pluginIter = knownPlugins.iterator();
189 while(pluginIter.hasNext()){
190 URL aPluginURL = (URL)pluginIter.next();
191 DirectoryInfo dInfo = new DirectoryInfo(aPluginURL);
192 pluginData.put(aPluginURL, dInfo);
193 }
194
195 String pluginPath = getUserConfig().getString(LOAD_PLUGIN_PATH_KEY);
197 String prop = System.getProperty(LOAD_PLUGIN_PATH_SYSPROP_KEY);
199 if(prop != null && prop.length() > 0) pluginPath = prop;
200
201 if(pluginPath == null || pluginPath.length() == 0){
202 try{
204 pluginPath = new File(pluginsHome, "ANNIE/").toURL().toString();
205 getUserConfig().put(LOAD_PLUGIN_PATH_KEY, pluginPath);
206 }catch(MalformedURLException mue){
207 throw new GateRuntimeException(mue);
208 }
209 }
210
211 StringTokenizer strTok = new StringTokenizer(pluginPath, ";", false);
213 while(strTok.hasMoreTokens()){
214 String aDir = strTok.nextToken();
215 try{
216 URL aPluginURL = new URL(aDir);
217 if(!autoloadPlugins.contains(aPluginURL)){
218 autoloadPlugins.add(aPluginURL);
219 }
220 getCreoleRegister().registerDirectories(aPluginURL);
221 }catch(MalformedURLException mue){
222 System.err.println("Cannot load " + aDir + " CREOLE repository.");
223 mue.printStackTrace();
224 }catch(GateException ge){
225 System.err.println("Cannot load " + aDir + " CREOLE repository.");
226 ge.printStackTrace();
227 }
228 }
229 }
230
231
232 public static void initCreoleRegister() throws GateException {
233
234 for(int i=0; i<builtinCreoleDirectoryUrls.length; i++)
236 try {
237 creoleRegister.addDirectory(
238 new URL(builtinCreoleDirectoryUrls[i])
239 );
240 } catch(MalformedURLException e) {
241 throw new GateException(e);
242 }
243
244
248
252 creoleRegister.registerBuiltins();
254 }
256
257 public static void initDataStoreRegister() {
258 dataStoreRegister = new DataStoreRegister();
259 }
261
276 public static void initConfigData() throws GateException {
277 ConfigDataProcessor configProcessor = new ConfigDataProcessor();
278
279 URL configUrl =
281 Gate.getClassLoader().getResource("gate/resources/" + GATE_DOT_XML);
282
283 InputStream configStream = null;
285 try {
286 configStream = Files.getGateResourceAsStream(GATE_DOT_XML);
287 } catch(IOException e) {
288 throw new GateException(
289 "Couldn't open builtin config data file: " + configUrl + " " + e
290 );
291 }
292 configProcessor.parseConfigFile(configStream, configUrl);
293
294 File siteConfigFile = Gate.getSiteConfigFile();
296 if(siteConfigFile != null) {
297 try {
298 configUrl = siteConfigFile.toURL();
299 configStream = new FileInputStream(Gate.getSiteConfigFile());
300 } catch(IOException e) {
301 throw new GateException(
302 "Couldn't open site config data file: " + configUrl + " " + e
303 );
304 }
305 configProcessor.parseConfigFile(configStream, configUrl);
306 }
307
308 String userConfigName = getUserConfigFileName();
310 File userConfigFile = null;
311 URL userConfigUrl = null;
312 if(DEBUG) { Out.prln("loading user config from " + userConfigName); }
313 configStream = null;
314 boolean userConfigExists = true;
315 try {
316 userConfigFile = new File(userConfigName);
317 configStream = new FileInputStream(userConfigFile);
318 userConfigUrl = userConfigFile.toURL();
319 } catch(IOException e) {
320 userConfigExists = false;
321 }
322 if(userConfigExists)
323 configProcessor.parseConfigFile(configStream, userConfigUrl);
324
325 originalUserConfig.putAll(userConfig);
327
328 if(DEBUG) {
329 Out.prln(
330 "user config loaded; DBCONFIG=" + DataStoreRegister.getConfigData()
331 );
332 }
333
334
335 String creolepath = System.getProperty("creole.path");
337 if(creolepath != null && creolepath.length() > 0){
338 StringTokenizer strTok = new StringTokenizer(creolepath,
339 Strings.getPathSep(), false);
340 while(strTok.hasMoreTokens()){
341 String aPath = strTok.nextToken();
342 try{
344 URL creoleURL = new File(aPath).toURL();
345 Gate.getCreoleRegister().registerDirectories(creoleURL);
346 }catch(MalformedURLException mue){
347 throw new GateRuntimeException(mue);
348 }
349 }
350 }
351
352 }
354
357 public static String guessUnicodeFont(){
358 String[] fontNames = java.awt.GraphicsEnvironment.
360 getLocalGraphicsEnvironment().
361 getAvailableFontFamilyNames();
362 String unicodeFontName = null;
363 for(int i = 0; i < fontNames.length; i++){
364 if(fontNames[i].equalsIgnoreCase("Arial Unicode MS")){
365 unicodeFontName = fontNames[i];
366 break;
367 }
368 if(fontNames[i].toLowerCase().indexOf("unicode") != -1){
369 unicodeFontName = fontNames[i];
370 }
371 } return unicodeFontName;
373 }
374
375
403 public static URL getUrl() throws GateException {
404 if(urlBase != null) return urlBase;
405
406 try {
407
408 if(isNetConnected()) {
410 if(
411 tryNetServer("gate-internal.dcs.shef.ac.uk", 80, "/") ||
412 tryNetServer("gate.ac.uk", 80, "/")
414 ) {
415 if(DEBUG) Out.prln("getUrl() returned " + urlBase);
416 return urlBase;
417 }
418 }
420 if(
424 isLocalWebServer() &&
425 tryNetServer(
426 InetAddress.getLocalHost().getHostName(), 80, "/gate.ac.uk/"
427 )
428 ) {
429 if(DEBUG) Out.prln("getUrlBase() returned " + urlBase);
430 return urlBase;
431 }
432
433 tryFileSystem();
435
436 } catch(MalformedURLException e) {
437 throw new GateException("Bad URL, getUrlBase(): " + urlBase + ": " + e);
438 } catch(UnknownHostException e) {
439 throw new GateException("No host, getUrlBase(): " + urlBase + ": " + e);
440 }
441
442 if(DEBUG) Out.prln("getUrlBase() returned " + urlBase);
444 return urlBase;
445 }
447
454 public static URL getUrl(String path) throws GateException {
455 getUrl();
456 if(urlBase == null)
457 return null;
458
459 URL newUrl = null;
460 try {
461 newUrl = new URL(urlBase, path);
462 } catch(MalformedURLException e) {
463 throw new GateException("Bad URL, getUrl( " + path + "): " + e);
464 }
465
466 if(DEBUG) Out.prln("getUrl(" + path + ") returned " + newUrl);
467 return newUrl;
468 }
470
473 private static boolean netConnected = true;
474
475 private static int lastSym;
476
477
481 private static Set registeredIREngines = new HashSet();
482
483
491 public static void registerIREngine(String className)
492 throws GateException, ClassNotFoundException{
493 Class aClass = Class.forName(className);
494 if(gate.creole.ir.IREngine.class.isAssignableFrom(aClass)){
495 registeredIREngines.add(className);
496 }else{
497 throw new GateException(className + " does not implement the " +
498 gate.creole.ir.IREngine.class.getName() +
499 " interface!");
500 }
501 }
502
503
509 public static boolean unregisterIREngine(String className){
510 return registeredIREngines.remove(className);
511 }
512
513
517 public static Set getRegisteredIREngines(){
518 return Collections.unmodifiableSet(registeredIREngines);
519 }
520
521
522 public static boolean isNetConnected() { return netConnected; }
523
524
528 public static void setNetConnected(boolean b) { netConnected = b; }
529
530
535 private static boolean localWebServer = true;
536
537
538 public static boolean isLocalWebServer() { return localWebServer; }
539
540
541 public static void setLocalWebServer(boolean b) { localWebServer = b; }
542
543
551 public static boolean tryNetServer(
552 String hostName, int serverPort, String path
553 ) throws MalformedURLException {
554 Socket socket = null;
555 if(DEBUG)
556 Out.prln(
557 "tryNetServer(hostName=" + hostName + ", serverPort=" + serverPort +
558 ", path=" + path +")"
559 );
560
561 try{
563 URL url = new URL("http://" + hostName + ":" + serverPort + "/");
564 URLConnection uConn = url.openConnection();
565 HttpURLConnection huConn = null;
566 if(uConn instanceof HttpURLConnection)
567 huConn = (HttpURLConnection)uConn;
568 if(huConn.getResponseCode() == -1) return false;
569 } catch (IOException e){
570 return false;
571 }
572
573 urlBase = new URL("http", hostName, serverPort, path);
575 return true;
576
578 }
581
582 protected static boolean tryFileSystem() throws MalformedURLException {
583 String urlBaseName = locateGateFiles();
584 if(DEBUG) Out.prln("tryFileSystem: " + urlBaseName);
585
586 urlBase = new URL(urlBaseName + "gate/resources/gate.ac.uk/");
587 return urlBase == null;
588 }
590
594 public static String locateGateFiles() {
595 String aGateResourceName = "gate/resources/creole/creole.xml";
596 URL resourcesUrl = Gate.getClassLoader().getResource(aGateResourceName);
597
598 StringBuffer basePath = new StringBuffer(resourcesUrl.toExternalForm());
599 String urlBaseName =
600 basePath.substring(0, basePath.length() - aGateResourceName.length());
601
602 return urlBaseName;
603 }
605
608 public static boolean isGateType(String classname){
609 boolean res = getCreoleRegister().containsKey(classname);
610 if(!res){
611 try{
612 Class aClass = Class.forName(classname);
613 res = Resource.class.isAssignableFrom(aClass) ||
614 Controller.class.isAssignableFrom(aClass) ||
615 DataStore.class.isAssignableFrom(aClass);
616 }catch(ClassNotFoundException cnfe){
617 return false;
618 }
619 }
620 return res;
621 }
622
623
624 static public boolean getHiddenAttribute(FeatureMap fm){
625 if(fm == null) return false;
626 Object value = fm.get("gate.HIDDEN");
627 return value != null &&
628 value instanceof String &&
629 ((String)value).equals("true");
630 }
631
632
633 static public void setHiddenAttribute(FeatureMap fm, boolean hidden){
634 if(hidden){
635 fm.put("gate.HIDDEN", "true");
636 }else{
637 fm.remove("gate.HIDDEN");
638 }
639 }
640
641
642
644 public static synchronized void addCreoleListener(CreoleListener l){
645 creoleRegister.addCreoleListener(l);
646 }
648
649 public static void setUrlBase(URL urlBase) { Gate.urlBase = urlBase; }
650
651
652 private static URL urlBase = null;
653
654
657 private static GateClassLoader classLoader = null;
658
659
660 public static GateClassLoader getClassLoader() { return classLoader; }
661
662
663 private static CreoleRegister creoleRegister = null;
664
665
666 public static CreoleRegister getCreoleRegister() { return creoleRegister; }
667
668
669 private static DataStoreRegister dataStoreRegister = null;
670
671
674 private static gate.Executable currentExecutable;
675
676
677 public static DataStoreRegister getDataStoreRegister() {
678 return dataStoreRegister;
679 }
681
688 public synchronized static void setExecutable(gate.Executable executable) {
689 if(executable == null) currentExecutable = executable;
690 else{
691 while(getExecutable() != null){
692 try{
693 Thread.sleep(200);
694 }catch(InterruptedException ie){
695 throw new LuckyException(ie.toString());
696 }
697 }
698 currentExecutable = executable;
699 }
700 }
702
706 public synchronized static gate.Executable getExecutable() {
707 return currentExecutable;
708 }
710
711
714 public synchronized static String genSym() {
715 StringBuffer buff = new StringBuffer(Integer.toHexString(lastSym++).
716 toUpperCase());
717 for(int i = buff.length(); i <= 4; i++) buff.insert(0, '0');
718 return buff.toString();
719 }
721
722 private static OptionsMap userConfig = new OptionsMap();
723
724
728 private static OptionsMap originalUserConfig = new OptionsMap();
729
730
731 private static String userConfigElement = "GATECONFIG";
732
733
737 public static String getUserConfigElement() { return userConfigElement; }
738
739
745 public static File getSiteConfigFile() {
746 if(siteConfigFile == null) {
747 String gateConfigProperty = System.getProperty(GATE_CONFIG_PROPERTY);
748 if(gateConfigProperty != null)
749 siteConfigFile = new File(gateConfigProperty);
750 }
751 return siteConfigFile;
752 }
754
755 public static void setSiteConfigFile(File siteConfigFile) {
756 Gate.siteConfigFile = siteConfigFile;
757 }
759
760 private static File siteConfigFile;
761
762
763 private static String nl = Strings.getNl();
764
765
766 private static String emptyConfigFile =
767 "<?xml version=\"1.0\"?>" + nl +
768 "<!-- " + GATE_DOT_XML + ": GATE configuration data -->" + nl +
769 "<GATE>" + nl +
770 "" + nl +
771 "<!-- NOTE: the next element may be overwritten by the GUI!!! -->" + nl +
772 "<" + userConfigElement + "/>" + nl +
773 "" + nl +
774 "</GATE>" + nl;
775
776
780 public static String getEmptyConfigFile() { return emptyConfigFile; }
781
782
786 public static OptionsMap getUserConfig() { return userConfig; }
787
788
793 public static OptionsMap getOriginalUserConfig() {
794 return originalUserConfig;
795 }
797
801 public static void writeUserConfig() throws GateException {
802 String knownPluginPath = "";
804 Iterator pluginIter = knownPlugins.iterator();
805 while(pluginIter.hasNext()){
806 URL aPluginURL = (URL)pluginIter.next();
807 if(knownPluginPath.length() > 0) knownPluginPath += ";";
808 knownPluginPath += aPluginURL.toExternalForm();
809 }
810 getUserConfig().put(KNOWN_PLUGIN_PATH_KEY, knownPluginPath);
811
812 String loadPluginPath = "";
814 pluginIter = autoloadPlugins.iterator();
815 while(pluginIter.hasNext()){
816 URL aPluginURL = (URL)pluginIter.next();
817 if(loadPluginPath.length() > 0) loadPluginPath += ";";
818 loadPluginPath += aPluginURL.toExternalForm();
819 }
820 getUserConfig().put(LOAD_PLUGIN_PATH_KEY, loadPluginPath);
821
822 String configFileName = getUserConfigFileName();
824 File configFile = new File(configFileName);
825
826 try {
828 if(! configFile.exists()) {
830 FileWriter writer = new FileWriter(configFile);
831 writer.write(emptyConfigFile);
832 writer.close();
833 }
834
835 Files.updateXmlElement(
837 new File(configFileName), userConfigElement, userConfig
838 );
839
840 } catch(IOException e) {
841 throw new GateException(
842 "problem writing user " + GATE_DOT_XML + ": " + nl + e.toString()
843 );
844 }
845 }
847
851 public static String getUserConfigFileName() {
852 String filePrefix = "";
853 if(runningOnUnix()) filePrefix = ".";
854
855 String userConfigName =
856 System.getProperty("user.home") + Strings.getFileSep() +
857 filePrefix + GATE_DOT_XML;
858 return userConfigName;
859 }
861
865 public static String getUserSessionFileName() {
866 String filePrefix = "";
867 if(runningOnUnix()) filePrefix = ".";
868
869 String userSessionName =
870 System.getProperty("user.home") + Strings.getFileSep() +
871 filePrefix + GATE_DOT_SER;
872 return userSessionName;
873 }
875
883 public static boolean runningOnUnix() {
884 return Strings.getFileSep().equals("/");
885 }
887
893 public static List getKnownPlugins(){
894 return knownPlugins;
895 }
896
897 public static void addKnownPlugin(URL pluginURL){
898 if(knownPlugins.contains(pluginURL)) return;
899 knownPlugins.add(pluginURL);
900 }
901
902
907 public static List getAutoloadPlugins(){
908 return autoloadPlugins;
909 }
910
911 public static void addAutoloadPlugin(URL pluginUrl){
912 if(autoloadPlugins.contains(pluginUrl))return;
913 addKnownPlugin(pluginUrl);
915 autoloadPlugins.add(pluginUrl);
917 }
918
919
924 public static DirectoryInfo getDirectoryInfo(URL directory){
925 if(!knownPlugins.contains(directory)) return null;
926 DirectoryInfo dInfo = (DirectoryInfo)pluginData.get(directory);
927 if(dInfo == null){
928 dInfo = new DirectoryInfo(directory);
929 pluginData.put(directory, dInfo);
930 }
931 return dInfo;
932 }
933
934
941 public static void removeKnownDirectory(URL directory){
942 DirectoryInfo dInfo = (DirectoryInfo)pluginData.get(directory);
943 if(dInfo != null){
944 creoleRegister.removeDirectory(directory);
945 knownPlugins.remove(directory);
946 pluginData.remove(directory);
947 }
948 }
949
950
953 public static class DirectoryInfo{
954 public DirectoryInfo(URL url){
955 this.url = url;
956 valid = true;
957 resourceInfoList = new ArrayList();
958 parseCreole();
960 }
961
962
966 protected void parseCreole(){
967 SAXBuilder builder = new SAXBuilder(false);
968 try{
969 if(!url.getPath().endsWith("/"))
970 url = new URL(url.getProtocol(), url.getHost(),
971 url.getPort(), url.getPath() + "/");
972 URL creoleFileURL = new URL(url, "creole.xml");
973 org.jdom.Document creoleDoc = builder.build(creoleFileURL);
974 List jobsList = new ArrayList();
975 jobsList.add(creoleDoc.getRootElement());
976 while(!jobsList.isEmpty()){
977 Element currentElem = (Element)jobsList.remove(0);
978 if(currentElem.getName().equalsIgnoreCase("RESOURCE")){
979 String resName = currentElem.getChildTextTrim("NAME");
981 String resClass = currentElem.getChildTextTrim("CLASS");
982 String resComment = currentElem.getChildTextTrim("COMMENT");
983 ResourceInfo rHandler = new ResourceInfo(resName, resClass,
985 resComment);
986 resourceInfoList.add(rHandler);
987 }else{
988 List newJobsList = new ArrayList(currentElem.getChildren());
991 newJobsList.addAll(jobsList);
992 jobsList = newJobsList;
993 }
994 }
995 }catch(IOException ioe){
996 valid = false;
997 ioe.printStackTrace();
998 }catch(JDOMException jde){
999 valid = false;
1000 jde.printStackTrace();
1001 }
1002 }
1003
1004
1007 public List getResourceInfoList(){
1008 return resourceInfoList;
1009 }
1010
1013 public URL getUrl(){
1014 return url;
1015 }
1016
1019 public boolean isValid(){
1020 return valid;
1021 }
1022
1025 protected URL url;
1026
1027
1031 protected boolean valid;
1032
1033
1036 protected List resourceInfoList;
1037 }
1038
1039
1045 public static class ResourceInfo{
1046 public ResourceInfo(String name, String className, String comment){
1047 this.resourceClassName = className;
1048 this.resourceName = name;
1049 this.resourceComment = comment;
1050 }
1051
1052
1055 public String getResourceClassName(){
1056 return resourceClassName;
1057 }
1058
1061 public String getResourceComment(){
1062 return resourceComment;
1063 }
1064
1067 public String getResourceName(){
1068 return resourceName;
1069 }
1070
1073 protected String resourceClassName;
1074
1075
1078 protected String resourceName;
1079
1080
1083 protected String resourceComment;
1084 }
1085
1086
1090 protected static List knownPlugins;
1091
1092
1097 protected static List autoloadPlugins;
1098
1099
1100
1103 protected static Map pluginData;
1104
1105
1106
1107
1108 private static boolean slugGui = false;
1109
1110
1111 public static boolean isSlugGui() { return slugGui; }
1112
1113
1114 public static void setSlugGui(boolean b) { slugGui = b; }
1115
1116
1117 private static boolean enableJapeDebug = false;
1118
1119
1120 public static boolean isEnableJapeDebug() { return enableJapeDebug; }
1121
1122
1123 public static void setEnableJapeDebug(boolean b) { enableJapeDebug = b; }
1124
1125}