Search in sources :

Example 1 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class CreoleRegisterImpl method getAllInstances.

public List<Resource> getAllInstances(String type, boolean includeHidden) throws GateException {
    List<Resource> res = new ArrayList<Resource>();
    Class<? extends Resource> targetClass;
    try {
        targetClass = Gate.getClassLoader().loadClass(type).asSubclass(Resource.class);
    } catch (ClassNotFoundException cnfe) {
        throw new GateException("Invalid type " + type);
    }
    for (Map.Entry<String, ResourceData> entry : entrySet()) {
        String aType = entry.getKey();
        Class<?> aClass;
        try {
            aClass = entry.getValue().getResourceClass();
            if (targetClass.isAssignableFrom(aClass)) {
                // filter out hidden instances
                Iterator<? extends Resource> newInstancesIter = get(aType).getInstantiations().iterator();
                while (newInstancesIter.hasNext()) {
                    Resource instance = newInstancesIter.next();
                    if (includeHidden || !Gate.getHiddenAttribute(instance.getFeatures())) {
                        res.add(instance);
                    }
                }
            }
        } catch (ClassNotFoundException cnfe) {
            throw new GateRuntimeException("A type registered in the creole register does not exist in the VM!");
        }
    }
    return res;
}
Also used : GateException(gate.util.GateException) VisualResource(gate.VisualResource) Resource(gate.Resource) LanguageResource(gate.LanguageResource) ProcessingResource(gate.ProcessingResource) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) GateRuntimeException(gate.util.GateRuntimeException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class CreoleAnnotationHandler method processElement.

/**
 * Processes parameter annotations on a single element. Can support both Field
 * and Method elements.
 *
 * @param element
 *          The Method of Field from which to discern parameters
 * @param bi
 *          the BeanInfo for the corresponding class.
 * @param resourceElement
 *          the RESOURCE element to which the PARAMETERs are to be added
 * @param parameterMap
 *          a map from parameter names to the PARAMETER elements that define
 *          them. This is used as we combine information from the original
 *          creole.xml, the parameter annotation on the target method and the
 *          annotations on the same method of its superclasses and interfaces.
 *          Parameter names that have been hidden by a
 *          {@link HiddenCreoleParameter} annotation are explicitly mapped to
 *          <code>null</code> in this map.
 * @param disjunctionMap
 *          a map from disjunction IDs to the OR elements that define them.
 *          Disjunctive parameters are handled by specifying a disjunction ID
 *          on the {@link CreoleParameter} annotations - parameters with the
 *          same disjunction ID are grouped under the same OR element.
 */
private void processElement(AnnotatedElement element, BeanInfo bi, Element resourceElement, Map<String, Element> parameterMap, Map<String, Element> disjunctionMap) throws GateException {
    CreoleParameter paramAnnot = element.getAnnotation(CreoleParameter.class);
    HiddenCreoleParameter hiddenParamAnnot = element.getAnnotation(HiddenCreoleParameter.class);
    // Extracted name of this parameter
    String paramName;
    Class<?> paramType;
    // The type of this parameter.
    Type genericParamType;
    if (paramAnnot != null || hiddenParamAnnot != null) {
        // Enforce constraints relevant for this type of element
        if (element.getClass().equals(java.lang.reflect.Field.class)) {
            java.lang.reflect.Field field = (java.lang.reflect.Field) element;
            paramName = field.getName();
            genericParamType = field.getGenericType();
            paramType = field.getType();
            PropertyDescriptor paramDescriptor = null;
            for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
                if (paramName.equals(pd.getName())) {
                    paramDescriptor = pd;
                    break;
                }
            }
            if (paramDescriptor == null) {
                throw new GateException("CREOLE parameter annotation found on field " + field + " but no corresponding JavaBean accessor methods exist.");
            } else if (paramDescriptor.getReadMethod() == null || paramDescriptor.getWriteMethod() == null) {
                throw new GateException("CREOLE parameter annotation found on field " + field + " but getter or setter is missing.  CREOLE parameters require both.");
            }
        } else if (element.getClass().equals(Method.class)) {
            Method method = (Method) element;
            // Extract the parameter name from the BeanInfo
            PropertyDescriptor paramDescriptor = null;
            for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
                if (method.equals(pd.getWriteMethod())) {
                    paramDescriptor = pd;
                    break;
                }
            }
            if (paramDescriptor == null) {
                throw new GateException("CREOLE parameter annotation found on " + method + " but this method is not a Java Bean property setter.");
            }
            paramName = paramDescriptor.getName();
            // And the type is that of the first argument
            genericParamType = method.getGenericParameterTypes()[0];
            paramType = method.getParameterTypes()[0];
        } else {
            throw new GateException("CREOLE parameter annotation found on " + element + " but can only be placed on Method or Field");
        }
        // Hidden parameters can be added straight to the map.
        if (hiddenParamAnnot != null && !parameterMap.containsKey(paramName)) {
            parameterMap.put(paramName, null);
        }
        // Visible parameters need converting to JDOM Elements
        if (paramAnnot != null) {
            Element paramElt = null;
            if (parameterMap.containsKey(paramName)) {
                // Use existing annotation if there is such a thing.
                paramElt = parameterMap.get(paramName);
            } else {
                // Otherwise create on - type depends on whether it is disjunctive or
                // not.
                paramElt = new Element("PARAMETER").setAttribute("NAME", paramName);
                if (!"".equals(paramAnnot.disjunction())) {
                    // Disjunctive parameters (cannot both be set) need special markup.
                    Element disjunctionElt = disjunctionMap.get(paramAnnot.disjunction());
                    if (disjunctionElt == null) {
                        disjunctionElt = new Element("OR");
                        resourceElement.addContent(disjunctionElt);
                        disjunctionMap.put(paramAnnot.disjunction(), disjunctionElt);
                    }
                    disjunctionElt.addContent(paramElt);
                } else {
                    resourceElement.addContent(paramElt);
                }
                parameterMap.put(paramName, paramElt);
            }
            if (paramElt != null) {
                // which has not been masked by a @HiddenCreoleParameter
                if (paramElt.getTextTrim().length() == 0) {
                    // The text of the element should be the the type
                    paramElt.setText(paramType.getName());
                    // the item type.
                    if ((!Resource.class.isAssignableFrom(paramType)) && Collection.class.isAssignableFrom(paramType)) {
                        determineCollectionElementType(element, genericParamType, paramElt);
                    }
                }
                // other attributes
                addAttribute(paramElt, paramAnnot.comment(), "", "COMMENT");
                addAttribute(paramElt, paramAnnot.suffixes(), "", "SUFFIXES");
                addAttribute(paramElt, paramAnnot.defaultValue(), CreoleParameter.NO_DEFAULT_VALUE, "DEFAULT");
                addAttribute(paramElt, String.valueOf(paramAnnot.priority()), String.valueOf(CreoleParameter.DEFAULT_PRIORITY), "PRIORITY");
                // runtime and optional are based on marker annotations
                String runtimeParam = "";
                if (element.isAnnotationPresent(RunTime.class)) {
                    runtimeParam = String.valueOf(element.getAnnotation(RunTime.class).value());
                }
                addAttribute(paramElt, runtimeParam, "", "RUNTIME");
                String optionalParam = "";
                if (element.isAnnotationPresent(Optional.class)) {
                    optionalParam = String.valueOf(element.getAnnotation(Optional.class).value());
                }
                addAttribute(paramElt, optionalParam, "", "OPTIONAL");
            }
        }
    }
}
Also used : RunTime(gate.creole.metadata.RunTime) PropertyDescriptor(java.beans.PropertyDescriptor) Optional(gate.creole.metadata.Optional) GateException(gate.util.GateException) Element(org.jdom.Element) AnnotatedElement(java.lang.reflect.AnnotatedElement) Resource(gate.Resource) CreoleResource(gate.creole.metadata.CreoleResource) Method(java.lang.reflect.Method) Field(java.lang.reflect.Field) Field(java.lang.reflect.Field) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) GuiType(gate.creole.metadata.GuiType) HiddenCreoleParameter(gate.creole.metadata.HiddenCreoleParameter) CreoleParameter(gate.creole.metadata.CreoleParameter) Collection(java.util.Collection) HiddenCreoleParameter(gate.creole.metadata.HiddenCreoleParameter)

