use of gate.creole.Plugin in project gate-core by GateNLP.
the class PluginUpdateManager method loadDefaultPlugins.
public static void loadDefaultPlugins() {
if (defaultPlugins != null)
return;
defaultPlugins = new HashSet<Plugin>();
// TODO load the default set from somewhere more sensible
try (BufferedReader in = new BufferedReader(new InputStreamReader(PluginUpdateManager.class.getClassLoader().getResource("gate/resources/creole/defaultPlugins.tsv").openStream()))) {
for (String line = in.readLine(); line != null; line = in.readLine()) {
try {
String[] parts = line.split("\t", 3);
// if we don't have three parts then skip this line
if (parts.length != 3)
continue;
Plugin.Maven plugin = new Plugin.Maven(parts[0], parts[1], parts[2]);
// this triggers the resolve of the creole metadata jar so we have
// all the details to fill the table -- but it slows us down!
plugin.getMetadataXML();
defaultPlugins.add(plugin);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ioe) {
System.err.println("Unable to completely load list of default plugins");
ioe.printStackTrace();
}
}
use of gate.creole.Plugin in project gate-core by GateNLP.
the class Gate method initCreoleRepositories.
/**
* Loads the CREOLE repositories (aka plugins) that the user has selected for
* automatic loading. Loads the information about known plugins in memory.
*/
protected static void initCreoleRepositories() {
// the logic is:
// get the list of know plugins from gate.xml
// add all the installed plugins
// get the list of loadable plugins
// load loadable plugins
// TODO reinstate this bit
// process the known plugins list
/*String knownPluginsPath =
(String)getUserConfig().get(KNOWN_PLUGIN_PATH_KEY);
if(knownPluginsPath != null && knownPluginsPath.length() > 0) {
StringTokenizer strTok =
new StringTokenizer(knownPluginsPath, ";", false);
while(strTok.hasMoreTokens()) {
String aKnownPluginPath = strTok.nextToken();
try {
URL aPluginURL = new URL(aKnownPluginPath);
addKnownPlugin(aPluginURL);
}
catch(MalformedURLException mue) {
log.error("Plugin error: " + aKnownPluginPath + " is an invalid URL!");
}
}
}
// add all the installed plugins
// pluginsHome is now set by initLocalPaths
// File pluginsHome = new File(System.getProperty(GATE_HOME_PROPERTY_NAME),
// "plugins");
File[] dirs = pluginsHome.listFiles();
for(int i = 0; i < dirs.length; i++) {
File creoleFile = new File(dirs[i], "creole.xml");
if(creoleFile.exists()) {
try {
URL pluginURL = dirs[i].toURI().toURL();
addKnownPlugin(new Plugin.Directory(pluginURL));
}
catch(MalformedURLException mue) {
// this should never happen
throw new GateRuntimeException(mue);
}
}
}*/
// register plugins installed in the user plugin directory
/*File userPluginsHome = PluginUpdateManager.getUserPluginsHome();
if (userPluginsHome != null && userPluginsHome.isDirectory()) {
for (File dir : userPluginsHome.listFiles()) {
File creoleFile = new File(dir, "creole.xml");
if(creoleFile.exists()) {
try {
URL pluginURL = dir.toURI().toURL();
addKnownPlugin(new Plugin.Directory(pluginURL));
}
catch(MalformedURLException mue) {
// this should never happen
throw new GateRuntimeException(mue);
}
}
}
}*/
// process the autoload plugins
String pluginPath = getUserConfig().getString(AUTOLOAD_PLUGIN_PATH_KEY);
// can be overridden by system property
String prop = System.getProperty(AUTOLOAD_PLUGIN_PATH_PROPERTY_NAME);
if (prop != null && prop.length() > 0)
pluginPath = prop;
if (pluginPath == null || pluginPath.length() == 0) {
// no plugin to load stop here
return;
}
// load all loadable plugins
StringTokenizer strTok = new StringTokenizer(pluginPath, ";", false);
while (strTok.hasMoreTokens()) {
String aDir = strTok.nextToken();
try {
URL aPluginURL = new URL(aDir);
Plugin plugin = new Plugin.Directory(aPluginURL);
addAutoloadPlugin(plugin);
} catch (MalformedURLException mue) {
log.error("Cannot load " + aDir + " CREOLE repository.", mue);
}
try {
Iterator<Plugin> loadPluginsIter = getAutoloadPlugins().iterator();
while (loadPluginsIter.hasNext()) {
getCreoleRegister().registerPlugin(loadPluginsIter.next());
}
} catch (GateException ge) {
log.error("Cannot load " + aDir + " CREOLE repository.", ge);
}
}
}
use of gate.creole.Plugin in project gate-core by GateNLP.
the class CreoleProxy method createResource.
/**
* Create an instance of a resource using default parameter values.
*
* @see #createResource(String,FeatureMap)
*/
public static Resource createResource(String resourceClassName) throws ResourceInstantiationException {
// get the resource metadata
ResourceData resData = Gate.getCreoleRegister().get(resourceClassName);
if (resData == null) {
Set<Plugin> plugins = Gate.getPlugins(resourceClassName);
StringBuilder msg = new StringBuilder();
msg.append("Couldn't get resource data for ").append(resourceClassName).append(".\n\n");
if (plugins.isEmpty()) {
msg.append("You may need first to load the plugin that contains your resource.\n");
msg.append("For example, to create a gate.creole.tokeniser.DefaultTokeniser\n");
msg.append("you need first to load the ANNIE plugin.\n\n");
} else if (plugins.size() == 1) {
msg.append(resourceClassName).append(" can be found in the ").append(plugins.iterator().next().getName()).append(" plugin\n\n");
} else {
msg.append(resourceClassName).append(" can be found in the following plugins\n ");
for (Plugin dInfo : plugins) {
msg.append(dInfo.getName()).append(", ");
}
msg.setLength(msg.length() - 2);
msg.append("\n\n");
}
msg.append("Go to the menu File->Manage CREOLE plugins or use the method\n");
msg.append("Gate.getCreoleRegister().registerDirectories(pluginDirectoryURL).");
throw new ResourceInstantiationException(msg.toString());
}
// get the parameter list and default values
ParameterList paramList = resData.getParameterList();
FeatureMap parameterValues = null;
try {
parameterValues = paramList.getInitimeDefaults();
} catch (ParameterException e) {
throw new ResourceInstantiationException("Couldn't get default parameters for " + resourceClassName + ": " + e);
}
return createResource(resourceClassName, parameterValues);
}
use of gate.creole.Plugin in project gate-core by GateNLP.
the class CreoleProxy method createResource.
/**
* Create an instance of a resource, and return it. Callers of this
* method are responsible for querying the resource's parameter lists,
* putting together a set that is complete apart from runtime
* parameters, and passing a feature map containing these parameter
* settings.
*
* In the case of ProcessingResources they will have their runtime
* parameters initialised to their default values.
*
* @param resourceClassName the name of the class implementing the
* resource.
* @param parameterValues the feature map containing intialisation
* time parameterValues for the resource.
* @param features the features for the new resource or null to not
* assign any (new) features.
* @param resourceName the name to be given to the resource or null to
* assign a default name.
* @return an instantiated resource.
*/
public static Resource createResource(String resourceClassName, FeatureMap parameterValues, FeatureMap features, String resourceName) throws ResourceInstantiationException {
// get the resource metadata
ResourceData resData = Gate.getCreoleRegister().get(resourceClassName);
if (resData == null) {
Set<Plugin> plugins = Gate.getPlugins(resourceClassName);
StringBuilder msg = new StringBuilder();
msg.append("Couldn't get resource data for ").append(resourceClassName).append(".\n\n");
if (plugins.isEmpty()) {
msg.append("You may need first to load the plugin that contains your resource.\n");
msg.append("For example, to create a gate.creole.tokeniser.DefaultTokeniser\n");
msg.append("you need first to load the ANNIE plugin.\n\n");
} else if (plugins.size() == 1) {
msg.append(resourceClassName).append(" can be found in the ").append(plugins.iterator().next().getName()).append(" plugin\n\n");
} else {
msg.append(resourceClassName).append(" can be found in the following plugins\n ");
for (Plugin dInfo : plugins) {
msg.append(dInfo.getName()).append(", ");
}
msg.setLength(msg.length() - 2);
msg.append("\n\n");
}
msg.append("Go to the menu File->Manage CREOLE plugins or use the method\n");
msg.append("Gate.getCreoleRegister().registerDirectories(pluginDirectoryURL).");
throw new ResourceInstantiationException(msg.toString());
}
// get the default implementation class
Class<? extends Resource> resClass = null;
try {
resClass = resData.getResourceClass();
} catch (ClassNotFoundException e) {
throw new ResourceInstantiationException("Couldn't get resource class from the resource data:" + Strings.getNl() + e);
}
// create a pointer for the resource
Resource res = null;
// if the object is an LR and it should come from a DS then create
// that way
DataStore dataStore;
if (LanguageResource.class.isAssignableFrom(resClass) && ((dataStore = (DataStore) parameterValues.get(DataStore.DATASTORE_FEATURE_NAME)) != null)) {
// ask the datastore to create our object
if (dataStore instanceof SerialDataStore) {
// serialisability
if (!Serializable.class.isAssignableFrom(resClass))
throw new ResourceInstantiationException("Resource cannot be (de-)serialized: " + resClass.getName());
}
// get the datastore instance id and retrieve the resource
Object instanceId = parameterValues.get(DataStore.LR_ID_FEATURE_NAME);
if (instanceId == null)
throw new ResourceInstantiationException("No instance id for " + resClass);
try {
res = dataStore.getLr(resClass.getName(), instanceId);
} catch (PersistenceException pe) {
throw new ResourceInstantiationException("Bad read from DB: " + pe);
} catch (SecurityException se) {
throw new ResourceInstantiationException("Insufficient permissions: " + se);
}
resData.addInstantiation(res);
if (features != null) {
if (res.getFeatures() == null) {
res.setFeatures(newFeatureMap());
}
res.getFeatures().putAll(features);
}
// set the name
if (res.getName() == null) {
res.setName(resourceName == null ? resData.getName() + "_" + Gate.genSym() : resourceName);
}
// fire the event
creoleProxy.fireResourceLoaded(new CreoleEvent(res, CreoleEvent.RESOURCE_LOADED));
return res;
}
// create an object using the resource's default constructor
try {
if (DEBUG)
Out.prln("Creating resource " + resClass.getName());
res = resClass.newInstance();
} catch (IllegalAccessException e) {
throw new ResourceInstantiationException("Couldn't create resource instance, access denied: " + e);
} catch (InstantiationException e) {
throw new ResourceInstantiationException("Couldn't create resource instance due to newInstance() failure: " + e);
}
if (LanguageResource.class.isAssignableFrom(resClass)) {
// type-specific stuff for LRs
if (DEBUG)
Out.prln(resClass.getName() + " is a LR");
} else if (ProcessingResource.class.isAssignableFrom(resClass)) {
// type-specific stuff for PRs
if (DEBUG)
Out.prln(resClass.getName() + " is a PR");
// set the runtime parameters to their defaults
try {
FeatureMap parameters = newFeatureMap();
parameters.putAll(resData.getParameterList().getRuntimeDefaults());
res.setParameterValues(parameters);
} catch (ParameterException pe) {
throw new ResourceInstantiationException("Could not set the runtime parameters " + "to their default values for: " + res.getClass().getName() + " :\n" + pe.toString());
}
// type-specific stuff for VRs
} else if (VisualResource.class.isAssignableFrom(resClass)) {
if (DEBUG)
Out.prln(resClass.getName() + " is a VR");
} else if (Controller.class.isAssignableFrom(resClass)) {
// type specific stuff for Controllers
if (DEBUG)
Out.prln(resClass.getName() + " is a Controller");
}
// set the parameterValues of the resource
try {
FeatureMap parameters = newFeatureMap();
// put the defaults
parameters.putAll(resData.getParameterList().getInitimeDefaults());
// overwrite the defaults with the user provided values
parameters.putAll(parameterValues);
res.setParameterValues(parameters);
} catch (ParameterException pe) {
throw new ResourceInstantiationException("Could not set the init parameters for: " + res.getClass().getName() + " :\n" + pe.toString());
}
// suitable name if the resource doesn't already have one
if (resourceName != null && resourceName.trim().length() > 0) {
res.setName(resourceName);
} else if (res.getName() == null) {
// -> let's try and find a reasonable one
try {
// first try to get a filename from the various parameters
URL sourceUrl = null;
if (res instanceof SimpleDocument) {
sourceUrl = ((SimpleDocument) res).getSourceUrl();
} else if (res instanceof AnnotationSchema) {
sourceUrl = ((AnnotationSchema) res).getXmlFileUrl();
} else if (res.getClass().getName().startsWith("gate.creole.ontology.owlim.")) {
// get the name for the OWLIM2 ontology LR
java.lang.reflect.Method m = resClass.getMethod("getRdfXmlURL");
sourceUrl = (java.net.URL) m.invoke(res);
if (sourceUrl == null) {
m = resClass.getMethod("getN3URL");
sourceUrl = (java.net.URL) m.invoke(res);
}
if (sourceUrl == null) {
m = resClass.getMethod("getNtriplesURL");
sourceUrl = (java.net.URL) m.invoke(res);
}
if (sourceUrl == null) {
m = resClass.getMethod("getTurtleURL");
sourceUrl = (java.net.URL) m.invoke(res);
}
} else if (res.getClass().getName().startsWith("gate.creole.ontology.impl.")) {
java.lang.reflect.Method m = resClass.getMethod("getSourceURL");
sourceUrl = (java.net.URL) m.invoke(res);
}
if (sourceUrl != null) {
URI sourceURI = sourceUrl.toURI();
resourceName = sourceURI.getPath();
if (resourceName == null || resourceName.length() == 0 || resourceName.equals("/")) {
// this URI has no path -> use the whole string
resourceName = sourceURI.toString();
} else {
// there is a significant path value -> get the last element
resourceName = resourceName.trim();
int lastSlash = resourceName.lastIndexOf('/');
if (lastSlash >= 0) {
String subStr = resourceName.substring(lastSlash + 1);
if (subStr.trim().length() > 0)
resourceName = subStr;
}
}
}
} catch (RuntimeException t) {
// even runtime exceptions are safe to ignore at this point
} catch (Exception t) {
// there were problems while trying to guess a name
// we can safely ignore them
} finally {
// make sure there is a name provided, whatever happened
if (resourceName == null || resourceName.trim().length() == 0) {
resourceName = resData.getName();
}
}
resourceName += "_" + Gate.genSym();
res.setName(resourceName);
}
// else if(res.getName() == null)
// if res.getName() != null, leave it as it is
Map<String, EventListener> listeners = new HashMap<String, EventListener>(gate.Gate.getListeners());
// set the listeners if any
if (!listeners.isEmpty()) {
try {
if (DEBUG)
Out.prln("Setting the listeners for " + res.toString());
AbstractResource.setResourceListeners(res, listeners);
} catch (Exception e) {
if (DEBUG)
Out.prln("Failed to set listeners for " + res.toString());
throw new ResourceInstantiationException("Parameterisation failure" + e);
}
}
// set them to the features of the resource data
if (res.getFeatures() == null || res.getFeatures().isEmpty()) {
FeatureMap fm = newFeatureMap();
fm.putAll(resData.getFeatures());
res.setFeatures(fm);
}
// add the features specified by the user
if (features != null)
res.getFeatures().putAll(features);
// initialise the resource
if (DEBUG)
Out.prln("Initialising resource " + res.toString());
res = res.init();
// remove the listeners if any
if (!listeners.isEmpty()) {
try {
if (DEBUG)
Out.prln("Removing the listeners for " + res.toString());
AbstractResource.removeResourceListeners(res, listeners);
} catch (Exception e) {
if (DEBUG)
Out.prln("Failed to remove the listeners for " + res.toString());
throw new ResourceInstantiationException("Parameterisation failure" + e);
}
}
// record the instantiation on the resource data's stack
resData.addInstantiation(res);
// fire the event
creoleProxy.fireResourceLoaded(new CreoleEvent(res, CreoleEvent.RESOURCE_LOADED));
return res;
}
use of gate.creole.Plugin in project gate-core by GateNLP.
the class AvailablePlugins method updateAvailablePlugins.
protected Set<Plugin> updateAvailablePlugins(Plugin.DownloadListener progressPanel) {
Set<Plugin> creoleDirectories = Gate.getCreoleRegister().getPlugins();
// update the data structures to reflect the user's choices
Iterator<Plugin> pluginIter = loadNowByURL.keySet().iterator();
Set<Plugin> toLoad = new HashSet<Plugin>();
while (pluginIter.hasNext()) {
Plugin aPluginURL = pluginIter.next();
boolean load = loadNowByURL.get(aPluginURL);
boolean loaded = creoleDirectories.contains(aPluginURL);
if (load && !loaded) {
// remember that we need to load this plugin
toLoad.add(aPluginURL);
}
if (!load && loaded) {
// remove the directory
Gate.getCreoleRegister().unregisterPlugin(aPluginURL);
}
}
pluginIter = loadAlwaysByURL.keySet().iterator();
while (pluginIter.hasNext()) {
Plugin aPluginURL = pluginIter.next();
boolean load = loadAlwaysByURL.get(aPluginURL);
boolean loaded = Gate.getAutoloadPlugins().contains(aPluginURL);
if (load && !loaded) {
// set autoload to true
Gate.addAutoloadPlugin(aPluginURL);
}
if (!load && loaded) {
// set autoload to false
Gate.removeAutoloadPlugin(aPluginURL);
}
}
while (!toLoad.isEmpty()) {
// lets finally try loading all the plugings
int numToLoad = toLoad.size();
List<Throwable> errors = new ArrayList<Throwable>();
pluginIter = toLoad.iterator();
while (pluginIter.hasNext()) {
Plugin aPluginURL = pluginIter.next();
// load the directory
try {
aPluginURL.addDownloadListener(progressPanel);
((CreoleRegisterImpl) Gate.getCreoleRegister()).registerPlugin(aPluginURL);
pluginIter.remove();
} catch (Throwable ge) {
// TODO suppress the errors unless we are going to break out of the loop
// ge.printStackTrace();
errors.add(ge);
} finally {
aPluginURL.removeDownloadListener(progressPanel);
}
}
if (numToLoad == toLoad.size()) {
// we didn't actually achieve anything
for (Throwable t : errors) {
t.printStackTrace();
}
break;
}
}
loadNowByURL.clear();
loadAlwaysByURL.clear();
return toLoad;
}
Aggregations