
////////////////////////////////////////////
//
//    sr.java    version 1.11
//
//    Search and Replace with GUI User Interface 
//    
//    This program with search for and replace a single string in multiple
//    files and multiple directories.
//    
//    Created 4/14/96 by Kenny A. Chaffin
//    Last updated 6/15/96 by Kenny A. Chaffin
//    Updated 6/15/96 by Kenny A. Chaffin -- adjusted size/color for jdk 1.02
//
//    Copyright (c) 1996 Kenny A. Chaffin. All Rights Reserved
//
//
// Note: This is not commercial software and the author makes no warranties
// about the suitability of this software for any system. The author shall 
// not be liable for any damages suffered as a result of anyone using, modifying,
// or distributing this software or its derivatives.
//
// Feel free to copy, modify, and distribute this program provided you 
// leave the above information intact.
//
////////////////////////////////////////////

import java.awt.*;
import java.io.*;

// support Classes *********

class EndsWithFilter implements FilenameFilter
  {
    private String extension;
    public EndsWithFilter(String extension)
      {
        this.extension = extension;
      }
    public boolean accept(File dir, String name)
      {
        if (name.endsWith(extension)) return true;
        else return (new File(dir, name)).isDirectory();
      }
  }

class procdir1
    {
       
  public String[] list_directory(String directory,  FilenameFilter filter) throws IOException
      {
        File cwd;      
        String[] entries;

        File dir = new File(directory);
        
        if (!dir.isDirectory())
          throw new IllegalArgumentException("list_directory: no such directory");
        cwd = dir;
        
        entries = cwd.list(filter);
        return entries;       
      }

    
  public static String Replace(String line, String findString, String repString)
    {				//Replace a string in the supplied line
        StringBuffer newstring;
        int position;
        
        newstring = new StringBuffer();

        if ((position = line.indexOf(findString)) != -1)
           { 
             newstring.append(line.substring(0, position));
             newstring.append(repString);
             position = position + findString.length();
             newstring.append(line.substring(position, line.length()));
             return newstring.toString();
           }
         else
           {
             newstring.append(line);
             return newstring.toString();
           }
      }

     public procdir1(sr WhereToPrint, String dir, String ext, String sstring, String rstring, boolean dosubdirs) throws IOException
      {
        FilenameFilter filter = null;
        String directory = null;
        FileInputStream in = null;
        FileOutputStream out = null;
        String line;
        StringBuffer newfilename;
        StringBuffer backupname;
	int position;
	File testfile = null;
	File backupfile = null;
	File outfile = null;
	File tempfile = null;
	File WorkingDirectory = null;
	procdir1 p;
	String[] entries;
	
	
    filter = new EndsWithFilter(ext);
    entries = list_directory(dir, filter);
    WorkingDirectory = new File(dir);
        
// we've got the file list in entries[]
// process them here
    
//    WhereToPrint.OutputArea.appendText("Here we go.\n");
    WhereToPrint.OutputArea.appendText("Processing directory: " + WorkingDirectory + "\n");
    
//    for (int i=0; i < entries.length; i++)   //for testing
//      WhereToPrint.OutputArea.appendText(entries[i] + "\n");
 
    for (int i=0; i < entries.length; i++)
     { 
       try
         {testfile = new File(WorkingDirectory, entries[i]);}   //set up new file name
       catch(Throwable e)
         { 
           WhereToPrint.OutputArea.appendText("Error opening file: " + entries[i] + "\n");
           System.exit(1);
         }
  
       if (testfile.isFile())
        {    
           in = new FileInputStream(testfile);
           newfilename = new StringBuffer();
           backupname = new StringBuffer();		//for renaming

           if ((position = entries[i].indexOf('.')) != -1)
              { 
                newfilename.append(entries[i].substring(0, position));
                newfilename.append(".out");
                backupname.append(entries[i].substring(0, position));
                backupname.append(".old");
                
              }
              
	   WhereToPrint.OutputArea.appendText("   " + entries[i] + "\n");
//           System.out.println(newfilename.toString());
           out = new FileOutputStream(new File(WorkingDirectory, newfilename.toString()));
           backupfile = new File(WorkingDirectory, backupname.toString());
           outfile = new File(WorkingDirectory, newfilename.toString());
      
       DataInputStream datainfile = new DataInputStream(in);
       DataOutputStream dataoutfile = new DataOutputStream(out);
       try
         {
           while ((line = datainfile.readLine()) != null)
             {			//  process lines here            
                dataoutfile.writeBytes(Replace(line, sstring, rstring) + "\r\n");
//                System.out.println(Replace(line, sstring, rstring));
             }
           
           in.close();
           out.close();
           if (backupfile.exists())        // if there's an old one get rid of it 
             backupfile.delete();
           tempfile = testfile;
           testfile.renameTo(backupfile);
           outfile.renameTo(tempfile);           
         }
       catch(IOException e)
         {
//           System.out.println("I/O Error");
	   WhereToPrint.OutputArea.appendText("I/O Error");           
           System.exit(1);
         }
      }
     else
       {
         if (dosubdirs)
           {
             p = new procdir1(WhereToPrint, WorkingDirectory + "\\" + entries[i], ext, sstring, rstring, dosubdirs);
           };
       }
    }
  }
}