Example 3 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class OntologyUtilities method getOntology.

/**
 * Checks the availability of an existing instance of the Ontology
 * with the given URL in the GATE's CreoleRegister. If found, returns
 * the first available one (doesn't guranttee in which order). If not
 * found, attempts to create one using OWLIM implementation with
 * RDF/XML as ontology type and if successful returns the newly
 * created instance of the ontology.
 * @throws ResourceInstantiationException
 * @deprecated - this method should be avoided
 */
@Deprecated
public static Ontology getOntology(URL url) throws ResourceInstantiationException {
    java.util.List<Resource> loadedOntologies = null;
    Ontology ontology = null;
    try {
        loadedOntologies = Gate.getCreoleRegister().getAllInstances(Ontology.class.getName());
    } catch (GateException ge) {
        throw new ResourceInstantiationException("Cannot list loaded ontologies", ge);
    }
    Iterator<Resource> ontIter = loadedOntologies.iterator();
    while (ontology == null && ontIter.hasNext()) {
        Ontology anOntology = (Ontology) ontIter.next();
        if (anOntology.getURL().equals(url)) {
            ontology = anOntology;
            break;
        }
    }
    try {
        // if not found, load it
        if (ontology == null) {
            // hardcoded to use OWL as the ontology type
            FeatureMap params = Factory.newFeatureMap();
            params.put("persistLocation", File.createTempFile("abc", "abc").getParentFile().toURI().toURL());
            params.put("rdfXmlURL", url);
            ontology = (Ontology) Factory.createResource("gate.creole.ontology.owlim.OWLIMOntologyLR", params);
        }
    } catch (Exception e) {
        throw new ResourceInstantiationException("Cannot create a new instance of ontology", e);
    }
    return ontology;
}
Also used : FeatureMap(gate.FeatureMap) GateException(gate.util.GateException) Resource(gate.Resource) ResourceInstantiationException(gate.creole.ResourceInstantiationException) GateException(gate.util.GateException) ResourceInstantiationException(gate.creole.ResourceInstantiationException)

