Search in sources :

Example 41 with FeatureMap

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

the class TestXml method helperBuildMatchesMap.

// End of buildMatchesMap()
/**
 * This is a helper metod. It scans an annotation set and adds the ID of the annotations
 * which have the matches feature to the map.
 * @param sourceAnnotSet  The annotation set investigated
 * @param aMap
 */
private void helperBuildMatchesMap(AnnotationSet sourceAnnotSet, Map<Integer, List<Integer>> aMap) {
    for (Iterator<Annotation> it = sourceAnnotSet.iterator(); it.hasNext(); ) {
        Annotation a = it.next();
        FeatureMap aFeatMap = a.getFeatures();
        // Skip those annotations who don't have features
        if (aFeatMap == null)
            continue;
        // Extract the matches feat
        @SuppressWarnings("unchecked") List<Integer> matchesVal = (List<Integer>) aFeatMap.get("matches");
        if (matchesVal == null)
            continue;
        Integer id = a.getId();
        aMap.put(id, matchesVal);
    }
// End for
}
Also used : FeatureMap(gate.FeatureMap) List(java.util.List) LinkedList(java.util.LinkedList) Annotation(gate.Annotation)

Example 42 with FeatureMap

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

the class TestXml method runCompleteTestWithAFormat.

// testGateDocumentToAndFromXmlWithDifferentKindOfFormats
private void runCompleteTestWithAFormat(URL url, String urlDescription) throws Exception {
    // Load the xml Key Document and unpack it
    gate.Document keyDocument = null;
    FeatureMap params = Factory.newFeatureMap();
    params.put(Document.DOCUMENT_URL_PARAMETER_NAME, url);
    params.put(Document.DOCUMENT_MARKUP_AWARE_PARAMETER_NAME, "false");
    keyDocument = (Document) Factory.createResource("gate.corpora.DocumentImpl", params);
    assertTrue("Coudn't create a GATE document instance for " + url.toString() + " Can't continue.", keyDocument != null);
    gate.DocumentFormat keyDocFormat = null;
    keyDocFormat = gate.DocumentFormat.getDocumentFormat(keyDocument, keyDocument.getSourceUrl());
    assertTrue("Fail to recognize " + url.toString() + " as being " + urlDescription + " !", keyDocFormat != null);
    // Unpack the markup
    keyDocFormat.unpackMarkup(keyDocument);
    // Verfy if all annotations from the default annotation set are consistent
    gate.corpora.TestDocument.verifyNodeIdConsistency(keyDocument);
    // Verifies if the maximum annotation ID on the GATE doc is less than the
    // Annotation ID generator of the document.
    verifyAnnotationIDGenerator(keyDocument);
    // Save the size of the document and the number of annotations
    long keyDocumentSize = keyDocument.getContent().size().longValue();
    int keyDocumentAnnotationSetSize = keyDocument.getAnnotations().size();
    // Export the Gate document called keyDocument as  XML, into a temp file,
    // using the working encoding
    File xmlFile = null;
    xmlFile = Files.writeTempFile(keyDocument.toXml(), workingEncoding);
    assertTrue("The temp GATE XML file is null. Can't continue.", xmlFile != null);
    // Load the XML Gate document form the tmp file into memory
    gate.Document gateDoc = null;
    gateDoc = gate.Factory.newDocument(xmlFile.toURI().toURL(), workingEncoding);
    assertTrue("Coudn't create a GATE document instance for " + xmlFile.toURI().toURL().toString() + " Can't continue.", gateDoc != null);
    gate.DocumentFormat gateDocFormat = null;
    gateDocFormat = DocumentFormat.getDocumentFormat(gateDoc, gateDoc.getSourceUrl());
    assertTrue("Fail to recognize " + xmlFile.toURI().toURL().toString() + " as being a GATE XML document !", gateDocFormat != null);
    gateDocFormat.unpackMarkup(gateDoc);
    // Verfy if all annotations from the default annotation set are consistent
    gate.corpora.TestDocument.verifyNodeIdConsistency(gateDoc);
    // Save the size of the document snd the number of annotations
    long gateDocSize = keyDocument.getContent().size().longValue();
    int gateDocAnnotationSetSize = keyDocument.getAnnotations().size();
    assertTrue("Exporting as GATE XML resulted in document content size lost." + " Something went wrong.", keyDocumentSize == gateDocSize);
    assertTrue("Exporting as GATE XML resulted in annotation lost." + " No. of annotations missing =  " + Math.abs(keyDocumentAnnotationSetSize - gateDocAnnotationSetSize), keyDocumentAnnotationSetSize == gateDocAnnotationSetSize);
    // Verifies if the maximum annotation ID on the GATE doc is less than the
    // Annotation ID generator of the document.
    verifyAnnotationIDGenerator(gateDoc);
    // Don't need tmp Gate XML file.
    xmlFile.delete();
}
Also used : FeatureMap(gate.FeatureMap) DocumentFormat(gate.DocumentFormat) Document(gate.Document) File(java.io.File)

