Member Avatar for loserspearl
loserspearl

I've been working on a search engine that users manually add files to, build and inversed index, and can search some text and the program will saw which files have that text in them, you can choose and, or, or phrase search (just working on and & or search at the moment). I'm just confused about how to read collections, I believe I have the collection built right.

Here is the main search class

/* GUI program that allows users to manually add files to an index
 * and search the content of them for specific words 
 * 
 */
package project3;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class SearchEngine extends JFrame {
    
    /**
     * @param args the command line arguments
     */
    //defining GUI objects used
    JRadioButton andRB, orRB, phraseRB;
    BtnListener BL = new BtnListener();
    JButton srchBtn, fileBtn, aboutBtn;
    JLabel titleLbl, srchLbl, infoLbl;
    JTextArea srchTxt;
    
    public void srchGUI() {
        
        //building of the the frame
        LayoutManager lo;
        lo = new FlowLayout();
        this.setLayout(lo);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("FileSearch NGEN");
        this.setSize(400,200);
        this.addWindowListener( new WindowAdapter()
            {@Override
            public void windowClosing ( WindowEvent we )
                { System.exit( 0 ); }
            }
        );
        this.setLocation(150, 150);
        
       
        //defining GUI objects
        titleLbl = new JLabel("FileSearch NGEN");
        titleLbl.setFont(new Font("SansSeriff", Font.BOLD, 20));

        Font stdFont = new Font("SanSeriff", Font.PLAIN, 14);
        srchLbl = new JLabel("Search: ");
        srchLbl.setFont(stdFont);

        infoLbl = new JLabel("        FileSearch v1.2        ");
        infoLbl.setFont(new Font("SanSeriff", Font.PLAIN, 12));

        srchBtn = new JButton("Search");
        srchBtn.setActionCommand("srchAct");
        srchBtn.setToolTipText("Search files");
        srchBtn.addActionListener(BL);

        fileBtn = new JButton("Files");
        fileBtn.setActionCommand("fileAct");
        fileBtn.setToolTipText("Open file index");
        fileBtn.addActionListener(BL);

        aboutBtn = new JButton("About");
        aboutBtn.setActionCommand("aboutAct");
        aboutBtn.setToolTipText("Information");
        aboutBtn.addActionListener(BL);

        srchTxt = new JTextArea(1, 20);
        srchTxt.setFont(stdFont);
        srchTxt.setEditable(true);

        andRB = new JRadioButton("And");
        orRB = new JRadioButton("Or");
        phraseRB = new JRadioButton("Phrase");

        //adding action listeners and radio button grouping
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(andRB);
        btnGroup.add(orRB);
        btnGroup.add(phraseRB);
        andRB.addActionListener(BL);
        orRB.addActionListener(BL);
        phraseRB.addActionListener(BL);
        
        //ADD OUTPUT DISPLAY AS NECESSARY
        
        //add contents to panels
        JPanel title = new  JPanel();
            title.setLayout(new BorderLayout());
            title.add(titleLbl, BorderLayout.CENTER);
            
        JPanel top = new JPanel();
            top.setLayout(new BorderLayout());
            top.add(srchLbl, BorderLayout.WEST);
            top.add(srchTxt, BorderLayout.CENTER);
            top.add(srchBtn, BorderLayout.EAST);

        JPanel rBtn = new JPanel();
            rBtn.setLayout(new BorderLayout());
            rBtn.add(andRB, BorderLayout.WEST);
            rBtn.add(orRB, BorderLayout.CENTER);
            rBtn.add(phraseRB, BorderLayout.EAST);

        JPanel bot = new JPanel();
            bot.setLayout(new BorderLayout());
            bot.add(fileBtn, BorderLayout.WEST);
            bot.add(infoLbl, BorderLayout.CENTER);
            bot.add(aboutBtn, BorderLayout.EAST);

        //add panels to frame
        this.add(title);
        this.add(top);
        this.add(rBtn);
        this.add(bot);
        this.setVisible(true);
    }                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        new SearchEngine().srchGUI();      

    }

