use of gate.creole.Parameter 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.Parameter 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.Parameter in project gate-core by GateNLP.
the class TeamwareUtils method populateOutputSetNamesForController.
/**
* Populate the set of output annotation set names for a controller
* based on heuristics. In the strict case, we assume that if a PR in
* the controller has an outputASName or annotationSetName parameter
* whose value is not used as the inputASName or annotationSetName of
* a later PR then it is probably a set that will be output from the
* controller. In the non-strict case we simply take all outputASName
* and annotationSetName parameter values from the controller's PRs
* without regard for which ones may simply be feeding later PRs in
* the controller (also, the default annotation set is always included
* in non-strict mode).
*/
private static void populateOutputSetNamesForController(Set<String> setNames, Controller c, boolean strict) {
Collection<ProcessingResource> prs = c.getPRs();
try {
for (ProcessingResource pr : prs) {
ResourceData rd = Gate.getCreoleRegister().get(pr.getClass().getName());
List<List<Parameter>> runtimeParams = rd.getParameterList().getRuntimeParameters();
// PR.
if (strict) {
for (List<Parameter> disjunction : runtimeParams) {
for (Parameter param : disjunction) {
if (param.getName().equals("inputASName") || param.getName().equals("annotationSetName")) {
setNames.remove(pr.getParameterValue(param.getName()));
}
}
}
}
// parameters
for (List<Parameter> disjunction : runtimeParams) {
for (Parameter param : disjunction) {
if (param.getName().equals("outputASName") || param.getName().equals("annotationSetName")) {
setNames.add((String) pr.getParameterValue(param.getName()));
}
}
}
}
// finally, add the default set for non-strict mode
if (!strict) {
setNames.add(null);
}
} catch (Exception e) {
// ignore - this is all heuristics, after all
}
}
use of gate.creole.Parameter in project gate-core by GateNLP.
the class TeamwareUtils method populateInputSetNamesForController.
/**
* Populate the set of input annotation set names for a controller
* based on heuristics. In the strict case we assume that if a PR in
* the controller has an inputASName parameter whose value is not the
* default set, and there is no PR earlier in the pipeline which has
* the same set as its outputASName or annotationSetName parameter,
* then it is probably a set that needs to be provided externally. In
* the non-strict case we simply take all inputASName and
* annotationSetName parameter values from the controller's PRs,
* without regard for whether they may have been satisfied by an
* earlier PR in the pipeline.
*
* @param setNames
* @param c
* @param strict
*/
private static void populateInputSetNamesForController(Set<String> setNames, Controller c, boolean strict) {
Set<String> outputSetNamesSoFar = new HashSet<String>();
Collection<ProcessingResource> prs = c.getPRs();
try {
for (ProcessingResource pr : prs) {
ResourceData rd = Gate.getCreoleRegister().get(pr.getClass().getName());
List<List<Parameter>> runtimeParams = rd.getParameterList().getRuntimeParameters();
// check for inputASName and annotationSetName params
for (List<Parameter> disjunction : runtimeParams) {
for (Parameter param : disjunction) {
if (param.getName().equals("inputASName")) {
String setName = (String) pr.getParameterValue(param.getName());
if (!strict || (setName != null && !outputSetNamesSoFar.contains(setName))) {
setNames.add(setName);
}
} else if (!strict && param.getName().equals("annotationSetName")) {
setNames.add((String) pr.getParameterValue(param.getName()));
}
}
}
// check for output set names and update that set
if (strict) {
for (List<Parameter> disjunction : runtimeParams) {
for (Parameter param : disjunction) {
if (param.getName().equals("outputASName") || param.getName().equals("annotationSetName")) {
outputSetNamesSoFar.add(String.valueOf(pr.getParameterValue(param.getName())));
}
}
}
}
}
} catch (Exception e) {
// ignore - this is all heuristics, after all
}
}
use of gate.creole.Parameter in project gate-core by GateNLP.
the class SerialControllerEditor method selectPR.
/**
* Called when a PR has been selected in the member PRs table;
* @param index row index in {@link #memberPRsTable} (or -1 if no PR is
* currently selected)
*/
protected void selectPR(int index) {
// stop current editing of parameters
if (parametersEditor.getResource() != null) {
try {
parametersEditor.setParameters();
} catch (ResourceInstantiationException rie) {
JOptionPane.showMessageDialog(SerialControllerEditor.this, "Failed to set parameters for \"" + parametersEditor.getResource().getName() + "\"!\n", "GATE", JOptionPane.ERROR_MESSAGE);
rie.printStackTrace(Err.getPrintWriter());
}
if (conditionalMode) {
if (selectedPRRunStrategy != null && selectedPRRunStrategy instanceof AnalyserRunningStrategy) {
AnalyserRunningStrategy strategy = (AnalyserRunningStrategy) selectedPRRunStrategy;
strategy.setFeatureName(featureNameTextField.getText());
strategy.setFeatureValue(featureValueTextField.getText());
}
selectedPRRunStrategy = null;
}
}
// find the new PR
ProcessingResource pr = null;
if (index >= 0 && index < controller.getPRs().size()) {
pr = controller.getPRs().get(index);
}
if (pr != null) {
// update the GUI for the new PR
ResourceData rData = Gate.getCreoleRegister().get(pr.getClass().getName());
// update the border name
parametersBorder.setTitle(" Runtime Parameters for the \"" + pr.getName() + "\" " + rData.getName() + ": ");
// update the params editor
// this is a list of lists
List<List<Parameter>> parameters = rData.getParameterList().getRuntimeParameters();
if (corpusControllerMode) {
// remove corpus and document
// create a new list so we don't change the one from CreoleReg.
List<List<Parameter>> oldParameters = parameters;
parameters = new ArrayList<List<Parameter>>();
for (List<Parameter> aDisjunction : oldParameters) {
List<Parameter> newDisjunction = new ArrayList<Parameter>();
for (Parameter parameter : aDisjunction) {
if (!parameter.getName().equals("corpus") && !parameter.getName().equals("document")) {
newDisjunction.add(parameter);
}
}
if (!newDisjunction.isEmpty())
parameters.add(newDisjunction);
}
}
parametersEditor.init(pr, parameters);
if (conditionalMode) {
strategyBorder.setTitle(" Run \"" + pr.getName() + "\"? ");
// update the state of the run strategy buttons
yes_RunRBtn.setEnabled(true);
no_RunRBtn.setEnabled(true);
conditional_RunRBtn.setEnabled(true);
// editing the strategy panel causes the edits to be sent to the current
// strategy object, which can lead to a race condition.
// So we used a cached value instead.
selectedPRRunStrategy = null;
RunningStrategy newStrategy = ((ConditionalController) controller).getRunningStrategies().get(index);
if (newStrategy instanceof AnalyserRunningStrategy) {
featureNameTextField.setEnabled(true);
featureValueTextField.setEnabled(true);
conditional_RunRBtn.setEnabled(true);
featureNameTextField.setText(((AnalyserRunningStrategy) newStrategy).getFeatureName());
featureValueTextField.setText(((AnalyserRunningStrategy) newStrategy).getFeatureValue());
} else {
featureNameTextField.setEnabled(false);
featureValueTextField.setEnabled(false);
conditional_RunRBtn.setEnabled(false);
}
switch(newStrategy.getRunMode()) {
case RunningStrategy.RUN_ALWAYS:
{
yes_RunRBtn.setSelected(true);
break;
}
case RunningStrategy.RUN_NEVER:
{
no_RunRBtn.setSelected(true);
break;
}
case RunningStrategy.RUN_CONDITIONAL:
{
conditional_RunRBtn.setSelected(true);
break;
}
}
// switch
// now that the UI is updated, we can safely link to the new strategy
selectedPRRunStrategy = newStrategy;
}
} else {
// selected PR == null -> clean all mentions of the old PR from the GUI
parametersBorder.setTitle(" No processing resource selected... ");
parametersEditor.init(null, null);
if (conditionalMode) {
strategyBorder.setTitle(" No processing resource selected... ");
yes_RunRBtn.setEnabled(false);
no_RunRBtn.setEnabled(false);
conditional_RunRBtn.setEnabled(false);
featureNameTextField.setText("");
featureNameTextField.setEnabled(false);
featureValueTextField.setText("");
featureValueTextField.setEnabled(false);
}
}
// this seems to be needed to show the changes
SerialControllerEditor.this.repaint(100);
}
Aggregations