Search in sources :

Example 46 with FeatureMap

use of gate.FeatureMap in project gate-core by GateNLP.

the class NameBearerHandle method buildViews.

protected void buildViews() {
    viewsBuilt = true;
    fireStatusChanged("Building views...");
    // build the large views
    List<String> largeViewNames = Gate.getCreoleRegister().getLargeVRsForResource(target.getClass().getName());
    if (largeViewNames != null && !largeViewNames.isEmpty()) {
        largeView = new JTabbedPane(JTabbedPane.BOTTOM);
        Iterator<String> classNameIter = largeViewNames.iterator();
        while (classNameIter.hasNext()) {
            try {
                String className = classNameIter.next();
                ResourceData rData = Gate.getCreoleRegister().get(className);
                FeatureMap params = Factory.newFeatureMap();
                FeatureMap features = Factory.newFeatureMap();
                Gate.setHiddenAttribute(features, true);
                VisualResource view = (VisualResource) Factory.createResource(className, params, features);
                try {
                    view.setTarget(target);
                } catch (IllegalArgumentException iae) {
                    // the view cannot display this particular target
                    Factory.deleteResource(view);
                    view = null;
                }
                if (view != null) {
                    view.setHandle(this);
                    ((JTabbedPane) largeView).add((Component) view, rData.getName());
                    // publishers
                    if (view instanceof ActionsPublisher)
                        actionPublishers.add((ActionsPublisher) view);
                }
            } catch (ResourceInstantiationException rie) {
                rie.printStackTrace(Err.getPrintWriter());
            }
        }
        // select the first view by default
        ((JTabbedPane) largeView).setSelectedIndex(0);
    }
    // build the small views
    List<String> smallViewNames = Gate.getCreoleRegister().getSmallVRsForResource(target.getClass().getName());
    if (smallViewNames != null && !smallViewNames.isEmpty()) {
        smallView = new JTabbedPane(JTabbedPane.BOTTOM);
        Iterator<String> classNameIter = smallViewNames.iterator();
        while (classNameIter.hasNext()) {
            try {
                String className = classNameIter.next();
                ResourceData rData = Gate.getCreoleRegister().get(className);
                FeatureMap params = Factory.newFeatureMap();
                FeatureMap features = Factory.newFeatureMap();
                Gate.setHiddenAttribute(features, true);
                VisualResource view = (VisualResource) Factory.createResource(className, params, features);
                try {
                    view.setTarget(target);
                } catch (IllegalArgumentException iae) {
                    // the view cannot display this particular target
                    Factory.deleteResource(view);
                    view = null;
                }
                if (view != null) {
                    view.setHandle(this);
                    ((JTabbedPane) smallView).add((Component) view, rData.getName());
                    if (view instanceof ActionsPublisher)
                        actionPublishers.add((ActionsPublisher) view);
                }
            } catch (ResourceInstantiationException rie) {
                rie.printStackTrace(Err.getPrintWriter());
            }
        }
        ((JTabbedPane) smallView).setSelectedIndex(0);
    }
    fireStatusChanged("Views built!");
    // Add the CTRL +F4 key & action combination to the resource
    JComponent largeView = this.getLargeView();
    if (largeView != null) {
        largeView.getActionMap().put("Close resource", new CloseAction());
        if (target instanceof Controller) {
            largeView.getActionMap().put("Close recursively", new CloseRecursivelyAction());
        }
    /*if(target instanceof gate.TextualDocument) {
        largeView.getActionMap().put("Save As XML", new SaveAsXmlAction());
      }// End if*/
    }
// End if
}
Also used : ResourceData(gate.creole.ResourceData) VisualResource(gate.VisualResource) JTabbedPane(javax.swing.JTabbedPane) JComponent(javax.swing.JComponent) SerialAnalyserController(gate.creole.SerialAnalyserController) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) CorpusController(gate.CorpusController) ConditionalController(gate.creole.ConditionalController) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap)

Example 47 with FeatureMap

use of gate.FeatureMap in project gate-core by GateNLP.

the class NewResourceDialog method show.

