Search in sources :

Example 6 with GateException

use of gate.util.GateException 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 7 with GateException

use of gate.util.GateException 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 8 with GateException

use of gate.util.GateException in project gate-core by GateNLP.

the class CorpusEditor method initGuiComponents.

protected void initGuiComponents() {
    setLayout(new BorderLayout());
    renderer = new DocumentNameRenderer();
    docTable = new XJTable(docTableModel);
    docTable.setSortable(true);
    docTable.setSortedColumn(DocumentTableModel.COL_INDEX);
    docTable.setAutoResizeMode(XJTable.AUTO_RESIZE_LAST_COLUMN);
    docTable.getColumnModel().getColumn(DocumentTableModel.COL_NAME).setCellRenderer(renderer);
    docTable.setDragEnabled(true);
    docTable.setTransferHandler(new TransferHandler() {

        // drag and drop to move up and down the table rows
        // import selected documents from the resources tree
        String source = "";

        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            int[] selectedRows = docTable.getSelectedRows();
            Arrays.sort(selectedRows);
            return new StringSelection("CorpusEditor" + Arrays.toString(selectedRows));
        }

        @Override
        protected void exportDone(JComponent c, Transferable data, int action) {
        }

        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (DataFlavor flavor : flavors) {
                if (DataFlavor.stringFlavor.equals(flavor)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean importData(JComponent c, Transferable t) {
            if (!canImport(c, t.getTransferDataFlavors())) {
                return false;
            }
            try {
                source = (String) t.getTransferData(DataFlavor.stringFlavor);
                if (source.startsWith("ResourcesTree")) {
                    int insertion = docTable.getSelectedRow();
                    List<Document> documents = new ArrayList<Document>();
                    source = source.replaceFirst("^ResourcesTree\\[", "");
                    source = source.replaceFirst("\\]$", "");
                    final String[] documentsNames = source.split(", ");
                    List<Resource> loadedDocuments;
                    try {
                        loadedDocuments = Gate.getCreoleRegister().getAllInstances("gate.Document");
                    } catch (GateException e) {
                        e.printStackTrace();
                        return false;
                    }
                    // get the list of documents selected when dragging started
                    for (String documentName : documentsNames) {
                        for (Resource loadedDocument : loadedDocuments) {
                            if (loadedDocument.getName().equals(documentName) && !corpus.contains(loadedDocument)) {
                                documents.add((Document) loadedDocument);
                            }
                        }
                    }
                    // add the documents at the insertion point
                    for (Document document : documents) {
                        if (insertion != -1) {
                            corpus.add(docTable.rowViewToModel(insertion), document);
                            if (insertion == docTable.getRowCount()) {
                                insertion++;
                            }
                        } else {
                            corpus.add(document);
                        }
                    }
                    // select the moved/already existing documents
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            docTable.clearSelection();
                            for (String documentName : documentsNames) {
                                for (int row = 0; row < docTable.getRowCount(); row++) {
                                    if (docTable.getValueAt(row, docTable.convertColumnIndexToView(1)).equals(documentName)) {
                                        docTable.addRowSelectionInterval(row, row);
                                    }
                                }
                            }
                        }
                    });
                    changeMessage();
                    return true;
                } else if (source.startsWith("CorpusEditor")) {
                    int insertion = docTable.getSelectedRow();
                    int initialInsertion = insertion;
                    List<Document> documents = new ArrayList<Document>();
                    source = source.replaceFirst("^CorpusEditor\\[", "");
                    source = source.replaceFirst("\\]$", "");
                    String[] selectedRows = source.split(", ");
                    if (Integer.parseInt(selectedRows[0]) < insertion) {
                        insertion++;
                    }
                    // get the list of documents selected when dragging started
                    for (String row : selectedRows) {
                        if (Integer.parseInt(row) == initialInsertion) {
                            // the user dragged the selected rows on themselves, do nothing
                            return false;
                        }
                        documents.add(corpus.get(docTable.rowViewToModel(Integer.parseInt(row))));
                        if (Integer.parseInt(row) < initialInsertion) {
                            insertion--;
                        }
                    }
                    // remove the documents selected when dragging started
                    for (Document document : documents) {
                        corpus.remove(document);
                    }
                    // add the documents at the insertion point
                    for (Document document : documents) {
                        corpus.add(docTable.rowViewToModel(insertion), document);
                        insertion++;
                    }
                    // select the moved documents
                    docTable.addRowSelectionInterval(insertion - selectedRows.length, insertion - 1);
                    return true;
                } else {
                    return false;
                }
            } catch (UnsupportedFlavorException ufe) {
                return false;
            } catch (IOException ioe) {
                return false;
            }
        }
    });
    JScrollPane scroller = new JScrollPane(docTable);
    scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroller.getViewport().setBackground(docTable.getBackground());
    add(scroller, BorderLayout.CENTER);
    toolbar = new JToolBar();
    toolbar.setFloatable(false);
    toolbar.add(newDocumentAction = new NewDocumentAction());
    toolbar.add(removeDocumentsAction = new RemoveDocumentsAction());
    toolbar.addSeparator();
    toolbar.add(moveUpAction = new MoveUpAction());
    toolbar.add(moveDownAction = new MoveDownAction());
    toolbar.addSeparator();
    toolbar.add(openDocumentsAction = new OpenDocumentsAction());
    removeDocumentsAction.setEnabled(false);
    moveUpAction.setEnabled(false);
    moveDownAction.setEnabled(false);
    openDocumentsAction.setEnabled(false);
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.add(toolbar, BorderLayout.NORTH);
    messageLabel = new JLabel();
    changeMessage();
    topPanel.add(messageLabel, BorderLayout.SOUTH);
    add(topPanel, BorderLayout.NORTH);
}
Also used : XJTable(gate.swing.XJTable) StringSelection(java.awt.datatransfer.StringSelection) DataFlavor(java.awt.datatransfer.DataFlavor) BorderLayout(java.awt.BorderLayout) GateException(gate.util.GateException) Transferable(java.awt.datatransfer.Transferable) CreoleResource(gate.creole.metadata.CreoleResource) AbstractVisualResource(gate.creole.AbstractVisualResource) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException)