public class BtnListener implements ActionListener {
@Override
    public void actionPerformed(ActionEvent e) {
       String srchStr = srchTxt.getText();
    
        if(e.getSource() == srchBtn)
        {
            if(andRB.isSelected())  {
                Search andSrch = new Search();
                andSrch.andSearch(srchStr);
            }
            else if (orRB.isSelected()) {
                Search orSrch = new Search();
                orSrch.orSearch(srchStr);
            }
            
            else if (phraseRB.isSelected()) {
                Search phraseSrch = new Search();
                phraseSrch.phraseSearch(srchStr);
            }
            else JOptionPane.showMessageDialog(null, "Radio Button Search Error", "Error", JOptionPane.ERROR_MESSAGE);            
        }
        
        else if(e.getSource() == fileBtn)
        {
            new FileViewer().fileGUI();            
        }
        else if("aboutAct".equals(e.getActionCommand()))
        {
            new AboutViewer().aboutGUI(); 
        }
        else
        {
            //debugging
            //JOptionPane.showMessageDialog(null, "Something has gone wrong with actions", "Error", JOptionPane.ERROR_MESSAGE);            
        }
    }
}
        
}

and the class that users add files

/* GUI window that allows users to add, remove, and update the files
 * they want to search through in an index
 */
package project3;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.*;


public class FileViewer extends JFrame {
    //defining objects used
    BtnListener BL = new BtnListener();
    JFileChooser addFile;
    DefaultListModel fileModel, statusModel;
    File tempFile;
    String rdyStr = "File Ready", notStr = "Needs Rebuild";
    public static String[] pathStr = new String[10];
    String[] nameStr = new String[10];
    JLabel titleLbl, fileLbl, statusLbl, spaceLbl;
    JButton addBtn, rmvBtn, updtBtn;
    JList fileList, statusList;

    
    public void fileGUI() {
        LayoutManager lo;

        //building of the the frame
        lo = new FlowLayout();
        this.setLayout(lo);
        this.setTitle("FileSearch NDEX");
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setSize(320,300);
        this.setLocationRelativeTo(null);
                
        titleLbl = new JLabel("   File Search Index   ");
        titleLbl.setFont(new Font("SansSeriff", Font.BOLD, 20));
        
        Font stdFont = new Font("SanSeriff", Font.PLAIN, 14);
        fileLbl = new JLabel("File Name     ");
        fileLbl.setFont(stdFont);
        
        statusLbl = new JLabel("Status        ");
        statusLbl.setFont(stdFont);
        
        spaceLbl = new JLabel("   ");
        spaceLbl.setFont(stdFont);
        
        fileModel = new DefaultListModel();
        fileList = new JList(fileModel);
        fileList.setSelectionMode(NORMAL);
        fileList.setLayoutOrientation(JList.VERTICAL);
        fileList.setVisibleRowCount(-1);
        
        statusModel = new DefaultListModel();
        statusList = new JList(statusModel);
        statusList.setSelectionMode(NORMAL);
        statusList.setLayoutOrientation(JList.VERTICAL);
        statusList.setVisibleRowCount(-1);

        addBtn = new JButton("Add");
        addBtn.setActionCommand("srchAct");
        addBtn.setToolTipText("Add files to the index");
        addBtn.addActionListener(BL);
        
        rmvBtn = new JButton("Remove");
        rmvBtn.setToolTipText("Remove files from the index");
        rmvBtn.addActionListener(BL);
        
        updtBtn = new JButton("Rebuild");
        updtBtn.setToolTipText("Update the indexed files");
        updtBtn.addActionListener(BL);
        
        JPanel title = new  JPanel();
            title.setLayout(new BorderLayout());
            title.add(titleLbl, BorderLayout.CENTER);
            
        JPanel top = new JPanel();
            top.setLayout(new BorderLayout());
            top.add(fileLbl, BorderLayout.WEST);
            top.add(spaceLbl, BorderLayout.CENTER);
            top.add(statusLbl, BorderLayout.EAST);
            
        JPanel mid = new JPanel();
            mid.setLayout(new BorderLayout());
            mid.add(fileList, BorderLayout.WEST);
            mid.add(spaceLbl, BorderLayout.CENTER);
            mid.add(statusList, BorderLayout.EAST);
            
        JPanel bot = new JPanel();
            bot.setLayout(new BorderLayout());
            bot.add(addBtn, BorderLayout.WEST);
            bot.add(rmvBtn, BorderLayout.CENTER);
            bot.add(updtBtn, BorderLayout.EAST);
            
        this.add(title);
        this.add(top);
        this.add(mid);
        this.add(bot);                  
        this.setVisible(true);     
    }
    //for command line debugging        
    public static void main(String args[]) {
        new FileViewer().fileGUI();

    }

public class BtnListener implements ActionListener {
@Override
    public void actionPerformed(ActionEvent e) {
    int i = 0;
    if(e.getSource() == addBtn)

        {
            //possible new addfile indexing class
            addFile = new JFileChooser();
            if (addFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                tempFile = addFile.getSelectedFile();
                    try {
                        //absolute path for location and file name for viewing
                        pathStr[i] = tempFile.getCanonicalPath();
                    } catch (IOException fileEx) {
                        JOptionPane.showMessageDialog(null, "File " + i + " canonical path error: " + fileEx.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                    }
                nameStr[i] = tempFile.getName();
                fileModel.addElement(nameStr[i]);
                statusModel.addElement(notStr);
                                      
                
                i++;
            }
            else
                JOptionPane.showMessageDialog(null, "No file has been selected to add", "No File to Add", JOptionPane.INFORMATION_MESSAGE);

        }
        else if(e.getSource() == rmvBtn)
        {
            if (fileList.getSelectedIndex() != -1) {
                int rmvIndex = fileList.getSelectedIndex();
                fileModel.remove(rmvIndex);
                statusModel.remove(rmvIndex);
            }
            //opens new removefile indexing class
            else 
                JOptionPane.showMessageDialog(null, "No file has been selected to remove", "No File to Remove", JOptionPane.INFORMATION_MESSAGE);
                        
        }
        else if(e.getSource() == updtBtn)
        {
            
            statusModel.clear();
            while (i > 0) {
                statusModel.addElement(rdyStr);
                --i;
            }

            //passing the array of conical paths to the indexer
            ReadFiles r = new ReadFiles();
            r.ReadsFileToIndex(pathStr);
       
            WriteIndex wi = new WriteIndex();
            wi.writeIndexFile(pathStr);
 
        }
        else
        {
            //debugging
            JOptionPane.showMessageDialog(null, "Something has gone wrong with File Index action", "Error", JOptionPane.ERROR_MESSAGE);            
        }
    }
}

}

and the building of the collection

/* Reads and records the content of files located in the array
 * and builds an inverse index collection of the files' contents
 */
package project3;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 *
 * @author BJ Fink
 */

