Search in sources :

Example 26 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class TextualDocumentView method scrollAnnotationToVisible.

// changeOrientation
public void scrollAnnotationToVisible(Annotation ann) {
    // if at least part of the blinking section is visible then we
    // need to do no scrolling
    // this is required for long annotations that span more than a
    // screen
    Rectangle visibleView = scroller.getViewport().getViewRect();
    int viewStart = textView.viewToModel(visibleView.getLocation());
    Point endPoint = new Point(visibleView.getLocation());
    endPoint.translate(visibleView.width, visibleView.height);
    int viewEnd = textView.viewToModel(endPoint);
    int annStart = ann.getStartNode().getOffset().intValue();
    int annEnd = ann.getEndNode().getOffset().intValue();
    if (annEnd < viewStart || viewEnd < annStart) {
        try {
            textView.scrollRectToVisible(textView.modelToView(annStart));
        } catch (BadLocationException ble) {
            // this should never happen
            throw new GateRuntimeException(ble);
        }
    }
}
Also used : GateRuntimeException(gate.util.GateRuntimeException) Rectangle(java.awt.Rectangle) Point(java.awt.Point) Point(java.awt.Point) BadLocationException(javax.swing.text.BadLocationException)

Example 27 with GateRuntimeException

use of gate.util.GateRuntimeException 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 28 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class LuceneDataStoreSearchGUI method setTarget.

/**
 * Called by the GUI when this viewer/editor has to initialise itself
 * for a specific object.
 *
 * @param target the object (be it a {@link gate.Resource},
 *          {@link gate.DataStore}or whatever) this viewer has to
 *          display
 */
@Override
public void setTarget(Object target) {
    if (!(target instanceof LuceneDataStoreImpl) && !(target instanceof Searcher)) {
        throw new IllegalArgumentException("The GATE LuceneDataStoreSearchGUI can only be used with a GATE LuceneDataStores!\n" + target.getClass().toString() + " is not a GATE LuceneDataStore or an object of Searcher!");
    }
    this.target = target;
    // standalone Java application
    if (target instanceof LuceneDataStoreImpl) {
        ((LuceneDataStoreImpl) target).addDatastoreListener(this);
        corpusToSearchIn.setEnabled(true);
        searcher = ((LuceneDataStoreImpl) target).getSearcher();
        updateSetsTypesAndFeatures();
        try {
            // get the corpus names from the datastore
            java.util.List<String> corpusPIds = ((LuceneDataStoreImpl) target).getLrIds(SerialCorpusImpl.class.getName());
            if (corpusIds != null) {
                for (Object corpusPId : corpusPIds) {
                    String name = ((LuceneDataStoreImpl) target).getLrName(corpusPId);
                    this.corpusIds.add(corpusPId);
                    // add the corpus name to combobox
                    ((DefaultComboBoxModel<String>) corpusToSearchIn.getModel()).addElement(name);
                }
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    corpusToSearchIn.updateUI();
                    corpusToSearchIn.setSelectedItem(Constants.ENTIRE_DATASTORE);
                }
            });
        } catch (PersistenceException e) {
            System.out.println("Couldn't find any available corpusIds.");
            throw new GateRuntimeException(e);
        }
    } else // Java Web Start application
    {
        searcher = (Searcher) target;
        corpusToSearchIn.setEnabled(false);
        // find out all annotation sets that are indexed
        try {
            annotationSetIDsFromDataStore = searcher.getIndexedAnnotationSetNames();
            allAnnotTypesAndFeaturesFromDatastore = searcher.getAnnotationTypesMap();
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    updateAnnotationSetsList();
                }
            });
        } catch (SearchException e) {
            throw new GateRuntimeException(e);
        }
    }
}
Also used : Searcher(gate.creole.annic.Searcher) SearchException(gate.creole.annic.SearchException) LuceneDataStoreImpl(gate.persist.LuceneDataStoreImpl) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel) SerialCorpusImpl(gate.corpora.SerialCorpusImpl) GateRuntimeException(gate.util.GateRuntimeException) PersistenceException(gate.persist.PersistenceException) EventObject(java.util.EventObject)

