use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.
the class DocumentImpl method init.
/**
* Initialise this resource, and return it.
*/
@Override
public Resource init() throws ResourceInstantiationException {
// set up the source URL and create the content
if (sourceUrl == null) {
if (stringContent == null) {
throw new ResourceInstantiationException("The sourceURL and document's content were null.");
}
content = new DocumentContentImpl(stringContent);
getFeatures().put("gate.SourceURL", "created from String");
} else {
try {
content = new DocumentContentImpl(sourceUrl, getEncoding(), sourceUrlStartOffset, sourceUrlEndOffset);
getFeatures().put("gate.SourceURL", sourceUrl.toExternalForm());
} catch (IOException e) {
throw new ResourceInstantiationException("DocumentImpl.init: " + e);
}
}
if (preserveOriginalContent.booleanValue() && content != null) {
String originalContent = ((DocumentContentImpl) content).getOriginalContent();
getFeatures().put(GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME, originalContent);
}
// set up a DocumentFormat if markup unpacking required
if (getMarkupAware().booleanValue()) {
DocumentFormat docFormat = null;
// if a specific MIME type has been given, use it
if (this.mimeType != null && this.mimeType.length() > 0) {
MimeType theType = DocumentFormat.getMimeTypeForString(mimeType);
if (theType == null) {
throw new ResourceInstantiationException("MIME type \"" + this.mimeType + " has no registered DocumentFormat");
}
docFormat = DocumentFormat.getDocumentFormat(this, theType);
} else {
docFormat = DocumentFormat.getDocumentFormat(this, sourceUrl);
}
try {
if (docFormat != null) {
StatusListener sListener = (StatusListener) gate.Gate.getListeners().get("gate.event.StatusListener");
if (sListener != null)
docFormat.addStatusListener(sListener);
// set the flag if true and if the document format support collecting
docFormat.setShouldCollectRepositioning(collectRepositioningInfo);
if (docFormat.getShouldCollectRepositioning().booleanValue()) {
// unpack with collectiong of repositioning information
RepositioningInfo info = new RepositioningInfo();
String origContent = (String) getFeatures().get(GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME);
RepositioningInfo ampCodingInfo = new RepositioningInfo();
if (origContent != null) {
boolean shouldCorrectCR = docFormat instanceof XmlDocumentFormat;
collectInformationForAmpCodding(origContent, ampCodingInfo, shouldCorrectCR);
if (docFormat.getMimeType().equals(new MimeType("text", "html"))) {
collectInformationForWS(origContent, ampCodingInfo);
}
// if
}
// if
docFormat.unpackMarkup(this, info, ampCodingInfo);
if (origContent != null && docFormat instanceof XmlDocumentFormat) {
// CRLF correction of RepositioningInfo
correctRepositioningForCRLFInXML(origContent, info);
}
// if
getFeatures().put(GateConstants.DOCUMENT_REPOSITIONING_INFO_FEATURE_NAME, info);
} else {
// normal old fashioned unpack
docFormat.unpackMarkup(this);
}
docFormat.removeStatusListener(sListener);
}
// if format != null
} catch (DocumentFormatException e) {
throw new ResourceInstantiationException("Couldn't unpack markup in document " + (sourceUrl != null ? sourceUrl.toExternalForm() : "") + "!", e);
}
}
// }
return this;
}
use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.
the class CreoleProxy method createResource.
/**
* Create an instance of a resource using default parameter values.
*
* @see #createResource(String,FeatureMap)
*/
public static Resource createResource(String resourceClassName) 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 parameter list and default values
ParameterList paramList = resData.getParameterList();
FeatureMap parameterValues = null;
try {
parameterValues = paramList.getInitimeDefaults();
} catch (ParameterException e) {
throw new ResourceInstantiationException("Couldn't get default parameters for " + resourceClassName + ": " + e);
}
return createResource(resourceClassName, parameterValues);
}
use of gate.creole.ResourceInstantiationException 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;
}
use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.
the class DocumentEditor method initViews.
protected void initViews() {
viewsInited = true;
// start building the UI
setLayout(new BorderLayout());
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, progressBar.getPreferredSize().height));
add(progressBar, BorderLayout.CENTER);
progressBar.setString("Building views");
progressBar.setValue(10);
// create the skeleton UI
topSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, null, null);
topSplit.setResizeWeight(0.3);
topSplit.setContinuousLayout(true);
topSplit.setOneTouchExpandable(true);
bottomSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplit, null);
bottomSplit.setResizeWeight(0.7);
bottomSplit.setContinuousLayout(true);
bottomSplit.setOneTouchExpandable(true);
horizontalSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, bottomSplit, null);
horizontalSplit.setResizeWeight(0.7);
horizontalSplit.setContinuousLayout(true);
horizontalSplit.setOneTouchExpandable(true);
// create the bars
topBar = new JToolBar(JToolBar.HORIZONTAL);
topBar.setFloatable(false);
add(topBar, BorderLayout.NORTH);
progressBar.setValue(40);
centralViews = new ArrayList<DocumentView>();
verticalViews = new ArrayList<DocumentView>();
horizontalViews = new ArrayList<DocumentView>();
// parse all Creole resources and look for document views
Set<String> vrSet = Gate.getCreoleRegister().getVrTypes();
List<ResourceData> viewTypes = new ArrayList<ResourceData>();
for (String vr : vrSet) {
ResourceData rData = Gate.getCreoleRegister().get(vr);
try {
if (DocumentView.class.isAssignableFrom(rData.getResourceClass())) {
viewTypes.add(rData);
}
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
// sort view types by label
Collections.sort(viewTypes, new Comparator<ResourceData>() {
@Override
public int compare(ResourceData rd1, ResourceData rd2) {
return rd1.getName().compareTo(rd2.getName());
}
});
for (ResourceData viewType : viewTypes) {
try {
// create the resource
DocumentView aView = (DocumentView) Factory.createResource(viewType.getClassName());
aView.setTarget(document);
aView.setOwner(this);
// add the view
addView(aView, viewType.getName());
} catch (ResourceInstantiationException rie) {
rie.printStackTrace();
}
}
// select the main central view only
if (centralViews.size() > 0)
setCentralView(0);
// populate the main VIEW
remove(progressBar);
add(horizontalSplit, BorderLayout.CENTER);
searchAction = new SearchAction();
JButton searchButton = new JButton(searchAction);
searchButton.setMargin(new Insets(0, 0, 0, 0));
topBar.add(Box.createHorizontalStrut(5));
topBar.add(searchButton);
// add a key binding for the search function
getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), "Search in text");
getActionMap().put("Search in text", searchAction);
// create menu that contains several options for the document editor
final OptionsMap config = Gate.getUserConfig();
final JPopupMenu optionsMenu = new JPopupMenu("Options menu");
final JMenuItem saveCurrentLayoutMenuItem = new JMenuItem(new AbstractAction("Save Current Layout") {
@Override
public void actionPerformed(ActionEvent evt) {
saveSettings();
}
});
optionsMenu.add(saveCurrentLayoutMenuItem);
final JCheckBoxMenuItem restoreLayoutAutomaticallyMenuItem = new JCheckBoxMenuItem("Restore Layout Automatically");
restoreLayoutAutomaticallyMenuItem.setSelected(Gate.getUserConfig().getBoolean(DocumentEditor.class.getName() + ".restoreLayoutAutomatically"));
restoreLayoutAutomaticallyMenuItem.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// whenever the user checks/unchecks, update the config
config.put(DocumentEditor.class.getName() + ".restoreLayoutAutomatically", restoreLayoutAutomaticallyMenuItem.isSelected());
}
});
optionsMenu.add(restoreLayoutAutomaticallyMenuItem);
final JCheckBoxMenuItem readOnly = new JCheckBoxMenuItem("Read-only");
readOnly.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
config.put(GateConstants.DOCEDIT_READ_ONLY, readOnly.isSelected());
setEditable(!readOnly.isSelected());
}
});
readOnly.setSelected(config.getBoolean(GateConstants.DOCEDIT_READ_ONLY));
optionsMenu.addSeparator();
optionsMenu.add(readOnly);
// right to left orientation
final JCheckBoxMenuItem rightToLeftOrientation = new JCheckBoxMenuItem("Right To Left Orientation");
rightToLeftOrientation.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
config.put(GateConstants.DOC_RTOL_ORIENTATION, rightToLeftOrientation.isSelected());
setRightToLeftOrientation(rightToLeftOrientation.isSelected());
}
});
optionsMenu.addSeparator();
optionsMenu.add(rightToLeftOrientation);
ButtonGroup buttonGroup = new ButtonGroup();
final JRadioButtonMenuItem insertAppend = new JRadioButtonMenuItem("Insert Append");
buttonGroup.add(insertAppend);
insertAppend.setSelected(config.getBoolean(GateConstants.DOCEDIT_INSERT_APPEND));
insertAppend.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
config.put(GateConstants.DOCEDIT_INSERT_APPEND, insertAppend.isSelected());
}
});
optionsMenu.addSeparator();
optionsMenu.add(insertAppend);
final JRadioButtonMenuItem insertPrepend = new JRadioButtonMenuItem("Insert Prepend");
buttonGroup.add(insertPrepend);
insertPrepend.setSelected(config.getBoolean(GateConstants.DOCEDIT_INSERT_PREPEND));
insertPrepend.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
config.put(GateConstants.DOCEDIT_INSERT_PREPEND, insertPrepend.isSelected());
}
});
optionsMenu.add(insertPrepend);
// if none set then set the default one
if (!(insertAppend.isSelected() || insertPrepend.isSelected())) {
insertAppend.setSelected(true);
}
JMenuButton menuButton = new JMenuButton(optionsMenu);
menuButton.setIcon(MainFrame.getIcon("expanded"));
menuButton.setToolTipText("Options for the document editor");
// icon is not centred
menuButton.setMargin(new Insets(0, 0, 0, 1));
topBar.add(Box.createHorizontalGlue());
topBar.add(menuButton);
// when the editor is shown restore views if layout saving is enable
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (Gate.getUserConfig().getBoolean(DocumentEditor.class.getName() + ".restoreLayoutAutomatically")) {
restoreSettings();
}
}
});
validate();
}
use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.
the class TestRepositioningInfo method setUp.
/**
* This method sets up the parameters for the files to be tested
*/
@Override
protected void setUp() throws Exception {
if (!Gate.isInitialised()) {
Gate.runInSandbox(true);
Gate.init();
}
testFile = TestDocument.getTestServerName() + "tests/test-inline.xml";
// creating documents
try {
FeatureMap params = Factory.newFeatureMap();
params.put("sourceUrl", new URL(testFile));
params.put("preserveOriginalContent", new Boolean("true"));
params.put("collectRepositioningInfo", new Boolean("true"));
doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", params);
} catch (MalformedURLException murle) {
fail("Document cannot be created ");
} catch (ResourceInstantiationException rie) {
fail("Resources cannot be created for the test document");
}
}
Aggregations