Example 9 with GateException

use of gate.util.GateException in project gate-core by GateNLP.

the class TestConfig method readConfig.

// tearDown
/**
 * Helper method that processes a config file.
 */
private void readConfig(URL configUrl) throws Exception {
    ConfigDataProcessor configProcessor = new ConfigDataProcessor();
    // open a stream to the builtin config data file (tests version)
    InputStream configStream = null;
    try {
        configStream = configUrl.openStream();
    } catch (IOException e) {
        throw new GateException("Couldn't open config data test file: " + configUrl + " " + e);
    }
    if (DEBUG)
        Out.prln("Parsing config file ... " + configStream + "from URL" + configUrl);
    configProcessor.parseConfigFile(configStream, configUrl);
}
Also used : InputStream(java.io.InputStream) GateException(gate.util.GateException) IOException(java.io.IOException)

Example 10 with GateException

use of gate.util.GateException 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);
        }
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) MalformedURLException(java.net.MalformedURLException) GateException(gate.util.GateException) URL(java.net.URL) Plugin(gate.creole.Plugin)

Aggregations

GateException (gate.util.GateException)23 IOException (java.io.IOException)11 URL (java.net.URL)10 GateRuntimeException (gate.util.GateRuntimeException)8 MalformedURLException (java.net.MalformedURLException)8 Resource (gate.Resource)5 JDOMException (org.jdom.JDOMException)5 Plugin (gate.creole.Plugin)3 InputStream (java.io.InputStream)3 LanguageResource (gate.LanguageResource)2 ProcessingResource (gate.ProcessingResource)2 VisualResource (gate.VisualResource)2 ResourceInstantiationException (gate.creole.ResourceInstantiationException)2 CreoleResource (gate.creole.metadata.CreoleResource)2 GateClassLoader (gate.util.GateClassLoader)2 BeanInfo (java.beans.BeanInfo)2 IntrospectionException (java.beans.IntrospectionException)2 PropertyDescriptor (java.beans.PropertyDescriptor)2 File (java.io.File)2 AnnotatedElement (java.lang.reflect.AnnotatedElement)2