Search in sources :

Example 1 with AnnotationSchema

use of gate.creole.AnnotationSchema in project gate-core by GateNLP.

the class AnnotationEditor method initData.

protected void initData() {
    schemasByType = new HashMap<String, AnnotationSchema>();
    java.util.List<LanguageResource> schemas = Gate.getCreoleRegister().getLrInstances("gate.creole.AnnotationSchema");
    for (Iterator<LanguageResource> schIter = schemas.iterator(); schIter.hasNext(); ) {
        AnnotationSchema aSchema = (AnnotationSchema) schIter.next();
        schemasByType.put(aSchema.getAnnotationName(), aSchema);
    }
    CreoleListener creoleListener = new CreoleListener() {

        @Override
        public void resourceLoaded(CreoleEvent e) {
            Resource newResource = e.getResource();
            if (newResource instanceof AnnotationSchema) {
                AnnotationSchema aSchema = (AnnotationSchema) newResource;
                schemasByType.put(aSchema.getAnnotationName(), aSchema);
            }
        }

        @Override
        public void resourceUnloaded(CreoleEvent e) {
            Resource newResource = e.getResource();
            if (newResource instanceof AnnotationSchema) {
                AnnotationSchema aSchema = (AnnotationSchema) newResource;
                if (schemasByType.containsValue(aSchema)) {
                    schemasByType.remove(aSchema.getAnnotationName());
                }
            }
        }

        @Override
        public void datastoreOpened(CreoleEvent e) {
        }

        @Override
        public void datastoreCreated(CreoleEvent e) {
        }

        @Override
        public void datastoreClosed(CreoleEvent e) {
        }

        @Override
        public void resourceRenamed(Resource resource, String oldName, String newName) {
        }
    };
    Gate.getCreoleRegister().addCreoleListener(creoleListener);
}
Also used : CreoleListener(gate.event.CreoleListener) AnnotationSchema(gate.creole.AnnotationSchema) LanguageResource(gate.LanguageResource) CreoleEvent(gate.event.CreoleEvent) Resource(gate.Resource) LanguageResource(gate.LanguageResource) AbstractVisualResource(gate.creole.AbstractVisualResource)

Example 2 with AnnotationSchema

use of gate.creole.AnnotationSchema in project gate-core by GateNLP.

the class AnnotationEditor method editAnnotation.

@Override
public void editAnnotation(Annotation ann, AnnotationSet set) {
    this.ann = ann;
    this.set = set;
    if (ann == null) {
        typeCombo.setModel(new DefaultComboBoxModel<String>());
        featuresEditor.setSchema(new AnnotationSchema());
        // popupWindow.doLayout();
        popupWindow.validate();
        return;
    }
    // repopulate the types combo
    String annType = ann.getType();
    Set<String> types = new HashSet<String>(schemasByType.keySet());
    types.add(annType);
    types.addAll(set.getAllTypes());
    java.util.List<String> typeList = new ArrayList<String>(types);
    Collections.sort(typeList);
    typeCombo.setModel(new DefaultComboBoxModel<String>(typeList.toArray(new String[typeList.size()])));
    typeCombo.setSelectedItem(annType);
    featuresEditor.setSchema(schemasByType.get(annType));
    featuresEditor.setTargetFeatures(ann.getFeatures());
    setEditingEnabled(true);
    popupWindow.pack();
    setVisible(true);
    if (!pinnedButton.isSelected()) {
        hideTimer.restart();
    }
}
Also used : AnnotationSchema(gate.creole.AnnotationSchema) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 3 with AnnotationSchema

use of gate.creole.AnnotationSchema in project gate-core by GateNLP.

the class NameBearerHandle method buildStaticPopupItems.