Example 4 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class LuceneDataStoreSearchGUI method resourceDeleted.

/**
 * This method is called by datastore when an existing resource is
 * deleted
 */
@Override
public void resourceDeleted(DatastoreEvent de) {
    Resource resource = de.getResource();
    if (resource instanceof Corpus) {
        // lets check if it is already available in our list
        Object id = de.getResourceID();
        int index = corpusIds.indexOf(id);
        if (index < 0) {
            return;
        }
        // skip the first element in combo box that is "EntireDataStore"
        index++;
        // now lets remove it from the comboBox as well
        ((DefaultComboBoxModel<String>) corpusToSearchIn.getModel()).removeElementAt(index);
    }
// Added a refresh button which user should click to refresh types
// updateSetsTypesAndFeatures();
}
Also used : Resource(gate.Resource) CreoleResource(gate.creole.metadata.CreoleResource) AbstractVisualResource(gate.creole.AbstractVisualResource) EventObject(java.util.EventObject) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel) Corpus(gate.Corpus)

Example 5 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class MainFrame method resourceLoaded.

@Override
public void resourceLoaded(CreoleEvent e) {
    final Resource res = e.getResource();
    if (Gate.getHiddenAttribute(res.getFeatures()) || res instanceof VisualResource)
        return;
    // SwingUtilities.invokeLater(new Runnable() {
    // @Override
    // public void run() {
    NameBearerHandle handle = null;
    if (res instanceof Controller) {
        handle = new NameBearerHandle(res, MainFrame.this);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(handle, false);
        resourcesTreeModel.insertNodeInto(node, applicationsRoot, 0);
    } else if (res instanceof ProcessingResource) {
        handle = new NameBearerHandle(res, MainFrame.this);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(handle, false);
        resourcesTreeModel.insertNodeInto(node, processingResourcesRoot, 0);
    } else if (res instanceof LanguageResource) {
        handle = new NameBearerHandle(res, MainFrame.this);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(handle, false);
        resourcesTreeModel.insertNodeInto(node, languageResourcesRoot, 0);
    }
    if (handle != null)
        handle.addProgressListener(MainFrame.this);
    if (handle != null)
        handle.addStatusListener(MainFrame.this);
// }
// });
// JPopupMenu popup = handle.getPopup();
// 
// // Create a CloseViewAction and a menu item based on it
// CloseViewAction cva = new CloseViewAction(handle);
// XJMenuItem menuItem = new XJMenuItem(cva, this);
// // Add an accelerator ATL+F4 for this action
// menuItem.setAccelerator(KeyStroke.getKeyStroke(
// KeyEvent.VK_H, ActionEvent.CTRL_MASK));
// popup.insert(menuItem, 1);
// popup.insert(new JPopupMenu.Separator(), 2);
// 
// popup.insert(new XJMenuItem(
// new RenameResourceAction(
// new TreePath(resourcesTreeModel.getPathToRoot(node))),
// MainFrame.this) , 3);
// 
// // Put the action command in the component's action map
// if (handle.getLargeView() != null)
// handle.getLargeView().getActionMap().put("Hide current
// view",cva);
// 
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) VisualResource(gate.VisualResource) LanguageResource(gate.LanguageResource) ProcessingResource(gate.ProcessingResource) VisualResource(gate.VisualResource) Resource(gate.Resource) LanguageResource(gate.LanguageResource) ProcessingResource(gate.ProcessingResource) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) PackagedController(gate.creole.PackagedController)

Aggregations

Resource (gate.Resource)26 LanguageResource (gate.LanguageResource)9 CreoleResource (gate.creole.metadata.CreoleResource)9 FeatureMap (gate.FeatureMap)8 ProcessingResource (gate.ProcessingResource)8 VisualResource (gate.VisualResource)6 GateException (gate.util.GateException)5 GateRuntimeException (gate.util.GateRuntimeException)5 URL (java.net.URL)5 AbstractVisualResource (gate.creole.AbstractVisualResource)4 Corpus (gate.Corpus)3 AbstractResource (gate.creole.AbstractResource)3 ResourceData (gate.creole.ResourceData)3 ResourceInstantiationException (gate.creole.ResourceInstantiationException)3 PersistenceException (gate.persist.PersistenceException)3 ArrayList (java.util.ArrayList)3 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)3 Controller (gate.Controller)2 Document (gate.Document)2 ResourceInfo (gate.Gate.ResourceInfo)2