Warning: Can't use blame annotator:
svn blame failed on trunk/src/tmcsim/paramicscommunicator/ParamicsFileReader.java: ("Can't find a temporary directory: Internal error", 20014)

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

Revision 47, 6.8 KB checked in by jdalbey, 10 years ago (diff)

Merge 305 modifications into trunk.

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