Sunday, March 10, 2013

A Java Code Searcher


Recently, in my computer, I noticed by accident that the "File Search" functionality in my Eclipse Helios is broken, and I don't know why. Whenever I press Ctrl + H, click the File Search tab, input a string I want to search, and click the search button, the result is always "0 matches in working space." After searching the Internet a while to look forward a solution, I still haven't found one. Thus, I wrote a simple but useful executable jar application for searching codes inside a project. The following are the codes and a tutorial about how to it.

Step 1: Download the CodeSearcher.jar from https://sites.google.com/site/moderntone/CodeSearcher.jar?attredirects=0&d=1

Step 2: Copy the CodeSearcher.jar to the project folder



Step 3: Click the jar file, type the string you want to search in your project codes, and found lines are immediately shown in the JScrollPane. You can also press the Enter key to refresh the JScrollPane.




You can also configure the CodeSearcher.java on your own and compile a new code searcher. For example, to search codes in a C# project or other types to files, you can assign "new String[] {".cs", ".log"};" instead of "new String[] {".java"};" to the static final String[] extensions. If you want to search the whole workspace, copy the CodeSearch.jar to your workspace folder.

CodeSearcher.java

package com.codesearcher;

import java.io.File;
import java.util.ArrayList;

public class CodeSearcher {
 
 private static final String[] extensions = new String[] {".java"};
 private String fileOrDirectoryPath;
 private ArrayList files;
 
 public CodeSearcher(String fileOrDirectoryPath) {
  this.fileOrDirectoryPath = fileOrDirectoryPath;
 }

 public CodeSearcher(){
  String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
  this.fileOrDirectoryPath = path.substring(1, path.lastIndexOf("/"));
  files = getAllFiles();
 }
 
 public ArrayList getAllFiles(){
  if (files == null){
   ArrayList files = new ArrayList();
   File directoryOrFile = new File(fileOrDirectoryPath);
   if (!directoryOrFile.exists())
    return files;
   
   File[] listOfFiles = directoryOrFile.listFiles(); 
   if (listOfFiles == null){
    boolean fitsExtension = false;
    for (String extension : extensions){
     if (directoryOrFile.getAbsolutePath().endsWith(extension))
      fitsExtension = true;
    }
    if (fitsExtension) files.add(directoryOrFile);
    return files;
   }
   else {
    for (File file : listOfFiles){
     CodeSearcher searcher = new CodeSearcher(file.getAbsolutePath());
     files.addAll(searcher.getAllFiles());
    }
    return files;
   }
  }
  return files;
  
 }

 public ArrayList searchLines(ArrayList allLines, String target){
  ArrayList linesFound = new ArrayList();
  String targetToLowerCase = target.toLowerCase();
  
  for (String line : allLines){
   int indexOfColonPlus1 = line.indexOf(":") + 1;
   String lineToLowerCase = line.substring(indexOfColonPlus1).toLowerCase();
   if (lineToLowerCase.contains(targetToLowerCase))
    linesFound.add(line);
  }
  return linesFound;
 }
}

Main.java

package com.codesearcher;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import javax.swing.border.*;

public class Main extends JFrame {

 private static final long serialVersionUID = 1L;
 private JPanel contentPane;
 private JTextField textField;
 private JTextArea textArea;
 
 private static ArrayList allFiles;
 private static ArrayList allLines;
 private static CodeSearcher codeSearcher;
 
 private static Main frame;
 public static void main(String[] args) {
  
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     frame = new Main();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
  
  codeSearcher = new CodeSearcher();
  allFiles = codeSearcher.getAllFiles();
  setAllLines(allFiles);
 }


 public Main() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(300, 100, 700, 500);
  setResizable(false);
  setTitle("Code Searcher");
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  contentPane.setLayout(null);
  setContentPane(contentPane);
  
  textField = new JTextField();
  textField.setFont(new Font("Tahoma", Font.PLAIN, 15));
  textField.setBounds(259, 60, 180, 27);
  textField.addKeyListener(new KeyListener() {
   
   @Override
   public void keyTyped(KeyEvent arg0) {
   }
   
   @Override
   public void keyReleased(KeyEvent arg0) {
   }
   
   @Override
   public void keyPressed(KeyEvent arg0) {
    performAction();
   }
  });
  contentPane.add(textField);
  
  JLabel lblInputTextTo = new JLabel("Input text to search codes");
  lblInputTextTo.setFont(new Font("Century", Font.PLAIN, 18));
  lblInputTextTo.setForeground(Color.BLUE);
  lblInputTextTo.setBounds(242, 23, 220, 27);
  contentPane.add(lblInputTextTo);
  
  textArea = new JTextArea();
  textArea.setFont(new Font("Microsoft New Tai Lue", Font.PLAIN, 12));
  textArea.setEditable(false);
  textArea.setBorder(new EtchedBorder(EtchedBorder.RAISED, Color.MAGENTA, null));
  textArea.setBounds(48, 110, getWidth() - 100, 300);
  JScrollPane scrollPane = new JScrollPane(textArea,  
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  scrollPane.setBounds(48, 110, 600, 300);

  contentPane.add(scrollPane);
  
  JButton btnClear = new JButton("Clear");
  btnClear.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    textArea.setText("");
   }
  });
  btnClear.setBounds(317, 424, 74, 23);
  contentPane.add(btnClear);
  
  JButton btnSearch = new JButton("Search");
  btnSearch.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    performAction();
   }
  });
  btnSearch.setBounds(459, 61, 81, 25);
  contentPane.add(btnSearch);
 }
 
 private static void setAllLines(ArrayList files){
  if (allLines != null)
   return;
  
  allLines = new ArrayList();
  for (File javaFile : files){
   try {
    FileReader read = new FileReader(javaFile);
    BufferedReader reader = new BufferedReader(read);
    String line; 
    int count = 1;
    while ((line = reader.readLine()) != null) {
     line = javaFile.getName() + " " + count + " : " + line;
     allLines.add(line);
     count++;
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
 }
 
 private void performAction(){
  ArrayList linesFound = 
   codeSearcher.searchLines(allLines, textField.getText());
  StringBuilder builder = new StringBuilder();
  for (String foundLine : linesFound){
   builder.append(foundLine + "\n");
  }
  textArea.setText(builder.toString());
 }
}

No comments:

Post a Comment