public synchronized void show(ResourceData rData) {
    if (rData != null) {
        this.resourceData = rData;
        String name = "";
        try {
            // Only try to generate a name for a PR - other types should be named after what they contain, really!
            if (ProcessingResource.class.isAssignableFrom(rData.getResourceClass())) {
                name = rData.getName() + " " + Gate.genSym();
            }
        } catch (ClassNotFoundException e) {
            Err.getPrintWriter().println("Couldn't load input resource class when showing dialogue.");
        }
        nameField.setText(name);
        parametersEditor.init(null, rData, rData.getParameterList().getInitimeParameters());
        pack();
        setLocationRelativeTo(getOwner());
    } else {
    // dialog already populated
    }
    // default case when the dialog just gets closed
    userCanceled = true;
    // show the dialog
    setVisible(true);
    if (userCanceled) {
        // release resources
        dispose();
        return;
    } else {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // create the new resource
                FeatureMap params = parametersEditor.getParameterValues();
                gate.event.StatusListener sListener = (gate.event.StatusListener) Gate.getListeners().get("gate.event.StatusListener");
                if (sListener != null)
                    sListener.statusChanged("Loading " + nameField.getText() + "...");
                gate.event.ProgressListener pListener = (gate.event.ProgressListener) Gate.getListeners().get("gate.event.ProgressListener");
                if (pListener != null) {
                    pListener.progressChanged(0);
                }
                boolean success = true;
                try {
                    long startTime = System.currentTimeMillis();
                    FeatureMap features = Factory.newFeatureMap();
                    String name = nameField.getText();
                    if (name == null || name.length() == 0)
                        name = null;
                    Factory.createResource(resourceData.getClassName(), params, features, name);
                    long endTime = System.currentTimeMillis();
                    if (sListener != null)
                        sListener.statusChanged(nameField.getText() + " loaded in " + NumberFormat.getInstance().format((double) (endTime - startTime) / 1000) + " seconds");
                    if (pListener != null)
                        pListener.processFinished();
                } catch (ResourceInstantiationException rie) {
                    success = false;
                    JOptionPane.showMessageDialog(getOwner(), "Resource could not be created!\n" + rie.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
                    rie.printStackTrace(Err.getPrintWriter());
                    if (sListener != null)
                        sListener.statusChanged("Error loading " + nameField.getText() + "!");
                    if (pListener != null)
                        pListener.processFinished();
                } catch (Throwable thr) {
                    success = false;
                    JOptionPane.showMessageDialog(getOwner(), "Unhandled error!\n" + thr.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
                    thr.printStackTrace(Err.getPrintWriter());
                    if (sListener != null)
                        sListener.statusChanged("Error loading " + nameField.getText() + "!");
                    if (pListener != null)
                        pListener.processFinished();
                } finally {
                    if (!success) {
                        // re-show the dialog, to allow the suer to correct the entry
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                show(null);
                            }
                        });
                    } else {
                        dispose();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable, "");
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    }
}
Also used : ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap)

Example 48 with FeatureMap

use of gate.FeatureMap in project gate-core by GateNLP.

the class PRPersistence method extractDataFromSource.

/**
 * Populates this Persistence with the data that needs to be stored from the
 * original source object.
 */
@Override
public void extractDataFromSource(Object source) throws PersistenceException {
    if (!(source instanceof ProcessingResource)) {
        throw new UnsupportedOperationException(getClass().getName() + " can only be used for " + ProcessingResource.class.getName() + " objects!\n" + source.getClass().getName() + " is not a " + ProcessingResource.class.getName());
    }
    super.extractDataFromSource(source);
    Resource res = (Resource) source;
    ResourceData rData = Gate.getCreoleRegister().get(res.getClass().getName());
    if (rData == null)
        throw new PersistenceException("Could not find CREOLE data for " + res.getClass().getName());
    // now get the runtime params
    ParameterList params = rData.getParameterList();
    try {
        // get the values for the init time parameters
        runtimeParams = Factory.newFeatureMap();
        // this is a list of lists
        Iterator<List<Parameter>> parDisjIter = params.getRuntimeParameters().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) runtimeParams).put(parName, parValue);
                }
            }
        }
        runtimeParams = PersistenceManager.getPersistentRepresentation(runtimeParams);
    } catch (ResourceInstantiationException | ParameterException rie) {
        throw new PersistenceException(rie);
    }
}
Also used : ResourceData(gate.creole.ResourceData) ProcessingResource(gate.ProcessingResource) Resource(gate.Resource) ProcessingResource(gate.ProcessingResource) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap) PersistenceException(gate.persist.PersistenceException) ParameterList(gate.creole.ParameterList) Parameter(gate.creole.Parameter) ParameterList(gate.creole.ParameterList) List(java.util.List) ParameterException(gate.creole.ParameterException)

