Changeset 6 in tmcsimulator for trunk/src/tmcsim/paramicscommunicator
- Timestamp:
- 04/20/2016 02:29:52 PM (10 years ago)
- Location:
- trunk/src/tmcsim/paramicscommunicator
- Files:
-
- 3 edited
-
ParamicsCommunicator.java (modified) (6 diffs)
-
ParamicsFileReader.java (modified) (2 diffs)
-
gui/ParamicsCommunicatorGUI.java (modified) (8 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/tmcsim/paramicscommunicator/ParamicsCommunicator.java
r2 r6 17 17 import java.util.Properties; 18 18 import java.util.TreeMap; 19 import java.util.logging.FileHandler;20 19 import java.util.logging.Level; 21 20 import java.util.logging.Logger; 22 23 21 import javax.swing.JOptionPane; 24 22 import javax.swing.UIManager; 25 26 23 import org.w3c.dom.Document; 27 24 import org.w3c.dom.Element; 28 29 25 import tmcsim.common.CADProtocol.PARAMICS_ACTIONS; 30 26 import tmcsim.common.CADProtocol.PARAMICS_COMM_TAGS; … … 32 28 import tmcsim.paramicscommunicator.FileRegUpdate.REG_TYPE; 33 29 import tmcsim.paramicscommunicator.gui.ParamicsCommunicatorGUI; 34 import tmcsim.simulationmanager.SimulationManager;35 36 30 37 31 /** 38 * ParamicsCommunicator is the main class for this module. The Paramics 39 * Communicator is used to provide communication between the CAD Simulator 40 * and the Paramics traffic modeler. While the application is running, data 41 * is received on a socket from the CAD Simulator. Transmitted data are 42 * XML documents containing information and action commands. The CAD Simulator 43 * registers readers and writers with the ParamicsCommunicator. Any data read 44 * by a ParamicsReader is sent back to the CAD Simulator. All data to be 45 * written by a ParamicsWriter is received through the socket.<br><br> 46 * The properties file for the ParamicsCommunicator class contains the following data.<br> 32 * ParamicsCommunicator is the main class for this module. The Paramics 33 * Communicator is used to provide communication between the CAD Simulator and 34 * the Paramics traffic modeler. While the application is running, data is 35 * received on a socket from the CAD Simulator. Transmitted data are XML 36 * documents containing information and action commands. The CAD Simulator 37 * registers readers and writers with the ParamicsCommunicator. Any data read by 38 * a ParamicsReader is sent back to the CAD Simulator. All data to be written by 39 * a ParamicsWriter is received through the socket.<br><br> 40 * The properties file for the ParamicsCommunicator class contains the following 41 * data.<br> 47 42 * <code> 48 43 * -----------------------------------------------------------------------------<br> 49 * Socket Port The port number to use for socket communication.<br> 50 * Working Directory The working directory use for Paramics file communication.<br> 51 * Error File The target file to use for error logging.<br> 44 * Socket Port The port number to use for socket communication.<br> 45 * Working Directory The working directory use for Paramics file 46 * communication.<br> 47 * Error File The target file to use for error logging.<br> 52 48 * -----------------------------------------------------------------------------<br> 53 49 * Example File: <br> 54 * SocketPort = 4450 <br>55 * WorkingDirectory = c:\\tmc_simulator\\ <br>56 * ErrorFile = sim_mgr_error.xml <br>50 * SocketPort = 4450 <br> 51 * WorkingDirectory = c:\\tmc_simulator\\ <br> 52 * ErrorFile = sim_mgr_error.xml <br> 57 53 * -----------------------------------------------------------------------------<br> 58 54 * </code> 59 55 * 60 56 * @author Matthew Cechini (mcechini@calpoly.edu) 61 * @version $Date: 2009/04/17 16:27:46 $ $Revision: 1.7 57 * @version $Date: 2009/04/17 16:27:46 $ $Revision: 1.7 62 58 */ 63 public class ParamicsCommunicator extends Observable implements Observer, Runnable { 64 65 /** Error logger. */ 59 public class ParamicsCommunicator extends Observable implements Observer, Runnable 60 { 61 62 /** 63 * Error logger. 64 */ 66 65 private static Logger paramLogger = Logger.getLogger("tmcsim.paramicscommunicator"); 67 66 68 67 /** 69 68 * Enumeration containing property names. 69 * 70 70 * @author Matthew Cechini 71 71 */ 72 private static enum PROPERTIES {73 74 SOCKET_PORT ("SocketPort"), 75 WORKING_DIR ("WorkingDirectory");76 72 private static enum PROPERTIES 73 { 74 75 SOCKET_PORT("SocketPort"), 76 WORKING_DIR("WorkingDirectory"); 77 77 public String name; 78 79 private PROPERTIES(String n) { 78 79 private PROPERTIES(String n) 80 { 80 81 name = n; 81 82 } 82 83 } 83 84 85 /** Properties object. */ 86 private Properties paramicsCommProp = null; 87 88 /** Current working directory where files will be read and written */ 84 /** 85 * Properties object. 86 */ 87 private Properties paramicsCommProp = null; 88 /** 89 * Current working directory where files will be read and written 90 */ 89 91 private String workingDirectory = null; 90 91 /** Socket used to create socket communication with the CAD Simulator. */ 92 /** 93 * Socket used to create socket communication with the CAD Simulator. 94 */ 92 95 private ServerSocket serverSocket = null; 93 94 /** Soccket used to communicate with CAD Simulator.*/ 95 private Socket paramicsSocket = null; 96 97 /** Input Stream for reading data from the CAD Simulator. */ 96 /** 97 * Soccket used to communicate with CAD Simulator. 98 */ 99 private Socket paramicsSocket = null; 100 /** 101 * Input Stream for reading data from the CAD Simulator. 102 */ 98 103 private ObjectInputStream in = null; 99 100 /** Output Stream for writing data to the CAD Simulator. */ 104 /** 105 * Output Stream for writing data to the CAD Simulator. 106 */ 101 107 private ObjectOutputStream out = null; 102 103 /** Map of all current ParamicsFileWriters referenced by I/O ID. */ 108 /** 109 * Map of all current ParamicsFileWriters referenced by I/O ID. 110 */ 104 111 private TreeMap<String, ParamicsFileWriter> writers = null; 105 106 /** Map of all current ParamicsFileReaders referenced by I/O ID. */ 112 /** 113 * Map of all current ParamicsFileReaders referenced by I/O ID. 114 */ 107 115 private TreeMap<String, ParamicsFileReader> readers = null; 108 109 /** The view class for the ParamicsCommunicator. */ 116 /** 117 * The view class for the ParamicsCommunicator. 118 */ 110 119 private ParamicsCommunicatorGUI theGUI; 111 112 /** 113 * Constructor. Read in the property values. If the properties file 114 * does not contain a value for the working directory, open a dialog 115 * to prompt the user for the path of the Paramics working directory. 116 * An empty string is not accepted. A null signifies that the user 117 * pressed cancel. Prompt the user to accept the cancel and exit the 118 * application if confirmed. Continue until a valid directory has been 119 * entered, that exists, and append a '\' to the end of the directory 120 * if necessary. 121 * 122 * Initialize the Sockets 123 * and begin communication. 124 * 125 * @param propertiesFilePath File Path of ParamicsCommunicator properties file. 126 */ 127 public ParamicsCommunicator (String propertiesFile) 128 { 129 120 121 /** 122 * Constructor. Read in the property values. If the properties file does not 123 * contain a value for the working directory, open a dialog to prompt the 124 * user for the path of the Paramics working directory. An empty string is 125 * not accepted. A null signifies that the user pressed cancel. Prompt the 126 * user to accept the cancel and exit the application if confirmed. Continue 127 * until a valid directory has been entered, that exists, and append a '\' 128 * to the end of the directory if necessary. 129 * 130 * Initialize the Sockets and begin communication. 131 * 132 * @param propertiesFilePath File Path of ParamicsCommunicator properties 133 * file. 134 */ 135 public ParamicsCommunicator(String propertiesFile) 136 { 137 130 138 writers = new TreeMap<String, ParamicsFileWriter>(); 131 139 readers = new TreeMap<String, ParamicsFileReader>(); … … 133 141 theGUI = new ParamicsCommunicatorGUI(); 134 142 addObserver(theGUI); 135 theGUI.addWindowListener(new WindowListener() { 136 public void windowActivated(WindowEvent arg0) {}; 137 public void windowClosed(WindowEvent arg0) {}; 138 public void windowClosing(WindowEvent arg0) { 143 theGUI.addWindowListener(new WindowListener() 144 { 145 public void windowActivated(WindowEvent arg0) 146 { 147 } 148 149 ; 150 public void windowClosed(WindowEvent arg0) 151 { 152 } 153 154 ; 155 public void windowClosing(WindowEvent arg0) 156 { 139 157 System.exit(0); 140 158 } 141 public void windowDeactivated(WindowEvent arg0) {}; 142 public void windowDeiconified(WindowEvent arg0) {}; 143 public void windowIconified(WindowEvent arg0) {}; 144 public void windowOpened(WindowEvent arg0) {}; 159 160 public void windowDeactivated(WindowEvent arg0) 161 { 162 } 163 164 ; 165 public void windowDeiconified(WindowEvent arg0) 166 { 167 } 168 169 ; 170 public void windowIconified(WindowEvent arg0) 171 { 172 } 173 174 ; 175 public void windowOpened(WindowEvent arg0) 176 { 177 } 178 ; 145 179 }); 146 147 try { 180 181 try 182 { 148 183 paramicsCommProp = new Properties(); 149 184 paramicsCommProp.load(new FileInputStream(propertiesFile)); 150 151 if (paramicsCommProp.getProperty(PROPERTIES.SOCKET_PORT.name) == null)152 { 153 JOptionPane.showMessageDialog(theGUI, 154 "Properties file missing CAD Simulator Port information.", 185 186 if (paramicsCommProp.getProperty(PROPERTIES.SOCKET_PORT.name) == null) 187 { 188 JOptionPane.showMessageDialog(theGUI, 189 "Properties file missing CAD Simulator Port information.", 155 190 "Invalid Configuration", JOptionPane.ERROR_MESSAGE); 156 191 System.exit(0); 157 } 158 else if(paramicsCommProp.getProperty(PROPERTIES.WORKING_DIR.name) == null || 159 paramicsCommProp.getProperty(PROPERTIES.WORKING_DIR.name).length() == 0) { 160 161 try { 192 } else if (paramicsCommProp.getProperty(PROPERTIES.WORKING_DIR.name) == null 193 || paramicsCommProp.getProperty(PROPERTIES.WORKING_DIR.name).length() == 0) 194 { 195 196 try 197 { 162 198 String workingDir = null; 163 164 while (workingDir == null || workingDir.length() == 0) { 199 200 while (workingDir == null || workingDir.length() == 0) 201 { 165 202 workingDir = JOptionPane.showInputDialog(null, 166 203 "Please set the output directory for Paramics communication.", 167 204 "Paramics Working Directory", JOptionPane.QUESTION_MESSAGE); 168 169 if (workingDir == null) {170 171 } 172 else if(!new File(workingDir).exists()){205 206 if (workingDir == null) 207 { 208 } else if (!new File(workingDir).exists()) 209 { 173 210 JOptionPane.showMessageDialog(null, 174 211 "Directory does not exist.", 175 212 "Invalid Working Directory", JOptionPane.WARNING_MESSAGE); 176 213 177 214 workingDir = null; 178 } 179 else if(!new File(workingDir).isDirectory()){215 } else if (!new File(workingDir).isDirectory()) 216 { 180 217 JOptionPane.showMessageDialog(null, 181 218 workingDir + " is not a directory.", 182 219 "Invalid Working Directory", JOptionPane.WARNING_MESSAGE); 183 220 184 221 workingDir = null; 185 } 222 } 186 223 } 187 224 188 if(workingDir.lastIndexOf("\\") != workingDir.length()-1) { 225 if (workingDir.lastIndexOf("\\") != workingDir.length() - 1) 226 { 189 227 workingDir = workingDir + "\\"; 190 228 } 191 192 paramicsCommProp.setProperty(PROPERTIES.WORKING_DIR.name, workingDir); 229 230 paramicsCommProp.setProperty(PROPERTIES.WORKING_DIR.name, workingDir); 193 231 paramicsCommProp.store(new FileOutputStream(propertiesFile), ""); 194 } catch (IOException ioe) { 195 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 232 } catch (IOException ioe) 233 { 234 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 196 235 "Exception in writing properties file.", ioe); 197 236 } 198 237 199 238 } 200 239 201 240 workingDirectory = paramicsCommProp.getProperty( 202 PROPERTIES.WORKING_DIR.name).trim(); 203 204 } catch (Exception e) { 205 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 241 PROPERTIES.WORKING_DIR.name).trim(); 242 243 } catch (Exception e) 244 { 245 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 206 246 "Exception in reading properties file.", e); 207 247 } 208 209 210 try { 248 249 250 try 251 { 211 252 initializeSockets(Integer.parseInt(paramicsCommProp.getProperty( 212 253 PROPERTIES.SOCKET_PORT.name).trim())); 213 } 214 catch (Exception e){215 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 254 } catch (Exception e) 255 { 256 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Constructor", 216 257 "Exception in initializing sockets.", e); 217 258 } 218 259 219 260 } 220 261 221 262 /** 222 263 * Transmits a message XML document object to the CAD Simulator. … … 224 265 * @param mess The ParamicsCommMessage to be transmitted. 225 266 */ 226 private void write(Document mess) { 227 228 synchronized(paramicsSocket) { 229 try { 267 private void write(Document mess) 268 { 269 270 synchronized (paramicsSocket) 271 { 272 try 273 { 230 274 out.writeObject(mess); 231 275 out.flush(); 232 } 233 catch (Exception e){234 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "write", 276 } catch (Exception e) 277 { 278 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "write", 235 279 "Exception in writing to the socket.", e); 236 280 } 237 281 } 238 282 } 239 240 /** 241 * Observer/Observable update method. The Paramics Communicator observers242 * registered ParamicsReaders. When messages are to be sent, they are sent243 * through this method. All messages are ParamicsCommMessage objects. Send283 284 /** 285 * Observer/Observable update method. The Paramics Communicator observers 286 * registered ParamicsReaders. When messages are to be sent, they are sent 287 * through this method. All messages are ParamicsCommMessage objects. Send 244 288 * these messages to the write() method for transmission on the socket. 245 289 */ 246 public void update(Observable o, Object arg) { 247 248 if(arg instanceof Document) { 249 write((Document)arg); 250 } 251 } 252 253 /** 254 * Runnable method. While this thread is not interrupted, read in an 255 * object from the socket input stream. If an object exists, call 256 * doMessage() to parse and perform the received action in the message. 257 */ 258 public void run() { 259 260 while(true) { 261 try { 262 doMessage((Document)in.readObject()); 263 } 264 catch(SocketTimeoutException ste) { 290 public void update(Observable o, Object arg) 291 { 292 293 if (arg instanceof Document) 294 { 295 write((Document) arg); 296 } 297 } 298 299 /** 300 * Runnable method. While this thread is not interrupted, read in an object 301 * from the socket input stream. If an object exists, call doMessage() to 302 * parse and perform the received action in the message. 303 */ 304 public void run() 305 { 306 307 while (true) 308 { 309 try 310 { 311 doMessage((Document) in.readObject()); 312 } catch (SocketTimeoutException ste) 313 { 265 314 //just try again 266 } 267 catch(EOFException eofe){268 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", 315 } catch (EOFException eofe) 316 { 317 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", 269 318 "run", "EOF Exception in reading data from the socket.", eofe); 270 } 271 catch(Exception e){272 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", 319 } catch (Exception e) 320 { 321 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", 273 322 "run", "Exception in reading data from the socket.", e); 274 323 275 JOptionPane.showMessageDialog(theGUI, 276 "Connection has been lost to the CAD Simulator. " +277 "Paramics Communicator will now shutdown.",324 JOptionPane.showMessageDialog(theGUI, 325 "Connection has been lost to the CAD Simulator. " 326 + "Paramics Communicator will now shutdown.", 278 327 "Dropped Connection", JOptionPane.ERROR_MESSAGE); 279 328 break; 280 } 281 } 282 283 284 try { in.close(); } catch (Exception e) {} 285 try { out.close(); } catch (Exception e) {} 286 try { serverSocket.close(); } catch (Exception e) {} 287 try { paramicsSocket.close(); } catch (Exception e) {} 288 289 } 290 329 } 330 } 331 332 333 try 334 { 335 in.close(); 336 } catch (Exception e) 337 { 338 } 339 try 340 { 341 out.close(); 342 } catch (Exception e) 343 { 344 } 345 try 346 { 347 serverSocket.close(); 348 } catch (Exception e) 349 { 350 } 351 try 352 { 353 paramicsSocket.close(); 354 } catch (Exception e) 355 { 356 } 357 358 } 359 291 360 /** 292 361 * Perform the action represented in the received XML document message. 293 * First determine if the action is from a READER, WRITER, and RESET. 294 * If the paramics action is REGISTER, add a new ParamicsFileReader/Writer295 * to the local list of readers/writers and update the GUI with a296 * FileRegUpdate object. If the paramics action is UNREGISTER, remove the297 * ParamicsFileReader/Writer from the local list of readers/writers and update298 * the GUI with a FileRegUpdate object. If RESET is received, clear all299 * readers and writers.300 * 362 * First determine if the action is from a READER, WRITER, and RESET. If the 363 * paramics action is REGISTER, add a new ParamicsFileReader/Writer to the 364 * local list of readers/writers and update the GUI with a FileRegUpdate 365 * object. If the paramics action is UNREGISTER, remove the 366 * ParamicsFileReader/Writer from the local list of readers/writers and 367 * update the GUI with a FileRegUpdate object. If RESET is received, clear 368 * all readers and writers. 369 * 301 370 * @param mess Received XML document message. 302 371 */ 303 private void doMessage (Document mess) { 304 372 private void doMessage(Document mess) 373 { 374 305 375 Element rootElement = mess.getDocumentElement(); 306 376 307 String id = null;377 String id = null; 308 378 String action = null; 309 310 switch(PARAMICS_COMM_TAGS.fromString(rootElement.getNodeName())) { 379 380 switch (PARAMICS_COMM_TAGS.fromString(rootElement.getNodeName())) 381 { 311 382 case READER: 312 id = rootElement.getAttribute(PARAMICS_COMM_TAGS.ID.tag);383 id = rootElement.getAttribute(PARAMICS_COMM_TAGS.ID.tag); 313 384 action = rootElement.getAttribute(PARAMICS_COMM_TAGS.ACTION.tag); 314 315 switch(PARAMICS_ACTIONS.fromString(action)) { 385 386 switch (PARAMICS_ACTIONS.fromString(action)) 387 { 316 388 case REGISTER: 317 Integer interval = Integer.parseInt(rootElement.getChildNodes().item(0).getTextContent());318 String targetFile = rootElement.getChildNodes().item(1).getTextContent();319 320 readers.put(id, new ParamicsFileReader(workingDirectory, id, 389 Integer interval = Integer.parseInt(rootElement.getChildNodes().item(0).getTextContent()); 390 String targetFile = rootElement.getChildNodes().item(1).getTextContent(); 391 392 readers.put(id, new ParamicsFileReader(workingDirectory, id, 321 393 interval, targetFile)); 322 394 readers.get(id).addObserver(this); 323 395 readers.get(id).addObserver(theGUI); 324 396 325 397 setChanged(); 326 notifyObservers(new FileRegUpdate(IO_TYPE.READ, 398 notifyObservers(new FileRegUpdate(IO_TYPE.READ, 327 399 REG_TYPE.REGISTER, id, targetFile, interval)); 328 400 break; 329 case UNREGISTER: 401 case UNREGISTER: 330 402 readers.get(id).deleteObserver(this); 331 403 readers.get(id).deleteObserver(theGUI); … … 333 405 334 406 setChanged(); 335 notifyObservers(new FileRegUpdate(IO_TYPE.READ, 336 REG_TYPE.UNREGISTER, id, null, null)); 407 notifyObservers(new FileRegUpdate(IO_TYPE.READ, 408 REG_TYPE.UNREGISTER, id, null, null)); 337 409 break; 338 410 } 339 411 break; 340 412 case WRITER: 341 id = rootElement.getAttribute(PARAMICS_COMM_TAGS.ID.tag);413 id = rootElement.getAttribute(PARAMICS_COMM_TAGS.ID.tag); 342 414 action = rootElement.getAttribute(PARAMICS_COMM_TAGS.ACTION.tag); 343 344 switch(PARAMICS_ACTIONS.fromString(action)) { 415 416 switch (PARAMICS_ACTIONS.fromString(action)) 417 { 345 418 case REGISTER: 346 String targetFile = rootElement.getChildNodes().item(0).getTextContent(); 347 348 writers.put(id, new ParamicsFileWriter(id, 419 String targetFile = rootElement.getChildNodes().item(0).getTextContent(); 420 421 writers.put(id, new ParamicsFileWriter(id, 349 422 workingDirectory, targetFile)); 350 423 writers.get(id).addObserver(theGUI); 351 424 352 425 setChanged(); 353 notifyObservers(new FileRegUpdate(IO_TYPE.WRITE, 354 REG_TYPE.REGISTER, id, targetFile, null)); 426 notifyObservers(new FileRegUpdate(IO_TYPE.WRITE, 427 REG_TYPE.REGISTER, id, targetFile, null)); 355 428 break; 356 case UNREGISTER: 429 case UNREGISTER: 357 430 writers.remove(id); 358 431 359 432 writers.get(id).deleteObserver(theGUI); 360 433 361 434 setChanged(); 362 notifyObservers(new FileRegUpdate(IO_TYPE.WRITE, 435 notifyObservers(new FileRegUpdate(IO_TYPE.WRITE, 363 436 REG_TYPE.UNREGISTER, id, null, null)); 364 437 break; 365 438 case WRITE_FILE: 366 writers.get(id).writeMessage((Element) rootElement.getChildNodes().item(0));439 writers.get(id).writeMessage((Element) rootElement.getChildNodes().item(0)); 367 440 break; 368 441 } … … 372 445 writers.clear(); 373 446 break; 374 } 375 } 376 377 /** 378 * Method waits to accept a socket connection from the CAD Simulator. 379 * When a connection has been established the method exits. The input and 380 * output streams are created on the new socket. 381 * 382 * @param socketPort Socket port to use for establishing Socket communication. 383 * @throws IOException if there is an exception in establishing Socket communication. 384 */ 385 private void initializeSockets(Integer socketPort) throws IOException { 386 447 } 448 } 449 450 /** 451 * Method waits to accept a socket connection from the CAD Simulator. When a 452 * connection has been established the method exits. The input and output 453 * streams are created on the new socket. 454 * 455 * @param socketPort Socket port to use for establishing Socket 456 * communication. 457 * @throws IOException if there is an exception in establishing Socket 458 * communication. 459 */ 460 private void initializeSockets(Integer socketPort) throws IOException 461 { 462 387 463 boolean waiting = true; 388 389 try { 390 serverSocket = new ServerSocket(socketPort); 391 //delay for accept timeout(milliseconds) 392 serverSocket.setSoTimeout(10 * 1000); 393 } 394 catch (IOException ioe) { 395 throw new IOException("Exception in creating " + 396 "the server socket on port " + socketPort); 397 } 398 399 while(waiting) { 400 try{ 464 465 try 466 { 467 serverSocket = new ServerSocket(socketPort); 468 //delay for accept timeout(milliseconds) 469 serverSocket.setSoTimeout(10 * 1000); 470 } catch (IOException ioe) 471 { 472 throw new IOException("Exception in creating " 473 + "the server socket on port " + socketPort); 474 } 475 476 while (waiting) 477 { 478 try 479 { 401 480 paramicsSocket = serverSocket.accept(); 402 481 waiting = false; 403 } 404 catch(SocketTimeoutException ste){482 } catch (SocketTimeoutException ste) 483 { 405 484 System.out.println("...waiting..."); 406 } 407 catch(IOException ioe){408 throw new IOException("Exception in creating " +409 "the receiving socket on port " + socketPort);410 } 411 } 412 413 485 } catch (IOException ioe) 486 { 487 throw new IOException("Exception in creating " 488 + "the receiving socket on port " + socketPort); 489 } 490 } 491 492 414 493 //** out must be performed before in to unlock for connecting socket **// 415 try { 416 out = new ObjectOutputStream(paramicsSocket.getOutputStream()); 417 in = new ObjectInputStream(paramicsSocket.getInputStream()); 418 } 419 catch (IOException ioe) { 420 throw new IOException("Exception in creating input " + 421 "and output streams on socket."); 422 } 423 424 } 425 426 /** 427 * Construct the ParamicsCommunicator with the properties file path, 428 * either from the command line arguments or default. 429 * 494 try 495 { 496 out = new ObjectOutputStream(paramicsSocket.getOutputStream()); 497 in = new ObjectInputStream(paramicsSocket.getInputStream()); 498 } catch (IOException ioe) 499 { 500 throw new IOException("Exception in creating input " 501 + "and output streams on socket."); 502 } 503 504 } 505 506 /** 507 * Construct the ParamicsCommunicator with the properties file path, either 508 * from the command line arguments or default. 509 * 430 510 * @param args Command line arguments. 431 511 */ 432 public static void main(String[] args) { 433 434 try 435 { 436 if(System.getProperty("PARAMICS_COMM_PROPERTIES") != null) 512 public static void main(String[] args) 513 { 514 System.setProperty("PARAMICS_COMM_PROPERTIES", "config/paramics_communicator_config.properties"); 515 516 try 517 { 518 if (System.getProperty("PARAMICS_COMM_PROPERTIES") != null) 437 519 { 438 520 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 439 521 440 522 new Thread(new ParamicsCommunicator(System.getProperty( 441 523 "PARAMICS_COMM_PROPERTIES"))).start(); 442 } 443 else 444 { 445 throw new Exception ("PARAMICS_COMM_PROPERTIES system property not defined."); 446 } 447 } 448 catch (Exception e) 449 { 450 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Main", 524 } else 525 { 526 throw new Exception("PARAMICS_COMM_PROPERTIES system property not defined."); 527 } 528 } catch (Exception e) 529 { 530 paramLogger.logp(Level.SEVERE, "ParamicsCommunicator", "Main", 451 531 "Error occured initializing application", e); 452 532 453 JOptionPane.showMessageDialog(null, e.getMessage(), 454 "Error - Program Exiting", JOptionPane.ERROR_MESSAGE); 455 533 JOptionPane.showMessageDialog(null, e.getMessage(), 534 "Error - Program Exiting", JOptionPane.ERROR_MESSAGE); 535 456 536 System.exit(-1); 457 537 } 458 459 460 } 461 538 539 540 } 462 541 } -
trunk/src/tmcsim/paramicscommunicator/ParamicsFileReader.java
r2 r6 10 10 import java.util.logging.Level; 11 11 import java.util.logging.Logger; 12 13 12 import javax.xml.parsers.DocumentBuilderFactory; 14 15 13 import org.w3c.dom.Document; 16 14 import org.w3c.dom.Element; 17 18 15 import tmcsim.common.CADProtocol.PARAMICS_ACTIONS; 19 16 import tmcsim.common.CADProtocol.PARAMICS_COMM_TAGS; 20 17 import tmcsim.paramicscommunicator.FileIOUpdate.IO_TYPE; 21 18 22 23 19 /** 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. 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. 29 24 * 30 25 * @author Matthew Cechini 31 * @version 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 32 */ 33 public 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 */ 33 public 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 */ 39 43 private String readerID = null; 40 41 /** File reference to the file where data is read. */ 44 /** 45 * File reference to the file where data is read. 46 */ 42 47 private File inputFile = null; 43 44 /** FileReader used to read data from the input file. */ 48 /** 49 * FileReader used to read data from the input file. 50 */ 45 51 private FileReader fileReader = null; 46 47 /** FileWriter used to clear the input file. */ 52 /** 53 * FileWriter used to clear the input file. 54 */ 48 55 private FileWriter fileWriter = null; 49 50 /** Value (seconds since 1/1/1970) of input file's last modification time. */ 56 /** 57 * Value (seconds since 1/1/1970) of input file's last modification time. 58 */ 51 59 private long lastModified = 0; 52 53 /** Timer used to schedule file reading tasks. */ 60 /** 61 * Timer used to schedule file reading tasks. 62 */ 54 63 private Timer readerTimer = null; 55 56 /** 57 * Duration (in seconds) that the TimerTask will be scheduled to 58 * read from the target file. 64 /** 65 * Duration (in seconds) that the TimerTask will be scheduled to read from 66 * the target file. 59 67 */ 60 68 private long readerInterval; 61 69 62 70 /** 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. 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 * 65 75 * @author Matthew Cechini 66 76 */ 67 private class ReaderTimerTask extends TimerTask { 68 public void run() { 69 70 if (lastModified < inputFile.lastModified()) { 71 72 try { 77 private class ReaderTimerTask extends TimerTask 78 { 79 80 public void run() 81 { 82 83 if (lastModified < inputFile.lastModified()) 84 { 85 86 try 87 { 73 88 Document readerDoc = DocumentBuilderFactory.newInstance() 74 .newDocumentBuilder().newDocument();75 89 .newDocumentBuilder().newDocument(); 90 76 91 Element readerElem = readerDoc.createElement(PARAMICS_COMM_TAGS.READER.tag); 77 92 readerElem.setAttribute(PARAMICS_COMM_TAGS.ID.tag, readerID); 78 readerElem.setAttribute(PARAMICS_COMM_TAGS.ACTION.tag, 93 readerElem.setAttribute(PARAMICS_COMM_TAGS.ACTION.tag, 79 94 PARAMICS_ACTIONS.READ_FILE.action); 80 95 81 96 Element messageElem = readerDoc.createElement(PARAMICS_COMM_TAGS.MESSAGE.tag); 82 messageElem.appendChild(readerDoc.createTextNode(readFromFile())); 97 String fileContents = readFromFile(); 98 messageElem.appendChild(readerDoc.createTextNode(fileContents)); 83 99 readerElem.appendChild(messageElem); 84 85 readerDoc.appendChild(readerElem); 86 100 101 readerDoc.appendChild(readerElem); 102 87 103 setChanged(); 88 104 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);105 } catch (Exception e) 106 { 107 paramLogger.logp(Level.SEVERE, 108 "ParamicsFileReader.ReaderTimerTask", "run()", 109 "Exception in reading from file: " 110 + inputFile.getName(), e); 95 111 } 96 112 } … … 98 114 } 99 115 100 101 116 /** 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. 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 110 126 * @param mess ParamicsCommMessage object containing registration data. 111 127 * @param theComm Reference to the ParamicsCommunicator. 112 128 */ 113 public ParamicsFileReader(String workingDir, String id, Integer interval, String targetFile) { 114 115 try { 116 readerID = id; 129 public ParamicsFileReader(String workingDir, String id, Integer interval, String targetFile) 130 { 131 132 try 133 { 134 readerID = id; 117 135 readerInterval = interval; 118 119 inputFile = new File(workingDir + targetFile); 120 121 if(!inputFile.exists()) { 136 137 inputFile = new File(workingDir + targetFile); 138 139 if (!inputFile.exists()) 140 { 122 141 inputFile.createNewFile(); 123 142 } 124 143 125 144 readerTimer = new Timer(); 126 readerTimer.scheduleAtFixedRate(new ReaderTimerTask(), 127 0L, readerInterval * 1000); 128 129 } catch (IOException ioe) { 130 paramLogger.logp(Level.SEVERE, "ParamicsFileReader", 145 readerTimer.scheduleAtFixedRate(new ReaderTimerTask(), 146 0L, readerInterval * 1000); 147 148 } catch (IOException ioe) 149 { 150 paramLogger.logp(Level.SEVERE, "ParamicsFileReader", 131 151 "Constructor()", "Exception in initializing file reading.", ioe); 132 152 } 133 153 } 134 135 154 136 155 /** 137 * Method opens the target file and reads all contents. The file is then156 * Method opens the target file and reads all contents. The file is then 138 157 * cleared. 139 158 * 140 159 * @returns 141 * @throws IOException if there is an error in reading or writing to the file. 160 * @throws IOException if there is an error in reading or writing to the 161 * file. 142 162 */ 143 private String readFromFile() throws IOException { 144 145 char[] input = new char[(int)inputFile.length()]; 146 163 private String readFromFile() throws IOException 164 { 165 166 char[] input = new char[(int) inputFile.length()]; 167 147 168 fileReader = new FileReader(inputFile); 148 fileReader.read(input); 169 fileReader.read(input); 149 170 fileReader.close(); 150 171 151 172 //make sure the new file has a modified time that is different 152 try { 173 try 174 { 153 175 Thread.sleep(1000); 176 } catch (Exception e) 177 { 154 178 } 155 catch (Exception e) {} 156 179 157 180 //clear file after reading contents 158 181 fileWriter = new FileWriter(inputFile); 159 182 fileWriter.write(""); 160 183 fileWriter.close(); 161 184 162 185 lastModified = inputFile.lastModified(); 163 186 164 187 setChanged(); 165 notifyObservers(new FileIOUpdate(IO_TYPE.READ, readerID, (long) input.length));166 188 notifyObservers(new FileIOUpdate(IO_TYPE.READ, readerID, (long) input.length)); 189 167 190 return new String(input); 168 } 191 } 169 192 } -
trunk/src/tmcsim/paramicscommunicator/gui/ParamicsCommunicatorGUI.java
r2 r6 11 11 import java.util.logging.LogRecord; 12 12 import java.util.logging.Logger; 13 14 13 import javax.swing.BorderFactory; 15 14 import javax.swing.Box; 16 15 import javax.swing.BoxLayout; 17 16 import javax.swing.JFrame; 17 import javax.swing.JMenuBar; 18 import javax.swing.JOptionPane; 18 19 import javax.swing.JScrollPane; 19 20 import javax.swing.JTabbedPane; 20 21 import javax.swing.JTextArea; 21 22 import tmcsim.common.RevisionNumber; 22 23 import tmcsim.paramicscommunicator.FileIOUpdate; 23 24 import tmcsim.paramicscommunicator.FileRegUpdate; 24 25 25 26 /** 26 * ParamicsCommunicatorGUI is the view class for the ParamicsCommunicator. 27 * The user interface shows a tab for each I/O reader or writer that has28 * been registered with the ParamicsCommunicator. The tab shows the29 * history of I/O reads and writes, and the unique information for the30 * target file and I/Ointerval.31 * 27 * ParamicsCommunicatorGUI is the view class for the ParamicsCommunicator. The 28 * user interface shows a tab for each I/O reader or writer that has been 29 * registered with the ParamicsCommunicator. The tab shows the history of I/O 30 * reads and writes, and the unique information for the target file and I/O 31 * interval. 32 * 32 33 * @author Matthew Cechini 33 34 * @version 34 35 */ 35 36 @SuppressWarnings("serial") 36 public class ParamicsCommunicatorGUI extends JFrame implements Observer { 37 38 /** 39 * Logging handler that writes all received log records to the 40 * error text area. 37 public class ParamicsCommunicatorGUI extends JFrame implements Observer 38 { 39 40 /** 41 * Logging handler that writes all received log records to the error text 42 * area. 43 * 41 44 * @author Matthew Cechini 42 45 */ 43 protected class ParamicsLoggerHandler extends Handler { 46 protected class ParamicsLoggerHandler extends Handler 47 { 44 48 45 49 DateFormat timeFormat = DateFormat.getTimeInstance(); 46 47 public void close() throws SecurityException { 48 } 49 50 public void flush() { 51 } 52 53 public void publish(LogRecord record) { 50 51 public void close() throws SecurityException 52 { 53 } 54 55 public void flush() 56 { 57 } 58 59 public void publish(LogRecord record) 60 { 54 61 StringBuffer errorBuf = new StringBuffer(); 55 62 56 63 errorBuf.append(timeFormat.format(new Date(record.getMillis()))); 57 errorBuf.append(" - " + record.getMessage() + "\n"); 58 59 errorTA.setText(errorTA.getText() + errorBuf.toString()); 60 } 61 } 62 63 /** Map of FileIOTableModel objects for each reader id. */ 64 errorBuf.append(" - " + record.getMessage() + "\n"); 65 66 errorTA.setText(errorTA.getText() + errorBuf.toString()); 67 } 68 } 69 /** 70 * Map of FileIOTableModel objects for each reader id. 71 */ 64 72 protected TreeMap<String, FileIOTableModel> readerTables; 65 66 /** Map of FileIOTableModel objects for each writer id. */ 73 /** 74 * Map of FileIOTableModel objects for each writer id. 75 */ 67 76 protected TreeMap<String, FileIOTableModel> writerTables; 68 69 /** 70 * Constructor. Initialize local lists, set up the logging handler and77 78 /** 79 * Constructor. Initialize local lists, set up the logging handler and 71 80 * initialize the GUI. 72 81 */ 73 public ParamicsCommunicatorGUI() { 82 public ParamicsCommunicatorGUI() 83 { 74 84 super("Paramics Communicator"); 75 85 76 86 readerTables = new TreeMap<String, FileIOTableModel>(); 77 87 writerTables = new TreeMap<String, FileIOTableModel>(); 78 88 79 89 Logger.getLogger("tmcsim.paramicscommunicator").addHandler(new ParamicsLoggerHandler()); 80 90 81 91 initializeGUI(); 82 } 83 84 /** 85 * Observer update method. If the update object is a FileIOUpdate object, 86 * update the TableModel corresponding to the unique I/O id. If the 87 * update object is a FileRegUpdate object, add a new tab if the 88 * registration type is REGISTER, or update an existing tab if the 89 * registration type is UNREGISTER. 90 */ 91 public void update(Observable o, Object arg) { 92 93 if(arg instanceof FileIOUpdate) { 94 95 try { 96 FileIOUpdate update = (FileIOUpdate)arg; 97 98 switch(update.ioType) { 92 } 93 94 /** 95 * Observer update method. If the update object is a FileIOUpdate object, 96 * update the TableModel corresponding to the unique I/O id. If the update 97 * object is a FileRegUpdate object, add a new tab if the registration type 98 * is REGISTER, or update an existing tab if the registration type is 99 * UNREGISTER. 100 */ 101 public void update(Observable o, Object arg) 102 { 103 104 if (arg instanceof FileIOUpdate) 105 { 106 107 try 108 { 109 FileIOUpdate update = (FileIOUpdate) arg; 110 111 switch (update.ioType) 112 { 99 113 case READ: 100 114 readerTables.get(update.ioID).addIOUpdate(update); … … 104 118 break; 105 119 } 106 } 107 catch (Exception e){120 } catch (Exception e) 121 { 108 122 Logger.getLogger("tmcsim.paramicscommunicator.gui").logp( 109 Level.SEVERE, "ParamicsCommunicatorGUI", "update", 123 Level.SEVERE, "ParamicsCommunicatorGUI", "update", 110 124 "Exception in receiving FileIOUpdate object.", e); 111 125 } 112 } 113 else if(arg instanceof FileRegUpdate) { 114 try { 115 FileRegUpdate update = (FileRegUpdate)arg; 116 117 switch(update.ioType) { 126 } else if (arg instanceof FileRegUpdate) 127 { 128 try 129 { 130 FileRegUpdate update = (FileRegUpdate) arg; 131 132 switch (update.ioType) 133 { 118 134 case READ: 119 switch(update.regType) { 135 switch (update.regType) 136 { 120 137 case REGISTER: 121 138 FileIOTableModel model = new FileIOTableModel(); 122 139 readerTables.put(update.ioID, model); 123 140 124 141 addTab(update, model); 125 142 break; … … 130 147 break; 131 148 case WRITE: 132 switch(update.regType) { 149 switch (update.regType) 150 { 133 151 case REGISTER: 134 152 FileIOTableModel model = new FileIOTableModel(); 135 153 writerTables.put(update.ioID, model); 136 154 137 155 addTab(update, model); 138 156 break; … … 140 158 //unregister 141 159 break; 142 } 160 } 143 161 break; 144 162 } 145 163 146 } 147 catch (Exception e){164 } catch (Exception e) 165 { 148 166 Logger.getLogger("tmcsim.paramicscommunicator.gui").logp( 149 Level.SEVERE, "ParamicsCommunicatorGUI", "update", 167 Level.SEVERE, "ParamicsCommunicatorGUI", "update", 150 168 "Exception in receiving FileRegUpdate object.", e); 151 169 } 152 } 153 } 154 155 private void initializeGUI() { 156 157 /* Added by Nathaniel Lehrer */ 158 this.setJMenuBar(new javax.swing.JMenuBar() { 159 { 160 javax.swing.JMenu fileMenu = new javax.swing.JMenu("File"); 161 javax.swing.JMenuItem logItem = new javax.swing.JMenuItem("Show Log"); 162 163 logItem.addActionListener(new java.awt.event.ActionListener() { 164 public void actionPerformed(java.awt.event.ActionEvent evt) { 165 tmcsim.paramicslog.gui.ParamicsLogGUI.getInstance().display(); 166 } 167 }); 168 169 fileMenu.add(logItem); 170 this.add(fileMenu); 170 } 171 } 172 173 private void initializeGUI() 174 { 175 176 JMenuBar menuBar = new JMenuBar(); 177 178 javax.swing.JMenu fileMenu = new javax.swing.JMenu("File"); 179 javax.swing.JMenuItem logItem = new javax.swing.JMenuItem("Show Log"); 180 181 logItem.addActionListener(new java.awt.event.ActionListener() 182 { 183 public void actionPerformed(java.awt.event.ActionEvent evt) 184 { 185 tmcsim.paramicslog.gui.ParamicsLogGUI.getInstance().display(); 171 186 } 172 187 }); 173 /* End Add by Nathaniel Lehrer */ 174 188 189 fileMenu.add(logItem); 190 menuBar.add(fileMenu); 191 192 javax.swing.JMenu helpMenu = new javax.swing.JMenu("Help"); 193 javax.swing.JMenuItem aboutItem = new javax.swing.JMenuItem("About"); 194 195 aboutItem.addActionListener(new java.awt.event.ActionListener() 196 { 197 public void actionPerformed(java.awt.event.ActionEvent evt) 198 { 199 String ver = RevisionNumber.getString(); 200 JOptionPane.showMessageDialog(rootPane, "Version: " + ver, "About", JOptionPane.INFORMATION_MESSAGE); 201 } 202 }); 203 204 helpMenu.add(aboutItem); 205 menuBar.add(helpMenu); 206 207 this.setJMenuBar(menuBar); 208 175 209 fileIOTabs = new JTabbedPane(); 176 210 fileIOTabs.setAlignmentX(Box.CENTER_ALIGNMENT); … … 180 214 fileIOTabs.setBorder(BorderFactory.createCompoundBorder( 181 215 BorderFactory.createTitledBorder( 182 BorderFactory.createRaisedBevelBorder(), "Registered I/O"),183 BorderFactory.createEmptyBorder(5,5,5,5)));184 216 BorderFactory.createRaisedBevelBorder(), "Registered I/O"), 217 BorderFactory.createEmptyBorder(5, 5, 5, 5))); 218 185 219 errorTA = new JTextArea(); 186 220 errorTA.setLineWrap(true); 187 221 188 222 errorPane = new JScrollPane(); 189 223 errorPane.setViewportView(errorTA); … … 191 225 errorPane.setBorder(BorderFactory.createCompoundBorder( 192 226 BorderFactory.createTitledBorder( 193 BorderFactory.createRaisedBevelBorder(), "Errors"),194 BorderFactory.createEmptyBorder(5,5,5,5)));195 196 227 BorderFactory.createRaisedBevelBorder(), "Errors"), 228 BorderFactory.createEmptyBorder(5, 5, 5, 5))); 229 230 197 231 Box guiBox = new Box(BoxLayout.Y_AXIS); 198 232 guiBox.add(fileIOTabs); 199 233 guiBox.add(Box.createVerticalStrut(10)); 200 234 guiBox.add(errorPane); 201 235 202 236 add(guiBox); 203 237 204 238 setMinimumSize(new Dimension(420, 680)); 205 239 setPreferredSize(new Dimension(420, 680)); … … 208 242 setVisible(true); 209 243 } 210 211 /** 212 * Method creates a new tab for the new I/O object. The tab is labeled244 245 /** 246 * Method creates a new tab for the new I/O object. The tab is labeled 213 247 * "Reader #" or "Writer #", where '#' is the I/O object's ID. 248 * 214 249 * @param update Initial update object. 215 * @param model TableModel for reader/writer that will display I/O operations. 216 */ 217 private void addTab(FileRegUpdate update, FileIOTableModel model) { 218 250 * @param model TableModel for reader/writer that will display I/O 251 * operations. 252 */ 253 private void addTab(FileRegUpdate update, FileIOTableModel model) 254 { 255 219 256 String tabName = null; 220 221 switch(update.ioType) { 257 258 switch (update.ioType) 259 { 222 260 case READ: 223 261 tabName = "Reader " + update.ioID; … … 227 265 break; 228 266 } 229 267 230 268 fileIOTabs.add(tabName, new ParamicsIOInfoPanel(update, model)); 231 269 } 232 233 270 private JTabbedPane fileIOTabs; 234 235 271 private JScrollPane errorPane; 236 237 272 private JTextArea errorTA; 238 239 273 }
Note: See TracChangeset
for help on using the changeset viewer.