// End Support Classes *****



public class sr extends Frame
{

    TextArea OutputArea;
    TextField BeginDirectory;
    TextField FileExtension;
    TextField SearchStr;
    TextField ReplaceStr;
    Checkbox DoSubs;
    
    
public sr(String title)
  {
    setTitle(title);
    setBackground(Color.lightGray);
    resize(425,400);
    setLayout(new FlowLayout());
    SearchStr = new TextField(30);
    add(new Label("   Search String :     "));
    add(SearchStr);
    add(new Label("Replacement String : "));
    ReplaceStr = new TextField(30);
    add(ReplaceStr);
    add(new Label("File Type (extension) : "));
    FileExtension = new TextField(30);
    add(FileExtension);
    add(new Label("Beginning Directory : "));
    BeginDirectory = new TextField(30);
    add(BeginDirectory);
    add (new Label("Replace in Subdirectories : "));
    DoSubs = new Checkbox();
    add(DoSubs);
    add(new Button("Quit"));
    add(new Button("Do it!"));
    add(new Button("Clear"));
    OutputArea = new TextArea(10,50);
    add(OutputArea);
    show();
 
  }


public boolean handleEvent(Event e)
  { 
    if (e.id == Event.WINDOW_DESTROY)
      {
        System.exit(0);
        return true;
      }
    else
      {
        return super.handleEvent(e);
      }
  }


public boolean action(Event evt, Object arg)
  {
        String label = (String)arg;
        procdir1 p;
        
        if (label.equals("Quit"))
          {
            System.exit(0);
          }
        if (label.equals("Do it!"))
          {    
            String directory;
            directory = BeginDirectory.getText();
            if (directory == null) directory = System.getProperty("user.dir");
            try 
              {
                p = new procdir1(this, directory, FileExtension.getText(), SearchStr.getText(), ReplaceStr.getText(), DoSubs.getState());
//                OutputArea.appendText(directory + " , " + FileExtension.getText() + " , " + SearchStr.getText() + " , " + ReplaceStr.getText());
              } 
            catch (IOException e) {System.out.println(e);} 
            OutputArea.appendText("Done.\n");
          }

        if (label.equals("Clear"))
          {
            OutputArea.setText("");	//clear it
            SearchStr.setText("");	//clear it
            ReplaceStr.setText("");	//clear it
            BeginDirectory.setText("");	//clear it
            FileExtension.setText("");	//clear it
            DoSubs.setState(false);     //clear it
          }
     return true;
  }
         

public static void main(String[] args)
  {
     new sr("sr.java  -  Version 1.11");  //set up the interface and get input.
  }
 }