Example 29 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class LuceneDataStoreSearchGUI method updateSetsTypesAndFeatures.

protected void updateSetsTypesAndFeatures() {
    try {
        annotationSetIDsFromDataStore = searcher.getIndexedAnnotationSetNames();
        allAnnotTypesAndFeaturesFromDatastore = searcher.getAnnotationTypesMap();
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                updateAnnotationSetsList();
            }
        });
    } catch (SearchException se) {
        throw new GateRuntimeException(se);
    }
}
Also used : GateRuntimeException(gate.util.GateRuntimeException) SearchException(gate.creole.annic.SearchException)

Example 30 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class MainFrame method createSearchableDataStore.

/**
 * Method is used in NewDSAction
 * @return the new datastore or null if an error occurs
 */
protected DataStore createSearchableDataStore() {
    try {
        JPanel mainPanel = new JPanel(new GridBagLayout());
        final JTextField dsLocation = new JTextField("", 20);
        dsLocation.setEditable(false);
        final JTextField indexLocation = new JTextField("", 20);
        indexLocation.setToolTipText("directory to store the the lucene index");
        JTextField btat = new JTextField("Token", 20);
        btat.setToolTipText("Examples: Token, AnnotationSetName.Token, " + Constants.DEFAULT_ANNOTATION_SET_NAME + ".Token");
        JCheckBox createTokensAutomatically = new JCheckBox("Create Tokens Automatically");
        createTokensAutomatically.setSelected(true);
        JTextField iuat = new JTextField("", 20);
        iuat.setToolTipText("Examples: Sentence, AnnotationSetName.Sentence, " + Constants.DEFAULT_ANNOTATION_SET_NAME + ".Sentence");
        final List<String> inputASList = new ArrayList<String>();
        inputASList.add("Key");
        inputASList.add(Constants.DEFAULT_ANNOTATION_SET_NAME);
        final JTextField inputAS = new JTextField("", 20);
        inputAS.setText("Key;" + Constants.DEFAULT_ANNOTATION_SET_NAME);
        inputAS.setEditable(false);
        JButton editInputAS = new JButton(getIcon("edit-list"));
        editInputAS.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                ListEditorDialog listEditor = new ListEditorDialog(instance, inputASList, "java.lang.String");
                @SuppressWarnings("unchecked") List<String> result = listEditor.showDialog();
                if (result != null) {
                    inputASList.clear();
                    inputASList.addAll(result);
                    if (inputASList.size() > 0) {
                        String text = inputASList.get(0) == null ? Constants.DEFAULT_ANNOTATION_SET_NAME : inputASList.get(0);
                        for (int j = 1; j < inputASList.size(); j++) {
                            text += ";" + (inputASList.get(j) == null ? Constants.DEFAULT_ANNOTATION_SET_NAME : inputASList.get(j));
                        }
                        inputAS.setText(text);
                    } else {
                        inputAS.setText("");
                    }
                }
            }
        });
        JComboBox<String> asie = new JComboBox<String>(new String[] { "include", "exclude" });
        inputAS.setToolTipText("Leave blank for indexing all annotation sets. \"" + Constants.DEFAULT_ANNOTATION_SET_NAME + "\" indicates the default annotation set");
        final List<String> fteList = new ArrayList<String>();
        fteList.add("SpaceToken");
        fteList.add("Split");
        final JTextField fte = new JTextField("", 20);
        fte.setText("SpaceToken;Split");
        fte.setEditable(false);
        JButton editFTE = new JButton(getIcon("edit-list"));
        editFTE.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                ListEditorDialog listEditor = new ListEditorDialog(instance, fteList, "java.lang.String");
                @SuppressWarnings("unchecked") List<String> result = listEditor.showDialog();
                if (result != null) {
                    fteList.clear();
                    fteList.addAll(result);
                    if (fteList.size() > 0) {
                        String text = fteList.get(0) == null ? Constants.DEFAULT_ANNOTATION_SET_NAME : fteList.get(0);
                        for (int j = 1; j < fteList.size(); j++) {
                            text += ";" + (fteList.get(j) == null ? Constants.DEFAULT_ANNOTATION_SET_NAME : fteList.get(j));
                        }
                        fte.setText(text);
                    } else {
                        fte.setText("");
                    }
                }
            }
        });
        JComboBox<String> ftie = new JComboBox<String>(new String[] { "include", "exclude" });
        ftie.setSelectedIndex(1);
        fte.setToolTipText("Leave blank for inclusion of all features");
        JButton indexBrowse = new JButton(getIcon("open-file"));
        indexBrowse.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                // first we need to ask for a new empty directory
                fileChooser.setDialogTitle("Please create a new empty directory for datastore");
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.setResource("gate.DataStore.index");
                if (fileChooser.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
                    try {
                        indexLocation.setText(fileChooser.getSelectedFile().toURI().toURL().toExternalForm());
                    } catch (Exception e) {
                        indexLocation.setText("");
                    }
                }
            }
        });
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 0;
        constraints.gridwidth = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Datastore URL:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 0;
        constraints.gridwidth = 6;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(dsLocation, constraints);
        // second row
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Index Location:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 1;
        constraints.gridwidth = 5;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(indexLocation, constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 1;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(indexBrowse, constraints);
        indexBrowse.setBorderPainted(false);
        indexBrowse.setContentAreaFilled(false);
        // third row row
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 2;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Annotation Sets:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 2;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(asie, constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 2;
        constraints.gridwidth = 5;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(inputAS, constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(editInputAS, constraints);
        editInputAS.setBorderPainted(false);
        editInputAS.setContentAreaFilled(false);
        // fourth row row
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 3;
        constraints.gridwidth = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Base Token Type:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 3;
        constraints.gridwidth = 5;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(btat, constraints);
        // fifth row
        constraints = new GridBagConstraints();
        constraints.gridx = 4;
        constraints.gridy = 4;
        constraints.gridwidth = 5;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(createTokensAutomatically, constraints);
        // sixth row
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 5;
        constraints.gridwidth = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Index Unit Type:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 5;
        constraints.gridwidth = 5;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(iuat, constraints);
        // seventh row
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 6;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.NONE;
        constraints.insets = new Insets(0, 0, 0, 5);
        mainPanel.add(new JLabel("Features:"), constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 6;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(ftie, constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 6;
        constraints.gridwidth = 5;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(0, 0, 0, 10);
        mainPanel.add(fte, constraints);
        constraints = new GridBagConstraints();
        constraints.gridx = GridBagConstraints.RELATIVE;
        constraints.gridy = 6;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(editFTE, constraints);
        editFTE.setBorderPainted(false);
        editFTE.setContentAreaFilled(false);
        // get the URL (a folder in this case)
        fileChooser.setDialogTitle("Please create a new empty directory");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter());
        fileChooser.setResource("gate.persist.LuceneDataStoreImpl");
        int response = fileChooser.showOpenDialog(MainFrame.this);
        if (response == JFileChooser.APPROVE_OPTION) {
            try {
                File dsFolder = fileChooser.getSelectedFile();
                dsLocation.setText(dsFolder.toURI().toURL().toExternalForm());
                File indexFolder = new File(dsFolder.getParentFile(), dsFolder.getName() + "-index");
                indexLocation.setText(indexFolder.toURI().toURL().toExternalForm());
            } catch (MalformedURLException mue) {
                JOptionPane.showMessageDialog(MainFrame.this, "Invalid location\n " + mue.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            return null;
        }
        boolean validEntry = false;
        while (!validEntry) {
            int returnValue = JOptionPane.showOptionDialog(MainFrame.this, mainPanel, "SearchableDataStore", JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, getIcon("empty"), new String[] { "OK", "Cancel" }, "OK");
            if (returnValue == JOptionPane.OK_OPTION) {
                if (dsLocation.getText().equals(indexLocation.getText())) {
                    JOptionPane.showMessageDialog(MainFrame.this, "Datastore and index cannot be stored in the same directory", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    // check if index folder can be created
                    try {
                        File indexDir = new File(new URL(indexLocation.getText()).getFile());
                        if (indexDir.exists() && indexDir.isFile()) {
                            JOptionPane.showMessageDialog(MainFrame.this, indexDir.getAbsolutePath() + " is a file on your disk. Index directory must be an" + " empty folder.", "Error", JOptionPane.ERROR_MESSAGE);
                            continue;
                        } else if (indexDir.isDirectory() && indexDir.list().length > 0) {
                            JOptionPane.showMessageDialog(instance, "Index directory " + indexDir.getAbsolutePath() + " must be an empty folder. ", "Error", JOptionPane.ERROR_MESSAGE);
                            continue;
                        } else {
                            if (!indexDir.exists()) {
                                if (!indexDir.mkdirs()) {
                                    JOptionPane.showMessageDialog(MainFrame.this, "Cannot create index directory " + indexDir.getAbsolutePath() + "an empty folder. ", "Error", JOptionPane.ERROR_MESSAGE);
                                    continue;
                                }
                            }
                        }
                    } catch (MalformedURLException mue) {
                        JOptionPane.showMessageDialog(MainFrame.this, "Invalid index location " + indexLocation.getText(), "Error", JOptionPane.ERROR_MESSAGE);
                        continue;
                    } catch (SecurityException se) {
                        JOptionPane.showMessageDialog(MainFrame.this, "Could not create a directory " + indexLocation.getText() + " because " + se.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }
                    // if here.. an empty index directory exists
                    // break the loop by setting validEntry to true
                    validEntry = true;
                    DataStore ds = Factory.createDataStore("gate.persist.LuceneDataStoreImpl", dsLocation.getText());
                    // we need to set Indexer
                    Class<?>[] consParam = new Class<?>[1];
                    consParam[0] = URL.class;
                    Constructor<?> constructor = Class.forName("gate.creole.annic.lucene.LuceneIndexer", true, Gate.getClassLoader()).getConstructor(consParam);
                    Object indexer = constructor.newInstance(new URL(indexLocation.getText()));
                    Map<String, Object> parameters = new HashMap<String, Object>();
                    parameters.put(Constants.INDEX_LOCATION_URL, new URL(indexLocation.getText()));
                    parameters.put(Constants.BASE_TOKEN_ANNOTATION_TYPE, btat.getText());
                    parameters.put(Constants.INDEX_UNIT_ANNOTATION_TYPE, iuat.getText());
                    parameters.put(Constants.CREATE_TOKENS_AUTOMATICALLY, createTokensAutomatically.isSelected());
                    if (inputAS.getText().trim().length() > 0) {
                        ArrayList<String> inputASList1 = new ArrayList<String>();
                        String[] inputASArray = inputAS.getText().trim().split(";");
                        if (inputASArray != null && inputASArray.length > 0) {
                            inputASList1.addAll(Arrays.asList(inputASArray));
                        }
                        if (asie.getSelectedIndex() == 0) {
                            // user has provided values for inclusion
                            parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_INCLUDE, inputASList1);
                            parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_EXCLUDE, new ArrayList<String>());
                        } else {
                            // user has provided values for exclusion
                            parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_EXCLUDE, inputASList1);
                            parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_INCLUDE, new ArrayList<String>());
                        }
                    } else {
                        parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_EXCLUDE, new ArrayList<String>());
                        parameters.put(Constants.ANNOTATION_SETS_NAMES_TO_INCLUDE, new ArrayList<String>());
                    }
                    if (fte.getText().trim().length() > 0) {
                        ArrayList<String> fteList1 = new ArrayList<String>();
                        String[] inputASArray = fte.getText().trim().split(";");
                        if (inputASArray != null && inputASArray.length > 0) {
                            fteList1.addAll(Arrays.asList(inputASArray));
                        }
                        if (ftie.getSelectedIndex() == 0) {
                            // user has provided values for inclusion
                            parameters.put(Constants.FEATURES_TO_INCLUDE, fteList1);
                            parameters.put(Constants.FEATURES_TO_EXCLUDE, new ArrayList<String>());
                        } else {
                            // user has provided values for exclusion
                            parameters.put(Constants.FEATURES_TO_EXCLUDE, fteList1);
                            parameters.put(Constants.FEATURES_TO_INCLUDE, new ArrayList<String>());
                        }
                    } else {
                        parameters.put(Constants.FEATURES_TO_EXCLUDE, new ArrayList<String>());
                        parameters.put(Constants.FEATURES_TO_INCLUDE, new ArrayList<String>());
                    }
                    Class<?>[] params = new Class<?>[2];
                    params[0] = Class.forName("gate.creole.annic.Indexer", true, Gate.getClassLoader());
                    params[1] = Map.class;
                    Method indexerMethod = ds.getClass().getMethod("setIndexer", params);
                    indexerMethod.invoke(ds, indexer, parameters);
                    // Class[] searchConsParams = new Class[0];
                    Constructor<?> searcherConst = Class.forName("gate.creole.annic.lucene.LuceneSearcher", true, Gate.getClassLoader()).getConstructor();
                    Object searcher = searcherConst.newInstance();
                    Class<?>[] searchParams = new Class<?>[1];
                    searchParams[0] = Class.forName("gate.creole.annic.Searcher", true, Gate.getClassLoader());
                    Method searcherMethod = ds.getClass().getMethod("setSearcher", searchParams);
                    searcherMethod.invoke(ds, searcher);
                    return ds;
                }
            } else {
                validEntry = true;
            }
        }
        return null;
    } catch (Exception e) {
        throw new GateRuntimeException(e);
    }
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) MalformedURLException(java.net.MalformedURLException) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) URL(java.net.URL) DataStore(gate.DataStore) GateRuntimeException(gate.util.GateRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) JList(javax.swing.JList) JComboBox(javax.swing.JComboBox) JLabel(javax.swing.JLabel) Method(java.lang.reflect.Method) ResourceInstantiationException(gate.creole.ResourceInstantiationException) BenchmarkReportException(gate.util.reporting.exceptions.BenchmarkReportException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) PersistenceException(gate.persist.PersistenceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GateRuntimeException(gate.util.GateRuntimeException) MalformedURLException(java.net.MalformedURLException) GateException(gate.util.GateException) Point(java.awt.Point) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) File(java.io.File)

Aggregations

GateRuntimeException (gate.util.GateRuntimeException)42 ArrayList (java.util.ArrayList)12 URL (java.net.URL)6 FeatureMap (gate.FeatureMap)5 PersistenceException (gate.persist.PersistenceException)5 GateException (gate.util.GateException)5 Point (java.awt.Point)5 LinkedList (java.util.LinkedList)5 DataStore (gate.DataStore)4 ResourceInstantiationException (gate.creole.ResourceInstantiationException)4 InvalidOffsetException (gate.util.InvalidOffsetException)4 GridBagConstraints (java.awt.GridBagConstraints)4 GridBagLayout (java.awt.GridBagLayout)4 MalformedURLException (java.net.MalformedURLException)4 List (java.util.List)4 JButton (javax.swing.JButton)4 JPanel (javax.swing.JPanel)4 Annotation (gate.Annotation)3 AnnotationSet (gate.AnnotationSet)3 Corpus (gate.Corpus)3