source: tmcsimulator/trunk/src/tmcsim/paramicscommunicator/ParamicsFileReader.java @ 2

Revision 2, 5.9 KB checked in by jdalbey, 10 years ago (diff)

Initial Import of project files

Line 
1package tmcsim.paramicscommunicator;
2
3import java.io.File;
4import java.io.FileReader;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.util.Observable;
8import java.util.Timer;
9import java.util.TimerTask;
10import java.util.logging.Level;
11import java.util.logging.Logger;
12
13import javax.xml.parsers.DocumentBuilderFactory;
14
15import org.w3c.dom.Document;
16import org.w3c.dom.Element;
17
18import tmcsim.common.CADProtocol.PARAMICS_ACTIONS;
19import tmcsim.common.CADProtocol.PARAMICS_COMM_TAGS;
20import tmcsim.paramicscommunicator.FileIOUpdate.IO_TYPE;
21
22
23/**
24 * The ParamicsFileReader handles reading fom a target file which
25 * is written to by Paramics.  Once initialized, a timer task is
26 * started which periodically checks the target file for updates.
27 * If the file has been modified, it is read and cleared.  The read
28 * data is transmitted to the CAD Simulator.
29 *
30 * @author Matthew Cechini
31 * @version
32 */
33public class ParamicsFileReader extends Observable {
34   
35    /** Error Logger. */
36    private Logger paramLogger = Logger.getLogger("tmcsim.paramicscommunicator");   
37   
38    /** FileReader ID used for creation of the ParamicsCommMessage */
39    private String readerID = null;
40   
41    /** File reference to the file where data is read. */
42    private File inputFile = null;
43   
44    /** FileReader used to read data from the input file. */
45    private FileReader fileReader = null;
46   
47    /** FileWriter used to clear the input file. */
48    private FileWriter fileWriter = null;
49   
50    /** Value (seconds since 1/1/1970) of input file's last modification time. */
51    private long lastModified = 0;
52   
53    /** Timer used to schedule file reading tasks. */
54    private Timer readerTimer = null;
55   
56    /**
57     * Duration (in seconds) that the TimerTask will be scheduled to
58     * read from the target file.
59     */
60    private long readerInterval;
61   
62    /**
63     * A TimerTask to read from the target file.  If the file has been modified since
64     * last read, read the file and transmit the data to the CAD Simulator.
65     * @author Matthew Cechini
66     */
67    private class ReaderTimerTask extends TimerTask {
68        public void run() {     
69           
70            if (lastModified < inputFile.lastModified()) {
71                               
72                try {
73                    Document readerDoc = DocumentBuilderFactory.newInstance()
74                        .newDocumentBuilder().newDocument();
75           
76                    Element readerElem = readerDoc.createElement(PARAMICS_COMM_TAGS.READER.tag);
77                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ID.tag, readerID);
78                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ACTION.tag, 
79                            PARAMICS_ACTIONS.READ_FILE.action);
80                   
81                    Element messageElem = readerDoc.createElement(PARAMICS_COMM_TAGS.MESSAGE.tag);
82                    messageElem.appendChild(readerDoc.createTextNode(readFromFile()));
83                    readerElem.appendChild(messageElem);
84                   
85                    readerDoc.appendChild(readerElem);         
86                       
87                    setChanged();
88                    notifyObservers(readerDoc);
89                }                   
90                catch (Exception e) {
91                    paramLogger.logp(Level.SEVERE, 
92                            "ParamicsFileReader.ReaderTimerTask", "run()", 
93                            "Exception in reading from file: " + 
94                            inputFile.getName(), e);
95                }
96            }
97        }
98    }
99
100
101    /**
102     * Constructor.  Set the reader id and interval from the parsed
103     * ParamicsCommMessage.  The interval is found within the first three
104     * characters of the object's "message" data member.  Create a file
105     * object for the target file, and create a new file if it does
106     * not already exist.  Instantiate the timer and ReaderTimerTask
107     * to begin periodic reading of the file.
108     *
109     * @param workingDir Target working directory.
110     * @param mess ParamicsCommMessage object containing registration data.
111     * @param theComm Reference to the ParamicsCommunicator.
112     */
113    public ParamicsFileReader(String workingDir, String id, Integer interval, String targetFile) {
114       
115        try {       
116            readerID       = id;
117            readerInterval = interval;
118                   
119            inputFile = new File(workingDir + targetFile); 
120                       
121            if(!inputFile.exists()) {
122                inputFile.createNewFile();
123            }
124           
125            readerTimer = new Timer();
126            readerTimer.scheduleAtFixedRate(new ReaderTimerTask(), 
127                0L, readerInterval * 1000); 
128           
129        } catch (IOException ioe) {
130            paramLogger.logp(Level.SEVERE, "ParamicsFileReader", 
131                    "Constructor()", "Exception in initializing file reading.", ioe);
132        }
133    }
134   
135   
136    /**
137     * Method opens the target file and reads all contents.  The file is then
138     * cleared.
139     *
140     * @returns
141     * @throws IOException if there is an error in reading or writing to the file.
142     */
143    private String readFromFile() throws IOException {
144       
145        char[] input = new char[(int)inputFile.length()];
146       
147        fileReader = new FileReader(inputFile);
148        fileReader.read(input);     
149        fileReader.close();
150       
151        //make sure the new file has a modified time that is different
152        try {
153            Thread.sleep(1000);
154        }
155        catch (Exception e) {}
156       
157        //clear file after reading contents
158        fileWriter = new FileWriter(inputFile);
159        fileWriter.write("");
160        fileWriter.close();
161       
162        lastModified = inputFile.lastModified();
163       
164        setChanged();
165        notifyObservers(new FileIOUpdate(IO_TYPE.READ, readerID, (long)input.length));     
166                       
167        return new String(input);
168    }       
169}
Note: See TracBrowser for help on using the repository browser.