use of gate.creole.ResourceData in project gate-core by GateNLP.
the class SerialDatastoreViewer method initGuiComponents.
protected void initGuiComponents() {
treeRoot = new DefaultMutableTreeNode(datastore.getName(), true);
treeModel = new DefaultTreeModel(treeRoot, true);
mainTree = new JTree();
mainTree.setModel(treeModel);
mainTree.setExpandsSelectedPaths(true);
mainTree.expandPath(new TreePath(treeRoot));
mainTree.addTreeWillExpandListener(new TreeWillExpandListener() {
@Override
public void treeWillCollapse(TreeExpansionEvent e) {
// ignore these events as we don't care about collapsing trees, timmmmmmmmmber!
}
@Override
public void treeWillExpand(TreeExpansionEvent e) {
TreePath path = e.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node.getChildCount() == 0 && node.getUserObject() instanceof DSType) {
DSType dsType = (DSType) node.getUserObject();
if (dsType.expanded)
return;
node.removeAllChildren();
try {
Iterator<String> lrIDsIter = datastore.getLrIds(dsType.type).iterator();
while (lrIDsIter.hasNext()) {
String id = lrIDsIter.next();
DSEntry entry = new DSEntry(datastore.getLrName(id), id, dsType.type);
DefaultMutableTreeNode lrNode = new DefaultMutableTreeNode(entry, false);
treeModel.insertNodeInto(lrNode, node, node.getChildCount());
node.add(lrNode);
}
dsType.expanded = true;
} catch (PersistenceException pe) {
throw new GateRuntimeException(pe.toString());
}
}
}
});
try {
Iterator<String> lrTypesIter = datastore.getLrTypes().iterator();
CreoleRegister cReg = Gate.getCreoleRegister();
while (lrTypesIter.hasNext()) {
String type = lrTypesIter.next();
ResourceData rData = cReg.get(type);
DSType dsType = new DSType(rData.getName(), type);
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dsType);
treeModel.insertNodeInto(node, treeRoot, treeRoot.getChildCount());
}
} catch (PersistenceException pe) {
throw new GateRuntimeException(pe.toString());
}
DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel();
selectionModel.setSelectionMode(DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
mainTree.setSelectionModel(selectionModel);
getViewport().setView(mainTree);
popup = new JPopupMenu();
deleteAction = new DeleteAction();
loadAction = new LoadAction();
popup.add(deleteAction);
popup.add(loadAction);
}
use of gate.creole.ResourceData in project gate-core by GateNLP.
the class DocumentExportMenu method addExporter.
private void addExporter(final DocumentExporter de) {
if (itemByResource.containsKey(de))
return;
final ResourceData rd = Gate.getCreoleRegister().get(de.getClass().getCanonicalName());
if (DocumentExportMenu.this.getItemCount() == 1) {
DocumentExportMenu.this.addSeparator();
}
JMenuItem item = DocumentExportMenu.this.add(new AbstractAction(de.getFileType() + " (." + de.getDefaultExtension() + ")", MainFrame.getIcon(rd.getIcon(), rd.getResourceClassLoader())) {
@Override
public void actionPerformed(ActionEvent ae) {
List<List<Parameter>> params = rd.getParameterList().getRuntimeParameters();
final FeatureMap options = Factory.newFeatureMap();
final File selectedFile = getSelectedFile(params, de, options);
if (selectedFile == null)
return;
Runnable runnable = new Runnable() {
public void run() {
if (handle.getTarget() instanceof Document) {
long start = System.currentTimeMillis();
listener.statusChanged("Saving as " + de.getFileType() + " to " + selectedFile.toString() + "...");
try {
de.export((Document) handle.getTarget(), selectedFile, options);
} catch (IOException e) {
e.printStackTrace();
}
long time = System.currentTimeMillis() - start;
listener.statusChanged("Finished saving as " + de.getFileType() + " into " + " the file: " + selectedFile.toString() + " in " + ((double) time) / 1000 + "s");
} else {
// corpus
if (de instanceof CorpusExporter) {
long start = System.currentTimeMillis();
listener.statusChanged("Saving as " + de.getFileType() + " to " + selectedFile.toString() + "...");
try {
((CorpusExporter) de).export((Corpus) handle.getTarget(), selectedFile, options);
} catch (IOException e) {
e.printStackTrace();
}
long time = System.currentTimeMillis() - start;
listener.statusChanged("Finished saving as " + de.getFileType() + " into " + " the file: " + selectedFile.toString() + " in " + ((double) time) / 1000 + "s");
} else {
// not a CorpusExporter
try {
File dir = selectedFile;
// create the top directory if needed
if (!dir.exists()) {
if (!dir.mkdirs()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Could not create top directory!", "GATE", JOptionPane.ERROR_MESSAGE);
return;
}
}
MainFrame.lockGUI("Saving...");
Corpus corpus = (Corpus) handle.getTarget();
// iterate through all the docs and save
// each of
// them
Iterator<Document> docIter = corpus.iterator();
boolean overwriteAll = false;
int docCnt = corpus.size();
int currentDocIndex = 0;
Set<String> usedFileNames = new HashSet<String>();
while (docIter.hasNext()) {
boolean docWasLoaded = corpus.isDocumentLoaded(currentDocIndex);
Document currentDoc = docIter.next();
URL sourceURL = currentDoc.getSourceUrl();
String fileName = null;
if (sourceURL != null) {
fileName = sourceURL.getPath();
fileName = Files.getLastPathComponent(fileName);
}
if (fileName == null || fileName.length() == 0) {
fileName = currentDoc.getName();
}
// makes sure that the filename does not
// contain
// any
// forbidden character
fileName = fileName.replaceAll("[\\/:\\*\\?\"<>|]", "_");
if (fileName.toLowerCase().endsWith("." + de.getDefaultExtension())) {
fileName = fileName.substring(0, fileName.length() - de.getDefaultExtension().length() - 1);
}
if (usedFileNames.contains(fileName)) {
// name clash -> add unique ID
String fileNameBase = fileName;
int uniqId = 0;
fileName = fileNameBase + "-" + uniqId++;
while (usedFileNames.contains(fileName)) {
fileName = fileNameBase + "-" + uniqId++;
}
}
usedFileNames.add(fileName);
if (!fileName.toLowerCase().endsWith("." + de.getDefaultExtension()))
fileName += "." + de.getDefaultExtension();
File docFile = null;
boolean nameOK = false;
do {
docFile = new File(dir, fileName);
if (docFile.exists() && !overwriteAll) {
// ask the user if we can overwrite
// the file
Object[] opts = new Object[] { "Yes", "All", "No", "Cancel" };
MainFrame.unlockGUI();
int answer = JOptionPane.showOptionDialog(MainFrame.getInstance(), "File " + docFile.getName() + " already exists!\n" + "Overwrite?", "GATE", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, opts, opts[2]);
MainFrame.lockGUI("Saving...");
switch(answer) {
case 0:
{
nameOK = true;
break;
}
case 1:
{
nameOK = true;
overwriteAll = true;
break;
}
case 2:
{
// user said NO, allow them to
// provide
// an
// alternative name;
MainFrame.unlockGUI();
fileName = (String) JOptionPane.showInputDialog(MainFrame.getInstance(), "Please provide an alternative file name", "GATE", JOptionPane.QUESTION_MESSAGE, null, null, fileName);
if (fileName == null) {
handle.processFinished();
return;
}
MainFrame.lockGUI("Saving");
break;
}
case 3:
{
// user gave up; return
handle.processFinished();
return;
}
}
} else {
nameOK = true;
}
} while (!nameOK);
// save the file
try {
// do the actual exporting
de.export(currentDoc, docFile, options);
} catch (Exception ioe) {
MainFrame.unlockGUI();
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Could not create write file:" + ioe.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
ioe.printStackTrace(Err.getPrintWriter());
return;
}
listener.statusChanged(currentDoc.getName() + " saved");
// loaded
if (!docWasLoaded) {
corpus.unloadDocument(currentDoc);
Factory.deleteResource(currentDoc);
}
handle.progressChanged(100 * currentDocIndex++ / docCnt);
}
// while(docIter.hasNext())
listener.statusChanged("Corpus Saved");
handle.processFinished();
} finally {
MainFrame.unlockGUI();
}
}
}
}
};
Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable, "Document Exporter Thread");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
});
itemByResource.put(de, item);
}
use of gate.creole.ResourceData in project gate-core by GateNLP.
the class PRViewer method setTarget.
@Override
public void setTarget(Object target) {
if (target == null)
return;
if (!(target instanceof Resource)) {
throw new GateRuntimeException(this.getClass().getName() + " can only be used to display " + Resource.class.getName() + "\n" + target.getClass().getName() + " is not a " + Resource.class.getName() + "!");
}
Resource pr = (Resource) target;
ResourceData rData = Gate.getCreoleRegister().get(pr.getClass().getName());
if (rData != null) {
editor.init(pr, rData.getParameterList().getInitimeParameters());
} else {
editor.init(pr, null);
}
editor.removeCreoleListenerLink();
}
use of gate.creole.ResourceData in project gate-core by GateNLP.
the class ResourcePersistence method extractDataFromSource.
@Override
public void extractDataFromSource(Object source) throws PersistenceException {
if (!(source instanceof Resource)) {
throw new UnsupportedOperationException(getClass().getName() + " can only be used for " + Resource.class.getName() + " objects!\n" + source.getClass().getName() + " is not a " + Resource.class.getName());
}
Resource res = (Resource) source;
resourceType = res.getClass().getName();
resourceName = ((NameBearer) res).getName();
ResourceData rData = Gate.getCreoleRegister().get(resourceType);
if (rData == null)
throw new PersistenceException("Could not find CREOLE data for " + resourceType);
ParameterList params = rData.getParameterList();
try {
// get the values for the init time parameters
initParams = Factory.newFeatureMap();
// this is a list of lists
Iterator<List<Parameter>> parDisjIter = params.getInitimeParameters().iterator();
while (parDisjIter.hasNext()) {
Iterator<Parameter> parIter = parDisjIter.next().iterator();
while (parIter.hasNext()) {
Parameter parameter = parIter.next();
String parName = parameter.getName();
Object parValue = res.getParameterValue(parName);
if (storeParameterValue(parValue, parameter.getDefaultValue())) {
((FeatureMap) initParams).put(parName, parValue);
}
}
}
initParams = PersistenceManager.getPersistentRepresentation(initParams);
// get the features
if (res.getFeatures() != null) {
features = Factory.newFeatureMap();
((FeatureMap) features).putAll(res.getFeatures());
features = PersistenceManager.getPersistentRepresentation(features);
}
} catch (ResourceInstantiationException | ParameterException rie) {
throw new PersistenceException(rie);
}
}
use of gate.creole.ResourceData in project gate-core by GateNLP.
the class CreoleProxy method defaultDuplicate.
/**
* Implementation of the default duplication algorithm described in
* the comment for {@link #duplicate(Resource)}. This method is public
* for the benefit of resources that implement
* {@link CustomDuplication} but only need to do some post-processing
* after the default duplication algorithm; they can call this method
* to obtain an initial duplicate and then post-process it before
* returning. If they need to duplicate child resources they should
* call {@link #duplicate(Resource, DuplicationContext)} in the normal
* way. Calls to this method made outside the context of a
* {@link CustomDuplication#duplicate CustomDuplication.duplicate}
* call will fail with a runtime exception.
*
* @param res the resource to duplicate
* @param ctx the current context
* @return a duplicate of the given resource, constructed using the
* default algorithm. In particular, if <code>res</code>
* implements {@link CustomDuplication} its own duplicate
* method will <i>not</i> be called.
* @throws ResourceInstantiationException if an error occurs while
* duplicating the given resource.
*/
public static Resource defaultDuplicate(Resource res, DuplicationContext ctx) throws ResourceInstantiationException {
checkDuplicationContext(ctx);
String className = res.getClass().getName();
ResourceData resData = Gate.getCreoleRegister().get(className);
if (resData == null) {
throw new ResourceInstantiationException("Could not find CREOLE data for " + className);
}
String resName = res.getName();
FeatureMap newResFeatures = duplicate(res.getFeatures(), ctx);
// init parameters
FeatureMap initParams = AbstractResource.getInitParameterValues(res);
// remove parameters that are also sharable properties
for (String propName : resData.getSharableProperties()) {
initParams.remove(propName);
}
// duplicate any Resources in the params map (excluding sharable
// ones)
initParams = duplicate(initParams, ctx);
// may be registered parameters but others may not be.
for (String propName : resData.getSharableProperties()) {
initParams.put(propName, res.getParameterValue(propName));
}
// create the new resource
Resource newResource = createResource(className, initParams, newResFeatures, resName);
if (newResource instanceof ProcessingResource) {
// runtime params
FeatureMap runtimeParams = AbstractProcessingResource.getRuntimeParameterValues(res);
// remove parameters that are also sharable properties
for (String propName : resData.getSharableProperties()) {
runtimeParams.remove(propName);
}
// duplicate any Resources in the params map (excluding sharable
// ones)
runtimeParams = duplicate(runtimeParams, ctx);
// do not need to add sharable properties here, they have already
// been injected by createResource
newResource.setParameterValues(runtimeParams);
}
return newResource;
}
Aggregations