Example 43 with FeatureMap

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

the class LuceneDocument method createTokens.

private boolean createTokens(gate.Document gateDocument, AnnotationSet set) {
    String gateContent = gateDocument.getContent().toString();
    int start = -1;
    for (int i = 0; i < gateContent.length(); i++) {
        char c = gateContent.charAt(i);
        if (Character.isWhitespace(c)) {
            if (start != -1) {
                FeatureMap features = gate.Factory.newFeatureMap();
                String string = gateContent.substring(start, i);
                if (string.trim().length() > 0) {
                    features.put("string", string);
                    try {
                        set.add(Long.valueOf(start), Long.valueOf(i), Constants.ANNIC_TOKEN, features);
                    } catch (InvalidOffsetException ioe) {
                        ioe.printStackTrace();
                        return false;
                    }
                }
                start = i + 1;
            }
        } else {
            if (start == -1)
                start = i;
        }
    }
    if (start == -1)
        return false;
    if (start < gateContent.length()) {
        FeatureMap features = gate.Factory.newFeatureMap();
        String string = gateContent.substring(start, gateContent.length());
        if (string.trim().length() > 0) {
            features.put("string", string);
            try {
                set.add(Long.valueOf(start), Long.valueOf(gateContent.length()), Constants.ANNIC_TOKEN, features);
            } catch (InvalidOffsetException ioe) {
                ioe.printStackTrace();
                return false;
            }
        }
    }
    return true;
}
Also used : FeatureMap(gate.FeatureMap) InvalidOffsetException(gate.util.InvalidOffsetException)

Example 44 with FeatureMap

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

the class LuceneDocument method getTokens.

/**
 * This method given a GATE document and other required parameters, for each
 * annotation of type indexUnitAnnotationType creates a separate list of
 * baseTokens underlying in it.
 */
