GUIFrame.java Source code

Java tutorial

Introduction

Here is the source code for GUIFrame.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

/*
 * @author Makli
 */
public final class GUIFrame extends javax.swing.JFrame {

    DefaultListModel<String> DocIDListModel = new DefaultListModel<>();
    DefaultListModel<String> SumListModel = new DefaultListModel<>();
    DefaultListModel<String> TermListModel = new DefaultListModel<>();
    PorterStemAnalyzer myAnalyzer;
    Directory myIndex;
    String userInput;

    /*
     * Creates new form GUIFrame
     */
    public GUIFrame() throws IOException, ParseException {
        initComponents();
        initComponentsVol2();
        myIndex = InitializeIndex(myIndex, myAnalyzer);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        GUIPanel = new javax.swing.JPanel();
        SearchBtn = new javax.swing.JButton();
        SearchField = new javax.swing.JTextField();
        ChartBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Information Retrieval System");
        setResizable(false);

        GUIPanel.setBackground(new java.awt.Color(204, 204, 255));

        SearchBtn.setText("Search");
        SearchBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SearchBtnActionPerformed(evt);
            }
        });

        SearchField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                SearchFieldKeyPressed(evt);
            }
        });

        ChartBtn.setText("Chart");
        ChartBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ChartBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout GUIPanelLayout = new javax.swing.GroupLayout(GUIPanel);
        GUIPanel.setLayout(GUIPanelLayout);
        GUIPanelLayout.setHorizontalGroup(GUIPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(GUIPanelLayout.createSequentialGroup()
                        .addGroup(GUIPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(GUIPanelLayout.createSequentialGroup().addGroup(GUIPanelLayout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(GUIPanelLayout.createSequentialGroup().addGap(417, 417, 417)
                                                .addComponent(SearchBtn))
                                        .addGroup(GUIPanelLayout.createSequentialGroup().addGap(312, 312, 312)
                                                .addComponent(SearchField, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        277, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(0, 318, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        GUIPanelLayout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                                .addComponent(ChartBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 73,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap()));
        GUIPanelLayout.setVerticalGroup(GUIPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, GUIPanelLayout.createSequentialGroup()
                        .addContainerGap(181, Short.MAX_VALUE)
                        .addComponent(SearchField, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55).addComponent(SearchBtn).addGap(74, 74, 74).addComponent(ChartBtn)
                        .addContainerGap()));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(GUIPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                GUIPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                Short.MAX_VALUE));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void initComponentsVol2() throws ParseException {
        setLocationRelativeTo(null);
        SearchBtn.setEnabled(false);
        SetIcon();
        SearchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                DisableBtn();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                DisableBtn();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                DisableBtn();
            }
        });

        // Specifying the analyzer for tokenizing text. The same custom analyzer will be used for indexing and searching
        myAnalyzer = new PorterStemAnalyzer();
    }

    public Directory InitializeIndex(Directory Index, PorterStemAnalyzer Analyzer) throws IOException {
        // Create the index
        Index = new RAMDirectory();
        IndexWriterConfig myConfig = new IndexWriterConfig(Version.LATEST, Analyzer);
        try (IndexWriter indoWriter = new IndexWriter(Index, myConfig)) {
            BufferedReader buffR = new BufferedReader(new FileReader("npl\\doc-text"));
            String currLine;
            StringBuilder idDoc = new StringBuilder();
            StringBuilder sumDoc = new StringBuilder();
            currLine = buffR.readLine();

            while (currLine != null) {
                if (currLine.matches(".*\\d+.*")) { // Check if current line contains a document's id
                    // Capture the document's id and summary
                    idDoc.append(currLine);
                    currLine = buffR.readLine();

                    // While the reader holds line of summary
                    while (!(currLine.contains("/"))) {
                        sumDoc.append(currLine).append(" ");
                        currLine = buffR.readLine();
                    }

                    // Add the new document to the index
                    AddDocument(indoWriter, idDoc.toString(), sumDoc.toString());

                    //System.out.println(idDoc.toString());
                    //System.out.println(sumDoc.toString());

                    // Clear the string builders
                    idDoc.delete(0, idDoc.length());
                    sumDoc.delete(0, sumDoc.length());

                    // Continue to next line
                    currLine = buffR.readLine();
                } else {
                    // Continue to next line
                    currLine = buffR.readLine();
                }
            }

        }

        return Index;
    }

    public void DisableBtn() {
        if (SearchField.getText().equals("")) {
            SearchBtn.setEnabled(false);
        } else if (SearchField.getText().trim().isEmpty()) {
            SearchBtn.setEnabled(false);
        } else {
            SearchBtn.setEnabled(true);
        }
    }

    private void SearchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchBtnActionPerformed
        userInput = SearchField.getText();
        try {
            int hits = SearchResults(myAnalyzer, myIndex, userInput, DocIDListModel);
            if (hits != 0) {
                ResultsDialog myResults = new ResultsDialog(this, true, DocIDListModel, SumListModel,
                        TermListModel);
                myResults.setVisible(true);
                DocIDListModel.clear();
                SumListModel.clear();
                TermListModel.clear();
            } else {
                JOptionPane.showMessageDialog(null, "No relevant documents were found.", "Search Result",
                        JOptionPane.INFORMATION_MESSAGE);
                TermListModel.clear();
            }
        } catch (ParseException | IOException ex) {
            Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_SearchBtnActionPerformed

    private void SearchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_SearchFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (SearchBtn.isEnabled()) {
                userInput = SearchField.getText();
                try {
                    int hits = SearchResults(myAnalyzer, myIndex, userInput, DocIDListModel);
                    if (hits != 0) {
                        ResultsDialog myResults = new ResultsDialog(this, true, DocIDListModel, SumListModel,
                                TermListModel);
                        myResults.setVisible(true);
                        DocIDListModel.clear();
                        SumListModel.clear();
                        TermListModel.clear();
                    } else {
                        JOptionPane.showMessageDialog(null, "No relevant documents were found.", "Search Result",
                                JOptionPane.INFORMATION_MESSAGE);
                        TermListModel.clear();
                    }
                } catch (ParseException | IOException ex) {
                    Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_SearchFieldKeyPressed

    @SuppressWarnings("null")
    private void ChartBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChartBtnActionPerformed
        // Create and show the chart frame
        ChartFrame chartFrame = null;

        try {
            chartFrame = new ChartFrame(myAnalyzer, myIndex);
        } catch (IOException | ParseException ex) {
            Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        chartFrame.setTitle("Query Choice");
        chartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        chartFrame.setResizable(false);
        chartFrame.pack();
        chartFrame.setLocationRelativeTo(this);
        chartFrame.setVisible(true);
    }//GEN-LAST:event_ChartBtnActionPerformed

    public int SearchResults(PorterStemAnalyzer Analyzer, Directory Index, String userInput,
            DefaultListModel DocList) throws ParseException, IOException {
        // The query
        userInput = userInput.replace("\"", "");
        Query q = new QueryParser(Version.LATEST, "summary", Analyzer).parse(userInput);

        // The search
        int hitsPerPage = 20; // return 20 top documents
        IndexReader indoReader = DirectoryReader.open(Index);
        IndexSearcher indoSearcher = new IndexSearcher(indoReader);
        TopScoreDocCollector docCollector = TopScoreDocCollector.create(hitsPerPage, true);
        indoSearcher.search(q, docCollector);
        ScoreDoc[] hits = docCollector.topDocs().scoreDocs;

        // Copy results to list models
        for (int i = 0; i < hits.length; ++i) {
            int docId = hits[i].doc;
            Document d = indoSearcher.doc(docId);
            DocList.addElement(d.get("docID"));
            SumListModel.addElement(d.get("summary"));
        }

        GetTerms(Index, Analyzer, "summary", userInput);

        return hits.length;
    }

    private void AddDocument(IndexWriter indoWriter, String docID, String summary) throws IOException {
        Document doc = new Document();
        Field docIDField = new TextField("docID", docID, Field.Store.YES);
        Field sumField = new TextField("summary", summary, Field.Store.YES);

        doc.add(docIDField);
        doc.add(sumField);

        indoWriter.addDocument(doc);
    }

    protected void GetTerms(Directory Index, PorterStemAnalyzer Analyzer, String field, String queryString)
            throws IOException, ParseException {
        Set<Term> results;

        IndexReader indoReader = DirectoryReader.open(Index);

        QueryParser qp = new QueryParser(Version.LUCENE_30, field, Analyzer);
        Query query = qp.parse(queryString);

        query.rewrite(indoReader);
        results = new HashSet<>();
        query.extractTerms(results);

        Iterator<Term> iterator = results.iterator();
        while (iterator.hasNext()) {
            String term = iterator.next().toString();
            TermListModel.addElement(term.substring(8));
        }
    }

    public void SetIcon() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("IRicon.png")));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new GUIFrame().setVisible(true);
                } catch (IOException | ParseException ex) {
                    Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ChartBtn;
    private javax.swing.JPanel GUIPanel;
    private javax.swing.JButton SearchBtn;
    private javax.swing.JTextField SearchField;
    // End of variables declaration//GEN-END:variables

}