Search in sources :

Example 1 with FeatureMap

use of gate.FeatureMap 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;
}
Also used : FeatureMap(gate.FeatureMap) GateException(gate.util.GateException) Resource(gate.Resource) ResourceInstantiationException(gate.creole.ResourceInstantiationException) GateException(gate.util.GateException) ResourceInstantiationException(gate.creole.ResourceInstantiationException)

Example 2 with FeatureMap

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

the class LuceneDataStoreSearchGUI method updateStackView.

/**
 * Updates the annotation stack in the central view.
 */
protected void updateStackView() {
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;
    if (resultTable.getSelectedRow() == -1) {
        // no result is selected in the result table
        centerPanel.removeAll();
        if (resultTable.getRowCount() > 0) {
            centerPanel.add(new JLabel("Select a row in the results table below."), gbc);
        } else {
            if (numberOfResultsSlider.getValue() > (numberOfResultsSlider.getMaximum() - 100)) {
                centerPanel.add(new JLabel("Retrieving all results..."), gbc);
            } else {
                centerPanel.add(new JLabel("Retrieving " + numberOfResultsSlider.getValue() + " results..."), gbc);
            }
        }
        centerPanel.validate();
        centerPanel.repaint();
        return;
    }
    // get information for the selected row in the results table
    Pattern result = (Pattern) results.get(resultTable.rowViewToModel(resultTable.getSelectionModel().getLeadSelectionIndex()));
    // initialize the annotation stack
    centerPanel.setText(result.getPatternText());
    centerPanel.setExpressionStartOffset(result.getStartOffset());
    centerPanel.setExpressionEndOffset(result.getEndOffset());
    centerPanel.setContextBeforeSize(result.getStartOffset() - result.getLeftContextStartOffset());
    centerPanel.setContextAfterSize(result.getRightContextEndOffset() - result.getEndOffset());
    centerPanel.setLastRowButton(configureStackViewButton);
    centerPanel.setTextMouseListener(new TextMouseListener());
    centerPanel.setHeaderMouseListener(new HeaderMouseListener());
    centerPanel.setAnnotationMouseListener(new AnnotationMouseListener());
    centerPanel.clearAllRows();
    // add each row to the annotation stack
    for (int row = 0; row < numStackRows; row++) {
        if (stackRows[row][DISPLAY].equals("false")) {
            continue;
        }
        String type = stackRows[row][ANNOTATION_TYPE];
        String feature = stackRows[row][FEATURE];
        String shortcut = stackRows[row][SHORTCUT];
        // remove button displayed at the end of each row
        JButton removeRowButton = new ButtonBorder(new Color(250, 250, 250), new Insets(0, 3, 0, 3), true);
        removeRowButton.setIcon(MainFrame.getIcon("Remove"));
        removeRowButton.setToolTipText("Hide this row.");
        final String typeFinal = type;
        final String featureFinal = feature;
        removeRowButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ie) {
                int row = findStackRow(ANNOTATION_TYPE, typeFinal, FEATURE, featureFinal);
                if (row >= 0) {
                    stackRows[row][DISPLAY] = "false";
                    saveStackViewConfiguration();
                }
                updateStackView();
            }
        });
        int crop;
        if (stackRows[row][CROP].equals("Crop start")) {
            crop = AnnotationStack.CROP_START;
        } else if (stackRows[row][CROP].equals("Crop end")) {
            crop = AnnotationStack.CROP_END;
        } else {
            crop = AnnotationStack.CROP_MIDDLE;
        }
        centerPanel.addRow(null, type, feature, removeRowButton, shortcut, crop);
        // annotations for this row
        PatternAnnotation[] annotations = result.getPatternAnnotations(type);
        if (annotations != null && annotations.length > 0) {
            for (PatternAnnotation annotation : annotations) {
                FeatureMap features = Factory.newFeatureMap();
                features.putAll(annotation.getFeatures());
                centerPanel.addAnnotation(annotation.getStartOffset(), annotation.getEndOffset(), annotation.getType(), features);
            }
        }
    }
    // draw the annotation stack
    centerPanel.drawStack();
}
Also used : Pattern(gate.creole.annic.Pattern) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) ActionEvent(java.awt.event.ActionEvent) PatternAnnotation(gate.creole.annic.PatternAnnotation) Color(java.awt.Color) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) FeatureMap(gate.FeatureMap) ActionListener(java.awt.event.ActionListener)

Example 3 with FeatureMap

use of gate.FeatureMap 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);
}
Also used : ResourceData(gate.creole.ResourceData) Set(java.util.Set) HashSet(java.util.HashSet) ActionEvent(java.awt.event.ActionEvent) CorpusExporter(gate.CorpusExporter) IOException(java.io.IOException) Document(gate.Document) Corpus(gate.Corpus) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) InvalidOffsetException(gate.util.InvalidOffsetException) IOException(java.io.IOException) ParameterException(gate.creole.ParameterException) FeatureMap(gate.FeatureMap) Iterator(java.util.Iterator) Parameter(gate.creole.Parameter) List(java.util.List) JMenuItem(javax.swing.JMenuItem) AbstractAction(javax.swing.AbstractAction) File(java.io.File)

Example 4 with FeatureMap

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

the class FeatureMapEditorDialog method initLocalData.

protected void initLocalData(FeatureMap data) {
    if (data != null) {
        FeatureMap fm = Factory.newFeatureMap();
        fm.putAll(data);
        tempFMHolder.setFeatures(fm);
    }
}
Also used : FeatureMap(gate.FeatureMap)

Example 5 with FeatureMap

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

the class ResourceParametersEditor method getParameterValues.

/**
 * Gets the current values for the parameters.
 *
 * @return a {@link FeatureMap} containing the curent values for the
 *         currently selected parameters in each disjunction.
 */
public FeatureMap getParameterValues() {
    // stop current edits
    if (getEditingColumn() != -1 && getEditingRow() != -1) {
        editingStopped(new ChangeEvent(getCellEditor(getEditingRow(), getEditingColumn())));
    }
    // get the parameters
    FeatureMap values = Factory.newFeatureMap();
    if (parameterDisjunctions != null) {
        for (int i = 0; i < parameterDisjunctions.size(); i++) {
            ParameterDisjunction pDisj = parameterDisjunctions.get(i);
            values.put(pDisj.getName(), pDisj.getValue());
        }
    }
    return values;
}
Also used : FeatureMap(gate.FeatureMap) ChangeEvent(javax.swing.event.ChangeEvent)

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