private List<Token>[] getTokens(gate.Document document, AnnotationSet inputAs, List<String> featuresToInclude, List<String> featuresToExclude, String baseTokenAnnotationType, AnnotationSet baseTokenSet, String indexUnitAnnotationType, AnnotationSet indexUnitSet, Set<String> indexedFeatures) {
    boolean excludeFeatures = false;
    boolean includeFeatures = false;
    // features
    if (!featuresToInclude.isEmpty()) {
        includeFeatures = true;
    } else if (!featuresToExclude.isEmpty()) {
        excludeFeatures = true;
    }
    HashSet<OffsetGroup> unitOffsetsSet = new HashSet<OffsetGroup>();
    if (indexUnitAnnotationType == null || indexUnitAnnotationType.trim().length() == 0 || indexUnitSet == null || indexUnitSet.size() == 0) {
        // the index Unit Annotation Type is not specified
        // therefore we consider the entire document as a single unit
        OffsetGroup group = new OffsetGroup();
        group.startOffset = 0L;
        group.endOffset = document.getContent().size();
        unitOffsetsSet.add(group);
    } else {
        Iterator<Annotation> iter = indexUnitSet.iterator();
        while (iter.hasNext()) {
            Annotation annotation = iter.next();
            OffsetGroup group = new OffsetGroup();
            group.startOffset = annotation.getStartNode().getOffset();
            group.endOffset = annotation.getEndNode().getOffset();
            unitOffsetsSet.add(group);
        }
    }
    Set<String> allTypes = new HashSet<String>();
    for (String aType : inputAs.getAllTypes()) {
        if (aType.indexOf(".") > -1 || aType.indexOf("=") > -1 || aType.indexOf(";") > -1 || aType.indexOf(",") > -1) {
            System.err.println("Annotations of type " + aType + " cannot be indexed as the type name contains one of the ., =, or ; character");
            continue;
        }
        allTypes.add(aType);
    }
    if (baseTokenSet != null && baseTokenSet.size() > 0) {
        allTypes.remove(baseTokenAnnotationType);
    }
    if (indexUnitSet != null && indexUnitSet.size() > 0)
        allTypes.remove(indexUnitAnnotationType);
    AnnotationSet toUseSet = new AnnotationSetImpl(document);
    for (String type : allTypes) {
        for (Annotation a : inputAs.get(type)) {
            try {
                toUseSet.add(a.getStartNode().getOffset(), a.getEndNode().getOffset(), a.getType(), a.getFeatures());
            } catch (InvalidOffsetException ioe) {
                throw new GateRuntimeException(ioe);
            }
        }
    }
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) List<Token>[] toReturn = (List<Token>[]) new List[unitOffsetsSet.size()];
    Iterator<OffsetGroup> iter = unitOffsetsSet.iterator();
    int counter = 0;
    while (iter.hasNext()) {
        OffsetGroup group = iter.next();
        List<Token> newTokens = new ArrayList<Token>();
        List<Annotation> tokens = new ArrayList<Annotation>(toUseSet.getContained(group.startOffset, group.endOffset));
        // add tokens from the baseTokenSet
        if (baseTokenSet != null && baseTokenSet.size() != 0) {
            tokens.addAll(baseTokenSet.getContained(group.startOffset, group.endOffset));
        }
        if (tokens.isEmpty())
            return null;
        Collections.sort(tokens, new OffsetComparator());
        int position = -1;
        for (int i = 0; i < tokens.size(); i++) {
            byte inc = 1;
            Annotation annot = tokens.get(i);
            String type = annot.getType();
            // if the feature is specified in featuresToExclude -exclude it
            if (excludeFeatures && featuresToExclude.contains(type))
                continue;
            // exclude it
            if (includeFeatures && !featuresToInclude.contains(type))
                continue;
            int startOffset = annot.getStartNode().getOffset().intValue();
            int endOffset = annot.getEndNode().getOffset().intValue();
            String text = document.getContent().toString().substring(startOffset, endOffset);
            Token token1 = new Token(type, startOffset, endOffset, "*");
            // we add extra info of position
            if (i > 0) {
                if (annot.getStartNode().getOffset().longValue() == tokens.get(i - 1).getStartNode().getOffset().longValue()) {
                    token1.setPositionIncrement(0);
                    inc = 0;
                }
            }
            position += inc;
            token1.setPosition(position);
            newTokens.add(token1);
            if (!type.equals(baseTokenAnnotationType) || (annot.getFeatures().get("string") == null)) {
                // we need to create one string feature for this
                Token tk1 = new Token(text, startOffset, endOffset, type + ".string");
                indexedFeatures.add(type + ".string");
                tk1.setPositionIncrement(0);
                tk1.setPosition(position);
                newTokens.add(tk1);
            }
            // now find out the features and add them
            FeatureMap features = annot.getFeatures();
            Iterator<Object> fIter = features.keySet().iterator();
            while (fIter.hasNext()) {
                String type1 = fIter.next().toString();
                // it
                if (excludeFeatures && featuresToExclude.contains(type + "." + type1)) {
                    continue;
                }
                // exclude it
                if (includeFeatures && !featuresToInclude.contains(type + "." + type1))
                    continue;
                Object tempText = features.get(type1);
                if (tempText == null)
                    continue;
                String text1 = tempText.toString();
                // we need to qualify the type names
                // for each annotation type feature we add AT.Feature=="**" to be able
                // to search for it
                // to calculate stats
                Token tempToken = new Token(text1, startOffset, endOffset, type + "." + type1);
                indexedFeatures.add(type + "." + type1);
                tempToken.setPositionIncrement(0);
                tempToken.setPosition(position);
                newTokens.add(tempToken);
                Token onlyATFeature = new Token(type + "." + type1, startOffset, endOffset, "**");
                onlyATFeature.setPosition(position);
                onlyATFeature.setPositionIncrement(0);
                newTokens.add(onlyATFeature);
            }
        }
        toReturn[counter] = newTokens;
        counter++;
    }
    return toReturn;
}
Also used : ArrayList(java.util.ArrayList) AnnotationSet(gate.AnnotationSet) Token(gate.creole.annic.apache.lucene.analysis.Token) GateRuntimeException(gate.util.GateRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) InvalidOffsetException(gate.util.InvalidOffsetException) Annotation(gate.Annotation) FeatureMap(gate.FeatureMap) AnnotationSetImpl(gate.annotation.AnnotationSetImpl) OffsetComparator(gate.util.OffsetComparator)

Example 45 with FeatureMap

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

the class LuceneDataStoreSearchGUI method initGui.

/**
 * Initialize the GUI.
 */