  // Create a file index

public class ReadFiles {
static HashMap <String, Set<int []>> WordsIndexedMap = new HashMap<>();
Integer FileID;

//HashMap LocationIndexMap = new HashMap(); 
//Set WordPositionSet = new HashSet(); 

    public  void ReadsFileToIndex(String[] FilesArray){
        //reads the files and creates the indexes
         int FileCount = 0;
        
        while (FileCount < FilesArray.length){
            openFile(FilesArray[FileCount],FileCount);
            closeFile();
            FileCount ++;
        }

    }
    
    private Scanner FileScanner;
    
    //opens the file
    public void openFile(String fileLoc,int FileCount){
       try{
           FileScanner = new Scanner(new File(fileLoc));           
           readFiles(FileCount);
       } 
       catch(Exception e){
           System.out.println("File Not Found!");
       }           
    }
    
    
    //closes the file
    public void closeFile(){FileScanner.close();}       
    
    
    //reads the file
    public void readFiles(int FileNum){
      int WordCounter = 1; 
      
        while(FileScanner.hasNext()){
            //reads next word in the file
            String word = FileScanner.next();
            //checks to see if is in the FilesMap
            CheckForWord(word,FileNum,WordCounter);
                 // System.out.println(word);
            WordCounter++;
        }
    }

    
    //checks to see if is in the FilesMap
    public void CheckForWord(String CheckWord,int FileNum, int wordCounter){
        //Checks to see if the word has already been add to the index  
        //and if not writes it to the Word
        
    
    //iterates through the WordsIndexedMap to find the current word
     Set<int []> wordLocationSet = WordsIndexedMap.get(CheckWord); 
   
    if (wordLocationSet == null){
        //Create a new WordLocationSet Object
          wordLocationSet = new  HashSet<>();
          WordsIndexedMap.put(CheckWord,wordLocationSet);
    }
        //create a new document loaction object
        int[] array_WordLoc = {FileNum,wordCounter};                  
        wordLocationSet.add(array_WordLoc);
        
    }
        
}

A seperate Search class with mothods corresponding to radio buttons is used for actual search operations. The collection has a word (or key) and a pair of numbers, the pair is what file and the offset of where that word is located (the offset is only used for phrase searchning). How can I read the word from the collection and give the corrseponding file(s) to that word?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.