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

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

A few minor fixes to the new ant task

  • 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("iuv", ".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 //only if within the given line range
162 if ( ( fromLine == -1 || lineNumber >= fromLine ) && ( toLine == -1 || lineNumber < toLine ) ) {
163 String oldLine = line;
164 if ( pattern != null ) {
165 int index = 0;
166 int prevIndex = 0;
167 StringBuffer newLine = new StringBuffer();
168 while((index = line.indexOf((String)pattern, index)) != -1)
169 {
170 newLine.append(line.substring(prevIndex, index));
171 newLine.append(pattern + count++);
172 index += pattern.length();
173 prevIndex = index;
174 }
175 newLine.append(line.substring(prevIndex, line.length()));
176 line = newLine.toString();
177 } else {
178 for ( int i=0; i<jobs.size(); i++ ) {
179 int index = 0;
180 int prevIndex = 0;
181 StringBuffer newLine = new StringBuffer();
182 String currentPattern = ((InsertUniqueValueJob)(jobs.get(i))).getPattern();
183 while((index = line.indexOf((String)currentPattern, index)) != -1)
184 {
185 newLine.append(line.substring(prevIndex, index));
186 newLine.append(currentPattern + count++);
187 index += currentPattern.length();
188 prevIndex = index;
189 }
190 newLine.append(line.substring(prevIndex, line.length()));
191 line = newLine.toString();
192 }
193 }
194 if ( !oldLine.equals( line ) ) {
195 noReplaces++;
196 }
197 }
198
199 try {
200 out.write( line );
201 out.newLine();
202 } catch ( Exception e ) {
203 throw new BuildException( "Error - Couldn't write to the temp file" );
204 }
205 }
206 lineNumber++;
207 }
208
209 try {
210 //close them both up
211 in.close();
212 out.close();
213 } catch ( Exception e ) {
214 throw new BuildException( "Error - Couldn't close a file" );
215 }
216
217
218 //copy the new file (temp) over the original
219 InputStream i;
220 OutputStream o;
221 try {
222 i = new FileInputStream(temp);
223 o = new FileOutputStream(inputFile);
224
225 } catch ( Exception e ) {
226 throw new BuildException( "Error - Couldn't open the temp file" );
227 }
228
229 try {
230
231 // Transfer bytes from in to out
232 byte[] buf = new byte[1024];
233 int len;
234 while ((len = i.read(buf)) > 0) {
235 o.write(buf, 0, len);
236 }
237
238 //close them up
239 i.close();
240 o.close();
241 } catch ( Exception e ) {
242 throw new BuildException( "Error - Couldn't write to the specified file" );
243 }
244
245
246 if ( noReplaces == 0 ) {
247 System.out.println( " No Changes Made" );
248 } else if ( noReplaces == 1 ) {
249 System.out.println( " Successfully changed 1 line" );
250 } else {
251 System.out.println( " Successfully changed " + noReplaces + " lines" );
252 }
253 System.out.println();
254
255 }
256
257 }
258
259 public void setFile(File file) {
260 if ( this.fileset != null || this.file != null ) {
261 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
262 }
263 this.file = file;
264 }
265
266 public void setLines(String lines) {
267 //lines should be in the form "2" or "2-5"
268
269 //trim
270 lines.replaceAll("\\s","");
271
272 if ( lines == "" ) {
273 throw new BuildException( "Error - no line number(s) given in lines attribute!! " );
274 }
275
276 //split into parts
277 String[] parts = lines.split("-",2);
278
279 try {
280 if ( parts.length == 1 ) {
281 this.fromLine = Integer.parseInt( parts[0] );
282 this.toLine = this.fromLine + 1;
283 } else {
284 if ( !parts[0].equals("") ) this.fromLine = Integer.parseInt( parts[0] );
285 if ( !parts[1].equals("") ) this.toLine = Integer.parseInt( parts[1] );
286 }
287 } catch( NumberFormatException nfe ) {
288 throw new BuildException( "Error - invalid line numbers given in lines attribute!! '" + parts[0] + "' - '" + parts[1] + "'" );
289 }
290
291 }
292
293
294 public void setPattern(String pattern) {
295 this.pattern = pattern;
296 }
297
298 public void setWinPath( boolean isWinPath ) {
299 this.winPath = isWinPath;
300 }
301
302 public InsertUniqueValueJob createJob() {
303 InsertUniqueValueJob job = new InsertUniqueValueJob();
304 if ( jobs == null ) {
305 jobs = new ArrayList();
306 }
307 jobs.add( job );
308 return job;
309
310 }
311
312 public FileSet createFileset() {
313 if ( this.fileset != null || this.file != null ) {
314 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
315 }
316 fileset = new FileSet();
317 return fileset;
318 }
319
320}
Note: See TracBrowser for help on using the repository browser.