protected void buildStaticPopupItems() {
    // build the static part of the popup
    staticPopupItems = new ArrayList<JComponent>();
    if (target instanceof ProcessingResource && !(target instanceof Controller)) {
        // actions for PRs (but not Controllers)
        staticPopupItems.add(null);
        staticPopupItems.add(new XJMenuItem(new ReloadAction(), sListenerProxy));
        staticPopupItems.add(new XJMenuItem(new ApplicationWithPRAction(), sListenerProxy));
    } else if (target instanceof LanguageResource) {
        // Language Resources
        staticPopupItems.add(null);
        if (target instanceof Document) {
            staticPopupItems.add(new XJMenuItem(new CreateCorpusForDocAction(), sListenerProxy));
        }
        if (target instanceof gate.TextualDocument) {
            staticPopupItems.add(null);
            staticPopupItems.add(new DocumentExportMenu(this));
        } else if (target instanceof Corpus) {
            corpusFiller = new CorpusFillerComponent();
            scfInputDialog = new SingleConcatenatedFileInputDialog();
            staticPopupItems.add(new XJMenuItem(new PopulateCorpusAction(), sListenerProxy));
            staticPopupItems.add(new XJMenuItem(new PopulateCorpusFromSingleConcatenatedFileAction(), sListenerProxy));
            staticPopupItems.add(null);
            staticPopupItems.add(new DocumentExportMenu(this));
        }
        if (((LanguageResource) target).getDataStore() != null) {
            // this item can be used only if the resource belongs to a
            // datastore
            staticPopupItems.add(new XJMenuItem(new SaveAction(), sListenerProxy));
        }
        if (!(target instanceof AnnotationSchema)) {
            staticPopupItems.add(new XJMenuItem(new SaveToAction(), sListenerProxy));
        }
    }
    if (target instanceof Controller) {
        // Applications
        staticPopupItems.add(null);
        if (target instanceof SerialAnalyserController) {
            staticPopupItems.add(new XJMenuItem(new MakeConditionalAction(), sListenerProxy));
        }
        staticPopupItems.add(new XJMenuItem(new DumpToFileAction(), sListenerProxy));
        staticPopupItems.add(new XJMenuItem(new ExportApplicationAction(), sListenerProxy));
    }
}
Also used : LanguageResource(gate.LanguageResource) ProcessingResource(gate.ProcessingResource) Document(gate.Document) IndexedCorpus(gate.creole.ir.IndexedCorpus) Corpus(gate.Corpus) AnnotationSchema(gate.creole.AnnotationSchema) SerialAnalyserController(gate.creole.SerialAnalyserController) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) JComponent(javax.swing.JComponent) SerialAnalyserController(gate.creole.SerialAnalyserController) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) CorpusController(gate.CorpusController) ConditionalController(gate.creole.ConditionalController) XJMenuItem(gate.swing.XJMenuItem)

Example 4 with AnnotationSchema

use of gate.creole.AnnotationSchema 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;
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) IdentityHashMap(java.util.IdentityHashMap) AbstractProcessingResource(gate.creole.AbstractProcessingResource) URI(java.net.URI) URL(java.net.URL) AnnotationSchema(gate.creole.AnnotationSchema) SerialDataStore(gate.persist.SerialDataStore) ParameterException(gate.creole.ParameterException) EventListener(java.util.EventListener) ResourceData(gate.creole.ResourceData) CreoleEvent(gate.event.CreoleEvent) AbstractProcessingResource(gate.creole.AbstractProcessingResource) AbstractResource(gate.creole.AbstractResource) ConditionalController(gate.creole.ConditionalController) ResourceInstantiationException(gate.creole.ResourceInstantiationException) PersistenceException(gate.persist.PersistenceException) ParameterException(gate.creole.ParameterException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) PersistenceException(gate.persist.PersistenceException) SerialDataStore(gate.persist.SerialDataStore) Plugin(gate.creole.Plugin) ResourceInstantiationException(gate.creole.ResourceInstantiationException)

Aggregations

AnnotationSchema (gate.creole.AnnotationSchema)4 LanguageResource (gate.LanguageResource)2 ConditionalController (gate.creole.ConditionalController)2 CreoleEvent (gate.event.CreoleEvent)2 Controller (gate.Controller)1 Corpus (gate.Corpus)1 CorpusController (gate.CorpusController)1 Document (gate.Document)1 ProcessingResource (gate.ProcessingResource)1 Resource (gate.Resource)1 AbstractProcessingResource (gate.creole.AbstractProcessingResource)1 AbstractResource (gate.creole.AbstractResource)1 AbstractVisualResource (gate.creole.AbstractVisualResource)1 ConditionalSerialAnalyserController (gate.creole.ConditionalSerialAnalyserController)1 ParameterException (gate.creole.ParameterException)1 Plugin (gate.creole.Plugin)1 ResourceData (gate.creole.ResourceData)1 ResourceInstantiationException (gate.creole.ResourceInstantiationException)1 SerialAnalyserController (gate.creole.SerialAnalyserController)1 IndexedCorpus (gate.creole.ir.IndexedCorpus)1