protected void initGui() {
    // see the global layout schema at the end
    setLayout(new BorderLayout());
    stringCollator = java.text.Collator.getInstance();
    stringCollator.setStrength(java.text.Collator.TERTIARY);
    Comparator<String> lastWordComparator = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            if (o1 == null || o2 == null) {
                return 0;
            }
            return stringCollator.compare(o1.substring(o1.trim().lastIndexOf(' ') + 1), o2.substring(o2.trim().lastIndexOf(' ') + 1));
        }
    };
    integerComparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 == null || o2 == null) {
                return 0;
            }
            return o1.compareTo(o2);
        }
    };
    /**
     ********************************
     * Stack view configuration frame *
     *********************************
     */
    configureStackViewFrame = new ConfigureStackViewFrame("Stack view configuration");
    configureStackViewFrame.setIconImage(((ImageIcon) MainFrame.getIcon("WindowNew")).getImage());
    configureStackViewFrame.setLocationRelativeTo(LuceneDataStoreSearchGUI.this);
    configureStackViewFrame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ESCAPE"), "close row manager");
    configureStackViewFrame.getRootPane().getActionMap().put("close row manager", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            configureStackViewFrame.setVisible(false);
        }
    });
    configureStackViewFrame.validate();
    configureStackViewFrame.setSize(200, 300);
    configureStackViewFrame.pack();
    // called when Gate is exited, in case the user doesn't close the
    // datastore
    MainFrame.getInstance().addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            // no parent so need to be disposed explicitly
            configureStackViewFrame.dispose();
        }
    });
    /**
     ***********
     * Top panel *
     ************
     */
    JPanel topPanel = new JPanel(new GridBagLayout());
    topPanel.setOpaque(false);
    topPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 0, 3));
    GridBagConstraints gbc = new GridBagConstraints();
    // first column, three rows span
    queryTextArea = new QueryTextArea();
    queryTextArea.setToolTipText("<html>Enter a query to search the datastore." + "<br><small>'{' or '.' activate auto-completion." + "<br>Ctrl+Enter add a new line.</small></html>");
    queryTextArea.setLineWrap(true);
    gbc.gridheight = 3;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.insets = new Insets(0, 0, 0, 4);
    topPanel.add(new JScrollPane(queryTextArea), gbc);
    gbc.gridheight = 1;
    gbc.weightx = 0;
    gbc.weighty = 0;
    gbc.insets = new Insets(0, 0, 0, 0);
    // second column, first row
    gbc.gridx = GridBagConstraints.RELATIVE;
    topPanel.add(new JLabel("Corpus: "), gbc);
    corpusToSearchIn = new JComboBox<String>();
    corpusToSearchIn.addItem(Constants.ENTIRE_DATASTORE);
    corpusToSearchIn.setPrototypeDisplayValue(Constants.ENTIRE_DATASTORE);
    corpusToSearchIn.setToolTipText("Select the corpus to search in.");
    if (target == null || target instanceof Searcher) {
        corpusToSearchIn.setEnabled(false);
    }
    corpusToSearchIn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ie) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    updateAnnotationSetsList();
                }
            });
        }
    });
    topPanel.add(corpusToSearchIn, gbc);
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    topPanel.add(new JLabel("Annotation set: "), gbc);
    annotationSetsToSearchIn = new JComboBox<String>();
    annotationSetsToSearchIn.setPrototypeDisplayValue(Constants.COMBINED_SET);
    annotationSetsToSearchIn.setToolTipText("Select the annotation set to search in.");
    annotationSetsToSearchIn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ie) {
            updateAnnotationTypesList();
        }
    });
    topPanel.add(annotationSetsToSearchIn, gbc);
    // refresh button
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    RefreshAnnotationSetsAndFeaturesAction refreshAction = new RefreshAnnotationSetsAndFeaturesAction();
    JButton refreshTF = new ButtonBorder(new Color(240, 240, 240), new Insets(4, 2, 4, 3), false);
    refreshTF.setAction(refreshAction);
    topPanel.add(refreshTF, gbc);
    // second column, second row
    gbc.gridy = 1;
    JLabel noOfResultsLabel = new JLabel("Results: ");
    topPanel.add(noOfResultsLabel, gbc);
    numberOfResultsSlider = new JSlider(1, 1100, 50);
    numberOfResultsSlider.setToolTipText("50 results per page");
    numberOfResultsSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            if (numberOfResultsSlider.getValue() > (numberOfResultsSlider.getMaximum() - 100)) {
                numberOfResultsSlider.setToolTipText("Retrieve all results.");
                nextResults.setText("Retrieve all results.");
                nextResultsAction.setEnabled(false);
            } else {
                numberOfResultsSlider.setToolTipText("Retrieve " + numberOfResultsSlider.getValue() + " results per page.");
                nextResults.setText("Next page of " + numberOfResultsSlider.getValue() + " results");
                if (searcher.getHits().length == noOfResults) {
                    nextResultsAction.setEnabled(true);
                }
            }
            // show the tooltip each time the value change
            ToolTipManager.sharedInstance().mouseMoved(new MouseEvent(numberOfResultsSlider, MouseEvent.MOUSE_MOVED, 0, 0, 0, 0, 0, false));
        }
    });
    // always show the tooltip for this component
    numberOfResultsSlider.addMouseListener(new MouseAdapter() {

        ToolTipManager toolTipManager = ToolTipManager.sharedInstance();

        int initialDelay, reshowDelay, dismissDelay;

        boolean enabled;

        @Override
        public void mouseEntered(MouseEvent e) {
            initialDelay = toolTipManager.getInitialDelay();
            reshowDelay = toolTipManager.getReshowDelay();
            dismissDelay = toolTipManager.getDismissDelay();
            enabled = toolTipManager.isEnabled();
            toolTipManager.setInitialDelay(0);
            toolTipManager.setReshowDelay(0);
            toolTipManager.setDismissDelay(Integer.MAX_VALUE);
            toolTipManager.setEnabled(true);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            toolTipManager.setInitialDelay(initialDelay);
            toolTipManager.setReshowDelay(reshowDelay);
            toolTipManager.setDismissDelay(dismissDelay);
            toolTipManager.setEnabled(enabled);
        }
    });
    gbc.insets = new Insets(5, 0, 0, 0);
    topPanel.add(numberOfResultsSlider, gbc);
    gbc.insets = new Insets(0, 0, 0, 0);
    topPanel.add(Box.createHorizontalStrut(4), gbc);
    JLabel contextWindowLabel = new JLabel("Context size: ");
    topPanel.add(contextWindowLabel, gbc);
    contextSizeSlider = new JSlider(1, 50, 5);
    contextSizeSlider.setToolTipText("Display 5 tokens of context in the results.");
    contextSizeSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            contextSizeSlider.setToolTipText("Display " + contextSizeSlider.getValue() + " tokens of context in the results.");
            ToolTipManager.sharedInstance().mouseMoved(new MouseEvent(contextSizeSlider, MouseEvent.MOUSE_MOVED, 0, 0, 0, 0, 0, false));
        }
    });
    // always show the tooltip for this component
    contextSizeSlider.addMouseListener(new MouseAdapter() {

        ToolTipManager toolTipManager = ToolTipManager.sharedInstance();

        int initialDelay, reshowDelay, dismissDelay;

        boolean enabled;

        @Override
        public void mouseEntered(MouseEvent e) {
            initialDelay = toolTipManager.getInitialDelay();
            reshowDelay = toolTipManager.getReshowDelay();
            dismissDelay = toolTipManager.getDismissDelay();
            enabled = toolTipManager.isEnabled();
            toolTipManager.setInitialDelay(0);
            toolTipManager.setReshowDelay(0);
            toolTipManager.setDismissDelay(Integer.MAX_VALUE);
            toolTipManager.setEnabled(true);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            toolTipManager.setInitialDelay(initialDelay);
            toolTipManager.setReshowDelay(reshowDelay);
            toolTipManager.setDismissDelay(dismissDelay);
            toolTipManager.setEnabled(enabled);
        }
    });
    gbc.insets = new Insets(5, 0, 0, 0);
    topPanel.add(contextSizeSlider, gbc);
    gbc.insets = new Insets(0, 0, 0, 0);
    // second column, third row
    gbc.gridy = 2;
    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    executeQueryAction = new ExecuteQueryAction();
    JButton executeQuery = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 2, 0, 3), false);
    executeQuery.setAction(executeQueryAction);
    panel.add(executeQuery);
    ClearQueryAction clearQueryAction = new ClearQueryAction();
    JButton clearQueryTF = new ButtonBorder(new Color(240, 240, 240), new Insets(4, 2, 4, 3), false);
    clearQueryTF.setAction(clearQueryAction);
    panel.add(Box.createHorizontalStrut(5));
    panel.add(clearQueryTF);
    nextResultsAction = new NextResultsAction();
    nextResultsAction.setEnabled(false);
    nextResults = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 0, 0, 3), false);
    nextResults.setAction(nextResultsAction);
    panel.add(Box.createHorizontalStrut(5));
    panel.add(nextResults);
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    topPanel.add(panel, gbc);
    // will be added to the GUI via a split panel
    /**
     **************
     * Center panel *
     ***************
     */
    // these components will be used in updateStackView()
    centerPanel = new AnnotationStack(150, 30);
    configureStackViewButton = new ButtonBorder(new Color(250, 250, 250), new Insets(0, 0, 0, 3), true);
    configureStackViewButton.setHorizontalAlignment(SwingConstants.LEFT);
    configureStackViewButton.setAction(new ConfigureStackViewAction());
    // will be added to the GUI via a split panel
    /**
     *******************
     * Bottom left panel *
     ********************
     */
    JPanel bottomLeftPanel = new JPanel(new GridBagLayout());
    bottomLeftPanel.setOpaque(false);
    gbc = new GridBagConstraints();
    // title of the table, results options, export and next results
    // button
    gbc.gridy = 0;
    panel = new JPanel();
    panel.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    titleResults = new JLabel("Results");
    titleResults.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
    panel.add(titleResults);
    panel.add(Box.createHorizontalStrut(5), gbc);
    exportResultsAction = new ExportResultsAction();
    exportResultsAction.setEnabled(false);
    JButton exportToHTML = new ButtonBorder(new Color(240, 240, 240), new Insets(0, 0, 0, 3), false);
    exportToHTML.setAction(exportResultsAction);
    panel.add(exportToHTML, gbc);
    bottomLeftPanel.add(panel, gbc);
    // table of results
    resultTableModel = new ResultTableModel();
    resultTable = new XJTable(resultTableModel);
    resultTable.setDefaultRenderer(String.class, new ResultTableCellRenderer());
    resultTable.setEnableHidingColumns(true);
    resultTable.addMouseListener(new MouseAdapter() {

        private JPopupMenu mousePopup;

        JMenuItem menuItem;

        @Override
        public void mousePressed(MouseEvent e) {
            int row = resultTable.rowAtPoint(e.getPoint());
            if (e.isPopupTrigger() && !resultTable.isRowSelected(row)) {
                // if right click outside the selection then reset selection
                resultTable.getSelectionModel().setSelectionInterval(row, row);
            }
            if (e.isPopupTrigger()) {
                createPopup();
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                createPopup();
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        private void createPopup() {
            mousePopup = new JPopupMenu();
            menuItem = new JMenuItem("Remove the selected result" + (resultTable.getSelectedRowCount() > 1 ? "s" : ""));
            mousePopup.add(menuItem);
            menuItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    int[] rows = resultTable.getSelectedRows();
                    for (int i = 0; i < rows.length; i++) {
                        rows[i] = resultTable.rowViewToModel(rows[i]);
                    }
                    Arrays.sort(rows);
                    for (int i = rows.length - 1; i >= 0; i--) {
                        results.remove(rows[i]);
                    }
                    resultTable.clearSelection();
                    resultTableModel.fireTableDataChanged();
                    mousePopup.setVisible(false);
                }
            });
            if (target instanceof LuceneDataStoreImpl && SwingUtilities.getRoot(LuceneDataStoreSearchGUI.this) instanceof MainFrame) {
                menuItem = new JMenuItem("Open the selected document" + (resultTable.getSelectedRowCount() > 1 ? "s" : ""));
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        Set<Pattern> patterns = new HashSet<Pattern>();
                        Set<String> documentIds = new HashSet<String>();
                        for (int rowView : resultTable.getSelectedRows()) {
                            // create and display the document for this result
                            int rowModel = resultTable.rowViewToModel(rowView);
                            Pattern pattern = (Pattern) results.get(rowModel);
                            if (!documentIds.contains(pattern.getDocumentID())) {
                                patterns.add(pattern);
                                documentIds.add(pattern.getDocumentID());
                            }
                        }
                        if (patterns.size() > 10) {
                            Object[] possibleValues = { "Open the " + patterns.size() + " documents", "Don't open" };
                            int selectedValue = JOptionPane.showOptionDialog(LuceneDataStoreSearchGUI.this, "Do you want to open " + patterns.size() + " documents in the central tabbed pane ?", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[1]);
                            if (selectedValue == 1 || selectedValue == JOptionPane.CLOSED_OPTION) {
                                return;
                            }
                        }
                        for (final Pattern pattern : patterns) {
                            // create and display the document for this result
                            FeatureMap features = Factory.newFeatureMap();
                            features.put(DataStore.DATASTORE_FEATURE_NAME, target);
                            features.put(DataStore.LR_ID_FEATURE_NAME, pattern.getDocumentID());
                            final Document doc;
                            try {
                                doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", features);
                            } catch (gate.util.GateException e) {
                                e.printStackTrace();
                                return;
                            }
                            // show the expression in the document
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    MainFrame.getInstance().select(doc);
                                }
                            });
                            if (patterns.size() == 1) {
                                // wait some time for the document to be displayed
                                Date timeToRun = new Date(System.currentTimeMillis() + 2000);
                                Timer timer = new Timer("Annic show document timer", true);
                                timer.schedule(new TimerTask() {

                                    @Override
                                    public void run() {
                                        showResultInDocument(doc, pattern);
                                    }
                                }, timeToRun);
                            }
                        }
                    }
                });
                mousePopup.add(menuItem);
            }
        }
    });
    // resultTable.addMouseListener
    // when selection change in the result table
    // update the stack view and export button
    resultTable.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {

        @Override
        public void valueChanged(javax.swing.event.ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateStackView();
            }
        }
    });
    resultTable.setColumnSelectionAllowed(false);
    resultTable.setRowSelectionAllowed(true);
    resultTable.setSortable(true);
    resultTable.setComparator(ResultTableModel.LEFT_CONTEXT_COLUMN, lastWordComparator);
    resultTable.setComparator(ResultTableModel.RESULT_COLUMN, stringCollator);
    resultTable.setComparator(ResultTableModel.RIGHT_CONTEXT_COLUMN, stringCollator);
    JScrollPane tableScrollPane = new JScrollPane(resultTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.NORTH;
    gbc.gridy = 1;
    gbc.gridx = 0;
    gbc.insets = new Insets(0, 0, 0, 0);
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    gbc.weightx = 1;
    gbc.weighty = 1;
    bottomLeftPanel.add(tableScrollPane, gbc);
    /**
     ************************
     * Statistics tabbed pane *
     *************************
     */
    statisticsTabbedPane = new JTabbedPane();
    globalStatisticsTable = new XJTable() {

        @Override
        public boolean isCellEditable(int rowIndex, int vColIndex) {
            return false;
        }
    };
    globalStatisticsTableModel = new DefaultTableModel(new Object[] { "Annotation Type", "Count" }, 0);
    globalStatisticsTable.setModel(globalStatisticsTableModel);
    globalStatisticsTable.setComparator(0, stringCollator);
    globalStatisticsTable.setComparator(1, integerComparator);
    globalStatisticsTable.setSortedColumn(1);
    globalStatisticsTable.setAscending(false);
    globalStatisticsTable.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                updateQuery();
            }
        }

        private void updateQuery() {
            int caretPosition = queryTextArea.getCaretPosition();
            String query = queryTextArea.getText();
            String type = (String) globalStatisticsTable.getValueAt(globalStatisticsTable.getSelectedRow(), globalStatisticsTable.convertColumnIndexToView(0));
            String queryMiddle = "{" + type + "}";
            String queryLeft = (queryTextArea.getSelectionStart() == queryTextArea.getSelectionEnd()) ? query.substring(0, caretPosition) : query.substring(0, queryTextArea.getSelectionStart());
            String queryRight = (queryTextArea.getSelectionStart() == queryTextArea.getSelectionEnd()) ? query.substring(caretPosition, query.length()) : query.substring(queryTextArea.getSelectionEnd(), query.length());
            queryTextArea.setText(queryLeft + queryMiddle + queryRight);
        }
    });
    statisticsTabbedPane.addTab("Global", null, new JScrollPane(globalStatisticsTable), "Global statistics on the Corpus and Annotation Set selected.");
    statisticsTabbedPane.addMouseListener(new MouseAdapter() {

        private JPopupMenu mousePopup;

        JMenuItem menuItem;

        @Override
        public void mousePressed(MouseEvent e) {
            int tabIndex = statisticsTabbedPane.indexAtLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && tabIndex > 0) {
                createPopup(tabIndex);
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            int tabIndex = statisticsTabbedPane.indexAtLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && tabIndex > 0) {
                createPopup(tabIndex);
                mousePopup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

        private void createPopup(final int tabIndex) {
            mousePopup = new JPopupMenu();
            if (tabIndex == 1) {
                menuItem = new JMenuItem("Clear table");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ie) {
                        oneRowStatisticsTableModel.setRowCount(0);
                    }
                });
            } else {
                menuItem = new JMenuItem("Close tab");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ie) {
                        statisticsTabbedPane.remove(tabIndex);
                    }
                });
            }
            mousePopup.add(menuItem);
        }
    });
    class RemoveCellEditorRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener {

        private JButton button;

        public RemoveCellEditorRenderer() {
            button = new JButton();
            button.setHorizontalAlignment(SwingConstants.CENTER);
            button.setIcon(MainFrame.getIcon("Delete"));
            button.setToolTipText("Remove this row.");
            button.setContentAreaFilled(false);
            button.setBorderPainted(false);
            button.setMargin(new Insets(0, 0, 0, 0));
            button.addActionListener(this);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int col) {
            button.setSelected(isSelected);
            return button;
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int editingRow = oneRowStatisticsTable.getEditingRow();
            fireEditingStopped();
            oneRowStatisticsTableModel.removeRow(oneRowStatisticsTable.rowViewToModel(editingRow));
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
            button.setSelected(isSelected);
            return button;
        }
    }
    oneRowStatisticsTable = new XJTable() {

        @Override
        public boolean isCellEditable(int rowIndex, int vColIndex) {
            return vColIndex == 2;
        }

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component c = super.prepareRenderer(renderer, row, col);
            if (c instanceof JComponent && col != 2) {
                // display a custom tooltip saved when adding statistics
                ((JComponent) c).setToolTipText("<html>" + oneRowStatisticsTableToolTips.get(rowViewToModel(row)) + "</html>");
            }
            return c;
        }
    };
    oneRowStatisticsTableModel = new DefaultTableModel(new Object[] { "Annotation Type/Feature", "Count", "" }, 0);
    oneRowStatisticsTable.setModel(oneRowStatisticsTableModel);
    oneRowStatisticsTable.getColumnModel().getColumn(2).setCellEditor(new RemoveCellEditorRenderer());
    oneRowStatisticsTable.getColumnModel().getColumn(2).setCellRenderer(new RemoveCellEditorRenderer());
    oneRowStatisticsTable.setComparator(0, stringCollator);
    oneRowStatisticsTable.setComparator(1, integerComparator);
    statisticsTabbedPane.addTab("One item", null, new JScrollPane(oneRowStatisticsTable), "<html>One item statistics.<br>" + "Right-click on an annotation<br>" + "to add statistics here.");
    oneRowStatisticsTableToolTips = new Vector<String>();
    // will be added to the GUI via a split panel
    /**
     ************************************************************
     * Vertical splits between top, center panel and bottom panel *
     *************************************************************
     */
    /**
     * ________________________________________
     * |               topPanel                 |
     * |__________________3_____________________|
     * |                                        |
     * |             centerPanel                |
     * |________2________ __________2___________|
     * |                 |                      |
     * | bottomLeftPanel 1 statisticsTabbedPane |
     * |_________________|______________________|
     *
     * 1 bottomSplitPane 2 centerBottomSplitPane 3 topBottomSplitPane
     */
    bottomSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    Dimension minimumSize = new Dimension(0, 0);
    bottomLeftPanel.setMinimumSize(minimumSize);
    statisticsTabbedPane.setMinimumSize(minimumSize);
    bottomSplitPane.add(bottomLeftPanel);
    bottomSplitPane.add(statisticsTabbedPane);
    bottomSplitPane.setOneTouchExpandable(true);
    bottomSplitPane.setResizeWeight(0.75);
    bottomSplitPane.setContinuousLayout(true);
    JSplitPane centerBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    centerBottomSplitPane.add(new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
    centerBottomSplitPane.add(bottomSplitPane);
    centerBottomSplitPane.setResizeWeight(0.5);
    centerBottomSplitPane.setContinuousLayout(true);
    JSplitPane topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    topBottomSplitPane.add(topPanel);
    topBottomSplitPane.add(centerBottomSplitPane);
    topBottomSplitPane.setContinuousLayout(true);
    add(topBottomSplitPane, BorderLayout.CENTER);
}
Also used : AnnotationStack(gate.gui.docview.AnnotationStack) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) ActionEvent(java.awt.event.ActionEvent) Document(gate.Document) Comparator(java.util.Comparator) BorderLayout(java.awt.BorderLayout) JSlider(javax.swing.JSlider) TableCellEditor(javax.swing.table.TableCellEditor) EmptyBorder(javax.swing.border.EmptyBorder) AbstractAction(javax.swing.AbstractAction) HashSet(java.util.HashSet) TableCellRenderer(javax.swing.table.TableCellRenderer) DefaultTableCellRenderer(javax.swing.table.DefaultTableCellRenderer) ToolTipManager(javax.swing.ToolTipManager) Searcher(gate.creole.annic.Searcher) Color(java.awt.Color) EventObject(java.util.EventObject) ActionListener(java.awt.event.ActionListener) JTable(javax.swing.JTable) XJTable(gate.swing.XJTable) EventObject(java.util.EventObject) JSplitPane(javax.swing.JSplitPane) MouseInputAdapter(javax.swing.event.MouseInputAdapter) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) XJTable(gate.swing.XJTable) JTabbedPane(javax.swing.JTabbedPane) DefaultTableModel(javax.swing.table.DefaultTableModel) JButton(javax.swing.JButton) WindowAdapter(java.awt.event.WindowAdapter) TimerTask(java.util.TimerTask) ChangeListener(javax.swing.event.ChangeListener) AbstractCellEditor(javax.swing.AbstractCellEditor) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) JComponent(javax.swing.JComponent) JScrollPane(javax.swing.JScrollPane) Pattern(gate.creole.annic.Pattern) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) LuceneDataStoreImpl(gate.persist.LuceneDataStoreImpl) Dimension(java.awt.Dimension) JPopupMenu(javax.swing.JPopupMenu) Date(java.util.Date) FeatureMap(gate.FeatureMap) ChangeEvent(javax.swing.event.ChangeEvent) Timer(java.util.Timer) WindowEvent(java.awt.event.WindowEvent)

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