View Javadoc

1   /*
2    * Created on Mar 5, 2005
3    */
4   package org.jdiagnose.remote.file;
5   
6   import java.io.BufferedWriter;
7   import java.io.File;
8   import java.io.FileWriter;
9   import java.io.IOException;
10  
11  import org.jdiagnose.remote.ExceptionListener;
12  import org.jdiagnose.remote.StdErrExceptionListener;
13  
14  /***
15   * @author jamie
16   */
17  public class BasicFileEmitter implements Emitter {
18  
19      public static final String LINE_SEPARATOR = System.getProperty("line.separator");
20  
21      private File file = null;
22      private BufferedWriter writer;
23      private ExceptionListener exceptionListener = StdErrExceptionListener.DEFAULT_STD_ERR_EXCEPTION_LISTENER;
24      private Object basicFileEmitterLock = new Object();
25      private boolean destroyed = false;
26      
27      public BasicFileEmitter() {
28          
29      }
30      
31      public BasicFileEmitter(String fileName) {
32          this.file = new File(fileName);
33      }
34      
35      public BasicFileEmitter(File file) {
36          this.file = file;
37      }
38      
39      public void init() throws IOException {
40          synchronized(basicFileEmitterLock) {
41              writer = new BufferedWriter(new FileWriter(file.getAbsolutePath(), true));
42              destroyed = false;
43          }
44      }
45      
46      public void destroy() throws IOException {
47          synchronized(basicFileEmitterLock) {
48  	        IOException throwable = null;
49  	        try {
50  	            writer.flush();
51  	        } catch (IOException e) {
52  	            throwable = e;
53  	        } finally {
54  	            try {
55  	                writer.close();
56  	            } catch (IOException e1) {
57  	                if(throwable != null) {
58  	                    throw throwable;
59  	                } else {
60  	                    throw e1;
61  	                }
62  	            }
63  	        }
64          }
65      }
66  
67      /***
68       * @param file The file to set.
69       */
70      public void setFile(File file) {
71          this.file = file;
72      }
73      
74      public File getFile() {
75          return this.file;
76      }
77  
78      /* (non-Javadoc)
79       * @see org.jdiagnose.remote.file.Emitter#emit(java.lang.String)
80       */
81      public void emit(StringBuffer value) {
82          synchronized(basicFileEmitterLock) {
83              if(!destroyed) {
84  		        try {
85  		            writer.write(value.toString());
86  		            writer.write(LINE_SEPARATOR);
87  		            writer.flush();
88  		        } catch (IOException e) {
89  		            exceptionListener.onException(e);
90  		        }
91              }
92          }
93      }
94  
95  }