package com.arsdigita.content;

import java.lang.reflect.*;
import java.sql.*;
import java.util.*;
import java.io.*;

import oracle.sql.*;
import oracle.jdbc.driver.*;

import sqlj.runtime.ref.DefaultContext;
import oracle.sqlj.runtime.Oracle;

import com.oroinc.text.perl.*;

public class Regexp {

  /** 
      Search for a pattern and replace it with another pattern 
      The patterns may be any valid Perl5 regular expressions
  **/

  public static boolean replace(int revisionID, String search, String replace) 
    throws SQLException, IOException, MalformedPerl5PatternException {

    Perl5Util util = new Perl5Util();
    String content;

    #sql { select blob_to_string(content) into :content from cr_revisions
      where revision_id = :revisionID };

    boolean hasMatch = util.match("/" + search + "/", content);
    if (hasMatch) {

      String pattern = "s/" + search + "/" + replace + "/";

      content = util.substitute(pattern, content);
      Integer copyID;
      BLOB blob;

      #sql {
        begin
          :OUT copyID := content_revision.copy(:revisionID);
        end;
      };

      #sql { select content into :blob from cr_revisions 
          where revision_id = :copyID };

      if (blob != null) 
	blob.putBytes(1, content.getBytes());
    }

    return hasMatch;
  }
}
 