Example 49 with FeatureMap

use of gate.FeatureMap in project gate-core by GateNLP.

the class CorpusBenchmarkTool method generateCorpus.

// setStartDirectory
protected void generateCorpus(File fileDir, File outputDir) {
    // 1. check if we have input files
    if (fileDir == null)
        return;
    // 2. create the output directory or clean it up if needed
    File outDir = outputDir;
    if (outputDir == null) {
        outDir = new File(currDir, PROCESSED_DIR_NAME);
    } else {
        // get rid of the directory, coz datastore wants it clean
        if (!Files.rmdir(outDir))
            Out.prln("cannot delete old output directory: " + outDir);
    }
    outDir.mkdir();
    // create the datastore and process each document
    try {
        SerialDataStore sds = new SerialDataStore(outDir.toURI().toURL().toString());
        sds.create();
        sds.open();
        File[] files = fileDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isFile())
                continue;
            // create a document
            Out.prln("Processing and storing document: " + files[i].toURI().toURL() + "<P>");
            FeatureMap params = Factory.newFeatureMap();
            params.put(Document.DOCUMENT_URL_PARAMETER_NAME, files[i].toURI().toURL());
            params.put(Document.DOCUMENT_ENCODING_PARAMETER_NAME, documentEncoding);
            FeatureMap features = Factory.newFeatureMap();
            // Gate.setHiddenAttribute(features, true);
            // create the document
            final Document doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", params, features);
            doc.setName(files[i].getName());
            processDocument(doc);
            final LanguageResource lr = sds.adopt(doc);
            sds.sync(lr);
            javax.swing.SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    Factory.deleteResource(doc);
                    Factory.deleteResource(lr);
                }
            });
        }
        // for
        sds.close();
    } catch (java.net.MalformedURLException ex) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex.getMessage()).initCause(ex);
    } catch (PersistenceException ex1) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex1.getMessage()).initCause(ex1);
    } catch (ResourceInstantiationException ex2) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex2.getMessage()).initCause(ex2);
    }
}
Also used : LanguageResource(gate.LanguageResource) Document(gate.Document) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap) PersistenceException(gate.persist.PersistenceException) File(java.io.File) SerialDataStore(gate.persist.SerialDataStore)

Example 50 with FeatureMap

use of gate.FeatureMap in project gate-core by GateNLP.

the class CorpusBenchmarkTool method evaluateMarkedStored.

