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");
}
}
}
}
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;
}
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);
}
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);
}
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);
}
}
}
Aggregations