View Javadoc

1   package com.explosion.utilities.process;
2   
3   /*
4    * =============================================================================
5    * 
6    * Copyright 2004 Stephen Cowx
7    * 
8    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9    * use this file except in compliance with the License. You may obtain a copy of
10   * the License at
11   * 
12   * http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   * 
20   * =============================================================================
21   */
22  
23  import java.io.BufferedReader;
24  import java.io.BufferedWriter;
25  import java.io.File;
26  import java.io.FileReader;
27  import java.io.FileWriter;
28  import java.io.IOException;
29  
30  import javax.swing.JOptionPane;
31  import javax.swing.SwingUtilities;
32  
33  import org.apache.log4j.LogManager;
34  import org.apache.log4j.Logger;
35  
36  import com.explosion.expf.Application;
37  import com.explosion.utilities.FileIterator;
38  import com.explosion.utilities.GeneralConstants;
39  import com.explosion.utilities.exception.ExceptionManagerFactory;
40  import com.explosion.utilities.process.threads.Finishable;
41  import com.explosion.utilities.process.threads.ProcessThread;
42  import com.explosion.utilities.process.threads.UnitisedProcessThread;
43  
44  /***
45   * @author Stephen Cowx Date created:@12-Feb-2003
46   */
47  public class MultiFileLineByLineReplacer implements com.explosion.utilities.process.threads.UnitisedProcess
48  {
49  
50      private boolean createBackupFiles = true;
51  
52      private static Logger log = LogManager.getLogger(MultiFileLineByLineReplacer.class);
53  
54      private FileIterator iterator;
55  
56      private LineProcessor lineProcessor;
57  
58      private int currentFileIndex = 0;
59  
60      private String statusText = "Processing";
61  
62      private boolean processUnitComplete = false;
63  
64      private ProcessThread parent;
65  
66      private Finishable finishable;
67  
68      private boolean initialised = false;
69  
70      private int numberofLinesProcessed = 0;
71      
72      private boolean isUserProcess = true;    
73  
74      public MultiFileLineByLineReplacer(Finishable finishable, String directoryPath, boolean recursive, String filenamePattern, LineProcessor lineProcessor, boolean createBackupFiles)
75              throws IOException
76      {
77          this.lineProcessor = lineProcessor;
78          this.finishable = finishable;
79          this.createBackupFiles = createBackupFiles;
80  
81          iterator = new FileIterator(directoryPath, filenamePattern, true, recursive, true);
82  
83          parent = new UnitisedProcessThread();
84          parent.setProcess(this);
85      }
86      
87      /***
88       * Returns a boolean value indicating whther this is a user process or not
89       * @return
90       */
91      public boolean isUserProcess()
92      {
93          return this.isUserProcess;
94      }
95      
96      /***
97       * Sets whtether or not this is a user process.  True means that it is
98       * @param truth
99       */
100     public void setIsUserProcess(boolean truth)
101     {
102         this.isUserProcess = true;
103     }    
104 
105     public void start()
106     {
107         parent.start();
108     }
109 
110     public ProcessThread getProcessControl()
111     {
112         return parent;
113     }
114 
115     public void setProcessControl(ProcessThread processThread)
116     {
117         parent = processThread;
118     }
119 
120     public final boolean isStopped()
121     {
122         return parent.getStatus() == ProcessThread.THREAD_STOPPED;
123     }
124 
125     /***
126      * @see com.explosion.utilities.process.UnitisedProcess#initialiseProcessing()
127      */
128     public void initialiseProcessing() throws Exception
129     {
130 
131     }
132 
133     /***
134      * @see com.explosion.utilities.process.UnitisedProcess#finaliseProcessing()
135      */
136     public void finaliseProcessing() throws Exception
137     {
138         if (finishable != null)
139         {
140             Runnable doFinished = new Runnable()
141             {
142 
143                 public void run()
144                 {
145                     finishable.finish();
146                 }
147             };
148             SwingUtilities.invokeLater(doFinished);
149         }
150         statusText = "Done";
151     }
152 
153     /***
154      * @see com.explosion.utilities.process.UnitisedProcess#finaliseProcessing(Exception)
155      */
156     public void finaliseProcessing(Exception e)
157     {
158         ExceptionManagerFactory.getExceptionManager().manageException(e, "Experienced exception while processing.");
159         try
160         {
161             finaliseProcessing();
162         }
163         catch (Exception e1)
164         {
165             //tried and failed, just log and ignore
166             log.debug("Exception while finalising processing.");
167         }
168     }
169 
170     /***
171      * @see com.explosion.utilities.process.UnitisedProcess#getPercentCompete()
172      */
173     public int getPercentComplete()
174     {
175         return iterator.getPercentComplete();
176     }
177 
178     /***
179      * @see com.explosion.utilities.process.UnitisedProcess#getPercentCompete()
180      */
181     public void setPercentComplete(int percentComplete)
182     {}
183 
184     /***
185      * @see com.explosion.utilities.process.UnitisedProcess#getStatusText()
186      */
187     public String getStatusText()
188     {
189         return statusText;
190     }
191 
192     /***
193      * @see com.explosion.utilities.process.UnitisedProcess#beginProcessUnit()
194      */
195     public void beginProcessUnit() throws Exception
196     {
197         processUnitComplete = false;
198     }
199 
200     /***
201      * @see com.explosion.utilities.process.UnitisedProcess#processUnit()
202      */
203     public void processUnit() throws Exception
204     {
205         if (iterator.hasNext())
206         {
207             File file = iterator.next();
208             statusText = "Searching " + file.getName();
209             try
210             {
211                 processFile(file.getAbsolutePath());
212             }
213             catch (Exception e)
214             {
215                 ExceptionManagerFactory.getExceptionManager().manageException(e, "Exception while processing " + file.getName());
216                 if (JOptionPane.NO_OPTION == JOptionPane.showOptionDialog(Application.getApplicationFrame(), "Continue with the next file ?", "Error", JOptionPane.YES_NO_OPTION,
217                         JOptionPane.ERROR_MESSAGE, null, null, null))
218                     parent.stop();
219             }
220         }
221         processUnitComplete = true;
222     }
223 
224     /***
225      * @see com.explosion.utilities.process.UnitisedProcess#endProcessUnit()
226      */
227     public void endProcessUnit() throws Exception
228     {
229         currentFileIndex++;
230     }
231 
232     /***
233      * @see com.explosion.utilities.process.UnitisedProcess#processUnitComplete()
234      */
235     public boolean processUnitComplete()
236     {
237         return processUnitComplete;
238     }
239 
240     public void processFile(String filepath) throws Exception
241     {
242         int num = 0;
243         BufferedReader reader = null;
244         BufferedWriter writer = null;
245         try
246         {
247             if (!parentStopped())
248             {
249                 lineProcessor.open();
250                 reader = new BufferedReader(new FileReader(filepath));
251                 writer = new BufferedWriter(new FileWriter(filepath + ".tmp"));
252                 while (!parentStopped() && reader.ready())
253                 {
254                     String s = reader.readLine();
255                     num++;
256                     numberofLinesProcessed++;
257                     if (s != null)
258                     {
259                         log.debug("<"+s);
260                         String r = lineProcessor.processLine(s, num, filepath);
261                         log.debug(">"+ r);
262                         writer.write( r + GeneralConstants.LS);
263                     }
264                     else
265                         break;
266                 }
267             }
268             
269             reader.close();
270             writer.close();
271 
272             File oldFile = new File(filepath);
273             File newFile = new File(filepath + ".tmp");
274 
275             oldFile.renameTo(new File(filepath + ".bak"));
276             newFile.renameTo(new File(filepath));
277 
278             if (!createBackupFiles)
279                 oldFile.delete();
280 
281         }
282         finally
283         {
284             try
285             {
286                 if (lineProcessor != null)
287                     lineProcessor.close();
288             }
289             catch (Exception e)
290             {
291                 ExceptionManagerFactory.getExceptionManager().manageException(e, "Exception caught while closing line action.");
292             }
293             try
294             {
295                 if (reader != null)
296                     reader.close();
297             }
298             catch (Exception e)
299             {
300                 ExceptionManagerFactory.getExceptionManager().manageException(e, "Exception caught while closing reader.");
301             }
302         }
303     }
304 
305     public boolean parentStopped()
306     {
307         return parent.getStatus() == ProcessThread.THREAD_STOPPED;
308     }
309 
310     /***
311      * Sets the value ofthestatusText for this process.
312      */
313     public void setStatusText(String statusText)
314     {
315         this.statusText = statusText;
316     }
317 
318     public void log(String string)
319     {}
320 
321     public void log(Exception exception, String message)
322     {}
323 
324 }