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

Revision 40, 6.9 KB checked in by jdalbey, 10 years ago (diff)

Remove some log messages from ParamicsFileReader? and Writer to address memory issues

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;
12import javax.xml.parsers.DocumentBuilderFactory;
13import org.w3c.dom.Document;
14import org.w3c.dom.Element;
15import tmcsim.common.CADProtocol.PARAMICS_ACTIONS;
16import tmcsim.common.CADProtocol.PARAMICS_COMM_TAGS;
17import tmcsim.paramicscommunicator.FileIOUpdate.IO_TYPE;
18
19/**
20 * The ParamicsFileReader handles reading fom a target file which is written to
21 * by Paramics. Once initialized, a timer task is started which periodically
22 * checks the target file for updates. If the file has been modified, it is read
23 * and cleared. The read data is transmitted to the CAD Simulator.
24 *
25 * @author Matthew Cechini
26 * @version 0.1 Notes by jdalbey: Paramics modeler is licensed third-party
27 * software and apparently we don't have an SDK for it. So it seems the
28 * workaround was to communicate with it via data files that the modeler
29 * produces. Wacky, but it works for now. Look at the run() method below: if
30 * (lastModified < inputFile.lastModified()) Means it's watching the file to
31 * see if it has been updated by the modeler.
32 */
33public class ParamicsFileReader extends Observable
34{
35
36    /**
37     * Error Logger.
38     */
39    private Logger paramLogger = Logger.getLogger("tmcsim.paramicscommunicator");
40    /**
41     * FileReader ID used for creation of the ParamicsCommMessage
42     */
43    private String readerID = null;
44    /**
45     * File reference to the file where data is read.
46     */
47    private File inputFile = null;
48    /**
49     * FileReader used to read data from the input file.
50     */
51    private FileReader fileReader = null;
52    /**
53     * FileWriter used to clear the input file.
54     */
55    private FileWriter fileWriter = null;
56    /**
57     * Value (seconds since 1/1/1970) of input file's last modification time.
58     */
59    private long lastModified = 0;
60    /**
61     * Timer used to schedule file reading tasks.
62     */
63    private Timer readerTimer = null;
64    /**
65     * Duration (in seconds) that the TimerTask will be scheduled to read from
66     * the target file.
67     */
68    private long readerInterval;
69
70    /**
71     * A TimerTask to read from the target file. If the file has been modified
72     * since last read, read the file and transmit the data to the CAD
73     * Simulator.
74     *
75     * @author Matthew Cechini
76     */
77    private class ReaderTimerTask extends TimerTask
78    {
79
80        public void run()
81        {
82//            paramLogger.logp(Level.INFO,
83//                    "ParamicsFileReader.ReaderTimerTask", "run()",
84//                    "Waiting for " + inputFile + " to be modified.");
85            if (lastModified < inputFile.lastModified())
86            {
87//                paramLogger.logp(Level.INFO,
88//                        "ParamicsFileReader.ReaderTimerTask", "run()",
89//                        "Cool, " + inputFile + " has been modified, let's read it.");
90
91                try
92                {
93                    Document readerDoc = DocumentBuilderFactory.newInstance()
94                            .newDocumentBuilder().newDocument();
95
96                    Element readerElem = readerDoc.createElement(PARAMICS_COMM_TAGS.READER.tag);
97                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ID.tag, readerID);
98                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ACTION.tag,
99                            PARAMICS_ACTIONS.READ_FILE.action);
100
101                    Element messageElem = readerDoc.createElement(PARAMICS_COMM_TAGS.MESSAGE.tag);
102                    String fileContents = readFromFile();
103 //                   int stringlen = Math.min(160, fileContents.length()-1);
104                    // Log two lines that were read
105//                    paramLogger.logp(Level.INFO,
106//                            "ParamicsFileReader.ReaderTimerTask", "run()",
107//                            "Nice, we read " + fileContents.length() + " bytes.");
108                    messageElem.appendChild(readerDoc.createTextNode(fileContents));
109                    readerElem.appendChild(messageElem);
110
111                    readerDoc.appendChild(readerElem);
112
113                    setChanged();
114                    notifyObservers(readerDoc);
115                } catch (Exception e)
116                {
117                    paramLogger.logp(Level.SEVERE,
118                            "ParamicsFileReader.ReaderTimerTask", "run()",
119                            "Exception in reading from file: "
120                            + inputFile.getName(), e);
121                }
122            }
123        }
124    }
125
126    /**
127     * Constructor. Set the reader id and interval from the parsed
128     * ParamicsCommMessage. The interval is found within the first three
129     * characters of the object's "message" data member. Create a file object
130     * for the target file, and create a new file if it does not already exist.
131     * Instantiate the timer and ReaderTimerTask to begin periodic reading of
132     * the file.
133     *
134     * @param workingDir Target working directory. // Oops, the following seem
135     * obsolete
136     * @param mess ParamicsCommMessage object containing registration data.
137     * @param theComm Reference to the ParamicsCommunicator.
138     */
139    public ParamicsFileReader(String workingDir, String id, Integer interval, String targetFile)
140    {
141
142        try
143        {
144            readerID = id;
145            readerInterval = interval;
146
147            inputFile = new File(workingDir + targetFile);
148
149            if (!inputFile.exists())
150            {
151                inputFile.createNewFile();
152            }
153
154            readerTimer = new Timer();
155            readerTimer.scheduleAtFixedRate(new ReaderTimerTask(),
156                    0L, readerInterval * 1000);
157
158        } catch (IOException ioe)
159        {
160            paramLogger.logp(Level.SEVERE, "ParamicsFileReader",
161                    "Constructor()", "Exception in initializing file reading.", ioe);
162        }
163    }
164
165    /**
166     * Method opens the target file and reads all contents. The file is then
167     * cleared.
168     *
169     * @returns
170     * @throws IOException if there is an error in reading or writing to the
171     * file.
172     */
173    private String readFromFile() throws IOException
174    {
175
176        char[] input = new char[(int) inputFile.length()];
177
178        fileReader = new FileReader(inputFile);
179        fileReader.read(input);
180        fileReader.close();
181
182        //make sure the new file has a modified time that is different
183        try
184        {
185            Thread.sleep(1000);
186        } catch (Exception e)
187        {
188        }
189
190        //clear file after reading contents
191        fileWriter = new FileWriter(inputFile);
192        fileWriter.write("");
193        fileWriter.close();
194
195        lastModified = inputFile.lastModified();
196
197        setChanged();
198        notifyObservers(new FileIOUpdate(IO_TYPE.READ, readerID, (long) input.length));
199
200        return new String(input);
201    }
202}
Note: See TracBrowser for help on using the repository browser.