source: main/trunk/ant-tasks/src/org/greenstone/anttasks/InsertUniqueValue.java@ 22480

Last change on this file since 22480 was 22480, checked in by sjm84, 14 years ago

Added an ant task that will insert a unique number to the end of a tokens that match the given pattern

  • Property svn:executable set to *
File size: 9.1 KB
Line 
1/*
2 * InsertUniqueValue.java
3 * A task to replace occurences of a given pattern with a given replacement in a given file
4 *
5 * Copyright (C) 2005 New Zealand Digital Library, http://www.nzdl.org
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21package org.greenstone.anttasks;
22
23import java.util.ArrayList;
24import org.apache.tools.ant.*;
25import org.apache.tools.ant.taskdefs.*;
26import java.util.*;
27import java.io.*;
28import java.util.regex.*;
29import org.apache.tools.ant.types.FileSet;
30import org.apache.tools.ant.DirectoryScanner;
31
32public class InsertUniqueValue extends Task {
33
34 private File file = null;
35 private ArrayList jobs = null;
36 private FileSet fileset = null;
37 private String pattern = null;
38 private int fromLine = -1;
39 private int toLine = -1;
40 private boolean winPath = false;
41 private int count = 0;
42
43 public static void main( String[] args ) {
44
45 InsertUniqueValue rsr = new InsertUniqueValue();
46 rsr.setFile(new File (args[0]));
47 rsr.setPattern(args[1]);
48 rsr.setLines(args[3]);
49
50 rsr.execute();
51
52 }
53
54 public void execute() {
55
56 if ( file == null && fileset == null ) {
57 throw new BuildException( "Error - No file or fileset specified !!" );
58 }
59
60 if ( file != null && !file.exists() ) {
61 throw new BuildException( "Error - File not found !!" );
62 }
63
64 DirectoryScanner dirScanner = null;
65 if ( fileset != null ) {
66 dirScanner = fileset.getDirectoryScanner(project);
67 dirScanner.scan();
68 }
69
70 if ( jobs == null && pattern == null ) {
71 throw new BuildException( "Error - No pattern attribute and no nested jobs !!" );
72 }
73
74 if ( jobs != null && pattern != null ) {
75 throw new BuildException( "Error - Both pattern attribute and nested jobs given !!" );
76 }
77
78 if ( jobs != null ) {
79 for ( int i=0; i<jobs.size(); i++ ) {
80 if ( ((InsertUniqueValueJob)(jobs.get(i))).getPattern() == null ) {
81 throw new BuildException( "Error - One of the jobs lacks a pattern!!" );
82 }
83 }
84 }
85
86
87 //sus out filename(s)
88 File[] files = null;
89 if ( file != null ) {
90 files = new File[1];
91 files[0] = file;
92 } else {
93 String[] fileStrings = dirScanner.getIncludedFiles();
94 files = new File[fileStrings.length];
95 for ( int i=0; i<fileStrings.length; i++ ) {
96 files[i] = new File( dirScanner.getBasedir() + File.separator + fileStrings[i] );
97 }
98 }
99
100 //output greeting
101 System.out.println( "-------------------" );
102 System.out.println( " InsertUniqueValue " );
103 System.out.println( "-------------------" );
104
105 //output lines if necessary
106 if ( this.fromLine != -1 || this.toLine != -1 ) {
107 System.out.println( "Lines: " + (this.fromLine==-1?"Start":Integer.toString(this.fromLine)) + " ~ " + (this.toLine==-1?"End":Integer.toString(this.toLine)) );
108 System.out.println();
109 }
110
111 System.out.println( "Files: " );
112 for ( int fileIndex=0; fileIndex<files.length; fileIndex++ ) {
113
114 int noReplaces = 0;
115
116 File inputFile = files[fileIndex];
117 System.out.println( " " + inputFile );
118
119 //create the output stream
120 BufferedWriter out = null;
121 File temp = null;
122 try {
123 //create temp file.
124 temp = File.createTempFile("rsr", ".tmp");
125
126 //delete temp file when program exits.
127 temp.deleteOnExit();
128
129 //writer to temp file
130 out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(temp), "UTF8") );
131
132 } catch (IOException e) {
133 throw new BuildException( "Error - Couldn't create or open the temp file" );
134 }
135
136
137 //create the input stream
138 BufferedReader in = null;
139 try {
140 in = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), "UTF8") );
141 } catch ( Exception e ) {
142 throw new BuildException( "Error - Couldn't open the specified file" );
143 }
144
145 //pass the file through, searching and replacing
146 String line = null;
147 int lineNumber = 1;
148 boolean hasMoreLines = true;
149 while ( hasMoreLines ) {
150
151 try {
152 line = in.readLine();
153 } catch ( Exception e ) {
154 System.err.println( e.getMessage() );
155 throw new BuildException( "Error - Couldn't read from the specified file" );
156 }
157
158 if ( line == null ) {
159 hasMoreLines = false;
160 } else {
161
162 //only if within the given line range
163 if ( ( fromLine == -1 || lineNumber >= fromLine ) && ( toLine == -1 || lineNumber < toLine ) ) {
164 String oldLine = line;
165 if ( pattern != null ) {
166 int index = 0;
167 int prevIndex = 0;
168 StringBuffer newLine = new StringBuffer();
169 while((index = line.indexOf((String)pattern, index)) != -1)
170 {
171 newLine.append(line.substring(prevIndex, index));
172 newLine.append(pattern + count++);
173 index += pattern.length();
174 prevIndex = index;
175 }
176 newLine.append(line.substring(prevIndex, line.length()));
177 line = newLine.toString();
178 } else {
179 for ( int i=0; i<jobs.size(); i++ ) {
180 int index = 0;
181 int prevIndex = 0;
182 StringBuffer newLine = new StringBuffer();
183 String currentPattern = ((InsertUniqueValueJob)(jobs.get(i))).getPattern();
184 while((index = line.indexOf((String)currentPattern, index)) != -1)
185 {
186 newLine.append(line.substring(prevIndex, index));
187 newLine.append(currentPattern + count++);
188 index += currentPattern.length();
189 prevIndex = index;
190 }
191 newLine.append(line.substring(prevIndex, line.length()));
192 line = newLine.toString();
193 }
194 }
195 if ( !oldLine.equals( line ) ) {
196 noReplaces++;
197 }
198 }
199
200 try {
201 out.write( line );
202 out.newLine();
203 } catch ( Exception e ) {
204 throw new BuildException( "Error - Couldn't write to the temp file" );
205 }
206 }
207 lineNumber++;
208 }
209
210 try {
211 //close them both up
212 in.close();
213 out.close();
214 } catch ( Exception e ) {
215 throw new BuildException( "Error - Couldn't close a file" );
216 }
217
218
219 //copy the new file (temp) over the original
220 InputStream i;
221 OutputStream o;
222 try {
223 i = new FileInputStream(temp);
224 o = new FileOutputStream(inputFile);
225
226 } catch ( Exception e ) {
227 throw new BuildException( "Error - Couldn't open the temp file" );
228 }
229
230 try {
231
232 // Transfer bytes from in to out
233 byte[] buf = new byte[1024];
234 int len;
235 while ((len = i.read(buf)) > 0) {
236 o.write(buf, 0, len);
237 }
238
239 //close them up
240 i.close();
241 o.close();
242 } catch ( Exception e ) {
243 throw new BuildException( "Error - Couldn't write to the specified file" );
244 }
245
246
247 if ( noReplaces == 0 ) {
248 System.out.println( " No Changes Made" );
249 } else if ( noReplaces == 1 ) {
250 System.out.println( " Successfully changed 1 line" );
251 } else {
252 System.out.println( " Successfully changed " + noReplaces + " lines" );
253 }
254 System.out.println();
255
256 }
257
258 }
259
260 public void setFile(File file) {
261 if ( this.fileset != null || this.file != null ) {
262 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
263 }
264 this.file = file;
265 }
266
267 public void setLines(String lines) {
268 //lines should be in the form "2" or "2-5"
269
270 //trim
271 lines.replaceAll("\\s","");
272
273 if ( lines == "" ) {
274 throw new BuildException( "Error - no line number(s) given in lines attribute!! " );
275 }
276
277 //split into parts
278 String[] parts = lines.split("-",2);
279
280 try {
281 if ( parts.length == 1 ) {
282 this.fromLine = Integer.parseInt( parts[0] );
283 this.toLine = this.fromLine + 1;
284 } else {
285 if ( !parts[0].equals("") ) this.fromLine = Integer.parseInt( parts[0] );
286 if ( !parts[1].equals("") ) this.toLine = Integer.parseInt( parts[1] );
287 }
288 } catch( NumberFormatException nfe ) {
289 throw new BuildException( "Error - invalid line numbers given in lines attribute!! '" + parts[0] + "' - '" + parts[1] + "'" );
290 }
291
292 }
293
294
295 public void setPattern(String pattern) {
296 this.pattern = pattern;
297 }
298
299 public void setWinPath( boolean isWinPath ) {
300 this.winPath = isWinPath;
301 }
302
303 public InsertUniqueValueJob createJob() {
304 InsertUniqueValueJob job = new InsertUniqueValueJob();
305 if ( jobs == null ) {
306 jobs = new ArrayList();
307 }
308 jobs.add( job );
309 return job;
310
311 }
312
313 public FileSet createFileset() {
314 if ( this.fileset != null || this.file != null ) {
315 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
316 }
317 fileset = new FileSet();
318 return fileset;
319 }
320
321}
Note: See TracBrowser for help on using the repository browser.