Search in sources :

Example 1 with CreoleEvent

use of gate.event.CreoleEvent 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 CreoleEvent

use of gate.event.CreoleEvent in project gate-core by GateNLP.

the class CorpusEditor method initListeners.

protected void initListeners() {
    // mouse double-click to open the document
    // context menu to get the actions for the selection
    docTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                processMouseEvent(e);
            }
        }

        private void processMouseEvent(MouseEvent e) {
            int row = docTable.rowAtPoint(e.getPoint());
            if (row == -1) {
                return;
            }
            if (e.isPopupTrigger()) {
                // context menu
                if (!docTable.isRowSelected(row)) {
                    // if right click outside the selection then reset selection
                    docTable.getSelectionModel().setSelectionInterval(row, row);
                }
                JPopupMenu popup = new XJPopupMenu();
                popup.add(openDocumentsAction);
                popup.add(removeDocumentsAction);
                popup.show(docTable, e.getPoint().x, e.getPoint().y);
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2) {
                // open document on double-click
                openDocumentsAction.actionPerformed(null);
            }
        }
    });
    // Enter key opens the selected documents
    docTable.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                openDocumentsAction.actionPerformed(null);
            }
        }
    });
    docTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // enable/disable buttons according to the selection
            removeDocumentsAction.setEnabled(docTable.getSelectedRowCount() > 0);
            openDocumentsAction.setEnabled(docTable.getSelectedRowCount() > 0);
            moveUpAction.setEnabled(docTable.getSelectedRowCount() > 0 && !docTable.isRowSelected(0));
            moveDownAction.setEnabled(docTable.getSelectedRowCount() > 0 && !docTable.isRowSelected(docTable.getRowCount() - 1));
        }
    });
    Gate.getCreoleRegister().addCreoleListener(new CreoleListener() {

        @Override
        public void resourceLoaded(CreoleEvent e) {
            if (e.getResource() instanceof Document) {
                documentsLoadedCount++;
                changeMessage();
            }
        }

        @Override
        public void resourceUnloaded(CreoleEvent e) {
            if (e.getResource() instanceof Document) {
                documentsLoadedCount--;
                changeMessage();
            }
        }

        @Override
        public void datastoreOpened(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void datastoreCreated(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void datastoreClosed(CreoleEvent e) {
        /* do nothing */
        }

        @Override
        public void resourceRenamed(Resource resource, String oldName, String newName) {
        /* do nothing */
        }
    });
}
Also used : CreoleEvent(gate.event.CreoleEvent) ListSelectionEvent(javax.swing.event.ListSelectionEvent) CreoleResource(gate.creole.metadata.CreoleResource) AbstractVisualResource(gate.creole.AbstractVisualResource) XJPopupMenu(gate.swing.XJPopupMenu) ListSelectionListener(javax.swing.event.ListSelectionListener) CreoleListener(gate.event.CreoleListener) XJPopupMenu(gate.swing.XJPopupMenu)

Example 3 with CreoleEvent

use of gate.event.CreoleEvent in project gate-core by GateNLP.

the class DataStoreRegister method clear.

// remove
/**
 * Removes all of the elements from this set. Overriden here for event
 * registration code.
 */
@Override
public void clear() {
    Set<DataStore> datastores = new HashSet<DataStore>(this);
    super.clear();
    Iterator<DataStore> iter = datastores.iterator();
    while (iter.hasNext()) {
        fireDatastoreClosed(new CreoleEvent(iter.next(), CreoleEvent.DATASTORE_CLOSED));
    }
// while
}
Also used : CreoleEvent(gate.event.CreoleEvent) HashSet(java.util.HashSet)

Example 4 with CreoleEvent

use of gate.event.CreoleEvent in project gate-core by GateNLP.

the class CreoleProxy method openDataStore.

// newFeatureMap
/**
 * Open an existing DataStore.
 */
public static DataStore openDataStore(String dataStoreClassName, String storageUrl) throws PersistenceException {
    DataStore ds = instantiateDataStore(dataStoreClassName, storageUrl);
    ds.open();
    if (Gate.getDataStoreRegister().add(ds))
        creoleProxy.fireDatastoreOpened(new CreoleEvent(ds, CreoleEvent.DATASTORE_OPENED));
    return ds;
}
Also used : SerialDataStore(gate.persist.SerialDataStore) CreoleEvent(gate.event.CreoleEvent)

Example 5 with CreoleEvent

use of gate.event.CreoleEvent 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

CreoleEvent (gate.event.CreoleEvent)7 SerialDataStore (gate.persist.SerialDataStore)3 AbstractVisualResource (gate.creole.AbstractVisualResource)2 AnnotationSchema (gate.creole.AnnotationSchema)2 ResourceData (gate.creole.ResourceData)2 CreoleListener (gate.event.CreoleListener)2 LanguageResource (gate.LanguageResource)1 Resource (gate.Resource)1 AbstractProcessingResource (gate.creole.AbstractProcessingResource)1 AbstractResource (gate.creole.AbstractResource)1 ConditionalController (gate.creole.ConditionalController)1 ParameterException (gate.creole.ParameterException)1 Plugin (gate.creole.Plugin)1 ResourceInstantiationException (gate.creole.ResourceInstantiationException)1 CreoleResource (gate.creole.metadata.CreoleResource)1 PersistenceException (gate.persist.PersistenceException)1 XJPopupMenu (gate.swing.XJPopupMenu)1 Serializable (java.io.Serializable)1 URI (java.net.URI)1 URL (java.net.URL)1