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

Revision 6, 6.2 KB checked in by jdalbey, 10 years ago (diff)

Multifile commit. Add version # to Paramics Communicator. Move Load button in Sim Mgr. Add several tests. Add package jars target.

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
83            if (lastModified < inputFile.lastModified())
84            {
85
86                try
87                {
88                    Document readerDoc = DocumentBuilderFactory.newInstance()
89                            .newDocumentBuilder().newDocument();
90
91                    Element readerElem = readerDoc.createElement(PARAMICS_COMM_TAGS.READER.tag);
92                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ID.tag, readerID);
93                    readerElem.setAttribute(PARAMICS_COMM_TAGS.ACTION.tag,
94                            PARAMICS_ACTIONS.READ_FILE.action);
95
96                    Element messageElem = readerDoc.createElement(PARAMICS_COMM_TAGS.MESSAGE.tag);
97                    String fileContents = readFromFile();
98                    messageElem.appendChild(readerDoc.createTextNode(fileContents));
99                    readerElem.appendChild(messageElem);
100
101                    readerDoc.appendChild(readerElem);
102
103                    setChanged();
104                    notifyObservers(readerDoc);
105                } catch (Exception e)
106                {
107                    paramLogger.logp(Level.SEVERE,
108                            "ParamicsFileReader.ReaderTimerTask", "run()",
109                            "Exception in reading from file: "
110                            + inputFile.getName(), e);
111                }
112            }
113        }
114    }
115
116    /**
117     * Constructor. Set the reader id and interval from the parsed
118     * ParamicsCommMessage. The interval is found within the first three
119     * characters of the object's "message" data member. Create a file object
120     * for the target file, and create a new file if it does not already exist.
121     * Instantiate the timer and ReaderTimerTask to begin periodic reading of
122     * the file.
123     *
124     * @param workingDir Target working directory. // Oops, the following seem
125     * obsolete
126     * @param mess ParamicsCommMessage object containing registration data.
127     * @param theComm Reference to the ParamicsCommunicator.
128     */
129    public ParamicsFileReader(String workingDir, String id, Integer interval, String targetFile)
130    {
131
132        try
133        {
134            readerID = id;
135            readerInterval = interval;
136
137            inputFile = new File(workingDir + targetFile);
138
139            if (!inputFile.exists())
140            {
141                inputFile.createNewFile();
142            }
143
144            readerTimer = new Timer();
145            readerTimer.scheduleAtFixedRate(new ReaderTimerTask(),
146                    0L, readerInterval * 1000);
147
148        } catch (IOException ioe)
149        {
150            paramLogger.logp(Level.SEVERE, "ParamicsFileReader",
151                    "Constructor()", "Exception in initializing file reading.", ioe);
152        }
153    }
154
155    /**
156     * Method opens the target file and reads all contents. The file is then
157     * cleared.
158     *
159     * @returns
160     * @throws IOException if there is an error in reading or writing to the
161     * file.
162     */
163    private String readFromFile() throws IOException
164    {
165
166        char[] input = new char[(int) inputFile.length()];
167
168        fileReader = new FileReader(inputFile);
169        fileReader.read(input);
170        fileReader.close();
171
172        //make sure the new file has a modified time that is different
173        try
174        {
175            Thread.sleep(1000);
176        } catch (Exception e)
177        {
178        }
179
180        //clear file after reading contents
181        fileWriter = new FileWriter(inputFile);
182        fileWriter.write("");
183        fileWriter.close();
184
185        lastModified = inputFile.lastModified();
186
187        setChanged();
188        notifyObservers(new FileIOUpdate(IO_TYPE.READ, readerID, (long) input.length));
189
190        return new String(input);
191    }
192}
Note: See TracBrowser for help on using the repository browser.