1 19 20 package org.netbeans.nbbuild; 21 22 import java.io.*; 23 import java.util.*; 24 25 import org.apache.tools.ant.*; 26 27 37 @Deprecated 38 public class Postprocess extends Task { 39 40 private File file; 41 42 private String oldString; 43 44 private String newString; 45 46 private int min = 0; 47 48 private int max = 1; 49 50 53 public void setFile (File f) { 54 this.file = f; 55 } 56 57 59 public void setOld (String s) { 60 this.oldString = s; 61 } 62 63 65 public void setNew (String s) { 66 this.newString = s; 67 } 68 69 71 public void setMin (int m) { 72 this.min = m; 73 } 74 75 77 public void setMax (int m) { 78 this.max = m; 79 } 80 81 public void execute () throws BuildException { 82 if (file == null) { 83 throw new BuildException ("A file must be specified"); } 85 86 if ( 87 oldString == null || newString == null || 88 oldString.length() != newString.length() 89 ) { 90 throw new BuildException ("New and old strings must be specified and they must have the same length"); } 92 93 try { 94 int len = (int)file.length(); 95 byte[] b = new byte[len]; 96 FileInputStream is = new FileInputStream (file); 97 try { 98 if (is.read(b) != len) throw new BuildException("Failed to read whole file", getLocation()); 99 } finally { 100 is.close (); 101 } 102 103 int cnt = replaceString (b); 104 105 if (cnt < min || cnt > max) { 106 throw new BuildException ("String " + oldString + " found " + cnt + " times, that is out of min/max range"); } 108 109 if (cnt > 0) { 110 log ("Replaced `" + oldString + "' by `" + newString + "' " + cnt + " times in " + file); 111 FileOutputStream os = new FileOutputStream (file); 112 try { 113 os.write (b); 114 } finally { 115 os.close (); 116 } 117 } 118 119 } catch (IOException ex) { 120 throw new BuildException (ex); 121 } 122 } 123 124 125 129 private int replaceString (byte[] b) { 130 131 try { 132 133 String arr = new String (b, "ISO8859_1"); 135 int cnt = 0; 136 int pos = -1; 137 138 byte[] newbytes = newString.getBytes("ISO8859_1"); 139 if (newbytes.length != oldString.getBytes("ISO8859_1").length) { 140 throw new BuildException("Strings to replace must be equal in length", getLocation()); 141 } 142 while ((pos = arr.indexOf(oldString, pos + 1)) != -1) { 143 System.arraycopy(newbytes, 0, b, pos, newbytes.length); 144 cnt++; 145 } 146 147 return cnt; 148 149 } catch (UnsupportedEncodingException e) { 150 throw new BuildException("Error replacing text", e, getLocation()); 151 } 152 } 153 154 } 155 | Popular Tags |