// evaluateCorpus
protected void evaluateMarkedStored(File markedDir, File storedDir, File errDir) {
    Document persDoc = null;
    Document cleanDoc = null;
    Document markedDoc = null;
    // open the datastore and process each document
    try {
        // open the data store
        DataStore sds = Factory.openDataStore("gate.persist.SerialDataStore", storedDir.toURI().toURL().toExternalForm());
        List<String> lrIDs = sds.getLrIds("gate.corpora.DocumentImpl");
        for (int i = 0; i < lrIDs.size(); i++) {
            String docID = lrIDs.get(i);
            // read the stored document
            FeatureMap features = Factory.newFeatureMap();
            features.put(DataStore.DATASTORE_FEATURE_NAME, sds);
            features.put(DataStore.LR_ID_FEATURE_NAME, docID);
            FeatureMap hparams = Factory.newFeatureMap();
            // Gate.setHiddenAttribute(hparams, true);
            persDoc = (Document) Factory.createResource("gate.corpora.DocumentImpl", features, hparams);
            if (isMoreInfoMode) {
                StringBuffer errName = new StringBuffer(persDoc.getName());
                errName.replace(persDoc.getName().lastIndexOf("."), persDoc.getName().length(), ".err");
                Out.prln("<H2>" + "<a href=\"err/" + errName.toString() + "\">" + persDoc.getName() + "</a>" + "</H2>");
            } else
                Out.prln("<H2>" + persDoc.getName() + "</H2>");
            if (!this.isMarkedDS) {
                // try finding the marked document as file
                StringBuffer docName = new StringBuffer(persDoc.getName());
                docName.replace(persDoc.getName().lastIndexOf("."), docName.length(), ".xml");
                File markedDocFile = new File(markedDir, docName.toString());
                if (!markedDocFile.exists()) {
                    Out.prln("Warning: Cannot find human-annotated document " + markedDocFile + " in " + markedDir);
                } else {
                    FeatureMap params = Factory.newFeatureMap();
                    params.put(Document.DOCUMENT_URL_PARAMETER_NAME, markedDocFile.toURI().toURL());
                    params.put(Document.DOCUMENT_ENCODING_PARAMETER_NAME, documentEncoding);
                    // create the document
                    markedDoc = (Document) Factory.createResource("gate.corpora.DocumentImpl", params, hparams);
                    markedDoc.setName(persDoc.getName());
                }
            // find marked as file
            } else {
                try {
                    // open marked from a DS
                    // open the data store
                    DataStore sds1 = Factory.openDataStore("gate.persist.SerialDataStore", markedDir.toURI().toURL().toExternalForm());
                    List<String> lrIDs1 = sds1.getLrIds("gate.corpora.DocumentImpl");
                    boolean found = false;
                    int k = 0;
                    // search for the marked doc with the same name
                    while (k < lrIDs1.size() && !found) {
                        String docID1 = lrIDs1.get(k);
                        // read the stored document
                        FeatureMap features1 = Factory.newFeatureMap();
                        features1.put(DataStore.DATASTORE_FEATURE_NAME, sds1);
                        features1.put(DataStore.LR_ID_FEATURE_NAME, docID1);
                        Document tempDoc = (Document) Factory.createResource("gate.corpora.DocumentImpl", features1, hparams);
                        // check whether this is our doc
                        if (((String) tempDoc.getFeatures().get("gate.SourceURL")).endsWith(persDoc.getName())) {
                            found = true;
                            markedDoc = tempDoc;
                        } else
                            k++;
                    }
                } catch (java.net.MalformedURLException ex) {
                    Out.prln("Error finding marked directory " + markedDir.getAbsolutePath());
                } catch (gate.persist.PersistenceException ex1) {
                    Out.prln("Error opening marked as a datastore (-marked_ds specified)");
                } catch (gate.creole.ResourceInstantiationException ex2) {
                    Out.prln("Error opening marked as a datastore (-marked_ds specified)");
                }
            }
            evaluateDocuments(persDoc, cleanDoc, markedDoc, errDir);
            if (persDoc != null) {
                final gate.Document pd = persDoc;
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        Factory.deleteResource(pd);
                    }
                });
            }
            if (markedDoc != null) {
                final gate.Document md = markedDoc;
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        Factory.deleteResource(md);
                    }
                });
            }
        }
        // for loop through saved docs
        sds.close();
    } catch (java.net.MalformedURLException ex) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex.getMessage()).initCause(ex);
    } catch (PersistenceException ex1) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex1.getMessage()).initCause(ex1);
    } catch (ResourceInstantiationException ex2) {
        throw (GateRuntimeException) new GateRuntimeException("CorpusBenchmark: " + ex2.getMessage()).initCause(ex2);
    }
}
Also used : ResourceInstantiationException(gate.creole.ResourceInstantiationException) Document(gate.Document) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap) PersistenceException(gate.persist.PersistenceException) SerialDataStore(gate.persist.SerialDataStore) DataStore(gate.DataStore) PersistenceException(gate.persist.PersistenceException) Document(gate.Document) File(java.io.File)

Aggregations

FeatureMap (gate.FeatureMap)55 Document (gate.Document)15 URL (java.net.URL)14 ResourceInstantiationException (gate.creole.ResourceInstantiationException)11 File (java.io.File)10 Resource (gate.Resource)8 GateRuntimeException (gate.util.GateRuntimeException)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 PersistenceException (gate.persist.PersistenceException)6 Annotation (gate.Annotation)5 AnnotationSet (gate.AnnotationSet)5 DataStore (gate.DataStore)5 LanguageResource (gate.LanguageResource)5 TestDocument (gate.corpora.TestDocument)4 ResourceData (gate.creole.ResourceData)4 SerialDataStore (gate.persist.SerialDataStore)4 InvalidOffsetException (gate.util.InvalidOffsetException)4 Corpus (gate.Corpus)3 ProcessingResource (gate.ProcessingResource)3