You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Replace.java 8.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 1999 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.taskdefs;
  55. import org.apache.tools.ant.*;
  56. import java.io.*;
  57. import java.util.*;
  58. /**
  59. * Replaces all the occurrences of the given string token with the given
  60. * string value of the indicated files.
  61. *
  62. * @author Stefano Mazzocchi <a href="mailto:stefano@apache.org">stefano@apache.org</a>
  63. * @author <a href="mailto:erik@desknetinc.com">Erik Langenbach</a>
  64. */
  65. public class Replace extends MatchingTask {
  66. private File src = null;
  67. private NestedString token = null;
  68. private NestedString value = new NestedString();
  69. private File dir = null;
  70. public class NestedString {
  71. private StringBuffer buf = new StringBuffer();
  72. public void addText(String val) {
  73. buf.append(val);
  74. }
  75. public String getText() {
  76. return buf.toString();
  77. }
  78. }
  79. /**
  80. * Do the execution.
  81. */
  82. public void execute() throws BuildException {
  83. if (token == null) {
  84. throw new BuildException("replace token must not be null", location);
  85. }
  86. if (token.getText().equals("")) {
  87. throw new BuildException("replace token must not be empty", location);
  88. }
  89. if (src == null && dir == null) {
  90. throw new BuildException("Either the file or the dir attribute must be specified", location);
  91. }
  92. log("Replacing " + token.getText() + " --> " + value.getText());
  93. if (src != null) {
  94. processFile(src);
  95. }
  96. if (dir != null) {
  97. DirectoryScanner ds = super.getDirectoryScanner(dir);
  98. String[] srcs = ds.getIncludedFiles();
  99. for(int i=0; i<srcs.length; i++) {
  100. File file = new File(dir,srcs[i]);
  101. processFile(file);
  102. }
  103. }
  104. }
  105. /**
  106. * Perform the replacement on the given file.
  107. *
  108. * The replacement is performed on a temporary file which then replaces the original file.
  109. *
  110. * @param src the source file
  111. */
  112. private void processFile(File src) throws BuildException {
  113. if (!src.exists()) {
  114. throw new BuildException("Replace: source file " + src.getPath() + " doesn't exist", location);
  115. }
  116. File temp = new File(src.getPath() + ".temp");
  117. if (temp.exists()) {
  118. throw new BuildException("Replace: temporary file " + temp.getPath() + " already exists", location);
  119. }
  120. try {
  121. BufferedReader br = new BufferedReader(new FileReader(src));
  122. BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
  123. // read the entire file into a char[]
  124. int fileLength = (int)(src.length());
  125. char[] tmpBuf = new char[fileLength];
  126. int numread = 0;
  127. int totread = 0;
  128. while (numread != -1 && totread < fileLength) {
  129. numread = br.read(tmpBuf,totread,fileLength);
  130. totread += numread;
  131. }
  132. // create a String so we can use indexOf
  133. String buf = new String(tmpBuf);
  134. // line separators in values and tokens are "\n"
  135. // in order to compare with the file contents, replace them
  136. // as needed
  137. String linesep = System.getProperty("line.separator");
  138. String val = stringReplace(value.getText(), "\n", linesep);
  139. String tok = stringReplace(token.getText(), "\n", linesep);
  140. // for each found token, replace with value
  141. String newString = stringReplace(buf, tok, val);
  142. boolean changes = !newString.equals(buf);
  143. if (changes) {
  144. bw.write(newString,0,newString.length());
  145. bw.flush();
  146. }
  147. // cleanup
  148. bw.close();
  149. br.close();
  150. // If there were changes, move the new one to the old one, otherwise, delete the new one
  151. if (changes) {
  152. src.delete();
  153. temp.renameTo(src);
  154. } else {
  155. temp.delete();
  156. }
  157. } catch (IOException ioe) {
  158. ioe.printStackTrace();
  159. throw new BuildException(ioe, location);
  160. }
  161. }
  162. /**
  163. * Set the source file.
  164. */
  165. public void setFile(File file) {
  166. this.src = file;
  167. }
  168. /**
  169. * Set the source files path when using matching tasks.
  170. */
  171. public void setDir(File dir) {
  172. this.dir = dir;
  173. }
  174. /**
  175. * Set the string token to replace.
  176. */
  177. public void setToken(String token) {
  178. createReplaceToken().addText(token);
  179. }
  180. /**
  181. * Set the string value to use as token replacement.
  182. */
  183. public void setValue(String value) {
  184. createReplaceValue().addText(value);
  185. }
  186. /**
  187. * Nested <replacetoken> element.
  188. */
  189. public NestedString createReplaceToken() {
  190. if (token == null) {
  191. token = new NestedString();
  192. }
  193. return token;
  194. }
  195. /**
  196. * Nested <replacevalue> element.
  197. */
  198. public NestedString createReplaceValue() {
  199. return value;
  200. }
  201. /**
  202. * Replace occurrences of str1 in string str with str2
  203. */
  204. private String stringReplace(String str, String str1, String str2) {
  205. StringBuffer ret = new StringBuffer();
  206. int start = 0;
  207. int found = str.indexOf(str1);
  208. while (found >= 0) {
  209. // write everything up to the found str1
  210. if (found > start) {
  211. ret.append(str.substring(start, found));
  212. }
  213. // write the replacement str2
  214. if (str2 != null) {
  215. ret.append(str2);
  216. }
  217. // search again
  218. start = found + str1.length();
  219. found = str.indexOf(str1,start);
  220. }
  221. // write the remaining characters
  222. if (str.length() > start) {
  223. ret.append(str.substring(start, str.length()));
  224. }
  225. return ret.toString();
  226. }
  227. }